luat_lib_luf.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include "luat_base.h"
  2. #include "luat_malloc.h"
  3. #include "lprefix.h"
  4. #include <stddef.h>
  5. #include "lua.h"
  6. #include "lapi.h"
  7. #include "lobject.h"
  8. #include "lstate.h"
  9. #include "lundump.h"
  10. #include "luat_zbuff.h"
  11. int luf_dump(lua_State *L, const Proto *f, lua_Writer w, void *data, int strip, int ptroffset);
  12. LClosure *luat_luf_undump(lua_State *L, const char* ptr, size_t len, const char *name);
  13. void luat_luf_cmp(lua_State *L, const Proto* p1, const Proto *p2);
  14. static int writer (lua_State *L, const void *b, size_t size, void *B) {
  15. (void)L;
  16. luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
  17. return 0;
  18. }
  19. static int l_luf_dump(lua_State* L) {
  20. luaL_Buffer b;
  21. TValue *o;
  22. int strip = lua_toboolean(L, 2);
  23. uint32_t ptroffset = 0;
  24. luaL_checktype(L, 1, LUA_TFUNCTION);
  25. luat_zbuff_t *zbuff = NULL;
  26. if (lua_isuserdata(L, 3)) {
  27. zbuff = luaL_checkudata(L, 3, LUAT_ZBUFF_TYPE);
  28. ptroffset = (uint32_t)zbuff->addr;
  29. }
  30. else if (lua_isinteger(L, 3)) {
  31. ptroffset = luaL_checkinteger(L, 3);
  32. }
  33. lua_settop(L, 1);
  34. luaL_buffinit(L,&b);
  35. lua_lock(L);
  36. api_checknelems(L, 1);
  37. o = L->top - 1;
  38. if (luf_dump(L, getproto(o), writer, &b, strip, ptroffset) != 0)
  39. return luaL_error(L, "unable to dump given function");
  40. luaL_pushresult(&b);
  41. lua_unlock(L);
  42. return 1;
  43. }
  44. static int l_luf_undump(lua_State* L) {
  45. size_t len;
  46. const char* data = luaL_checklstring(L, 1, &len);
  47. luat_luf_undump(L, data, len, NULL);
  48. return 1;
  49. }
  50. static int l_luf_cmp(lua_State* L) {
  51. luaL_checktype(L, 1, LUA_TFUNCTION);
  52. luaL_checktype(L, 2, LUA_TFUNCTION);
  53. lua_settop(L, 2);
  54. TValue *o;
  55. Proto* p1;
  56. Proto* p2;
  57. o = L->top - 2;
  58. p1 = getproto(o);
  59. o = L->top - 1;
  60. p2 = getproto(o);
  61. luat_luf_cmp(L, p1, p2);
  62. return 0;
  63. }
  64. #include "rotable2.h"
  65. static const rotable_Reg_t reg_luf[] =
  66. {
  67. { "dump" , ROREG_FUNC(l_luf_dump)},
  68. { "undump" , ROREG_FUNC(l_luf_undump)},
  69. { "cmp", ROREG_FUNC(l_luf_cmp)},
  70. { NULL, {}}
  71. };
  72. LUAMOD_API int luaopen_luf( lua_State *L ) {
  73. luat_newlib2(L, reg_luf);
  74. return 1;
  75. }