- OCaml 76%
- C 24%
mbr #
Master Boot Record manipulation in pure OCaml.
Overview #
A disk image for a virtual machine or a unikernel needs a partition table
before a firmware or a bootloader can find its filesystems, and the Master
Boot Record is the oldest and simplest one: a 512-byte first sector with
bootstrap code, a disk signature and up to four primary partitions. mbr
reads and writes it in pure OCaml, so an image can be built without
fdisk or root privileges.
Building a record checks what the format leaves implicit: at most four
partitions, at most one marked bootable, and no two overlapping. The library
also synthesises a CHS geometry for pre-LBA firmware. CHS (cylinder, head,
sector) addresses a sector by the disk's physical geometry, the scheme that
came before the linear LBA (logical block address) numbering, and an MBR
partition entry stores both. Its CHS fields hold at most 1024 cylinders, 255
heads and 63 sectors of 512 bytes, 1024 × 255 × 63 × 512 = 8,422,686,720
bytes (about 7.8 GiB), so beyond that the CHS fields cannot address a sector
and only the LBA counts. The library also exposes the 16-byte
partition entry as a wire codec.
The package derives from mirage/ocaml-mbr,
whose history CHANGES.md records.
Installation #
Install with opam:
$ opam install mbr
If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install mbr
Usage #
Creating an MBR #
(* FAT16 (type 6), starting at sector 2048, 32MB. *)
let part =
match Mbr.Partition.v ~active:true ~partition_type:6 2048L 65536L with
| Ok p -> p
| Error e -> failwith e
let mbr =
match Mbr.v [ part ] with
| Ok m -> m
| Error e -> failwith e
let () = Fmt.pr "%a@." Mbr.pp mbr
Serialization #
let bytes = Mbr.to_string mbr
let () =
match Mbr.of_string bytes with
| Ok mbr ->
List.iter
(fun p ->
Fmt.pr "Partition: start=%Ld, size=%Ld@."
(Mbr.Partition.sector_start p)
(Mbr.Partition.size_sectors p))
mbr.Mbr.partitions
| Error e -> failwith e
API #
Partition #
Mbr.Partition.vbuilds a partition from anint64start sector and length.Mbr.Partition.sector_startandsize_sectorsread them back asint64.Mbr.Partition.codecis the wire codec of the 16-byte partition entry.
MBR #
Mbr.vbuilds a record from up to four partitions, checking overlaps and active flags.Mbr.ppformats a record.Mbr.sizeofis 512, the size of a record in bytes.Mbr.default_partition_startis sector 2048L, the usual first partition offset.
Serialization #
Mbr.of_stringandMbr.to_stringconvert from and to strings.
Requirements #
- OCaml >= 5.1
- wire, fmt
Licence #
ISC