程式語言 - Lua - DynASM - x64 - Modify RAX



參考資訊:
https://luajit.org/dynasm.html
https://luajit.org/download.html
https://hackmd.io/@RinHizakura/SkvY4N9cv
https://corsix.github.io/dynasm-doc/tutorial.html

main.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

#include "dasm_proto.h"
#include "dasm_x86.h"

int main(int argc, char* argv[])
{
    size_t len = 0;
    void *buf = NULL;
    int (*pfn)(void);
    dasm_State *d = NULL;

    |.arch x64
    |.section code

    dasm_init(&d, DASM_MAXSECTION);

    |.globals lbl_

    void *labels[lbl__MAX] = { 0 };
    dasm_setupglobal(&d, labels, lbl__MAX);

    |.actionlist bf_actions

    dasm_setup(&d, bf_actions);
    dasm_State **Dst = &d;

    |.code
    |->test:
    |   mov rax, 100
    |   ret

    dasm_link(&d, &len);
    buf = mmap(0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    dasm_encode(&d, buf);
    mprotect(buf, len, PROT_READ | PROT_EXEC);
    dasm_free(&d);

    pfn = labels[lbl_test];
    printf("r=%d\n", pfn());

    munmap(buf, len);
    return 0;
}

編譯、執行

$ luajit -v
    LuaJIT 2.1.1753364724 -- Copyright (C) 2005-2025 Mike Pall. https://luajit.org/

$ luajit /opt/luajit/dynasm/dynasm.lua -o x64.c -D X64 main.c
$ gcc x64.c -o test -I/opt/luajit/dynasm
$ ./test 
    r=100