Resources are never unloaded automatically #4

Open
opened 2026-10-22 20:51:43 +01:00 by pedro-bento · 0 comments
Owner

Summary

Every struct returned by Load* or Gen* is raw cdata with no lifetime. Forget one Unload*
and VRAM or RAM leaks until the process exits. The obvious fix — a __gc on Texture2D — does
not work, but a per-object finalizer does.

Why the obvious fix fails

__gc on a struct type only runs for values created by ffi.new. A struct returned by a C
function never gets a finalizer (lib_ffi.c:511-524). Type-level __gc would also double-free
every copy (ffi.new("Texture2D", tex)) and every borrowed view (font.texture,
renderTexture.texture, model.meshes[i]), because one policy cannot tell an owner from a view.

ffi.gc is the escape hatch: it arms any cdata, including a struct or pointer returned by C,
returns the same value, and ffi.gc(x, nil) disarms it. Verified against this repo's LuaJIT with
a struct-returning libc call.

Proposal

1. Arm the exact value that C returned

Use ffi.gc on the returned cdata. It attaches a finalizer to that specific value and returns it
unchanged, so the API still returns raylib.Texture2D and every call site keeps working:

function M.LoadTexture(fileName)
  return _own("gpu", C.UnloadTexture, C.LoadTexture(fileName))
end

-- caller
local tex = M.LoadTexture("a.png")
tex = nil            -- GC calls UnloadTexture once
local _can_unload = function(kind)
  if kind == "gpu" then return C.IsWindowReady() end
  if kind == "audio" then return C.IsAudioDeviceReady() end
  return true
end

local function _own(kind, unload, o)
  if o == nil then return nil end
  return ffi.gc(o, function(x)
    if not _can_unload(kind) then return end
    pcall(unload, x)
  end)
end

Use raylib's readiness queries, not Lua-side flags: they stay correct when the window is managed
through M.C. Leaking at teardown is deliberate — unloading a texture after CloseWindow crashes.

2. Own by type, with explicit exceptions

A return is owned if its struct type is in an asset table (Image, Texture2D, RenderTexture2D,
Shader, Mesh, Model, Material, Font, Wave, Sound, Music, AudioStream,
AutomationEventList, FilePathList, VrStereoConfig). That covers future Load* functions
without a function list.

Exceptions, all explicit:

Case Handling
GetShapesTexture, GetFontDefault borrowed; never armed
LoadSoundAlias UnloadSoundAlias (shares sample data with the source)
LoadModelFromMesh(mesh) disarm mesh first; the model owns it
GenImageFontAtlas free the image and the glyph rectangle array together

Fail generation when an owned type resolves no unloader, or when a borrowed name is in the owned
set. Add --dump-ownership so the map can be reviewed on every raylib bump.

3. Make explicit unload safe

Unload* disarms the finalizer, unloads, and zeroes the struct so a second unload is a no-op:

function M.UnloadTexture(texture)
  ffi.gc(texture, nil)
  C.UnloadTexture(texture)
  ffi.fill(ffi.cast("void *", texture), ffi.sizeof(texture))
end

Never zero a pointer result: ffi.fill on a pointer writes through it.

4. Keep C-retained values alive

These store a struct after returning, so the Lua object must not be collected: SetShapesTexture,
SetMaterialTexture, SetAutomationEventList. Pin the argument in a strong list. Pinning leaks
until process exit; that is acceptable and bounded.

SetAutomationEventList also has an existing bug: the wrapper passes a temporary
AutomationEventList[1] that raylib stores a pointer to. It dangles today and must be pinned.

5. Pointer results

Array returns (LoadImagePalette, LoadFontData, LoadModelAnimations, LoadMaterials) are
armed the same way, capturing the count in the closure (MemFree for LoadMaterials, which has
no unload function). bytes/lines/ints results from issue 04 are copied and freed immediately,
so no finalizer is needed.

Acceptance criteria

  • Load 10 000 textures without unloading, then collect: every one is unloaded and memory is flat.
  • Explicit unload, then GC: exactly one unload; a second explicit unload does not crash.
  • GetShapesTexture/GetFontDefault survive GC.
  • GenMeshCube → LoadModelFromMesh, mesh dropped: no double free.
  • LoadSoundAlias dropped: the source sound is still valid.
  • Load, CloseWindow(), drop, GC, exit: status 0.
  • make check-bindings passes.

Notes

  • M.C calls stay raw and never arm finalizers.
  • Do not copy owned resources with ffi.new; the copy would unload the original's id.
  • Dropping the last reference to a playing Sound stops it. Keep a reference to keep playing.
  • Rejected: handle structs (hnd_Texture2D) break drop-in usage; a strong live-resource registry
    prevents every finalizer; rewriting Load* → Unload* by name fails on *FromMesh,
    *FromImage, Gen* and LoadSoundAlias.
