PageRenderTime 72ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/luajit2/lib/bcsave.lua

#
Lua | 496 lines | 429 code | 40 blank | 27 comment | 70 complexity | ea7ffa426e90302fc6ee95b3b1c38979 MD5 | raw file
Possible License(s): GPL-3.0
  1. ----------------------------------------------------------------------------
  2. -- LuaJIT module to save/list bytecode.
  3. --
  4. -- Copyright (C) 2005-2012 Mike Pall. All rights reserved.
  5. -- Released under the MIT license. See Copyright Notice in luajit.h
  6. ----------------------------------------------------------------------------
  7. --
  8. -- This module saves or lists the bytecode for an input file.
  9. -- It's run by the -b command line option.
  10. --
  11. ------------------------------------------------------------------------------
  12. local jit = require("jit")
  13. assert(jit.version_num == 20000, "LuaJIT core/library version mismatch")
  14. -- Symbol name prefix for LuaJIT bytecode.
  15. local LJBC_PREFIX = "luaJIT_BC_"
  16. ------------------------------------------------------------------------------
  17. local function usage()
  18. io.stderr:write[[
  19. Save LuaJIT bytecode: luajit -b[options] input output
  20. -l Only list bytecode.
  21. -s Strip debug info (default).
  22. -g Keep debug info.
  23. -n name Set module name (default: auto-detect from input name).
  24. -t type Set output file type (default: auto-detect from output name).
  25. -a arch Override architecture for object files (default: native).
  26. -o os Override OS for object files (default: native).
  27. -e chunk Use chunk string as input.
  28. -- Stop handling options.
  29. - Use stdin as input and/or stdout as output.
  30. File types: c h obj o raw (default)
  31. ]]
  32. os.exit(1)
  33. end
  34. local function check(ok, ...)
  35. if ok then return ok, ... end
  36. io.stderr:write("luajit: ", ...)
  37. io.stderr:write("\n")
  38. os.exit(1)
  39. end
  40. local function readfile(input)
  41. if type(input) == "function" then return input end
  42. if input == "-" then input = nil end
  43. return check(loadfile(input))
  44. end
  45. local function savefile(name, mode)
  46. if name == "-" then return io.stdout end
  47. return check(io.open(name, mode))
  48. end
  49. ------------------------------------------------------------------------------
  50. local map_type = {
  51. raw = "raw", c = "c", h = "h", o = "obj", obj = "obj",
  52. }
  53. local map_arch = {
  54. x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true,
  55. }
  56. local map_os = {
  57. linux = true, windows = true, osx = true, freebsd = true, netbsd = true,
  58. openbsd = true, solaris = true,
  59. }
  60. local function checkarg(str, map, err)
  61. str = string.lower(str)
  62. local s = check(map[str], "unknown ", err)
  63. return s == true and str or s
  64. end
  65. local function detecttype(str)
  66. local ext = string.match(string.lower(str), "%.(%a+)$")
  67. return map_type[ext] or "raw"
  68. end
  69. local function checkmodname(str)
  70. check(string.match(str, "^[%w_.%-]+$"), "bad module name")
  71. return string.gsub(str, "[%.%-]", "_")
  72. end
  73. local function detectmodname(str)
  74. if type(str) == "string" then
  75. local tail = string.match(str, "[^/\\]+$")
  76. if tail then str = tail end
  77. local head = string.match(str, "^(.*)%.[^.]*$")
  78. if head then str = head end
  79. str = string.match(str, "^[%w_.%-]+")
  80. else
  81. str = nil
  82. end
  83. check(str, "cannot derive module name, use -n name")
  84. return string.gsub(str, "[%.%-]", "_")
  85. end
  86. ------------------------------------------------------------------------------
  87. local function bcsave_tail(fp, output, s)
  88. local ok, err = fp:write(s)
  89. if ok and output ~= "-" then ok, err = fp:close() end
  90. check(ok, "cannot write ", output, ": ", err)
  91. end
  92. local function bcsave_raw(output, s)
  93. local fp = savefile(output, "wb")
  94. bcsave_tail(fp, output, s)
  95. end
  96. local function bcsave_c(ctx, output, s)
  97. local fp = savefile(output, "w")
  98. if ctx.type == "c" then
  99. fp:write(string.format([[
  100. #ifdef _cplusplus
  101. extern "C"
  102. #endif
  103. #ifdef _WIN32
  104. __declspec(dllexport)
  105. #endif
  106. const char %s%s[] = {
  107. ]], LJBC_PREFIX, ctx.modname))
  108. else
  109. fp:write(string.format([[
  110. #define %s%s_SIZE %d
  111. static const char %s%s[] = {
  112. ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname))
  113. end
  114. local t, n, m = {}, 0, 0
  115. for i=1,#s do
  116. local b = tostring(string.byte(s, i))
  117. m = m + #b + 1
  118. if m > 78 then
  119. fp:write(table.concat(t, ",", 1, n), ",\n")
  120. n, m = 0, #b + 1
  121. end
  122. n = n + 1
  123. t[n] = b
  124. end
  125. bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n")
  126. end
  127. local function bcsave_elfobj(ctx, output, s, ffi)
  128. ffi.cdef[[
  129. typedef struct {
  130. uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
  131. uint16_t type, machine;
  132. uint32_t version;
  133. uint32_t entry, phofs, shofs;
  134. uint32_t flags;
  135. uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
  136. } ELF32header;
  137. typedef struct {
  138. uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
  139. uint16_t type, machine;
  140. uint32_t version;
  141. uint64_t entry, phofs, shofs;
  142. uint32_t flags;
  143. uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
  144. } ELF64header;
  145. typedef struct {
  146. uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize;
  147. } ELF32sectheader;
  148. typedef struct {
  149. uint32_t name, type;
  150. uint64_t flags, addr, ofs, size;
  151. uint32_t link, info;
  152. uint64_t align, entsize;
  153. } ELF64sectheader;
  154. typedef struct {
  155. uint32_t name, value, size;
  156. uint8_t info, other;
  157. uint16_t sectidx;
  158. } ELF32symbol;
  159. typedef struct {
  160. uint32_t name;
  161. uint8_t info, other;
  162. uint16_t sectidx;
  163. uint64_t value, size;
  164. } ELF64symbol;
  165. typedef struct {
  166. ELF32header hdr;
  167. ELF32sectheader sect[6];
  168. ELF32symbol sym[2];
  169. uint8_t space[4096];
  170. } ELF32obj;
  171. typedef struct {
  172. ELF64header hdr;
  173. ELF64sectheader sect[6];
  174. ELF64symbol sym[2];
  175. uint8_t space[4096];
  176. } ELF64obj;
  177. ]]
  178. local symname = LJBC_PREFIX..ctx.modname
  179. local is64, isbe = false, false
  180. if ctx.arch == "x64" then
  181. is64 = true
  182. elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" then
  183. isbe = true
  184. end
  185. -- Handle different host/target endianess.
  186. local function f32(x) return x end
  187. local f16, fofs = f32, f32
  188. if ffi.abi("be") ~= isbe then
  189. f32 = bit.bswap
  190. function f16(x) return bit.rshift(bit.bswap(x), 16) end
  191. if is64 then
  192. function fofs(x) return bit.bswap(x)*(2ll^32) end
  193. else
  194. fofs = f32
  195. end
  196. end
  197. -- Create ELF object and fill in header.
  198. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj")
  199. local hdr = o.hdr
  200. if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi.
  201. local bf = assert(io.open("/bin/ls", "rb"))
  202. local bs = bf:read(9)
  203. bf:close()
  204. ffi.copy(o, bs, 9)
  205. check(hdr.emagic[0] == 127, "no support for writing native object files")
  206. else
  207. hdr.emagic = "\127ELF"
  208. hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0
  209. end
  210. hdr.eclass = is64 and 2 or 1
  211. hdr.eendian = isbe and 2 or 1
  212. hdr.eversion = 1
  213. hdr.type = f16(1)
  214. hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20 })[ctx.arch])
  215. hdr.version = f32(1)
  216. hdr.shofs = fofs(ffi.offsetof(o, "sect"))
  217. hdr.ehsize = f16(ffi.sizeof(hdr))
  218. hdr.shentsize = f16(ffi.sizeof(o.sect[0]))
  219. hdr.shnum = f16(6)
  220. hdr.shstridx = f16(2)
  221. -- Fill in sections and symbols.
  222. local sofs, ofs = ffi.offsetof(o, "space"), 1
  223. for i,name in ipairs{
  224. ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack",
  225. } do
  226. local sect = o.sect[i]
  227. sect.align = fofs(1)
  228. sect.name = f32(ofs)
  229. ffi.copy(o.space+ofs, name)
  230. ofs = ofs + #name+1
  231. end
  232. o.sect[1].type = f32(2) -- .symtab
  233. o.sect[1].link = f32(3)
  234. o.sect[1].info = f32(1)
  235. o.sect[1].align = fofs(8)
  236. o.sect[1].ofs = fofs(ffi.offsetof(o, "sym"))
  237. o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0]))
  238. o.sect[1].size = fofs(ffi.sizeof(o.sym))
  239. o.sym[1].name = f32(1)
  240. o.sym[1].sectidx = f16(4)
  241. o.sym[1].size = fofs(#s)
  242. o.sym[1].info = 17
  243. o.sect[2].type = f32(3) -- .shstrtab
  244. o.sect[2].ofs = fofs(sofs)
  245. o.sect[2].size = fofs(ofs)
  246. o.sect[3].type = f32(3) -- .strtab
  247. o.sect[3].ofs = fofs(sofs + ofs)
  248. o.sect[3].size = fofs(#symname+1)
  249. ffi.copy(o.space+ofs+1, symname)
  250. ofs = ofs + #symname + 2
  251. o.sect[4].type = f32(1) -- .rodata
  252. o.sect[4].flags = fofs(2)
  253. o.sect[4].ofs = fofs(sofs + ofs)
  254. o.sect[4].size = fofs(#s)
  255. o.sect[5].type = f32(1) -- .note.GNU-stack
  256. o.sect[5].ofs = fofs(sofs + ofs + #s)
  257. -- Write ELF object file.
  258. local fp = savefile(output, "wb")
  259. fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
  260. bcsave_tail(fp, output, s)
  261. end
  262. local function bcsave_peobj(ctx, output, s, ffi)
  263. ffi.cdef[[
  264. typedef struct {
  265. uint16_t arch, nsects;
  266. uint32_t time, symtabofs, nsyms;
  267. uint16_t opthdrsz, flags;
  268. } PEheader;
  269. typedef struct {
  270. char name[8];
  271. uint32_t vsize, vaddr, size, ofs, relocofs, lineofs;
  272. uint16_t nreloc, nline;
  273. uint32_t flags;
  274. } PEsection;
  275. typedef struct __attribute((packed)) {
  276. union {
  277. char name[8];
  278. uint32_t nameref[2];
  279. };
  280. uint32_t value;
  281. int16_t sect;
  282. uint16_t type;
  283. uint8_t scl, naux;
  284. } PEsym;
  285. typedef struct __attribute((packed)) {
  286. uint32_t size;
  287. uint16_t nreloc, nline;
  288. uint32_t cksum;
  289. uint16_t assoc;
  290. uint8_t comdatsel, unused[3];
  291. } PEsymaux;
  292. typedef struct {
  293. PEheader hdr;
  294. PEsection sect[2];
  295. // Must be an even number of symbol structs.
  296. PEsym sym0;
  297. PEsymaux sym0aux;
  298. PEsym sym1;
  299. PEsymaux sym1aux;
  300. PEsym sym2;
  301. PEsym sym3;
  302. uint32_t strtabsize;
  303. uint8_t space[4096];
  304. } PEobj;
  305. ]]
  306. local symname = LJBC_PREFIX..ctx.modname
  307. local is64 = false
  308. if ctx.arch == "x86" then
  309. symname = "_"..symname
  310. elseif ctx.arch == "x64" then
  311. is64 = true
  312. end
  313. local symexport = " /EXPORT:"..symname..",DATA "
  314. -- The file format is always little-endian. Swap if the host is big-endian.
  315. local function f32(x) return x end
  316. local f16 = f32
  317. if ffi.abi("be") then
  318. f32 = bit.bswap
  319. function f16(x) return bit.rshift(bit.bswap(x), 16) end
  320. end
  321. -- Create PE object and fill in header.
  322. local o = ffi.new("PEobj")
  323. local hdr = o.hdr
  324. hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2 })[ctx.arch])
  325. hdr.nsects = f16(2)
  326. hdr.symtabofs = f32(ffi.offsetof(o, "sym0"))
  327. hdr.nsyms = f32(6)
  328. -- Fill in sections and symbols.
  329. o.sect[0].name = ".drectve"
  330. o.sect[0].size = f32(#symexport)
  331. o.sect[0].flags = f32(0x00100a00)
  332. o.sym0.sect = f16(1)
  333. o.sym0.scl = 3
  334. o.sym0.name = ".drectve"
  335. o.sym0.naux = 1
  336. o.sym0aux.size = f32(#symexport)
  337. o.sect[1].name = ".rdata"
  338. o.sect[1].size = f32(#s)
  339. o.sect[1].flags = f32(0x40300040)
  340. o.sym1.sect = f16(2)
  341. o.sym1.scl = 3
  342. o.sym1.name = ".rdata"
  343. o.sym1.naux = 1
  344. o.sym1aux.size = f32(#s)
  345. o.sym2.sect = f16(2)
  346. o.sym2.scl = 2
  347. o.sym2.nameref[1] = f32(4)
  348. o.sym3.sect = f16(-1)
  349. o.sym3.scl = 2
  350. o.sym3.value = f32(1)
  351. o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant.
  352. ffi.copy(o.space, symname)
  353. local ofs = #symname + 1
  354. o.strtabsize = f32(ofs + 4)
  355. o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs)
  356. ffi.copy(o.space + ofs, symexport)
  357. ofs = ofs + #symexport
  358. o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs)
  359. -- Write PE object file.
  360. local fp = savefile(output, "wb")
  361. fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
  362. bcsave_tail(fp, output, s)
  363. end
  364. local function bcsave_machobj(ctx, output, s, ffi)
  365. check(false, "NYI: no support for writing OSX object files")
  366. end
  367. local function bcsave_obj(ctx, output, s)
  368. local ok, ffi = pcall(require, "ffi")
  369. check(ok, "FFI library required to write this file type")
  370. if ctx.os == "windows" then
  371. return bcsave_peobj(ctx, output, s, ffi)
  372. elseif ctx.os == "osx" then
  373. return bcsave_machobj(ctx, output, s, ffi)
  374. else
  375. return bcsave_elfobj(ctx, output, s, ffi)
  376. end
  377. end
  378. ------------------------------------------------------------------------------
  379. local function bclist(input, output)
  380. local f = readfile(input)
  381. require("jit.bc").dump(f, savefile(output, "w"), true)
  382. end
  383. local function bcsave(ctx, input, output)
  384. local f = readfile(input)
  385. local s = string.dump(f, ctx.strip)
  386. local t = ctx.type
  387. if not t then
  388. t = detecttype(output)
  389. ctx.type = t
  390. end
  391. if t == "raw" then
  392. bcsave_raw(output, s)
  393. else
  394. if not ctx.modname then ctx.modname = detectmodname(input) end
  395. if t == "obj" then
  396. bcsave_obj(ctx, output, s)
  397. else
  398. bcsave_c(ctx, output, s)
  399. end
  400. end
  401. end
  402. local function docmd(...)
  403. local arg = {...}
  404. local n = 1
  405. local list = false
  406. local ctx = {
  407. strip = true, arch = jit.arch, os = string.lower(jit.os),
  408. type = false, modname = false,
  409. }
  410. while n <= #arg do
  411. local a = arg[n]
  412. if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then
  413. table.remove(arg, n)
  414. if a == "--" then break end
  415. for m=2,#a do
  416. local opt = string.sub(a, m, m)
  417. if opt == "l" then
  418. list = true
  419. elseif opt == "s" then
  420. ctx.strip = true
  421. elseif opt == "g" then
  422. ctx.strip = false
  423. else
  424. if arg[n] == nil or m ~= #a then usage() end
  425. if opt == "e" then
  426. if n ~= 1 then usage() end
  427. arg[1] = check(loadstring(arg[1]))
  428. elseif opt == "n" then
  429. ctx.modname = checkmodname(table.remove(arg, n))
  430. elseif opt == "t" then
  431. ctx.type = checkarg(table.remove(arg, n), map_type, "file type")
  432. elseif opt == "a" then
  433. ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture")
  434. elseif opt == "o" then
  435. ctx.os = checkarg(table.remove(arg, n), map_os, "OS name")
  436. else
  437. usage()
  438. end
  439. end
  440. end
  441. else
  442. n = n + 1
  443. end
  444. end
  445. if list then
  446. if #arg == 0 or #arg > 2 then usage() end
  447. bclist(arg[1], arg[2] or "-")
  448. else
  449. if #arg ~= 2 then usage() end
  450. bcsave(ctx, arg[1], arg[2])
  451. end
  452. end
  453. ------------------------------------------------------------------------------
  454. -- Public module functions.
  455. module(...)
  456. start = docmd -- Process -b command line option.