jingfei195887 opened a new pull request, #22537:
URL: https://github.com/apache/nuttx/pull/22537
## Summary
Add opt-in shared storage for file-descriptor allocation backtraces. With
`CONFIG_FS_BACKTRACE_SHARED`, descriptors with identical captured stacks hold
references to one libc backtrace record. Close, replacement and task exit
release those references. Diagnostic readers copy the stack while the
descriptor still holds its record.
## Impact
- New optional feature: YES. `FS_BACKTRACE` remains an integer and existing
configurations retain private arrays. Shared storage requires
`LIBC_BACKTRACE_DEPTH >= FS_BACKTRACE > 0`.
- Per-group capture control is preserved. File diagnostics display up to
`FS_BACKTRACE` frames when the configured depth is available. The default
skipped depth is 2 for private arrays and 4 for shared capture.
- Pool exhaustion may omit diagnostic records but does not fail otherwise
valid file operations. Pool metadata and reserved entries add RAM; savings
depend on descriptor count and repeated stacks.
- API addition: internal `fdlist_format_backtrace()` takes an untagged table
index, a held file reference and a live descriptor list. It produces an empty
snapshot if the slot has closed or changed files.
- Documentation and GDB support: YES. `fdinfo` supports both storage layouts
and missing records. If macro debug information is absent, it uses the stored
array or record depth.
- Build-system, hardware/driver and required user migration changes: NO.
`sim:citest` explicitly enables the new option. No `/proc/backtrace` inspector
is added.
## Testing
Linux x86_64 simulator; GCC 13.1.0. Baseline
`f9d3eb13c3f412426a2658227f2b332e21e3a526`; candidate
`e9fa907cf3f07b5cffdcb596d536663de8634f32`; functional tests at
`65661ae8f57fc81edfa174637e76a66c1ea10bbb` (all executable code/configuration
identical; final commit adds only the GDB documentation caveat); functional
apps `0a37af9866b7e558fe186da4de7d99cc3dda51d7`.
The 32-bit and 64-bit private-array controls each complete 219 checks with
one expected failure: arrays do not satisfy the new shared-storage assertion.
This matches the baseline behavior. With 128 open descriptors, baseline arrays
complete 427 checks with that same expected failure; shared mode completes 435
checks with none. The shared fixture adds eight snapshot checks.
The shared-mode matrix covers 32-bit and 64-bit descriptors, FDCHECK, a file
display depth of 3 with pool depth 8, fixed-pool exhaustion, pool growth,
capture initially disabled, and an injected descriptor-table extension error.
It also exercises duplication/replacement, descriptor limits, task inheritance
and exit, concurrent descriptor churn and procfs reads, small reads, descriptor
dumps and actual GDB `fdinfo` output.
At each of six debugger checkpoints, every pool reference is matched to a
live descriptor. The final live-record/reference counts return to their initial
values. The ordinary `-g` builds exercise missing-macro fallback. A separate
`-g3` build verifies that GDB loads `FS_BACKTRACE=3` and limits the displayed
stack to three frames. These checks run in a single-CPU simulator, not SMP.
Small-configuration text/data/bss deltas (bytes): disabled `(0, 0, 0)`;
enabled private-array baseline to shared mode `(2368, 0, 5248)`. The
128-descriptor workload changes static RAM plus measured heap use by `-3264`
bytes. Before opening the workload descriptors, the same measurement changes by
`3904` bytes. These figures are configuration-specific; they are not a claim of
unconditional savings. The optimized baseline and branch builds both report the
existing apps `readline_common.c` savednch warning; some coverage runs also
report libgcov profile checksum/overwrite warnings, retained in the runtime
excerpts. Dynamic pool storage is retained for reuse.
Protected `qemu-armv7r:pnsh` and kernel `qemu-armv8a:knsh` compile with
shared tracing, procfs and descriptor dumps enabled. The kernel configuration
also enables `FRAME_POINTER`; the first attempt omitted it and failed to link
`up_backtrace`, and is not counted as a successful build. No physical hardware,
protected/kernel runtime or SMP execution was tested. Allocation failure inside
the shared pool allocator was not injected; the fixed-pool exhaustion and
descriptor-extension failure cases are distinct tests.
| Configuration | Checks | Failures |
|---|---:|---:|
| private64 | 219 | 1 |
| private32 | 219 | 1 |
| shared-depth3 | 227 | 0 |
| final-fdcheck32 | 227 | 0 |
| final-gdb64 | 227 | 0 |
| final-gdb32 | 227 | 0 |
| final-exhaust | 225 | 0 |
| final-growth | 227 | 0 |
| final-default-off | 227 | 0 |
| final-fault | 231 | 0 |
| large-base | 427 | 1 |
| large-branch | 435 | 0 |
| depth 3 with macro debug information | 227 | 0 |
<details>
<summary>Actual runtime and debugger evidence</summary>
`depth3-g3` (selected lines, unchanged):
```text
FSTRACE_GDB configured depth=3
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=3
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=3
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943256, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2017432, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942152, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=3
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`private64` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=80 trace_size=64 mode=normal
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 12, "groups": 4,
"heap_used": 1942824, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
32, "stage": 0, "used": 0}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=23 missing=0
FAIL identical call sites share trace storage errno=0
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 36, "groups": 4,
"heap_used": 1945992, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 1, "used": 0}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 36, "groups": 4,
"heap_used": 1945944, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 2, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 36, "groups": 4,
"heap_used": 2020120, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 3, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 36, "groups": 4,
"heap_used": 2013992, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 4, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 12, "groups": 4,
"heap_used": 1944840, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 5, "used": 0}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=219 failures=1
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`private32` (selected lines, unchanged):
```text
FSTRACE bits=32 fd_size=40 trace_size=32 mode=normal
FSTRACE_POOL {"capacity": 0, "fd_size": 40, "files": 12, "groups": 4,
"heap_used": 1936640, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
32, "stage": 0, "used": 0}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=23 missing=0
FAIL identical call sites share trace storage errno=0
FSTRACE_POOL {"capacity": 0, "fd_size": 40, "files": 36, "groups": 4,
"heap_used": 1938448, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 1, "used": 0}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 0, "fd_size": 40, "files": 36, "groups": 4,
"heap_used": 1938416, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 2, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 40, "files": 36, "groups": 4,
"heap_used": 2012416, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 3, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 40, "files": 36, "groups": 4,
"heap_used": 2006288, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 4, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 40, "files": 12, "groups": 4,
"heap_used": 1937680, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
56, "stage": 5, "used": 0}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=219 failures=1
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`shared-depth3` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943256, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2017432, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942152, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-fdcheck32` (selected lines, unchanged):
```text
FSTRACE bits=32 fd_size=12 trace_size=4 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 12, "groups": 4,
"heap_used": 1935968, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 1937104, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 1937072, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 2011072, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 2004944, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 12, "groups": 4,
"heap_used": 1936336, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-gdb64` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943256, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2017432, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942152, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-gdb32` (selected lines, unchanged):
```text
FSTRACE bits=32 fd_size=12 trace_size=4 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 12, "groups": 4,
"heap_used": 1935968, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 1937104, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 1937072, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 2011072, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 36, "groups": 4,
"heap_used": 2004944, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 12, "files": 12, "groups": 4,
"heap_used": 1936336, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-exhaust` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=exhaust
FSTRACE_POOL {"capacity": 1, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 1, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=24
FSTRACE_POOL {"capacity": 1, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943304, "overflow": 25, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 1, "used": 1}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 1, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943256, "overflow": 109, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 2, "used": 1}
FSTRACE_POOL {"capacity": 1, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2017432, "overflow": 506, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 3, "used": 1}
FSTRACE_POOL {"capacity": 1, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011304, "overflow": 1306, "pool_refs": 6, "pooled": true,
"slots": 56, "stage": 4, "used": 1}
FSTRACE_POOL {"capacity": 1, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942152, "overflow": 1306, "pool_refs": 6, "pooled": true,
"slots": 56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=225 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-growth` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 4, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941704, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 4, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943528, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 8, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943848, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 8, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2018024, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 8, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011896, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 8, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942744, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
56, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-default-off` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 0, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 0, "pool_refs": 0, "pooled": true, "slots":
32, "stage": 0, "used": 0}
FSTRACE_GDB fdinfo stage=0 PASS depth=0
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943304, "overflow": 0, "pool_refs": 24, "pooled": true, "slots":
56, "stage": 1, "used": 1}
FSTRACE_GDB fdinfo stage=1 PASS depth=7
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943256, "overflow": 0, "pool_refs": 24, "pooled": true, "slots":
56, "stage": 2, "used": 2}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2017432, "overflow": 0, "pool_refs": 24, "pooled": true, "slots":
56, "stage": 3, "used": 2}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011304, "overflow": 0, "pool_refs": 24, "pooled": true, "slots":
56, "stage": 4, "used": 2}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942152, "overflow": 0, "pool_refs": 0, "pooled": true, "slots":
56, "stage": 5, "used": 0}
FSTRACE_GDB fdinfo stage=5 PASS depth=0
FSTRACE RESULT checks=227 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`final-fault` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943304, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
56, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 1943464, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
64, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2017640, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
64, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 36, "groups": 4,
"heap_used": 2011512, "overflow": 0, "pool_refs": 30, "pooled": true, "slots":
64, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1942360, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
64, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=231 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`large-base` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=80 trace_size=64 mode=normal
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 12, "groups": 4,
"heap_used": 1942824, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
32, "stage": 0, "used": 0}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=127 missing=0
FAIL identical call sites share trace storage errno=0
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 140, "groups": 4,
"heap_used": 1959672, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
160, "stage": 1, "used": 0}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 140, "groups": 4,
"heap_used": 1959624, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
160, "stage": 2, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 140, "groups": 4,
"heap_used": 2033800, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
160, "stage": 3, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 140, "groups": 4,
"heap_used": 2027672, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
160, "stage": 4, "used": 0}
FSTRACE_POOL {"capacity": 0, "fd_size": 80, "files": 12, "groups": 4,
"heap_used": 1953464, "overflow": 0, "pool_refs": 0, "pooled": false, "slots":
160, "stage": 5, "used": 0}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=427 failures=1
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
`large-branch` (selected lines, unchanged):
```text
FSTRACE bits=64 fd_size=24 trace_size=8 mode=normal
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1941480, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
32, "stage": 0, "used": 1}
FSTRACE_GDB fdinfo stage=0 PASS depth=8
FSTRACE identities different=0 missing=0
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 140, "groups": 4,
"heap_used": 1951160, "overflow": 0, "pool_refs": 134, "pooled": true, "slots":
160, "stage": 1, "used": 2}
FSTRACE_GDB fdinfo stage=1 PASS depth=8
FSTRACE_GDB missing macro fallback PASS
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 140, "groups": 4,
"heap_used": 1951112, "overflow": 0, "pool_refs": 134, "pooled": true, "slots":
160, "stage": 2, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 140, "groups": 4,
"heap_used": 2025288, "overflow": 0, "pool_refs": 134, "pooled": true, "slots":
160, "stage": 3, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 140, "groups": 4,
"heap_used": 2019160, "overflow": 0, "pool_refs": 134, "pooled": true, "slots":
160, "stage": 4, "used": 3}
FSTRACE_POOL {"capacity": 64, "fd_size": 24, "files": 12, "groups": 4,
"heap_used": 1944952, "overflow": 0, "pool_refs": 6, "pooled": true, "slots":
160, "stage": 5, "used": 1}
FSTRACE_GDB fdinfo stage=5 PASS depth=8
FSTRACE RESULT checks=435 failures=0
FSTRACE_POOL RESULT checkpoints=6 failures=0
```
</details>
<details>
<summary>Actual build evidence</summary>
`protected` compiler and build-log tail:
```text
arm-none-eabi-gcc (Arm GNU Toolchain 13.2.rel1 (Build arm-13.7)) 13.2.1
20231009
CC: qemu_bringup.c
CPP:
/home/mi/test/nuttx_apache/fs-upstream/nuttx/boards/arm/qemu/qemu-armv7r/scripts/nuttx.ld->
/home/mi/test/nuttx_apache/fs-upstream/nuttx/boards/arm/qemu/qemu-armv7r/scripts/nuttx.ld.tmp
LD: nuttx
arm-none-eabi-ld: warning:
/home/mi/test/nuttx_apache/fs-upstream/nuttx/nuttx has a LOAD segment with RWX
permissions
Memory region Used Size Region Size %age Used
kflash: 197536 B 512 KB 37.68%
uflash: 0 GB 512 KB 0.00%
ksram: 16 KB 8 MB 0.20%
usram: 0 GB 8 MB 0.00%
CP: nuttx.bin
qemu-armv7r:pnsh build PASS
```
Build warnings:
```text
Makefile:193: 目标“arm_perf.o”在同一个规则中给出了多次
CC: pthread/pthread_mutexattr_setpshared.c Makefile:193:
目标“arm_perf.o”在同一个规则中给出了多次
CC: spawn/lib_psfa_addopen.c fpu.c:57:8: warning: #warning "FPU test not
built; Only available in the flat build (CONFIG_BUILD_FLAT)" [-Wcpp]
arm-none-eabi-ld: warning:
/home/mi/test/nuttx_apache/fs-upstream/nuttx/nuttx has a LOAD segment with RWX
permissions
```
`kernel` compiler and build-log tail:
```text
aarch64-none-elf-gcc (GCC) 13.4.0
CC: qemu_boardinit.c
CC: qemu_bringup.c
CC: qemu_power.c
LD: nuttx
Memory region Used Size Region Size %age Used
dram: 320 KB 2 MB 15.62%
pgram: 0 B 4 MB 0.00%
CP: nuttx.hex
CP: nuttx.bin
qemu-armv8a:knsh build PASS
```
Final local gate:
```text
target : nuttx
branch : fs/fd-backtrace-pool
head : e9fa907cf3f07b5cffdcb596d536663de8634f32
subject : fs: replace fsbacktrace with global backtrace
commits : 1
base : f9d3eb13c3 (merge-base with upstream/master)
behind : 0 commits of upstream/master
nuttx : e9fa907cf3
apps : 0a37af9866
options : CONFIG_SCHED_BACKTRACE CONFIG_FRAME_POINTER
CONFIG_LIBC_BACKTRACE_DEPTH=8 CONFIG_FS_BACKTRACE=8 CONFIG_FS_BACKTRACE_SHARED
CONFIG_FS_PROCFS CONFIG_SCHED_DUMP_FDLIST CONFIG_DEBUG_ASSERTIONS
host : Linux x86_64, gcc (Ubuntu 13.1.0-8ubuntu1~22.04) 13.1.0
checkpatch: rc=0
signer : jingfei <[email protected]>
commits missing your Signed-off-by: 0
make build: rc=0
warnings in changed files: 0
ostest: Exiting with status 0
cmake reconfigure: rc=0
cmake build: rc=0
worktree tracked changes after: 0
RESULT: PASS
```
</details>
<details>
<summary>Local regression fixture</summary>
This NuttX PR supplies the simulator fixture below for reproducibility; it
does not add an app to nuttx-apps. Install the files under
`apps/examples/fstracecheck/`, configure `sim:nsh`, enable
`EXAMPLES_FSTRACECHECK`, `FS_PROCFS`, `SCHED_BACKTRACE`, `FRAME_POINTER`,
`SCHED_DUMP_FDLIST`, `SCHED_WAITPID` and `DEBUG_ASSERTIONS`, set
`RR_INTERVAL=10`, `FS_BACKTRACE=8`, `LIBC_BACKTRACE_DEPTH=8`, and disable
`FDCLONE_DISABLE` and `FDCLONE_STDIO`. Enable `FS_BACKTRACE_SHARED` on the
candidate for the shared checks. Run `make olddefconfig`, `make -j2`, then the
`fstracecheck` command. The `large`, `exhaust` and debugger-assisted `fault`
arguments select the corresponding cases. For the display-depth check set
`FS_BACKTRACE=3` and `DEBUG_SYMBOLS_LEVEL="-g3"`; for FDCHECK enable `FDCHECK`,
`SIM_M32` and set `LIBC_OPEN_MAX=128`; for fixed-pool exhaustion set
`LIBC_BACKTRACE_INIT_SIZE=1` and `LIBC_BACKTRACE_LOAD_FACTOR=100`; for growth
set the initial size to 2. Set `FSTRACE_FAULT=1` for the
debugger-assisted extension failure. The debugger setup is below.
`fstracecheck_main.c`
```text
/****************************************************************************
* apps/examples/fstracecheck/fstracecheck_main.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <nuttx/fs/fs.h>
#include <nuttx/sched.h>
#ifdef CONFIG_FDCHECK
# include <nuttx/fdcheck.h>
#endif
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define TRACE_FILES 128
#define TRACE_LOOPS 160
/****************************************************************************
* Private Types
****************************************************************************/
struct worker_s
{
bool reader;
int failures;
};
/****************************************************************************
* Private Data
****************************************************************************/
static int g_checks;
static int g_failures;
static char g_procpath[64];
static volatile int g_trace_stage;
static volatile int g_trace_fault;
static volatile int g_trace_injected;
/****************************************************************************
* Private Functions
****************************************************************************/
static void check(bool condition, FAR const char *label)
{
g_checks++;
if (!condition)
{
g_failures++;
printf("FAIL %s errno=%d\n", label, errno);
}
}
static noinline_function void trace_checkpoint(int stage)
{
g_trace_stage = stage;
}
static void set_capture(bool enabled)
{
FAR struct tcb_s *tcb = nxsched_get_tcb(gettid());
if (enabled)
{
tcb->group->tg_flags |= GROUP_FLAG_FD_BACKTRACE;
}
else
{
tcb->group->tg_flags &= ~GROUP_FLAG_FD_BACKTRACE;
}
}
static FAR void *trace_identity(int fd, FAR int *depth)
{
FAR struct file *filep;
FAR struct fd *fdp;
FAR void *identity = NULL;
*depth = 0;
if (file_get2(fd, &filep, &fdp) < 0)
{
return NULL;
}
#ifdef CONFIG_FS_BACKTRACE_SHARED
identity = fdp->f_backtrace;
backtrace_get(identity, depth);
#elif CONFIG_FS_BACKTRACE > 0
while (*depth < CONFIG_FS_BACKTRACE && fdp->f_backtrace[*depth] != NULL)
{
(*depth)++;
}
if (*depth != 0)
{
identity = fdp->f_backtrace;
}
#endif
file_put(filep);
return identity;
}
static int read_proc(size_t chunk)
{
char buffer[257];
ssize_t nread;
size_t total = 0;
int fd;
fd = open(g_procpath, O_RDONLY);
if (fd < 0)
{
return -1;
}
do
{
nread = read(fd, buffer, chunk);
if (nread > 0)
{
total += nread;
}
}
while (nread > 0 && total < 65536);
close(fd);
return nread == 0 && total > 0 && total < 65536 ? 0 : -1;
}
static FAR void *worker(FAR void *arg)
{
FAR struct worker_s *state = arg;
int fd;
int copy;
int i;
for (i = 0; i < TRACE_LOOPS; i++)
{
if (state->reader)
{
state->failures += read_proc(257) < 0;
continue;
}
fd = open("/dev/null", O_RDWR);
if (fd < 0)
{
state->failures++;
continue;
}
copy = dup(fd);
if (copy < 0)
{
state->failures++;
}
else
{
state->failures += write(copy, "t", 1) != 1;
state->failures += close(copy) != 0;
}
state->failures += close(fd) != 0;
}
return NULL;
}
static int child_main(int argc, FAR char *argv[])
{
int i;
for (i = 0; i < 6; i++)
{
if (open("/dev/null", O_RDWR) < 0)
{
return 1;
}
}
return 0;
}
static void check_failed_dup(int fd)
{
struct rlimit original;
struct rlimit limit;
int i;
int ret;
ret = getrlimit(RLIMIT_NOFILE, &original);
check(ret == 0, "read descriptor limit");
if (ret < 0)
{
return;
}
limit = original;
limit.rlim_cur = 3;
check(setrlimit(RLIMIT_NOFILE, &limit) == 0, "lower descriptor limit");
for (i = 0; i < 40; i++)
{
errno = 0;
ret = dup(fd);
check(ret < 0 && errno == EMFILE, "full table rejects duplication");
if (ret >= 0)
{
close(ret);
}
}
check(setrlimit(RLIMIT_NOFILE, &original) == 0,
"restore descriptor limit");
}
#ifdef CONFIG_FS_BACKTRACE_SHARED
static void check_snapshot(int source)
{
FAR struct file *filep;
FAR struct tcb_s *tcb = nxsched_get_tcb(gettid());
FAR struct fdlist *list = &tcb->group->tg_fdlist;
char buffer[BACKTRACE_BUFFER_SIZE(CONFIG_FS_BACKTRACE + 2)];
int depth;
int fd;
int index;
int ret;
fd = open("/dev/null", O_RDWR);
check(fd >= 0, "open snapshot descriptor");
ret = file_get(fd, &filep);
check(ret == 0, "hold snapshot file reference");
if (ret < 0)
{
close(fd);
return;
}
#ifdef CONFIG_FDCHECK
index = fdcheck_restore(fd);
#else
index = fd;
#endif
trace_identity(fd, &depth);
depth = depth < CONFIG_FS_BACKTRACE ? depth : CONFIG_FS_BACKTRACE;
ret = fdlist_format_backtrace(list, index, filep, buffer, sizeof(buffer));
check(ret == depth * BACKTRACE_PTR_FMT_WIDTH,
"snapshot respects descriptor depth");
buffer[0] = 'x';
ret = fdlist_format_backtrace(list, index, filep, buffer, 1);
check(ret == 0 && buffer[0] == '\0', "one-byte snapshot buffer");
check(dup2(source, fd) >= 0, "replace snapshot descriptor");
buffer[0] = 'x';
ret = fdlist_format_backtrace(list, index, filep, buffer, sizeof(buffer));
check(ret == 0 && buffer[0] == '\0', "reject replaced snapshot file");
check(close(fd) == 0, "close snapshot descriptor");
buffer[0] = 'x';
ret = fdlist_format_backtrace(list, index, filep, buffer, sizeof(buffer));
check(ret == 0 && buffer[0] == '\0', "closed snapshot is empty");
file_put(filep);
}
#endif
static void check_extend_failure(int source)
{
FAR struct tcb_s *tcb = nxsched_get_tcb(gettid());
int minimum = fdlist_count(&tcb->group->tg_fdlist);
int fd;
g_trace_injected = 0;
g_trace_fault = 1;
errno = 0;
fd = fcntl(source, F_DUPFD, minimum);
check(fd < 0 && errno == ENFILE, "descriptor extension error");
check(g_trace_injected == 1, "extension failure was injected");
if (fd >= 0)
{
close(fd);
}
g_trace_fault = 0;
fd = fcntl(source, F_DUPFD, minimum);
check(fd >= 0, "extension succeeds after transient failure");
check(close(fd) == 0, "close descriptor after extension");
}
/****************************************************************************
* Public Functions
****************************************************************************/
int main(int argc, FAR char *argv[])
{
struct worker_s states[3];
pthread_t threads[3];
bool started[3];
bool exhausted = argc > 1 && strcmp(argv[1], "exhaust") == 0;
bool fault = argc > 1 && strcmp(argv[1], "fault") == 0;
bool original;
FAR struct tcb_s *tcb;
FAR void *identity;
FAR void *first = NULL;
int fds[TRACE_FILES];
int nfiles = argc > 1 && strcmp(argv[1], "large") == 0 ? TRACE_FILES : 24;
int depth;
int missing = 0;
int different = 0;
int copy;
int fd;
int status;
int pid;
int i;
g_checks = 0;
g_failures = 0;
memset(states, 0, sizeof(states));
memset(started, 0, sizeof(started));
tcb = nxsched_get_tcb(gettid());
original = (tcb->group->tg_flags & GROUP_FLAG_FD_BACKTRACE) != 0;
snprintf(g_procpath, sizeof(g_procpath), "/proc/%d/group/fd", getpid());
printf("FSTRACE bits=%zu fd_size=%zu trace_size=%zu mode=%s\n",
sizeof(void *) * 8, sizeof(struct fd),
sizeof(((FAR struct fd *)0)->f_backtrace),
exhausted ? "exhaust" : "normal");
set_capture(false);
check(read_proc(257) == 0, "proc warmup");
trace_checkpoint(0);
set_capture(true);
for (i = 0; i < nfiles; i++)
{
fds[i] = open("/dev/null", O_RDWR);
check(fds[i] >= 0, "open independent descriptor");
identity = trace_identity(fds[i], &depth);
missing += identity == NULL || depth == 0;
if (i == 0)
{
first = identity;
}
else
{
different += identity != first;
}
}
printf("FSTRACE identities different=%d missing=%d\n", different, missing);
if (exhausted)
{
check(missing > 0, "bounded pool saturation is nonfatal");
}
else
{
check(missing == 0, "record enabled opens");
check(different == 0, "identical call sites share trace storage");
}
trace_checkpoint(1);
check(read_proc(257) == 0, "proc full reads");
check(read_proc(1) == 0, "proc byte reads");
fdlist_dump(&tcb->group->tg_fdlist);
for (i = 0; i < 40; i++)
{
check(dup2(fds[0], fds[1]) >= 0, "replace live descriptor");
check(write(fds[1], "r", 1) == 1, "replacement remains usable");
}
check(dup2(fds[0], fds[0]) == fds[0], "same descriptor no-op");
errno = 0;
check(dup3(fds[0], fds[1], O_APPEND) < 0 && errno == EINVAL,
"invalid dup flags");
errno = 0;
check(fcntl(fds[0], F_DUPFD, -1) < 0 && errno == EINVAL,
"invalid descriptor minimum");
check_failed_dup(fds[0]);
#ifdef CONFIG_FS_BACKTRACE_SHARED
check_snapshot(fds[0]);
#endif
if (fault)
{
check_extend_failure(fds[0]);
}
trace_checkpoint(2);
set_capture(false);
fd = open("/dev/null", O_RDWR);
check(fd >= 0, "open with capture disabled");
check(trace_identity(fd, &depth) == NULL && depth == 0,
"runtime disabled trace absent");
check(close(fd) == 0, "close unrecorded descriptor");
set_capture(true);
copy = dup(fds[0]);
check(copy >= 0, "dup with capture enabled");
if (!exhausted)
{
check(trace_identity(copy, &depth) != NULL && depth > 0,
"record enabled duplication");
}
check(close(copy) == 0, "close duplicate");
for (i = 0; i < 12; i++)
{
pid = task_create("traceexit", 100, 8192, child_main, NULL);
check(pid > 0, "create task with inherited descriptors");
if (pid > 0)
{
check(waitpid(pid, &status, 0) == pid && WIFEXITED(status) &&
WEXITSTATUS(status) == 0, "task exit closes descriptors");
}
}
trace_checkpoint(3);
for (i = 0; i < 3; i++)
{
states[i].reader = i == 2;
started[i] =
pthread_create(&threads[i], NULL, worker, &states[i]) == 0;
check(started[i], "start churn or diagnostic reader");
}
for (i = 0; i < 3; i++)
{
if (started[i])
{
check(pthread_join(threads[i], NULL) == 0, "join worker");
check(states[i].failures == 0,
"concurrent descriptor diagnostics");
}
}
trace_checkpoint(4);
for (i = 0; i < nfiles; i++)
{
check(close(fds[i]) == 0, "close independent descriptor");
}
set_capture(false);
check(read_proc(257) == 0, "proc after final close");
trace_checkpoint(5);
set_capture(original);
printf("FSTRACE RESULT checks=%d failures=%d\n", g_checks, g_failures);
return g_failures != 0;
}
```
`Kconfig`
```text
config EXAMPLES_FSTRACECHECK
tristate "File descriptor shared backtrace regression"
default n
depends on FS_PROCFS && SCHED_BACKTRACE && !DISABLE_PTHREAD
```
`Make.defs`
```text
ifneq ($(CONFIG_EXAMPLES_FSTRACECHECK),)
CONFIGURED_APPS += $(APPDIR)/examples/fstracecheck
endif
```
`Makefile`
```text
include $(APPDIR)/Make.defs
PROGNAME = fstracecheck
PRIORITY = SCHED_PRIORITY_DEFAULT
STACKSIZE = 16384
MODULE = $(CONFIG_EXAMPLES_FSTRACECHECK)
MAINSRC = fstracecheck_main.c
include $(APPDIR)/Application.mk
```
`CMakeLists.txt`
```text
if(CONFIG_EXAMPLES_FSTRACECHECK)
nuttx_add_application(NAME fstracecheck SRCS fstracecheck_main.c STACKSIZE
16384)
endif()
```
`gdb-check.py`
```python
import collections
import importlib.util
import json
import os
import pathlib
import sys
import types
import gdb
out = pathlib.Path(os.environ["FSTRACE_RUN_DIR"])
package = types.ModuleType("nxgdb")
package.__path__ = [str(pathlib.Path.cwd() / "tools/pynuttx/nxgdb")]
sys.modules["nxgdb"] = package
tool = pathlib.Path(__file__).with_name("candidate-fs.py")
spec = importlib.util.spec_from_file_location("nxgdb.fs", tool)
fs = importlib.util.module_from_spec(spec)
sys.modules["nxgdb.fs"] = fs
spec.loader.exec_module(fs)
fs.Fdinfo()
if os.environ.get("FSTRACE_EXPECT_DEPTH"):
expected_depth = int(os.environ["FSTRACE_EXPECT_DEPTH"])
assert fs.CONFIG_FS_BACKTRACE is not None, "configured macro was not
loaded"
assert int(fs.CONFIG_FS_BACKTRACE) == expected_depth, "wrong macro depth"
print("FSTRACE_GDB configured depth=%d" % expected_depth)
original_backtrace = fs.utils.Backtrace
rendered_depths = []
def checked_backtrace(addresses, *args, **kwargs):
addresses = list(addresses)
if fs.CONFIG_FS_BACKTRACE:
assert len(addresses) <= int(fs.CONFIG_FS_BACKTRACE), "fdinfo
exceeds FS depth"
rendered_depths.append(len(addresses))
return original_backtrace(addresses, *args, **kwargs)
fs.utils.Backtrace = checked_backtrace
snapshots = []
failures = []
is_pool = gdb.lookup_type("struct fd")["f_backtrace"].type.code !=
gdb.TYPE_CODE_ARRAY
def snapshot(stage):
pool = (gdb.parse_and_eval("g_backtrace_pool") if is_pool else
dict(capacity=0, used=0, overflow=0))
entries = {}
if is_pool:
pointer = gdb.lookup_type("struct backtrace_entry_s").pointer()
for bucket in range(int(pool["capacity"])):
entry = pool["bucket"][bucket]
while entry:
address = int(entry)
assert address not in entries, "duplicate entry in pool
chains"
entries[address] = int(entry["ref"])
assert entries[address] > 0, "zero reference in live bucket"
entry = entry["next"].cast(pointer)
assert len(entries) == int(pool["used"]), "pool used count differs"
groups = set()
descriptors = collections.Counter()
nfiles = 0
nslots = 0
pids = gdb.parse_and_eval("g_pidhash")
for index in range(int(gdb.parse_and_eval("g_npidhash"))):
tcb = pids[index]
if not tcb:
continue
group = tcb["group"]
if not group or int(group) in groups:
continue
groups.add(int(group))
table = group["tg_fdlist"]
width = int(table["fl_prefds"].type.sizeof / gdb.lookup_type("struct
fd").sizeof)
nslots += int(table["fl_rows"]) * width
for row in range(int(table["fl_rows"])):
for col in range(width):
slot = table["fl_fds"][row][col]
if slot["f_file"]:
nfiles += 1
if is_pool and slot["f_backtrace"]:
assert slot["f_file"], "closed descriptor retains trace"
descriptors[int(slot["f_backtrace"])] += 1
if is_pool:
assert dict(descriptors) == entries, "pool references differ from
live descriptors"
record = dict(stage=stage, capacity=int(pool["capacity"]),
used=int(pool["used"]),
overflow=int(pool["overflow"]),
pool_refs=sum(entries.values()),
files=nfiles, slots=nslots, groups=len(groups),
pooled=is_pool,
heap_used=int(gdb.parse_and_eval("g_mmheap->mm_curused")),
fd_size=gdb.lookup_type("struct fd").sizeof)
if snapshots and snapshots[-1]["stage"] == stage:
assert snapshots[-1] == record, "repeated checkpoint changed state"
print("FSTRACE_POOL repeated breakpoint stage=%d unchanged" % stage)
return
snapshots.append(record)
print("FSTRACE_POOL " + json.dumps(record, sort_keys=True))
if stage in (0, 1, 5):
rendered_depths.clear()
text = gdb.execute("fdinfo", to_string=True)
assert "/dev/console" in text, "fdinfo omitted normal descriptors"
assert "Traceback" not in text and "Python Exception" not in text
(out / ("fdinfo-stage%d.txt" % stage)).write_text(text)
print("FSTRACE_GDB fdinfo stage=%d PASS depth=%d" %
(stage, max(rendered_depths, default=0)))
if stage == 1:
saved_depth = fs.CONFIG_FS_BACKTRACE
try:
fs.CONFIG_FS_BACKTRACE = None
rendered_depths.clear()
fallback = gdb.execute("fdinfo", to_string=True)
assert any(rendered_depths), "missing macro hides all
backtraces"
assert "Traceback" not in fallback and "Python Exception"
not in fallback
(out / "fdinfo-no-macro.txt").write_text(fallback)
print("FSTRACE_GDB missing macro fallback PASS")
finally:
fs.CONFIG_FS_BACKTRACE = saved_depth
class Checkpoint(gdb.Breakpoint):
def stop(self):
try:
stage = int(gdb.newest_frame().read_var("stage"))
if snapshots and snapshots[-1]["stage"] == stage:
return False
gdb.set_convenience_variable("trace_last_stage",
gdb.Value(stage))
snapshot(stage)
except Exception as error:
failures.append(str(error))
print("FSTRACE_POOL FAIL " + str(error))
return False
gdb.set_convenience_variable("trace_last_stage", gdb.Value(-1))
checkpoint = Checkpoint("trace_checkpoint")
checkpoint.condition = "stage != $trace_last_stage"
if os.environ.get("FSTRACE_FAULT"):
injection = gdb.Breakpoint("fdlist_extend")
injection.condition = "g_trace_fault == 1"
gdb.execute("commands %d\nsilent\nset var g_trace_fault = 0\n"
"set var g_trace_injected = 1\nreturn
(int)-23\ncontinue\nend"
% injection.number)
def verify_results():
assert [s["stage"] for s in snapshots] == list(range(6)), "missing
checkpoint"
if is_pool:
for field in ("used", "pool_refs", "files"):
assert snapshots[0][field] == snapshots[-1][field], "leak in " +
field
assert not failures, repr(failures)
(out / "pool-snapshots.json").write_text(json.dumps(snapshots, indent=2)
+ "\n")
print("FSTRACE_POOL RESULT checkpoints=6 failures=0")
```
`gdb-run.py`
```python
import os
import pathlib
import shutil
import subprocess
import sys
out = pathlib.Path(os.environ["FSTRACE_RUN_DIR"])
out.mkdir(parents=True, exist_ok=True)
shutil.copy2(sys.argv[1], out / "nuttx")
shutil.copy2(".config", out / "config-gdb")
script = pathlib.Path(__file__).with_name("gdb-check.py")
args = ["gdb", "-q", "-nx", "-batch", "-ex", "set pagination off",
"-ex", "handle SIGUSR1 nostop noprint pass", "-ex", "handle SIGALRM
nostop noprint pass",
"-ex", "source " + str(script), "-ex", "run",
"-ex", "python verify_results()", "--args", sys.argv[1]]
sys.exit(subprocess.run(args).returncode)
```
The debugger script loads a copy of this PR's `tools/pynuttx/nxgdb/fs.py`
named `candidate-fs.py`. `FSTRACE_RUN_DIR` selects the output directory. Run
the simulator using `gdb-run.py ./nuttx` with an NSH input script containing
`fstracecheck` (plus the desired argument) followed by `poweroff`.
</details>
## PR verification Self-Check
- [x] This PR introduces only one functional change.
- [x] I have updated all required description fields above.
- [x] Commit message, author/sign-off and code style checks pass.
- [ ] My PR is still work in progress (not ready for review).
- [x] My PR is ready for review and can be safely merged into a codebase.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]