## Summary Every struct returned by `Load*` or `Gen*` is raw cdata with no lifetime. Forget one `Unload*` and VRAM or RAM leaks until the process exits. The obvious fix — a `__gc` on `Texture2D` — does not work, but a per-object finalizer does. ## Why the obvious fix fails `__gc` on a struct type only runs for values created by `ffi.new`. A struct returned by a C function never gets a finalizer (`lib_ffi.c:511-524`). Type-level `__gc` would also double-free every copy (`ffi.new("Texture2D", tex)`) and every borrowed view (`font.texture`, `renderTexture.texture`, `model.meshes[i]`), because one policy cannot tell an owner from a view. `ffi.gc` is the escape hatch: it arms *any* cdata, including a struct or pointer returned by C, returns the same value, and `ffi.gc(x, nil)` disarms it. Verified against this repo's LuaJIT with a struct-returning libc call. ## Proposal ### 1. Arm the exact value that C returned Use `ffi.gc` on the returned cdata. It attaches a finalizer to that specific value and returns it unchanged, so the API still returns `raylib.Texture2D` and every call site keeps working: ```lua function M.LoadTexture(fileName) return _own("gpu", C.UnloadTexture, C.LoadTexture(fileName)) end -- caller local tex = M.LoadTexture("a.png") tex = nil -- GC calls UnloadTexture once ``` ```lua local _can_unload = function(kind) if kind == "gpu" then return C.IsWindowReady() end if kind == "audio" then return C.IsAudioDeviceReady() end return true end local function _own(kind, unload, o) if o == nil then return nil end return ffi.gc(o, function(x) if not _can_unload(kind) then return end pcall(unload, x) end) end ``` Use raylib's readiness queries, not Lua-side flags: they stay correct when the window is managed through `M.C`. Leaking at teardown is deliberate — unloading a texture after `CloseWindow` crashes. ### 2. Own by type, with explicit exceptions A return is owned if its struct type is in an asset table (`Image`, `Texture2D`, `RenderTexture2D`, `Shader`, `Mesh`, `Model`, `Material`, `Font`, `Wave`, `Sound`, `Music`, `AudioStream`, `AutomationEventList`, `FilePathList`, `VrStereoConfig`). That covers future `Load*` functions without a function list. Exceptions, all explicit: | Case | Handling | |---|---| | `GetShapesTexture`, `GetFontDefault` | borrowed; never armed | | `LoadSoundAlias` | `UnloadSoundAlias` (shares sample data with the source) | | `LoadModelFromMesh(mesh)` | disarm `mesh` first; the model owns it | | `GenImageFontAtlas` | free the image and the glyph rectangle array together | Fail generation when an owned type resolves no unloader, or when a borrowed name is in the owned set. Add `--dump-ownership` so the map can be reviewed on every raylib bump. ### 3. Make explicit unload safe `Unload*` disarms the finalizer, unloads, and zeroes the struct so a second unload is a no-op: ```lua function M.UnloadTexture(texture) ffi.gc(texture, nil) C.UnloadTexture(texture) ffi.fill(ffi.cast("void *", texture), ffi.sizeof(texture)) end ``` Never zero a pointer result: `ffi.fill` on a pointer writes through it. ### 4. Keep C-retained values alive These store a struct after returning, so the Lua object must not be collected: `SetShapesTexture`, `SetMaterialTexture`, `SetAutomationEventList`. Pin the argument in a strong list. Pinning leaks until process exit; that is acceptable and bounded. `SetAutomationEventList` also has an existing bug: the wrapper passes a temporary `AutomationEventList[1]` that raylib stores a pointer to. It dangles today and must be pinned. ### 5. Pointer results Array returns (`LoadImagePalette`, `LoadFontData`, `LoadModelAnimations`, `LoadMaterials`) are armed the same way, capturing the count in the closure (`MemFree` for `LoadMaterials`, which has no unload function). `bytes`/`lines`/`ints` results from issue 04 are copied and freed immediately, so no finalizer is needed. ## Acceptance criteria - [ ] Load 10 000 textures without unloading, then collect: every one is unloaded and memory is flat. - [ ] Explicit unload, then GC: exactly one unload; a second explicit unload does not crash. - [ ] `GetShapesTexture`/`GetFontDefault` survive GC. - [ ] `GenMeshCube` → `LoadModelFromMesh`, mesh dropped: no double free. - [ ] `LoadSoundAlias` dropped: the source sound is still valid. - [ ] Load, `CloseWindow()`, drop, GC, exit: status 0. - [ ] `make check-bindings` passes. ## Notes - `M.C` calls stay raw and never arm finalizers. - Do not copy owned resources with `ffi.new`; the copy would unload the original's id. - Dropping the last reference to a playing `Sound` stops it. Keep a reference to keep playing. - Rejected: handle structs (`hnd_Texture2D`) break drop-in usage; a strong live-resource registry prevents every finalizer; rewriting `Load*` → `Unload*` by name fails on `*FromMesh`, `*FromImage`, `Gen*` and `LoadSoundAlias`.
pedro-bento changed title from garbage collection hooks to Resources are never unloaded automatically 2026-10-23 12:40:27 +01:00
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: pedro-bento/hate-no-d#4
No description provided.