probe
Some checks failed
release / linux/x86_64 (pull_request) Failing after 1m54s
release / freebsd/x86_64 (pull_request) Successful in 5m1s
release / linux/aarch64 (pull_request) Failing after 1m54s
release / linux/armv7 (pull_request) Failing after 2m12s
release / linux/i686 (pull_request) Failing after 1m59s
release / android (pull_request) Successful in 2m54s
release / windows/i686 (pull_request) Successful in 2m3s
release / windows/x86_64 (pull_request) Successful in 2m15s

This commit is contained in:
pedro-bento 2026-10-24 22:20:01 +01:00
parent 3b9bbd529a
commit 449be4c4b7
21 changed files with 3252 additions and 405 deletions

View file

@ -32,6 +32,7 @@ API_DIR := $(BUILD_DIR)/api
RLPARSER := $(BUILD_DIR)/rlparser RLPARSER := $(BUILD_DIR)/rlparser
RAYLIB_API := $(API_DIR)/raylib_api.lua RAYLIB_API := $(API_DIR)/raylib_api.lua
BINDING := hate-no-d.lua BINDING := hate-no-d.lua
OWNERSHIP_SNAPSHOT := ownership.txt
OBJ := $(BUILD_DIR)/hate-no-d.o OBJ := $(BUILD_DIR)/hate-no-d.o
BIN := hate-no-d BIN := hate-no-d
@ -257,6 +258,10 @@ help:
@echo " make [all] CLI for the current platform + hate-no-d.lua" @echo " make [all] CLI for the current platform + hate-no-d.lua"
@echo " make bindings regenerate hate-no-d.lua only" @echo " make bindings regenerate hate-no-d.lua only"
@echo " make check-bindings verify hate-no-d.lua is reproducible and loads" @echo " make check-bindings verify hate-no-d.lua is reproducible and loads"
@echo " make test run the functional test matrix"
@echo " make check-valgrind run RAM-only tests under valgrind"
@echo " make ownership regenerate the ownership snapshot (ownership.txt)"
@echo " make check bindings + test matrix + valgrind"
@echo " make print-config resolved configuration for the current target" @echo " make print-config resolved configuration for the current target"
@echo " make clean remove build/ and submodule build artifacts" @echo " make clean remove build/ and submodule build artifacts"
@echo " make help this text" @echo " make help this text"
@ -325,13 +330,29 @@ $(BINDING): gen-hate-no-d.lua $(API_DIR)/rlgl_api.lua $(API_DIR)/raymath_api.lua
bindings: $(BINDING) bindings: $(BINDING)
# Fail if regeneration is not byte-identical or the module does not load. # Fail if regeneration is not byte-identical, the ownership classification
# changed, or the module does not load.
check-bindings: $(BINDING) check-bindings: $(BINDING)
$(LUAJIT) gen-hate-no-d.lua --out=$(BUILD_DIR)/hate-no-d.lua.tmp $(GEN_FLAGS) $(LUAJIT) gen-hate-no-d.lua --out=$(BUILD_DIR)/hate-no-d.lua.tmp $(GEN_FLAGS)
cmp $(BINDING) $(BUILD_DIR)/hate-no-d.lua.tmp cmp $(BINDING) $(BUILD_DIR)/hate-no-d.lua.tmp
rm -f $(BUILD_DIR)/hate-no-d.lua.tmp rm -f $(BUILD_DIR)/hate-no-d.lua.tmp
$(LUAJIT) gen-hate-no-d.lua --dump-ownership=$(BUILD_DIR)/ownership.txt $(GEN_FLAGS)
cmp $(OWNERSHIP_SNAPSHOT) $(BUILD_DIR)/ownership.txt
$(LUAJIT) -e 'local M = dofile("$(BINDING)"); assert(type(M) == "table"); assert(type(M.GetMousePosition) == "function", "raylib"); assert(type(M.rlLoadIdentity) == "function", "rlgl"); assert(type(M.Vector2Add) == "function", "raymath"); print("bindings ok")' $(LUAJIT) -e 'local M = dofile("$(BINDING)"); assert(type(M) == "table"); assert(type(M.GetMousePosition) == "function", "raylib"); assert(type(M.rlLoadIdentity) == "function", "rlgl"); assert(type(M.Vector2Add) == "function", "raymath"); print("bindings ok")'
# Regenerate the committed ownership classification snapshot.
ownership:
$(LUAJIT) gen-hate-no-d.lua --dump-ownership=$(OWNERSHIP_SNAPSHOT) $(GEN_FLAGS)
test: $(LINK_TARGET) $(BINDING)
sh tests/run.sh
check-valgrind: $(LINK_TARGET) $(BINDING)
sh tests/run-valgrind.sh
check: all check-bindings test check-valgrind
@echo "check: ok"
# Resolved configuration for the current target; useful before a cross build. # Resolved configuration for the current target; useful before a cross build.
print-config: print-config:
@echo "PLATFORM = $(PLATFORM)" @echo "PLATFORM = $(PLATFORM)"
@ -366,4 +387,5 @@ clean:
rm -f $(BINDING) rm -f $(BINDING)
rm -f hate-no-d.o # object from builds that predate the move into build/ rm -f hate-no-d.o # object from builds that predate the move into build/
.PHONY: all clean print-config help bindings check-bindings .PHONY: all clean print-config help bindings check-bindings \
test check check-valgrind ownership

