Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

how to use vmloadpeanddependencies in miasm

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Coherecommand-a-03-2025’s answer.
  1. User

    how to use vm_load_pe_and_dependencies in miasm

  2. Assistant

    Below is a small, self-contained example that shows the typical workflow and explains every parameter you are likely to meet when you call

    vm_load_pe_and_dependencies(...)
    

    in Miasm.


    1. TL;DR – the four essential lines

    machine = Machine("x86_32")              # or "x86_64"
    jitter  = machine.jitter("python")       # or "unicorn"/"qemu"
    win_env = win_env_x86_32(jitter)         # create a minimal Windows VM
    entry   = vm_load_pe_and_dependencies(jitter, "sample.exe", win_env=win_env)
    

    entry is the VA of the program’s AddressOfEntryPoint; set jitter.cpu.EIP/RIP to it and hit jitter.run().


    1. Complete runnable demo

    #!/usr/bin/env python3
    import sys
    from pathlib import Path
    
    from miasm.analysis.machine    import Machine
    from miasm.os_dep.win_env      import win_env_x86_32   # <- 32-bit helpers
    from miasm.os_dep.win_pe       import vm_load_pe_and_dependencies
    
    def main(exe_path: Path):
        # 1) pick the architecture and spin a JIT engine
        machine = Machine("x86_32")           # use "x86_64" for 64-bit PEs
        jitter  = machine.jitter("python")    # "unicorn" is faster if you have it
    
        # 2) give the VM a stack
        jitter.init_stack(size=0x20000)
    
        # 3) prepare a Windows-like environment (PEB, TEB, heap, API stubs…)
        win_env = win_env_x86_32(jitter)
    
        # 4) OPTIONAL – add/override WinAPI hooks BEFORE loading the PE
        def my_MessageBoxA(jit):
            hwnd, txt, caption, flags = jit.func_args_stdcall(
                    ["hWnd", "lpText", "lpCaption", "uType"])
            print("Guest called MessageBoxA: %s" % jit.vm.get_str(txt))
            jit.func_ret_stdcall(0)           # return value
            return True                       # continue execution
        win_env.win_func_hooks["user32.dll!MessageBoxA"] = my_MessageBoxA
    
        # 5) actually map the PE + ALL its imported DLL tree
        entry_addr = vm_load_pe_and_dependencies(
                jitter,
                exe_path,
                win_env     = win_env,        # strongly recommended
                recurse     = True,           # default = True → load dll→dll→dll…
                relocate    = True,           # apply base-relocs if rebased
                verbose     = True)           # print what is loaded where
    
        # 6) fire it up
        jitter.cpu.EIP = entry_addr
        jitter.run()
    
    if __name__ == "__main__":
        if len(sys.argv) != 2:
            print("usage: %s <pe file>" % sys.argv[0])
            sys.exit(1)
        main(Path(sys.argv[1]))
    

    Run it:

    $ python3 run_pe.py calc.exe
    [+] Mapped calc.exe @ 0x400000 (size 0x31000)
    [+]   -> kernel32.dll @ 0x77B90000
    [+]   -> user32.dll   @ 0x77D50000
    [...]
    

    1. What the helper really does

    • Parses the PE header, maps every section at its RVA, and (optionally) applies relocations when the preferred base is not available.
    • Walks the import table; for each DLL it – locates the file on disk (System32, current dir, …)
    – recursively calls itself so that the whole tree is present in memory.
    • For every imported symbol it checks win_env.win_func_hooks:
    – if you provided a Python implementation ⇒ writes a trampoline that calls it.
    – else ⇒ writes a “ret 0” stub so that the guest can continue without crashing.
    • Builds minimal PEB / TEB / Heap structures so that Kernel32!GetProcessHeap, FS segment accesses, etc. work out of the box.


    1. Signature and important keyword args

    entry_va = vm_load_pe_and_dependencies(
                  jitter,
                  pe_path,               # str / pathlib.Path / bytes
                  win_env   = None,      # win_env_x86_32 / win_env_x86_64 instance
                  recurse   = True,      # load imported DLLs recursively
                  relocate  = True,      # apply relocations if image is rebased
                  base_addr = None,      # force-load at a given address
                  return_pe = False,     # True ⇒ returns (pe_obj, entry_va)
                  verbose   = False)     # print each mapped module
    

    1. Typical pitfalls

    • You must give the VM a stack before running: jitter.init_stack().
    • GUI programs often rely on user32.dll message loop; without extra hooks they will exit quickly or idle forever.
    • 64-bit: use Machine("x86_64") and win_env_x86_64; the rest is identical.
    • If a DLL cannot be found, add its directory to os.environ['PATH'] or pass an absolute path instead of just the name.


    1. Going further

    • Combine with Miasm’s debugger: jitter.add_breakpoint() / jitter.step() for live RE.
    • You can snapshot the VM after vm_load_pe_and_dependencies and reload it later (jitter.save_context, restore_context).
    • For complex hooks, subclass the env (class MyEnv(win_env_x86_32): …) and override or extend the default API set.

    That’s all you need to start emulating real Windows binaries – with all their DLLs automatically mapped – in less than 30 lines of Python. Have fun experimenting!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.