lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dr. Markus Walther wrote:
> Somewhat related, is the non-JIT interpreter that ships with luajit 2.0
> byte-code-compatible with the official Lua interpreter?

There is only one bytecode format in LJ2. It's not compatible with
the Lua bytecode.

> However, for a specific need I wrote in Lua a bytecode verifier to
> characterize some subset of 'safe' bytecodes similar to what is
> described in the Gems book.

You don't need a bytecode dump for this in LJ2. It has a full
reflection API for its bytecode. You can look into src/bc.lua to
see how to use the high-level API:

  local bc = require("jit.bc")
  local function foo() print("hello") end
  bc.dump(foo)           --> -- BYTECODE -- [...]
  print(bc.line(foo, 2)) --> 0002    KSTR     1   1      ; "hello"

In your case, the low-level API might be a better fit. Here's a
simple bytecode checker which verifies that a function can't
create any sub-functions (closures) -- modify as needed:

  local jutil = require("jit.util")
  local funcinfo, funcbc = jutil.funcinfo, jutil.funcbc
  local bcnames = require("jit.vmdef").bcnames
  local band = require("bit").band
  local sub = string.sub

  local function verifyfunc(func)
    local fi = funcinfo(func)
    if not fi or not fi.bytecodes then error("not a lua function", 2) end
    for pc=1,fi.bytecodes do
      local ins, m = funcbc(func, pc)
      if not ins then break end
      local oidx = 6*band(ins, 0xff)
      local name = sub(bcnames, oidx+1, oidx+6)
      if name == "FNEW  " then
        return false
      end
    end
    return true
  end

  local function f() end
  local function g() return function() end end

  print(verifyfunc(f))  --> true
  print(verifyfunc(g))  --> false

--Mike