1

For a project I'm writing I need to write a custom Lua module loading system, and I've done it before on my Raspberry Pi, but not on my Mac. The problem is that as soon as I try to access the lua_State in the shared object, the program segfaults.

main.cpp

#include <lua.hpp>
#include <dlfcn.h>
#include <iostream>

typedef void Register(lua_State*);

int main(){
    lua_State* L = luaL_newstate();
    void* lib = dlopen("module.so", RTLD_NOW);
    if(!lib){
        std::cerr << "Error opening module \""  << "\": " << dlerror() << std::endl;
        return;
    }
    Register* loadFunc = (Register*)dlsym(lib, "RegisterModule");
    if(!loadFunc){
        std::cerr << "Error loading symbols from module \""  << "\": " << dlerror() << std::endl;
        return;
    }
    loadFunc(L);
    for(;;){}


    return 1;
}

module.cpp

#include <lua.hpp>
#include <iostream>

static int Foo(lua_State* L){
    std::cout << "Hello World!" << std::endl;
}

extern "C" void RegisterModule(lua_State* L){
    lua_pushcfunction(L, Foo);
    lua_setglobal(L, "Foo");
}

Makefile

lua = -L /usr/lib/lua5.2 -I /usr/include/lua5.2 -llua
luaHeaders = -I /usr/include/lua5.2

all: main module.so
    rm -f main.o

main: main.o
    clang++ main.o -o main $(lua) -ldl

main.o: main.cpp
    clang++ -c main.cpp $(luaHeaders)

module.so: module.cpp
    clang++ -fPIC -shared module.cpp -o module.so $(lua)

My setup is:

  • Mac OS X 10.9 Mavericks, and Elementary OS Luna
  • Lua 5.2
  • Clang

Output from the debugger (lldb)

Process 19943 stopped
* thread #2: tid = 0x23ec1c, 0x0000000100295c31 myModule.so`luaH_newkey + 913, stop reason = EXC_BAD_ACCESS (code=2, address=0x100073db0)
    frame #0: 0x0000000100295c31 myModule.so`luaH_newkey + 913
myModule.so`luaH_newkey + 913:
-> 0x100295c31:  movq   %rax, 16(%r12)
   0x100295c36:  movl   8(%rbx), %eax
   0x100295c39:  movl   %eax, 24(%r12)
   0x100295c3e:  testb  $64, 8(%rbx)
Dirk
  • 2,094
  • 3
  • 25
  • 28

0 Answers0