View file

@ -53,6 +53,68 @@ hate-no-d.exe quick-start.lua
`hate-no-d.lua` is the generated raylib/rlgl/raymath binding; release archives `hate-no-d.lua` is the generated raylib/rlgl/raymath binding; release archives
ship it next to the binary. ship it next to the binary.
## Resource ownership
Every `Load*`/`Gen*` result that raylib hands to the caller is owned by the Lua
value you get back. hate-no-d attaches a finalizer to the underlying cdata, so
dropping the last reference is enough:
```lua
local tex = hnd.LoadTexture("sprite.png") -- armed
tex = nil
collectgarbage() -- raylib UnloadTexture() runs here
```
This covers textures, render textures, shaders, meshes, models, materials,
fonts, waves, sounds, music streams, audio streams, images, automation event
lists, directory listings, VR stereo configs, and the raw-pointer loaders
(`LoadImageColors`, `LoadImagePalette`, `LoadFontData`, `LoadMaterials`,
`LoadModelAnimations`, `LoadRandomSequence`, `LoadWaveSamples`,
`LoadCodepoints`, `LoadTextLines`, `LoadFileData`, `CompressData`,
`DecompressData`, `DecodeDataBase64`, `ExportImageToMemory`, `MemAlloc`, and
rlgl's pixel readers).
- **Readiness gates.** A finalizer never touches a dead subsystem. GPU releases
only run while a window is alive, audio releases only while the audio device
is alive, and anything still armed when a window is closed or recreated is
skipped rather than freed. `InitWindow`/`CloseWindow` bump an internal GPU
generation so stale handles are never unloaded against a new context.
- **`Unload*` is explicit and idempotent.** `hnd.UnloadImage(img)` frees
immediately, zeroes the struct, and is safe to call again. It also cancels
the finalizer, so a resource is never released twice. `M._ownership` exposes
`armed`/`released`/`skipped`/`errors` counters (mostly useful for tests).
- **Array loaders return their count.** Functions that fill a C `int *` count
out-parameter (`LoadImagePalette`, `LoadFontData`, `LoadMaterials`,
`LoadModelAnimations`, `LoadTextLines`, `LoadFileData`, `CompressData`,
`DecompressData`, `DecodeDataBase64`, `ExportImageToMemory`) now return
`pointer, count`. Passing a cdata still fills it, so existing code keeps
working; the extra return value is safe to ignore.
- **Views are never freed.** Values that alias raylib-owned memory are plain
copies: `font.texture`, `rt.texture`, `rt.depth`, `model.meshes[i]`,
`model.materials[i]`, `GetGlyphInfo()`, `GetFontDefault()`,
`GetShapesTexture()`, and `LoadDroppedFiles()`. Keep the owner alive while you
use a view — `GetGlyphInfo()`'s `image.data` points into the font.
- **Materials are special.** `UnloadMaterial`/the material finalizer free only
the `maps` array, never the shader or textures it references (those may be
shared). Textures assigned with `SetMaterialTexture` are pinned for the
lifetime of the material; `SetShapesTexture` pins the shapes texture, and
unloading that texture restores the previous one.
- **Mesh ownership transfers.** `LoadModelFromMesh(mesh)` consumes the mesh —
the model frees it. Calling `UnloadMesh` on the consumed handle is a no-op.
`LoadSoundAlias(src)` keeps `src` alive until the alias is released, and
`LoadMusicStreamFromMemory` keeps its buffer alive.
- **Raw memory.** `MemAlloc`/`MemRealloc` results are GC-managed; `MemFree`
cancels the finalizer before freeing, so explicit frees are safe.
`M.C` is the raw `ffi` namespace: calls made through it are unmanaged.
- **Process exit.** The CLI runs finalizers on normal exit (it calls
`lua_close`). `os.exit()` skips them; use `os.exit(code, true)` if you need
them to run.
The ownership classification is exhaustive: the generator refuses to emit a
binding if any function's return shape is unclassified, and `make check-bindings`
diffs `ownership.txt` against the current raylib API. `make check` runs the test
suite (including a valgrind pass over the RAM-only cases).
## Building ## Building
Precompiled builds can be found on the [releases page](https://git.pbento.pt/pedro-bento/hate-no-d/releases). Precompiled builds can be found on the [releases page](https://git.pbento.pt/pedro-bento/hate-no-d/releases).

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,46 @@
-- 01: 10k textures all reach the GC and are released; RSS plateaus.
local M = dofile("tests/helpers.lua")
local R = M.load()
if not M.window(64, 64) then
M.skip("01_many_textures", "no window")
return
end
M.reset()
local N = 10000
local img = R.GenImageColor(2, 2, R.RED)
M.ok(img.data ~= nil, "source image valid")
local b0 = M.snapshot()
do
local tex = {}
for i = 1, N do tex[i] = R.LoadTextureFromImage(img) end
end
M.eq(M.delta(b0, "armed"), N, "armed delta after batch 1")
M.gc(3)
M.eq(M.delta(b0, "released"), N, "released delta after batch 1")
M.eq(M.delta(b0, "errors"), 0, "errors after batch 1")
-- Second batch: compared against the RSS after the first batch has been
-- collected, so allocator warm-up does not count as growth.
local rss1 = M.rss_kb()
local b1 = M.snapshot()
do
local tex = {}
for i = 1, N do tex[i] = R.LoadTextureFromImage(img) end
end
M.gc(3)
M.eq(M.delta(b1, "released"), N, "released delta after batch 2")
M.eq(M.delta(b1, "errors"), 0, "errors after batch 2")
local rss2 = M.rss_kb()
if rss1 > 0 then
local growth = (rss2 - rss1) / rss1
M.ok(growth < 0.05, string.format(
"rss did not plateau: %d kB -> %d kB (%.1f%%)", rss1, rss2, growth * 100))
end
R.UnloadImage(img)
print("ok 01_many_textures")

View file

@ -0,0 +1,35 @@
-- 02: explicit UnloadImage is immediate, idempotent, and does not double-free
-- when the object is later collected.
local M = dofile("tests/helpers.lua")
local R = M.load()
M.reset()
local b = M.snapshot()
local img = R.GenImageColor(4, 4, R.RED)
M.ok(img.data ~= nil, "image data allocated")
M.eq(M.delta(b, "armed"), 1, "image armed")
R.UnloadImage(img)
M.eq(M.delta(b, "released"), 1, "explicit unload released exactly once")
M.eq(img.data, nil, "img.data nil after unload")
M.eq(img.width, 0, "img.width zero after unload")
M.eq(img.height, 0, "img.height zero after unload")
-- Calling it again is a no-op.
R.UnloadImage(img)
M.eq(M.delta(b, "released"), 1, "second explicit unload is a no-op")
-- Dropping the disarmed object must not release it a second time.
img = nil
M.gc(3)
M.eq(M.delta(b, "released"), 1, "GC after explicit unload is a no-op")
-- A plain GC-collected image releases exactly once.
local img2 = R.GenImageColor(4, 4, R.RED)
img2 = nil
M.gc(3)
M.eq(M.delta(b, "released"), 2, "GC released the second image exactly once")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
print("ok 02_explicit")

View file

@ -0,0 +1,32 @@
-- 03: GetShapesTexture / GetFontDefault return borrowed views: they must not
-- be armed and must stay stable across a GC cycle.
local M = dofile("tests/helpers.lua")
local R = M.load()
if not M.window(64, 64) then
M.skip("03_borrowed", "no window")
return
end
M.reset()
local b = M.snapshot()
local a = R.GetShapesTexture()
local f = R.GetFontDefault()
local ida, idb = a.id, f.texture.id
M.ok(ida ~= 0, "default shapes texture has an id")
M.eq(M.delta(b, "armed"), 0, "borrowed shapes texture was not armed")
-- Drop the views (and anything derived from them) and force a full GC. If
-- these were armed, the finalizers would unload raylib's static resources.
a, f = nil, nil
M.gc(3)
local a2 = R.GetShapesTexture()
local f2 = R.GetFontDefault()
M.eq(a2.id, ida, "shapes texture id survived GC")
M.eq(f2.texture.id, idb, "default font texture id survived GC")
M.eq(M.delta(b, "armed"), 0, "no borrowed resource was armed")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
print("ok 03_borrowed")

View file

@ -0,0 +1,45 @@
-- 04: LoadModelFromMesh consumes the mesh; unloading the model releases it
-- once, and a saved (zeroed) mesh copy is a harmless no-op.
local M = dofile("tests/helpers.lua")
local ffi = require("ffi")
local R = M.load()
if not M.window(64, 64) then
M.skip("04_model_from_mesh", "no window")
return
end
M.reset()
local b = M.snapshot()
local mesh = R.GenMeshCube(1, 1, 1)
M.ok(mesh.vertexCount > 0, "cube mesh built")
local model = R.LoadModelFromMesh(mesh)
M.eq(model.meshCount, 1, "model has one mesh")
M.ok(model.meshes[0].vertexCount > 0, "model mesh is valid")
if R.IsModelReady ~= nil then
M.ok(R.IsModelReady(model), "model is ready")
end
-- Ownership moved to the model: the mesh was disarmed and zeroed.
M.ok(mesh.vertices == nil,
"mesh was consumed (vertices cleared) by LoadModelFromMesh")
local mesh_copy = ffi.new("Mesh[1]", mesh)
mesh = nil
M.gc(3)
M.eq(M.delta(b, "released"), 0, "consumed mesh was not released separately")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors before unload")
R.UnloadModel(model)
M.eq(M.delta(b, "released"), 1, "UnloadModel released exactly once")
-- A saved copy of the (zeroed) mesh must be a no-op, not a crash/double free.
R.UnloadMesh(mesh_copy[0])
M.eq(M.delta(b, "errors"), 0, "saved mesh copy raised no errors")
M.ok(M.delta(b, "released") <= 2,
"saved mesh copy did not free the model's mesh again")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
print("ok 04_model_from_mesh")

View file

@ -0,0 +1,54 @@
-- 05: LoadSoundAlias keeps the source alive, and dropping the alias does not
-- invalidate the source.
local M = dofile("tests/helpers.lua")
local R = M.load()
if not M.audio() then
M.skip("05_sound_alias", "no audio device")
return
end
M.reset()
local data, size = M.wav_bytes(4410) -- 0.1 s, 44100 Hz mono s16
local wave = R.LoadWaveFromMemory(".wav", data, size)
M.ok(wave.data ~= nil, "WAV decoded")
M.eq(wave.channels, 1, "wave is mono")
M.ok(wave.frameCount > 0, "wave has samples")
local src = R.LoadSoundFromWave(wave)
M.ok(src.stream.buffer ~= nil, "sound created")
R.UnloadWave(wave)
-- Test A: alias outlives the Lua reference to its source.
local alias = R.LoadSoundAlias(src)
M.ok(alias.stream.buffer ~= nil, "alias created")
src = nil
M.gc(3)
M.ok(alias.stream.buffer ~= nil, "alias buffer valid after source GC")
M.ok(M.ow().errors == 0, "no finalizer errors with a live alias")
R.UnloadSoundAlias(alias)
alias = nil
M.gc(3)
-- Test B: dropping the alias first leaves the source usable.
local wave2 = R.LoadWaveFromMemory(".wav", data, size)
local src2 = R.LoadSoundFromWave(wave2)
R.UnloadWave(wave2)
M.ok(src2.stream.buffer ~= nil, "second sound created")
local alias2 = R.LoadSoundAlias(src2)
M.ok(alias2.stream.buffer ~= nil, "second alias created")
alias2 = nil
M.gc(3)
M.ok(src2.stream.buffer ~= nil, "source survives alias GC")
R.PlaySound(src2) -- must not crash / must not use a freed buffer
R.UnloadSound(src2)
src2 = nil
M.gc(3)
print("ok 05_sound_alias")

View file

@ -0,0 +1,52 @@
-- 06: closing the window makes GPU finalizers skip instead of calling into a
-- dead GL context. The process must survive and report no errors.
local M = dofile("tests/helpers.lua")
local R = M.load()
if not M.window(64, 64) then
M.skip("06_teardown", "no window")
return
end
M.reset()
local img = R.GenImageColor(4, 4, R.RED)
local b = M.snapshot()
-- Hold every resource until after CloseWindow so nothing can be collected
-- while the GPU context is still alive.
local pool = {}
for i = 1, 5 do
pool[i] = R.LoadTextureFromImage(img)
M.ok(pool[i].id ~= 0, "texture " .. i .. " created")
end
pool[6] = R.GenImageColor(4, 4, R.WHITE)
pool[7] = R.GenImageColor(4, 4, R.BLUE)
-- Kept out of the pool so it can be explicitly unloaded after the window dies.
local late = R.LoadTextureFromImage(img)
M.eq(M.delta(b, "armed"), 8, "six textures and two images armed")
R.CloseWindow()
-- Explicit unload after CloseWindow must also be a safe no-op: no GL call, the
-- handle is zeroed, and the counters stay clean.
local rel = M.snapshot()
R.UnloadTexture(late)
M.eq(M.delta(rel, "errors"), 0, "explicit unload after CloseWindow is safe")
M.eq(M.delta(rel, "released"), 0, "explicit unload after CloseWindow is skipped")
M.eq(late.id, 0, "explicit unload after CloseWindow zeroes the handle")
late = nil
-- After CloseWindow the five texture finalizers must refuse to touch the dead
-- GPU context. The two RAM images may still be released.
pool = nil
M.gc(3)
M.ok(M.delta(b, "skipped") >= 5,
string.format("expected >=5 skipped finalizers, got %d",
M.delta(b, "skipped")))
M.eq(M.delta(b, "errors"), 0, "no finalizer errors after CloseWindow")
M.eq(M.delta(b, "released"), 2, "RAM images still released after CloseWindow")
img = nil
M.gc(2)
print("ok 06_teardown")

37
tests/cases/07_inout.lua Normal file
View file

@ -0,0 +1,37 @@
-- 07: inout Image parameters mutate the caller's cdata in place, and the
-- wrapper returns that same object so the GC sees exactly one owner.
local M = dofile("tests/helpers.lua")
local R = M.load()
M.reset()
local b = M.snapshot()
local rgba = R.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
local gray = R.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE
local img = R.GenImageColor(4, 4, R.RED)
M.eq(img.format, rgba, "GenImageColor produced RGBA")
local out = R.ImageFormat(img, gray)
M.ok(rawequal(out, img), "ImageFormat returned the caller's cdata")
M.eq(img.format, gray, "ImageFormat mutated the cdata")
img = nil
out = nil
M.gc(3)
M.eq(M.delta(b, "released"), 1, "ImageFormat did not create a second owner")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
local img2 = R.GenImageColor(4, 4, R.RED)
local resized = R.ImageResize(img2, 2, 2)
M.ok(rawequal(resized, img2), "ImageResize returned the caller's cdata")
M.eq(img2.width, 2, "ImageResize width")
M.eq(img2.height, 2, "ImageResize height")
img2 = nil
resized = nil
M.gc(3)
M.eq(M.delta(b, "released"), 2, "ImageResize did not create a second owner")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors after resize")
print("ok 07_inout")

62
tests/cases/08_pins.lua Normal file
View file

@ -0,0 +1,62 @@
-- 08: pinned textures (shapes texture, material maps) stay alive while pinned,
-- and the pins are dropped when the owning object is released.
local M = dofile("tests/helpers.lua")
local ffi = require("ffi")
local R = M.load()
if not M.window(64, 64) then
M.skip("08_pins", "no window")
return
end
M.reset()
local b = M.snapshot()
local img = R.GenImageColor(2, 2, R.WHITE)
-- (a) shapes texture pin
local tex = R.LoadTextureFromImage(img)
local tex_id = tex.id
M.ok(tex_id ~= 0, "shapes texture created")
local tex_copy = ffi.new("Texture2D[1]", tex)
M.eq(tex_copy[0].id, tex_id, "saved raw texture copy")
R.SetShapesTexture(tex, ffi.new("Rectangle", 0, 0, 1, 1))
tex = nil
M.gc(3)
M.eq(M.delta(b, "released"), 0, "pinned shapes texture was not collected")
local shape = R.GetShapesTexture()
M.ok(shape.id ~= 0, "shapes texture is installed")
M.eq(shape.id, tex_id, "installed shapes texture is the pinned one")
-- Explicit unload of the saved copy must restore the previous shapes texture
-- and not crash. (The original cdata is the one held by the pin.)
R.UnloadTexture(tex_copy[0])
M.ok(R.GetShapesTexture().id ~= tex_id, "previous shapes texture restored")
-- (b) material map pin
local mat = R.LoadMaterialDefault()
M.ok(mat.maps ~= nil, "default material has maps")
local tex2 = R.LoadTextureFromImage(img)
local tex2_id = tex2.id
R.SetMaterialTexture(mat, R.MATERIAL_MAP_DIFFUSE, tex2)
M.eq(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id, tex2_id,
"material map references the texture")
tex2 = nil
M.gc(3)
M.ok(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id ~= 0,
"material pin kept the map texture alive")
M.eq(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id, tex2_id,
"material map still points at the pinned texture")
R.UnloadMaterial(mat)
mat = nil
-- Pins are dropped with the material; the texture can now go away.
M.gc(3)
R.UnloadImage(img)
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
print("ok 08_pins")

36
tests/cases/08b_views.lua Normal file
View file

@ -0,0 +1,36 @@
-- 08b: model sub-objects (meshes[i], materials[i], shader views) are views:
-- reading them must not arm anything, and the model owns the release.
local M = dofile("tests/helpers.lua")
local R = M.load()
if not M.window(64, 64) then
M.skip("08b_views", "no window")
return
end
M.reset()
local mesh = R.GenMeshCube(1, 1, 1)
local model = R.LoadModelFromMesh(mesh)
mesh = nil
M.eq(model.meshCount, 1, "model has one mesh")
M.eq(model.materialCount, 1, "model has one material")
local b = M.snapshot()
local m1 = model.meshes[0]
local mat1 = model.materials[0]
local probe = m1.vertexCount + mat1.shader.id
M.ok(m1.vertexCount > 0, "mesh view is readable (probe=" .. probe .. ")")
m1, mat1 = nil, nil
M.gc(3)
M.eq(M.delta(b, "armed"), 0, "views never arm")
R.UnloadModel(model)
M.ok(M.delta(b, "released") >= 1, "model released")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
model = nil
M.gc(2)
print("ok 08b_views")

View file

@ -0,0 +1,36 @@
-- 08c: GenImageFontAtlas attaches the Rectangle* output to the returned Image;
-- both must be freed exactly once (run under valgrind for the real proof).
local M = dofile("tests/helpers.lua")
local ffi = require("ffi")
local R = M.load()
M.reset()
local b = M.snapshot()
local keep = {}
local glyphs = ffi.new("GlyphInfo[2]")
for i = 0, 1 do
local im = R.GenImageColor(4, 4, R.WHITE)
keep[#keep + 1] = im
glyphs[i].value = 65 + i
glyphs[i].offsetX = 0
glyphs[i].offsetY = 0
glyphs[i].advanceX = 4
glyphs[i].image = im
end
local atlas, recs = R.GenImageFontAtlas(glyphs, 2, 8, 1, 0)
M.ok(atlas ~= nil, "font atlas returned")
M.ok(atlas.data ~= nil, "font atlas has pixel data")
M.ok(recs ~= nil, "glyph rectangles returned")
atlas, recs = nil, nil
keep = nil
glyphs = nil
M.gc(3)
M.ok(M.delta(b, "released") >= 1,
"atlas Image and attached Rectangle* were released")
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
print("ok 08c_font_atlas")

View file

@ -0,0 +1,50 @@
-- 09: every owned-pointer return releases exactly one allocation at GC time.
local M = dofile("tests/helpers.lua")
local ffi = require("ffi")
local R = M.load()
M.reset()
local img = R.GenImageColor(2, 2, R.RED)
M.ok(img.data ~= nil, "source image valid")
-- Baseline after the image exists: the image is armed too, and it is released
-- explicitly at the end of the case.
local b = M.snapshot()
local count = M.out_int()
local comp_size = M.out_int()
-- Keep every result alive until the batch is complete, then drop them all at
-- once so a single GC verifies the whole set.
local keep = {}
keep[#keep + 1] = R.LoadImageColors(img)
keep[#keep + 1] = R.LoadImagePalette(img, 8, count)
keep[#keep + 1] = R.LoadRandomSequence(4, 1, 5)
keep[#keep + 1] = R.LoadCodepoints("abc", count)
keep[#keep + 1] = R.LoadTextLines("a\nb\n", count)
keep[#keep + 1] = R.CompressData("abcd", 4, comp_size)
keep[#keep + 1] = R.DecodeDataBase64(
R.EncodeDataBase64("abcd", 4, count), count)
keep[#keep + 1] = R.TextReplaceAlloc("a", "a", "b")
local n = #keep
M.ok(n >= 8, "created at least 8 owned pointers, got " .. n)
for i = 1, n do
M.ok(keep[i] ~= nil, "pointer " .. i .. " is non-nil")
end
keep = nil
M.gc(3)
-- 7 of the 8 results are owned pointers; EncodeDataBase64/TextReplaceAlloc
-- return owned strings that the wrapper copies and frees immediately (valgrind
-- proves those). Every owned pointer must be armed and released exactly once.
M.ok(M.delta(b, "armed") >= 7,
string.format("expected >=7 armed pointers, got %d", M.delta(b, "armed")))
M.ok(M.delta(b, "released") >= 7,
string.format("expected >=7 released pointers, got %d",
M.delta(b, "released")))
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
R.UnloadImage(img)
print("ok 09_pointers")

57
tests/cases/10_ram.lua Normal file
View file

@ -0,0 +1,57 @@
-- 10: RAM-only owned structs (Image, AutomationEventList, FilePathList, Wave)
-- release at GC time and Image churn does not grow RSS.
local M = dofile("tests/helpers.lua")
local R = M.load()
M.reset()
local b = M.snapshot()
do
local img = R.GenImageColor(4, 4, R.RED)
M.ok(img.data ~= nil, "image allocated")
end
M.gc(2)
do
local list = R.LoadAutomationEventList(nil)
M.ok(list.events ~= nil, "empty automation event list allocated")
end
M.gc(2)
do
local files = R.LoadDirectoryFiles(".")
M.ok(files.paths ~= nil, "directory file list allocated")
M.ok(files.count > 0, "directory file list is non-empty")
end
M.gc(2)
do
local data, size = M.wav_bytes(441)
local wave = R.LoadWaveFromMemory(".wav", data, size)
M.ok(wave.data ~= nil, "wave allocated")
end
M.gc(2)
M.ok(M.delta(b, "released") >= 4,
string.format("expected >=4 released RAM resources, got %d",
M.delta(b, "released")))
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
-- 200 batches of 128x128 images: a leaked 64 kB image per batch would add
-- ~12.8 MB. Allow generous allocator noise, but not a real leak.
local rss0 = M.rss_kb()
for i = 1, 200 do
local im = R.GenImageColor(128, 128, R.RED)
M.ok(im.data ~= nil, "batch image " .. i .. " allocated")
M.gc(1)
end
M.gc(3)
local rss1 = M.rss_kb()
if rss0 > 0 and not M.under_valgrind() then
local growth_kb = rss1 - rss0
M.ok(growth_kb < 8 * 1024, string.format(
"rss grew %d kB across 200 image batches (%d -> %d kB)",
growth_kb, rss0, rss1))
end
print("ok 10_ram")

View file

@ -0,0 +1,47 @@
-- 11: string-returning wrappers copy and free inside the wrapper. This is a
-- regression test for TextInsertAlloc / TextReplaceAlloc / TextReplaceBetweenAlloc
-- and friends: no reference is kept, so RSS must not grow. Valgrind is the
-- authoritative leak check.
local M = dofile("tests/helpers.lua")
local ffi = require("ffi")
local R = M.load()
M.reset()
local b = M.snapshot()
local path = M.tmpfile("hate-no-d string regression\n")
local cps = ffi.new("int[3]", 97, 98, 99)
local out_size = M.out_int()
local failures = {}
local function check(label, v)
if v == nil then failures[#failures + 1] = label end
end
M.gc(2)
local rss0 = M.rss_kb()
for _ = 1, 2000 do
check("LoadFileText", R.LoadFileText(path))
check("LoadUTF8", R.LoadUTF8(cps, 3))
check("EncodeDataBase64", R.EncodeDataBase64("hello", 5, out_size))
check("TextInsertAlloc", R.TextInsertAlloc("abcd", "X", 2))
check("TextReplaceAlloc", R.TextReplaceAlloc("aaaa", "a", "b"))
check("TextReplaceBetweenAlloc",
R.TextReplaceBetweenAlloc("abcdef", "b", "e", "X"))
end
M.gc(3)
local rss1 = M.rss_kb()
os.remove(path)
M.eq(#failures, 0, "wrappers returned nil: " .. table.concat(failures, ", "))
M.eq(M.delta(b, "errors"), 0, "no finalizer errors")
if rss0 > 0 and not M.under_valgrind() then
local growth_kb = rss1 - rss0
M.ok(growth_kb < 20 * 1024, string.format(
"rss grew %d kB across 2000 string iterations (%d -> %d kB)",
growth_kb, rss0, rss1))
end
print("ok 11_strings")

189
tests/helpers.lua Normal file
View file

@ -0,0 +1,189 @@
-- tests/helpers.lua -- shared support for the hate-no-d test cases.
--
-- Cases are plain Lua runs under ./hate-no-d (the embedded raylib + LuaJIT
-- runtime). The module is cached here so a case can call helpers repeatedly
-- without re-executing hate-no-d.lua.
local ffi = require("ffi")
local M = {}
local ROOT = os.getenv("HATE_NO_D_ROOT") or "."
local CACHE = {}
--- Load (and cache) the generated binding.
function M.load()
if CACHE.M == nil then
CACHE.M = dofile(ROOT .. "/hate-no-d.lua")
-- Tests exercise thousands of loads; raylib's INFO logging would drown the
-- assertions (and valgrind output).
if CACHE.M.SetTraceLogLevel and CACHE.M.LOG_WARNING then
CACHE.M.SetTraceLogLevel(CACHE.M.LOG_WARNING)
end
end
return CACHE.M
end
--- The generated raylib module table (alias used by the spec's examples).
function M.R()
return M.load()
end
--- Run the Lua GC n times.
function M.gc(n)
for _ = 1, (n or 2) do collectgarbage("collect") end
end
--- M._ownership, with a clear error when the generator has not landed yet.
function M.ow()
local mod = M.load()
local o = mod._ownership
if type(o) ~= "table" then
error("hate-no-d.lua has no M._ownership (regenerate the binding)", 2)
end
return o
end
function M.reset()
M.ow().reset()
end
function M.snapshot()
local o = M.ow()
return {
armed = o.armed,
released = o.released,
skipped = o.skipped,
errors = o.errors,
}
end
function M.delta(before, field)
return M.ow()[field] - before[field]
end
function M.eq(a, b, msg)
if a ~= b then
error(string.format("%s: expected %s, got %s",
msg or "assert", tostring(b), tostring(a)), 2)
end
end
function M.ok(v, msg)
if not v then error(msg or "assertion failed", 2) end
end
--- RSS in kB from /proc/self/status, or 0 when unavailable.
function M.rss_kb()
local f = io.open("/proc/self/status", "r")
if f == nil then return 0 end
local rss = 0
for line in f:lines() do
local kb = line:match("^VmRSS:%s*(%d+)%s*kB")
if kb then rss = tonumber(kb); break end
end
f:close()
return rss
end
--- True when the runner told us there is no display.
function M.headless()
return os.getenv("HATE_NO_D_HEADLESS") == "1"
end
--- True when running under valgrind (RSS measurements are meaningless then).
function M.under_valgrind()
return os.getenv("HATE_NO_D_VALGRIND") == "1"
end
--- Ensure a window exists. Returns false (rather than failing) when the
--- environment cannot provide one, so callers can print "skip <name>".
function M.window(w, h)
if M.headless() then return false end
local R = M.load()
if not R.C.IsWindowReady() then
R.InitWindow(w or 64, h or 64, "hate-no-d test")
end
return R.C.IsWindowReady() and true or false
end
--- Ensure an audio device exists (same skip-friendly contract as window()).
function M.audio()
local R = M.load()
if not R.IsAudioDeviceReady() then
pcall(R.InitAudioDevice)
end
return R.IsAudioDeviceReady() and true or false
end
function M.skip(name, reason)
if reason then
print(string.format("skip %s (%s)", name, reason))
else
print("skip " .. name)
end
end
--- Accept either a Lua string (owned-string wrappers) or a cdata char* and
--- return a Lua string. Used where lane A may still hand back a pointer.
function M.tostr(x)
if type(x) == "string" then return x end
if x == nil then return nil end
return ffi.string(x)
end
function M.out_int(v)
local p = ffi.new("int[1]")
if v ~= nil then p[0] = v end
return p
end
function M.tmpfile(contents)
local path = os.tmpname()
local f = assert(io.open(path, "wb"))
f:write(contents)
f:close()
return path
end
--- Build a PCM WAV in memory: mono, 44100 Hz, signed 16-bit, `samples`
--- samples of silence. Returns (cdata uint8_t[44 + samples*2], size).
function M.wav_bytes(samples)
local data_size = samples * 2
local total = 44 + data_size
local b = ffi.new("uint8_t[?]", total)
local function put8(off, v) b[off] = v end
local function put16(off, v)
b[off] = v % 256
b[off + 1] = math.floor(v / 256) % 256
end
local function put32(off, v)
b[off] = v % 256
b[off + 1] = math.floor(v / 256) % 256
b[off + 2] = math.floor(v / 65536) % 256
b[off + 3] = math.floor(v / 16777216) % 256
end
local function puts(off, s)
for i = 1, #s do b[off + i - 1] = s:byte(i) end
end
puts(0, "RIFF")
put32(4, 36 + data_size)
puts(8, "WAVE")
puts(12, "fmt ")
put32(16, 16) -- fmt chunk size
put16(20, 1) -- PCM
put16(22, 1) -- mono
put32(24, 44100) -- sample rate
put32(28, 44100 * 2) -- byte rate
put16(32, 2) -- block align
put16(34, 16) -- bits per sample
puts(36, "data")
put32(40, data_size)
-- samples stay zero (silence)
return b, total
end
return M

51
tests/run-valgrind.sh Executable file
View file

@ -0,0 +1,51 @@
#!/bin/sh
# RAM-only cases under valgrind. Definite leaks are fatal (exit code 42).
#
# GPU finalizers are deliberately excluded: a headless/valgrind process has no
# GL context, so those cases would only exercise the "skip" gate.
set -u
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1
export HATE_NO_D_ROOT="$ROOT"
if ! command -v valgrind >/dev/null 2>&1; then
echo "skip valgrind (not installed)"
exit 0
fi
if [ ! -x ./hate-no-d ]; then
echo "run-valgrind.sh: ./hate-no-d not built (run make)" >&2
exit 1
fi
CASES="02_explicit 07_inout 08c_font_atlas 09_pointers 10_ram 11_strings"
fail=0
HATE_NO_D_VALGRIND=1
export HATE_NO_D_VALGRIND
for name in $CASES; do
case="tests/cases/$name.lua"
if [ ! -f "$case" ]; then
echo "FAIL $name (missing $case)" >&2
fail=1
continue
fi
echo "valgrind $name"
if valgrind --quiet --error-exitcode=42 \
--leak-check=full --show-leak-kinds=definite \
--errors-for-leak-kinds=definite \
--suppressions=tests/valgrind.supp \
./hate-no-d "$case"; then
:
else
status=$?
echo "FAIL $name (valgrind exit $status)" >&2
fail=1
fi
done
if [ "$fail" -eq 0 ]; then
echo "check-valgrind: ok"
fi
exit "$fail"

62
tests/run.sh Executable file
View file

@ -0,0 +1,62 @@
#!/bin/sh
# Functional test matrix for hate-no-d.
#
# Every case is a self-contained process: it prints "ok <name>" or
# "skip <name> (...)", or raises with a specific message. Cases must run under
# ./hate-no-d -- the system luajit has no raylib symbols.
set -u
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1
export HATE_NO_D_ROOT="$ROOT"
if [ ! -x ./hate-no-d ]; then
echo "run.sh: ./hate-no-d not built (run make)" >&2
exit 1
fi
# If there is no display, retry the whole matrix under a virtual X server when
# one is available. Otherwise mark the run headless and let window cases skip.
if [ -z "${DISPLAY:-}" ] && [ "${HATE_NO_D_XVFB:-0}" != "1" ]; then
if command -v xvfb-run >/dev/null 2>&1; then
HATE_NO_D_XVFB=1
export HATE_NO_D_XVFB
exec xvfb-run -a "$0" "$@"
fi
echo "run.sh: no DISPLAY and no xvfb-run; window cases will be skipped" >&2
HATE_NO_D_HEADLESS=1
export HATE_NO_D_HEADLESS
fi
# Cases that need a window. The cases themselves also gate on IsWindowReady;
# this list just avoids starting them at all when the runner knows it is
# headless.
WINDOW_CASES="01_many_textures 03_borrowed 04_model_from_mesh 06_teardown 08_pins 08b_views"
is_window_case() {
for w in $WINDOW_CASES; do
[ "$w" = "$1" ] && return 0
done
return 1
}
fail=0
for case in tests/cases/*.lua; do
name=$(basename "$case" .lua)
if [ "${HATE_NO_D_HEADLESS:-0}" = "1" ] && is_window_case "$name"; then
echo "skip $name (no display)"
continue
fi
if out=$(./hate-no-d "$case" 2>&1); then
echo "$out"
else
echo "FAIL $name" >&2
echo "$out" >&2
fail=1
fi
done
if [ "$fail" -eq 0 ]; then
echo "test: ok"
fi
exit "$fail"

15
tests/valgrind.supp Normal file
View file

@ -0,0 +1,15 @@
# Valgrind suppressions for the hate-no-d test suite.
#
# Start empty. Only suppress reports that originate inside LuaJIT, the JIT
# tracer, or glibc internals -- never frames from _release_* / Unload* /
# MemFree, because those are exactly what the RAM cases exist to check.
#
# Each entry needs a comment naming the rule, for example:
#
# # LuaJIT allocator arena still reachable at exit (not a definite leak).
# {
# luajit-alloc-arena
# Memcheck:Leak
# match-leak-kinds: reachable
# ...
# }