// DumpMem.java <out> <addr_hex> <len> [<addr2> <len2> ...]
// Doc N bytes tai dia chi VA trong program da import (Ghidra da ap dung fixup).
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.*;
import ghidra.program.model.mem.*;
import java.io.*;

public class DumpMem extends GhidraScript {
    @Override
    public void run() throws Exception {
        String[] args = getScriptArgs();
        Memory mem = currentProgram.getMemory();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i + 1 < args.length; i += 2) {
            long addr = Long.parseLong(args[i].replace("0x", ""), 16);
            int len = Integer.parseInt(args[i + 1]);
            byte[] b = new byte[len];
            int n = mem.getBytes(toAddr(addr), b);
            StringBuilder hex = new StringBuilder();
            StringBuilder asc = new StringBuilder();
            for (int j = 0; j < n; j++) {
                hex.append(String.format("%02x ", b[j] & 0xff));
                asc.append((b[j] >= 0x20 && b[j] < 0x7f) ? (char) b[j] : '.');
            }
            sb.append(String.format("addr=0x%x len=%d%nhex: %s%nasc: %s%n", addr, n, hex, asc));
        }
        try (PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(args[0]), "UTF-8")))) {
            pw.print(sb.toString());
        }
        println("DumpMem done -> " + args[0]);
    }
}
