Skip to content

Instantly share code, notes, and snippets.

@dpino
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save dpino/2c898d69f20045974d54 to your computer and use it in GitHub Desktop.

Select an option

Save dpino/2c898d69f20045974d54 to your computer and use it in GitHub Desktop.
Queries Luajit bytecode mnemonic by index or name
#!/usr/bin/env luajit
-- Prints out LuaJIT bytecode (name, number), by number or name.
--
-- usage: lj-bcname <bc_name|bc_number>...
--
-- example:
--
-- $ luajit-2.1 lj-bcname UCOL
-- UCOL (51)
--
-- $ luajit-2.1 lj-bcname 51 52
-- UCOL (51)
-- FNEW (52)
--
-- From: http://www.freelists.org/post/luajit/frames-and-tail-calls,1
local function usage()
print([[
Usage: lj-bcname <BYTECODE_NUMBER|BYTECODE_ID>...
]])
os.exit(-1)
end
local bcnames = require("jit.vmdef").bcnames
local BC_LENGTH = 6
local function trim (s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local function bc_arr(bcnames)
local result = {}
while #bcnames > 0 do
local bc = string.sub(bcnames, 1, BC_LENGTH)
table.insert(result, trim(bc))
bcnames = string.sub(bcnames, BC_LENGTH + 1)
end
return result
end
local function bc_hash(bcnames)
local result = {}
for i, val in ipairs(bc_arr(bcnames)) do
result[val] = i
end
return result
end
local function print_bc(bc, index)
print(("%s (%d)"):format(bc, index))
end
if #arg == 0 then
usage()
end
for _, val in ipairs(arg) do
if tonumber(val) then
local bytecodes_by_number = bc_arr(bcnames)
local index = tonumber(val)
index = index + 1
local bc = bytecodes_by_number[index]
if bc then print_bc(bc, index - 1) end
elseif tostring(val) then
local bytecodes_by_name = bc_hash(bcnames)
local bcname = val
local index = bytecodes_by_name[bcname]
if index then print_bc(bcname, index - 1) end
else
usage()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment