Skip to content

Commit 861ebc0

Browse files
authored
Add heaptrack support (#25257)
This PR, courtesy of @NagyZoltanPeter (waku-org/nwaku#3522) adds the ability to track memory allocations in a program suitable for use with [heaptrack](https://github.com/KDE/heaptrack). By passing `-d:heaptrack --debugger:native` to compilation, calls to heaptrack will be injected when memory is being allocated and released - unlike `-d:useMalloc` this strategy also works with `refc` and the default memory pool. See https://github.com/KDE/heaptrack for usage examples. The resulting binary needs to be run with `heaptrack` and with the shared `libheaptrack_preload.so` in the `LD_LIBRARY_PATH`.
1 parent 1d08c4e commit 861ebc0

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

doc/nimc.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,8 @@ Define Effect
580580
Currently only clang and vcc.
581581
`strip` Strip debug symbols added by the backend compiler from
582582
the executable.
583+
`heaptrack` Track memory allocations using
584+
[heaptrack](https://github.com/KDE/heaptrack)
583585
====================== =========================================================
584586

585587

lib/system/alloc.nim

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,15 @@ when defined(gcDestructors):
837837
dec maxIters
838838
if it == nil: break
839839

840+
when defined(heaptrack):
841+
const heaptrackLib =
842+
when defined(heaptrack_inject):
843+
"libheaptrack_inject.so"
844+
else:
845+
"libheaptrack_preload.so"
846+
proc heaptrack_malloc(a: pointer, size: int) {.cdecl, importc, dynlib: heaptrackLib.}
847+
proc heaptrack_free(a: pointer) {.cdecl, importc, dynlib: heaptrackLib.}
848+
840849
proc rawAlloc(a: var MemRegion, requestedSize: int): pointer =
841850
when defined(nimTypeNames):
842851
inc(a.allocCounter)
@@ -959,6 +968,8 @@ proc rawAlloc(a: var MemRegion, requestedSize: int): pointer =
959968
sysAssert(isAccessible(a, result), "rawAlloc 14")
960969
sysAssert(allocInv(a), "rawAlloc: end")
961970
when logAlloc: cprintf("var pointer_%p = alloc(%ld) # %p\n", result, requestedSize, addr a)
971+
when defined(heaptrack):
972+
heaptrack_malloc(result, requestedSize)
962973

963974
proc rawAlloc0(a: var MemRegion, requestedSize: int): pointer =
964975
result = rawAlloc(a, requestedSize)
@@ -967,6 +978,8 @@ proc rawAlloc0(a: var MemRegion, requestedSize: int): pointer =
967978
proc rawDealloc(a: var MemRegion, p: pointer) =
968979
when defined(nimTypeNames):
969980
inc(a.deallocCounter)
981+
when defined(heaptrack):
982+
heaptrack_free(p)
970983
#sysAssert(isAllocatedPtr(a, p), "rawDealloc: no allocated pointer")
971984
sysAssert(allocInv(a), "rawDealloc: begin")
972985
var c = pageAddr(p)

0 commit comments

Comments
 (0)