Lua Notes

interdict function calls
Login

interdict function calls

Consider:

## cflags '-Wl,--wrap=malloc'
local function __real_malloc(size: usize): pointer <cimport, nodecl> end
## cemitdecl 'extern void *__real_malloc(size_t size);'

local function wrapmalloc(size: usize): pointer <cexport '__wrap_malloc'>
  print('malloc called to allocate:', size)
  return __real_malloc(size)
end

require 'string'
local s = 'a' .. 'b'
print(s)

Output:

malloc called to allocate:	64
malloc called to allocate:	3
malloc called to allocate:	64
malloc called to allocate:	16
ab

This is a gcc linker feature described in the manpage, and in this nim blog where I saw it used.

This can also be used for Nelua functions if you can predict (unitname_functionname), determine (<cexport>, as above), or reflect on the symbol name.

A wrapper that calls itself is likely to segfault. You can see that by allocating in wrapmalloc, above.