Re: Segfault when using ffi in a loop/stderr

  • From: "Yichun Zhang (agentzh)" <agentzh@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 30 Nov 2014 16:33:11 -0800

Hello!

On Sun, Nov 30, 2014 at 4:04 PM, Chris wrote:
> To reproduce the issue requires a few files. I put everything in a zip here:
> http://luadev.com/broken.zip
>
> "make" will create the test.so then run "luajit test.lua"
>

You need to anchor the "l" variable's value (returned by ffi.load) in
your Lua module test2.lua somehow. Right now it is not anchored and
can get GC'd prematurely. Valgrind reports the error

  ==21526== Jump to the invalid address stated on the next line
  ==21526==    at 0x4434520: ???
  ==21526==    by 0x809909F: lj_ccall_func (lj_ccall.c:877)
  ==21526==    by 0x8067AE3: lj_cf_ffi_meta___call (lib_ffi.c:230)
  ==21526==    by 0x806A561: lj_BC_FUNCC (in
/opt/luajit21dbg32/bin/luajit-2.1.0-alpha)
  ==21526==    by 0x8056D13: lua_pcall (lj_api.c:1041)
  ==21526==    by 0x804BA8D: docall (luajit.c:121)
  ==21526==    by 0x804C9A4: pmain (luajit.c:288)
  ==21526==    by 0x806A561: lj_BC_FUNCC (in
/opt/luajit21dbg32/bin/luajit-2.1.0-alpha)
  ==21526==    by 0x8056E18: lua_cpcall (lj_api.c:1063)
  ==21526==    by 0x804B4FD: main (luajit.c:565)
  ==21526==  Address 0x4434520 is not stack'd, malloc'd or (recently) free'd

An easy fix is to replace the following lines in your test2.lua

    local lib = {
      TestFn = l.TestFn,
    }

with

    local function TestFn()
       return l.TestFn()
    end

    local lib = {
      TestFn = TestFn,
    }

so that the library module "l" is anchored as the upvalue of the
function TestFn and can avoid getting collected.

I admit that it is not quite intuitive. To ensure catching such GC
related issues easily, we can add the following line to the beginning
of your Lua program:

    debug.sethook(function () collectgarbage() end, 'l')

then it crashes immediately in the first loop iteration:

    $ luajit-2.1.0-alpha test.lua
    before 0
    Segmentation fault (core dumped)

Regards,
-agentzh

Other related posts: