Question

Is it possible to change strings (content and size) in Lua bytecode so that it will still be correct? It's about translating strings in Lua bytecode. Of course, not every language has the same size for each word...

Was it helpful?

Solution

Yes, it is if you know what you're doing. Strings are prefixed by their size stored as an int. The size and endianness of that int is platform-dependent. But why do you have to edit bytecode? Have you lost the sources?

OTHER TIPS

After some diving throught Lua source-code I found such a solution:

#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;
}

Firstly, we have start Lua VM and load the script we want to modify. Compiled or not, doesn't matter. Then build a Lua function prototype, parse and change it's constant table. Dump Prototype to a file.

I hope You got that for the basic idea.

You can try using the decompiler LuaDec. The decompiler would allow the strings to be modified in generated Lua code similar to the original source.

ChunkSpy has A No-Frills Introduction to Lua 5.1 VM Instructions that may help you understand the compiled chunk format and make the changes directly to bytecode if necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top