Skip to content

Instantly share code, notes, and snippets.

@chobits
Created September 29, 2015 09:40
Show Gist options
  • Save chobits/32855ab77e1e1b18155b to your computer and use it in GitHub Desktop.
Save chobits/32855ab77e1e1b18155b to your computer and use it in GitHub Desktop.
luajit source notes
1.
luaopen_ffi()
 -> lj_ctype_init(L)
   -> setmref(G(L)->ctype_state, cts)
 -> lj_clib_default(L) # init ffi.C (default libc.so loader)
   -> cl = clib_new()
      cl->handle = RTLD_DEFAULT   

ctype_cts(L)
 -> return (mref((g)->ctype_state, CTState))

2. ffi.C -> __index
    -> lj_cf_ffi_clib___index lib_ffi.c:374
      -> ffi_clib_index lib_ffi.c:369
        -> lj_clib_index lj_clib.c:327
          -> lj_ctype_getname

               (GCstr *) strname
               cts->hash[ hash(strname) ] -> id
               ctype_get(cts, id) = cts->tab[id] -> ct
               gcref(ct->name) == obj2gco(strname) ??
               ct->next -> nextid -> id
          -> p = clib_getsym(cl, sym)  # sym -> (char *) "puts"
          -> cd = lj_cdata_new(...)
          -> *(void **)cdataptr(cd) = p;
          -> return lj_cdata_new(cts, id, ...) -> (GCcdata *) cd
              

3. ffi.C.puts() -> __call
  -> lj_cf_ffi_meta___call
      (GCcdata *) cd <- ffi.C.puts object
      -> lj_ccall_func(L, cd)
          C function address = cc.func <- *(void **)(cd + 1)
          call cc.func

4. cdef -> lj_ctype_addname 
   (lldb) p (char *)(((GCstr *)ct->name.gcptr32) + 1)     # get ct->name

  lj_cf_ffi_cdef
  -> lj_cparse
    -> lj_vm_cpcall
      -> cpcparser
        -> cp_decl_multi
          -> lj_ctype_addname

   NOTE this function only add symbol name into cts->hash[], it does not resolve symbol
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment