Out-params and arrays are raw pointers #10

Open
opened 2026-10-23 12:46:26 +01:00 by pedro-bento · 0 comments
Owner

Summary

Functions that return a count or an array through a pointer force the caller to allocate a buffer
and read it back. Some array inputs are wrapped in a one-element buffer and then passed with a
larger count, which reads out of bounds.

Current behavior

local size = ffi.new("int[1]")
local data = M.LoadFileData("file.bin", size)   -- cdata, never freed, size[0] by hand

SetWindowIcons is worse (hate-no-d.lua:3328): it allocates Image[1] and passes count.
raylib loops for (i = 0; i < count; i++) images[i], so count > 1 reads past the buffer.

Functions affected

24 functions need declarations, not special cases:

Kind Functions
Binary data + size LoadFileData, CompressData, DecompressData, EncodeDataBase64, DecodeDataBase64, ExportImageToMemory
Struct array + count LoadImagePalette, LoadFontData, LoadMaterials, LoadModelAnimations
String array + count LoadTextLines, TextSplit
Int array + count LoadCodepoints
Scalar out GetCodepoint* (3), QuaternionToAxisAngle, rlGenTextureMipmaps, rlGetGlTextureFormats (3), MatrixDecompose (3), CheckCollisionLines
Scalar inout TextAppend (position)
Count only LoadImageAnim*
Input, not output TextCopy (writable buffer), rlSetShader, SetWindowIcons, all Unload*

Proposal

1. Declare it

Two tables in the generator: one maps a parameter index to out or inout, the other maps the
return shape to its freeing function.

PARAM_DIR = { LoadFileData = { out = { 2 } }, ... }
RET = { LoadFileData = { shape = "bytes", free = "UnloadFileData", argc = 1 }, ... }

2. Keep old calls working

Out-params stay in the signature as optional arguments. If the caller passes a buffer, forward it
and return exactly what the C function returns, as today. If not, use a reused slot (issue 05),
convert, and return the values:

function M.LoadFileData(fileName, dataSize)
  if dataSize ~= nil then return C.LoadFileData(fileName, dataSize) end
  local _n, _d = slot("int")
  local p = C.LoadFileData(fileName, _n)
  local n = _n[0]
  unslot("int", _d)
  if p == nil then return nil, 0 end
  local s = ffi_string(p, n)
  C.UnloadFileData(p)
  return s, n
end

3. Return the useful shape

Shape Return Freed by
bytes Lua string plus size the owner function
ints Lua table of numbers the owner function
carray cdata plus count, caller frees the owner function with the documented arity
lines Lua table of strings (copy) UnloadTextLines(p, n); TextSplit is static
scalar the number nothing

Two loaders have no count out-param: derive it (LoadImageColors = width * height,
LoadWaveSamples = frameCount * channels) and append it as a second return value.

4. Accept arrays properly

For T *x, int count inputs: accept a Lua table (converted), a cdata array, or a single struct.
Default count to #table and reject a count larger than the table. Return nothing.

5. Warn on anything new

Sweep all non-const pointer params that are in neither PARAM_DIR nor an input allowlist. Warn;
never fail the build, so a raylib bump cannot break generation.

Acceptance criteria

  • LoadFileData round-trips 4 KiB of random bytes, returns the right size, and does not leak.
  • Base64 encode/decode round-trips binary data containing \0.
  • LoadTextLines returns {"a","b","c"}; a second TextSplit does not corrupt the first.
  • CheckCollisionLines returns false, nil when segments do not cross.
  • SetWindowIcons with three images does not crash.
  • The generator warning sweep is clean on the current raylib.
  • make check-bindings passes.

Notes

  • LoadMaterials has no unload function in raylib; free the array with MemFree and document it.
  • carray results are armed by gc-hooks, so a forgotten unload is safe; an explicit
    Unload* disarms the finalizer.
  • TextSplit reuses static storage, so the strings must be copied before returning.
  • Legacy calls keep ownership: passing a buffer must never free it.
