Portable Executable (PE32/PE32+) reader and writer in pure OCaml
README.md

ocaml-pe #

Portable Executable (PE32 / PE32+) reader and writer in pure OCaml, including UEFI applications.

Overview #

UEFI firmware boots Portable Executable images, the format of Windows binaries, so a tool that builds a bootable disk has to write and inspect PE files even on a system that never runs Windows. ocaml-pe reads and writes Portable Executable images, both Windows binaries (.exe, .dll) and UEFI applications (BOOTX64.EFI and its siblings for other architectures). The on-disk headers are described once with the wire combinator library and go through bytesrw in both directions, so one set of field definitions serves the decoder and the encoder.

With it a program can inspect a binary (its target machine among x86-64, aarch64, i386, arm and riscv64, PE32 or PE32+, subsystem, entry point and sections), tell whether it is a UEFI application (is_efi_application), and build a small, deterministic UEFI application from machine code.

Installation #

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam install pe

Writing and reading #

Pe.efi_application puts a blob of machine code into a minimal PE32+ UEFI application, with one executable .text section and the EFI-application subsystem. The output carries no timestamp, so the same code always gives the same bytes, and UEFI firmware loads it as is from the ESP.

The ESP (EFI System Partition) is a FAT partition with GPT type C12A7328-F81F-11D2-BA4B-00A0C93EC93B, from which UEFI firmware loads boot applications. When no boot entry is configured, the firmware loads \EFI\BOOT\BOOTX64.EFI, or BOOTAA64.EFI on aarch64 (UEFI 2.10, sections 3.5 and 13.3). Pe.machine gives the architecture of an image, and Pe.efi_boot_file the name the firmware looks for on the ESP for that architecture: BOOTX64.EFI for x86-64, BOOTAA64.EFI for aarch64, and so on.

let () =
  let app = Pe.efi_application "\x90\xc3" in  (* x86-64: nop; ret *)
  let bytes = Pe.to_string app in             (* a bootable BOOTX64.EFI *)
  match Pe.of_string bytes with
  | Error msg -> print_endline msg
  | Ok image ->
      Printf.printf "efi-application: %b, boots as %s\n"
        (Pe.is_efi_application image)
        (Pe.efi_boot_file (Pe.machine image))

Reading an image with of_string and writing it back with to_string gives the same bytes.

Status #

The reader parses PE32 and PE32+ headers and the section table, and checks every offset against the size of the input. The writer reproduces an image it has read byte for byte and produces canonical PE32+ UEFI applications. Relocations, the data directories, imports and Authenticode signatures are kept as opaque bytes; the library does not interpret them.

Licence #

ISC. See LICENSE.md.