是否可以更改Lua字节码中的字符串(内容和大小),以便它仍然是正确的?

时间:2010-09-07 16:04:35

标签: string lua size bytecode bytecode-manipulation

是否可以更改Lua字节码中的字符串(内容和大小)以使其仍然正确? 它是关于在Lua字节码中翻译字符串。当然,并非每种语言都有相同的大小......

3 个答案:

答案 0 :(得分:3)

是的,如果你知道你在做什么的话。字符串以其大小存储为int的前缀。该int的大小和字节顺序取决于平台。但是你为什么要编辑字节码呢?你丢失了消息来源吗?

答案 1 :(得分:1)

经过Lua源代码的一些潜水后,我找到了这样的解决方案:

#include "lua.h"
#include "lauxlib.h"

#include "lopcodes.h"
#include "lobject.h"
#include "lundump.h"

/* Definition from luac.c: */
#define toproto(L,i) (clvalue(L->top+(i))->l.p)

writer_function(lua_State* L, const void* p, size_t size, void* u)
{
    UNUSED(L);
    return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
}

static void
lua_bytecode_change_const(lua_State *l, Proto *f_proto,
                   int const_index, const char *new_const)
{
    TValue *tmp_tv = NULL;
    const TString *tmp_ts = NULL;

    tmp_ts = luaS_newlstr(l, new_const, strlen(new_const));
    tmp_tv = &f_proto->k[INDEXK(const_index)];
    setsvalue(l, tmp_tv, tmp_ts);

    return;
}

int main(void)
{
    lua_State *l = NULL;
    Proto *lua_function_prototype = NULL;
    FILE *output_file_hnd = NULL;

    l = lua_open();
    luaL_loadfile(l, "some_input_file.lua");
    lua_proto = toproto(l, -1);
    output_file_hnd = fopen("some_output_file.luac", "w");

    lua_bytecode_change_const(l, lua_function_prototype, some_const_index, "some_new_const");
    lua_lock(l);
    luaU_dump(l, lua_function_prototype, writer_function, output_file_hnd, 0);
    lua_unlock(l);

    return 0;
}

首先,我们启动Lua VM并加载我们想要修改的脚本。编译与否,无关紧要。然后构建一个Lua函数原型,解析并更改它的常量表。将原型转储到文件中。

我希望你能得到基本的想法。

答案 2 :(得分:0)

您可以尝试使用反编译器LuaDec。反编译器允许在生成的Lua代码中修改字符串,类似于原始源。

ChunkSpyA No-Frills Introduction to Lua 5.1 VM Instructions可帮助您理解已编译的块格式,并在必要时直接对字节码进行更改。