## Summary Functions that return a count or an array through a pointer force the caller to allocate a buffer and read it back. Some array inputs are wrapped in a one-element buffer and then passed with a larger count, which reads out of bounds. ## Current behavior ```lua local size = ffi.new("int[1]") local data = M.LoadFileData("file.bin", size) -- cdata, never freed, size[0] by hand ``` `SetWindowIcons` is worse (`hate-no-d.lua:3328`): it allocates `Image[1]` and passes `count`. raylib loops `for (i = 0; i < count; i++) images[i]`, so `count > 1` reads past the buffer. ## Functions affected 24 functions need declarations, not special cases: | Kind | Functions | |---|---| | Binary data + size | `LoadFileData`, `CompressData`, `DecompressData`, `EncodeDataBase64`, `DecodeDataBase64`, `ExportImageToMemory` | | Struct array + count | `LoadImagePalette`, `LoadFontData`, `LoadMaterials`, `LoadModelAnimations` | | String array + count | `LoadTextLines`, `TextSplit` | | Int array + count | `LoadCodepoints` | | Scalar out | `GetCodepoint*` (3), `QuaternionToAxisAngle`, `rlGenTextureMipmaps`, `rlGetGlTextureFormats` (3), `MatrixDecompose` (3), `CheckCollisionLines` | | Scalar inout | `TextAppend` (position) | | Count only | `LoadImageAnim*` | | Input, not output | `TextCopy` (writable buffer), `rlSetShader`, `SetWindowIcons`, all `Unload*` | ## Proposal ### 1. Declare it Two tables in the generator: one maps a parameter index to `out` or `inout`, the other maps the return shape to its freeing function. ```lua PARAM_DIR = { LoadFileData = { out = { 2 } }, ... } RET = { LoadFileData = { shape = "bytes", free = "UnloadFileData", argc = 1 }, ... } ``` ### 2. Keep old calls working Out-params stay in the signature as optional arguments. If the caller passes a buffer, forward it and return exactly what the C function returns, as today. If not, use a reused slot (issue 05), convert, and return the values: ```lua function M.LoadFileData(fileName, dataSize) if dataSize ~= nil then return C.LoadFileData(fileName, dataSize) end local _n, _d = slot("int") local p = C.LoadFileData(fileName, _n) local n = _n[0] unslot("int", _d) if p == nil then return nil, 0 end local s = ffi_string(p, n) C.UnloadFileData(p) return s, n end ``` ### 3. Return the useful shape | Shape | Return | Freed by | |---|---|---| | `bytes` | Lua string plus size | the owner function | | `ints` | Lua table of numbers | the owner function | | `carray` | cdata plus count, caller frees | the owner function with the documented arity | | `lines` | Lua table of strings (copy) | `UnloadTextLines(p, n)`; `TextSplit` is static | | scalar | the number | nothing | Two loaders have no count out-param: derive it (`LoadImageColors` = `width * height`, `LoadWaveSamples` = `frameCount * channels`) and append it as a second return value. ### 4. Accept arrays properly For `T *x, int count` inputs: accept a Lua table (converted), a cdata array, or a single struct. Default `count` to `#table` and reject a count larger than the table. Return nothing. ### 5. Warn on anything new Sweep all non-const pointer params that are in neither `PARAM_DIR` nor an input allowlist. Warn; never fail the build, so a raylib bump cannot break generation. ## Acceptance criteria - [ ] `LoadFileData` round-trips 4 KiB of random bytes, returns the right size, and does not leak. - [ ] Base64 encode/decode round-trips binary data containing `\0`. - [ ] `LoadTextLines` returns `{"a","b","c"}`; a second `TextSplit` does not corrupt the first. - [ ] `CheckCollisionLines` returns `false, nil` when segments do not cross. - [ ] `SetWindowIcons` with three images does not crash. - [ ] The generator warning sweep is clean on the current raylib. - [ ] `make check-bindings` passes. ## Notes - `LoadMaterials` has no unload function in raylib; free the array with `MemFree` and document it. - `carray` results are armed by gc-hooks, so a forgotten unload is safe; an explicit `Unload*` disarms the finalizer. - `TextSplit` reuses static storage, so the strings must be copied before returning. - Legacy calls keep ownership: passing a buffer must never free it.
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#10
No description provided.