Something went wrong. Try again.
BSDIFF40 binary diff and patch in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire <thomas@gazagnaire.org> Copyright 2003-2005 Colin Percival SPDX-License-Identifier: ISC
The matcher is a port of the reference bsdiff.c (BSD-licensed); the format follows bspatch.c. ---------------------------------------------------------------------------*)
module Error = Errormodule Suffix_array = Suffix_array
let magic_string = "BSDIFF40"
let string8_of_uint64 n = let b = Bytes.create 8 in Bytes.set_int64_le b 0 n; Bytes.unsafe_to_string b
let uint64_of_string8 s = if String.length s <> 8 then Fmt.invalid_arg "bsdiff: expected an 8-byte uint64 string"; Bytes.get_int64_le (Bytes.unsafe_of_string s) 0
let magic_u64 = uint64_of_string8 magic_string
(* BSDIFF40 integers: 64-bit little-endian sign-and-magnitude -- the magnitude in bits 0..62 and the sign in bit 63 (bsdiff.c's offtout). Only the source seek is genuinely signed. *)let decode_offt_exn ?ctx w = let mag = Int64.logand w Int64.max_int in if Int64.compare mag (Int64.of_int max_int) > 0 then Error.fail_corrupt ?ctx "integer exceeds the native int range"; let m = Int64.to_int mag in if Int64.compare w 0L < 0 then -m else m
let encode_offt i = if i < 0 then Int64.logor (Int64.of_int (-i)) Int64.min_int else Int64.of_int i
(* The header lengths and a triple's mix/copy counts are non-negative sizes stored in the same 8-byte slot with the sign bit clear. A set sign bit (or a magnitude past the native int range) is corruption: [usize] rejects it on decode, and [fits_native_int] carries the bound into the generated 3D as a [<= max_int] refinement, so EverParse's verified C validator rejects exactly the same words. *)let usize = Wire.map ~decode:(fun w -> match Wire.UInt64.to_int_opt w with | Some n -> n | None -> raise (Wire.Parse_error (Wire.parse_error (Wire.Value_out_of_range { value = Wire.UInt64.to_int64 w })))) ~encode:Wire.UInt64.of_int Wire.uint64
(* The 8-byte slots the codec reads as signed sign-and-magnitude words: the same eight bytes, carried as an [int64] for [decode_offt_exn]. *)let u64_int64 = Wire.map ~decode:Wire.UInt64.to_int64 ~encode:Wire.UInt64.of_int64 Wire.uint64
let fits_native_int r = Wire.Expr.(r <= Wire.int max_int)let fixed_uint64 n r = Wire.Expr.(r = Wire.int (Int64.to_int n))
(* Header: magic, lengths of the two leading bzip2 streams, target size. The extra stream runs to the end of the patch. *)type header = { hdr_magic : string; ctrl_len : int; diff_len : int; new_size : int;}
let f_magic = Wire.Field.v "magic" ~self_constraint:(fixed_uint64 magic_u64) (Wire.map ~decode:(fun w -> string8_of_uint64 (Wire.UInt64.to_int64 w)) ~encode:(fun s -> Wire.UInt64.of_int64 (uint64_of_string8 s)) Wire.uint64)
let f_ctrl_len = Wire.Field.v "ctrl_len" ~self_constraint:fits_native_int usizelet f_diff_len = Wire.Field.v "diff_len" ~self_constraint:fits_native_int usizelet f_new_size = Wire.Field.v "new_size" ~self_constraint:fits_native_int usizelet magic = Wire.Codec.(f_magic $ fun h -> h.hdr_magic)let ctrl_len = Wire.Codec.(f_ctrl_len $ fun h -> h.ctrl_len)let diff_len = Wire.Codec.(f_diff_len $ fun h -> h.diff_len)let new_size = Wire.Codec.(f_new_size $ fun h -> h.new_size)let header_size = 32
let header_codec = Wire.Codec.v "Bsdiff40Header" ~doc: "bsdiff 4.0 patch format: the 32-byte patch header -- the \"BSDIFF40\" \ magic (the 8 ASCII bytes read as a little-endian UINT64 = \ 0x3034464649445342), the compressed lengths of the control and diff \ bzip2 streams, and the target file size (the extra stream runs to the \ end of the patch)." (fun hdr_magic ctrl_len diff_len new_size -> { hdr_magic; ctrl_len; diff_len; new_size }) Wire.Codec.[ magic; ctrl_len; diff_len; new_size ]
(* Control triple: bytes of diff data to mix in, bytes of extra data to insert, and a signed seek in the source. *)type triple = { mix : int; copy : int; seek : int64 }
let triple_size = 24let f_mix = Wire.Field.v "mix" ~self_constraint:fits_native_int usizelet f_copy = Wire.Field.v "copy" ~self_constraint:fits_native_int usize
(* The seek is a sign-magnitude UINT64 (bit 63 the sign, bits 0..62 the magnitude; see [decode_offt_exn]), and its magnitude must fit a native int. Mask off the sign bit and bound the magnitude so the constraint projects into the generated 3D as [(Seek & 0x7fff...) <= max_int]: EverParse's verified C validator then rejects the same words [decode_offt_exn] rejects on decode. *)let seek_magnitude_fits self = Wire.Expr.( land64 self (int64 0x7FFF_FFFF_FFFF_FFFFL) <= int64 (Int64.of_int max_int))
let f_seek = Wire.Field.v "seek" ~self_int64:seek_magnitude_fits u64_int64let mix = Wire.Codec.(f_mix $ fun t -> t.mix)let copy = Wire.Codec.(f_copy $ fun t -> t.copy)let seek = Wire.Codec.(f_seek $ fun t -> t.seek)
let triple_codec = Wire.Codec.v "Bsdiff40Control" ~doc: "bsdiff 4.0 patch format: one 24-byte control triple -- the count of \ diff bytes to add to the source, the count of extra bytes to copy \ verbatim, and a seek to apply to the source pointer. The seek is stored \ in a UINT64 as 64-bit little-endian sign-and-magnitude (bit 63 is the \ sign, bits 0..62 the magnitude) -- NOT two's complement." (fun mix copy seek -> { mix; copy; seek }) Wire.Codec.[ mix; copy; seek ]
let bz2_compress s = Bytesrw.Bytes.Reader.filter_string [ Bytesrw_bz2.compress_reads () ] s
let decode_exn ~what codec bytes off = match Wire.Codec.decode_exn codec bytes off with | v -> v | exception Wire.Parse_error _ -> Error.fail_corrupt what
(* Apply (bspatch). *)
let parse_header patch = if String.length patch < 8 then ( if String.sub magic_string 0 (String.length patch) <> patch then Error.fail_magic_mismatch patch; Error.fail_truncated "header"); if String.sub patch 0 8 <> magic_string then Error.fail_magic_mismatch (String.sub patch 0 8); if String.length patch < header_size then Error.fail_truncated "header"; let h = decode_exn ~what:"header" header_codec (Bytes.unsafe_of_string patch) 0 in if h.hdr_magic <> magic_string then Error.fail_magic_mismatch h.hdr_magic; let patch_len = String.length patch in if h.ctrl_len > patch_len - header_size then Error.fail_truncated "control section"; if h.diff_len > patch_len - header_size - h.ctrl_len then Error.fail_truncated "diff section"; if h.new_size > Sys.max_string_length then Error.fail_corrupt "target size exceeds the maximum string size"; h
(* Apply (bspatch), streaming. The three sections are decompressed lazily and the target is pushed to the writer run by run, so resident memory is bounded by the stream slice length, not the target. *)
module Reader = Bytesrw.Bytes.Readermodule Writer = Bytesrw.Bytes.Writermodule Slice = Bytesrw.Bytes.Slice
(* A reader over the bzip2 stream occupying [patch[first, first+len)], decompressed on demand. [Reader.of_slice] views the compressed sub-range in place, so only the decompressed bytes are ever materialised. *)let section_reader patch ~first ~len = let raw = if len = 0 then Reader.empty () else Reader.of_slice (Slice.of_bytes (Bytes.unsafe_of_string patch) ~first ~last:(first + len - 1)) in Bytesrw_bz2.decompress_reads () raw
(* Pull exactly [n] bytes from [r], handing each consumed sub-slice to [f] as [bytes first length]. [on_short] is raised if the stream ends first. *)let read_exact r n ~on_short f = let remaining = ref n in while !remaining > 0 do let s = Reader.read r in if Slice.is_eod s then on_short (); let avail = Slice.length s in let take = if avail <= !remaining then avail else !remaining in f (Slice.bytes s) (Slice.first s) take; if take < avail then Reader.push_back r (Slice.make (Slice.bytes s) ~first:(Slice.first s + take) ~length:(avail - take)); remaining := !remaining - take done
(* Read one 24-byte control triple into [buf]. [`Eof] at a triple boundary ends the program; a partial triple is a corrupt control section. *)let read_triple r buf = let got = ref 0 and eod = ref false in while (not !eod) && !got < triple_size do let s = Reader.read r in if Slice.is_eod s then eod := true else begin let avail = Slice.length s in let take = if avail <= triple_size - !got then avail else triple_size - !got in Bytes.blit (Slice.bytes s) (Slice.first s) buf !got take; if take < avail then Reader.push_back r (Slice.make (Slice.bytes s) ~first:(Slice.first s + take) ~length:(avail - take)); got := !got + take end done; if !got = 0 then `Eof else if !got = triple_size then `Triple else Error.fail_corrupt "control section is not a whole number of triples"
(* One mixed run: [len] diff bytes from [bytes.[first..]] added to the source starting at [old_base] (in range), returned as a fresh buffer to write. *)let mix_run ~source ~old_size ~old_base bytes first len = let out = Bytes.create len in for i = 0 to len - 1 do let b = Char.code (Bytes.get bytes (first + i)) in let oi = old_base + i in let b = if oi >= 0 && oi < old_size then (b + Char.code source.[oi]) land 0xff else b in Bytes.unsafe_set out i (Char.unsafe_chr b) done; out
(* Stream one control triple to [w]: the mixed diff run then the extra copy. Returns the advanced (new_pos, old_pos). *)let stream_triple ~source ~diff_r ~extra_r ~w ~old_size ~h ~ctx t ~new_pos ~old_pos = let seek = decode_offt_exn ~ctx t.seek in if t.mix > h.new_size - new_pos then Error.fail_invalid ~ctx "diff data overruns the target size"; let mixed = ref 0 in read_exact diff_r t.mix ~on_short:(fun () -> Error.fail_invalid ~ctx "control overruns the diff section") (fun bytes first len -> Writer.write_bytes w (mix_run ~source ~old_size ~old_base:(old_pos + !mixed) bytes first len); mixed := !mixed + len); let new_pos = new_pos + t.mix in if t.copy > h.new_size - new_pos then Error.fail_invalid ~ctx "extra data overruns the target size"; read_exact extra_r t.copy ~on_short:(fun () -> Error.fail_invalid ~ctx "control overruns the extra section") (fun bytes first len -> Writer.write w (Slice.make bytes ~first ~length:len)); (new_pos + t.copy, old_pos + t.mix + seek)
let apply_exn ~source patch w = let h = parse_header patch in let diff_off = header_size + h.ctrl_len in let extra_off = diff_off + h.diff_len in let ctrl_r = section_reader patch ~first:header_size ~len:h.ctrl_len in let diff_r = section_reader patch ~first:diff_off ~len:h.diff_len in let extra_r = section_reader patch ~first:extra_off ~len:(String.length patch - extra_off) in let old_size = String.length source in let new_pos = ref 0 and old_pos = ref 0 in let tbuf = Bytes.create triple_size in (try let k = ref 0 and continue = ref true in while !continue do match read_triple ctrl_r tbuf with | `Eof -> continue := false | `Triple -> let ctx = Error.ctx_with_triple !k in let t = decode_exn ~what:"control triple" triple_codec tbuf 0 in let np, op = stream_triple ~source ~diff_r ~extra_r ~w ~old_size ~h ~ctx t ~new_pos:!new_pos ~old_pos:!old_pos in new_pos := np; old_pos := op; incr k done; (* Fully consume each section so a truncated or corrupt bzip2 stream is rejected even when the control program never reads from it. Discarding keeps memory bounded. *) Reader.discard diff_r; Reader.discard extra_r with Bytesrw.Bytes.Stream.Error e -> Error.fail_corrupt (Bytesrw.Bytes.Stream.error_message e)); if !new_pos <> h.new_size then Error.fail_invalid "control program does not produce the declared size"
let apply_writer ~source patch w = match apply_exn ~source patch w with | () -> Ok () | exception Loc.Error e -> Stdlib.Error e
let apply ~source patch = let buf = Buffer.create (String.length source) in match apply_exn ~source patch (Writer.of_buffer buf) with | () -> Ok (Buffer.contents buf) | exception Loc.Error e -> Stdlib.Error e
(* Diff (bsdiff). The matcher is the reference algorithm: greedy scan of the target against the suffix array, scored against extending the previous alignment, with forward/backward extension of the emitted region and overlap arbitration. *)
(* The constant inputs of one diff: the two buffers being aligned. *)type matcher = { source : string; target : string; old_size : int; new_size : int;}
(* The three output streams of a patch, plus scratch for the control codec. *)type output = { ctrl : Buffer.t; diffb : Buffer.t; extra : Buffer.t; tbuf : bytes;}
(* A resolved match region: the previous alignment [lastscan]/[lastpos] kept for [lenf] forward bytes, and the new match at [scan]/[pos] trimmed by [lenb] backward bytes. *)type region = { lastscan : int; lastpos : int; lenf : int; scan : int; pos : int; lenb : int;}
(* [true] if the source, shifted by the previous alignment [offset], still matches the target at position [i]. *)let same_offset_match m ~offset i = i + offset < m.old_size && m.source.[i + offset] = m.target.[i]
(* A match decisively beats extending the previous alignment: it is exact, or beats the same-offset score by more than 8 (the reference's slack). *)let match_is_decisive ~len ~oldscore = (len = oldscore && len <> 0) || len > oldscore + 8
(* Advance [scan] from its current position to the next match that beats the previous alignment, scoring the same-offset run as it goes. Returns the match (scan, len, pos) and the same-offset [oldscore] at that point. *)let next_match sa m ~lastoffset ~scan ~len ~pos = let scan = ref scan and len = ref len and pos = ref pos in let oldscore = ref 0 and scsc = ref scan.contents and break = ref false in while (not !break) && !scan < m.new_size do let l, p = Suffix_array.longest_match sa ~target:m.target ~pos:!scan in len := l; pos := p; while !scsc < !scan + !len do if same_offset_match m ~offset:lastoffset !scsc then incr oldscore; incr scsc done; if match_is_decisive ~len:!len ~oldscore:!oldscore then break := true else begin if same_offset_match m ~offset:lastoffset !scan then decr oldscore; incr scan end done; (!scan, !len, !pos, !oldscore)
(* Forward extension from the previous alignment: keep the prefix while at least half its bytes match. *)let forward_extent m ~lastscan ~lastpos ~scan = let s = ref 0 and sf = ref 0 and lenf = ref 0 and i = ref 0 in while lastscan + !i < scan && lastpos + !i < m.old_size do if m.source.[lastpos + !i] = m.target.[lastscan + !i] then incr s; incr i; if (2 * !s) - !i > (2 * !sf) - !lenf then begin sf := !s; lenf := !i end done; !lenf
(* Backward extension of the new match before [scan]. *)let backward_extent m ~lastscan ~scan ~pos = let s = ref 0 and sb = ref 0 and lenb = ref 0 and i = ref 1 in while scan >= lastscan + !i && pos >= !i do if m.source.[pos - !i] = m.target.[scan - !i] then incr s; if (2 * !s) - !i > (2 * !sb) - !lenb then begin sb := !s; lenb := !i end; incr i done; !lenb
(* The forward and backward extents may overlap; split the overlap where the running balance of matches flips, returning the region with [lenf]/[lenb] adjusted. *)let split_overlap m r = if r.lastscan + r.lenf <= r.scan - r.lenb then r else begin let overlap = r.lastscan + r.lenf - (r.scan - r.lenb) in let s = ref 0 and ss = ref 0 and lens = ref 0 in for i = 0 to overlap - 1 do if m.target.[r.lastscan + r.lenf - overlap + i] = m.source.[r.lastpos + r.lenf - overlap + i] then incr s; if m.target.[r.scan - r.lenb + i] = m.source.[r.pos - r.lenb + i] then decr s; if !s > !ss then begin ss := !s; lens := i + 1 end done; { r with lenf = r.lenf + !lens - overlap; lenb = r.lenb - !lens } end
(* Emit one matched region: the byte-wise diff of its [lenf]-byte prefix, the literal bytes up to the next match, and the control triple. *)let emit_region m out r = for i = 0 to r.lenf - 1 do Buffer.add_char out.diffb (Char.chr ((Char.code m.target.[r.lastscan + i] - Char.code m.source.[r.lastpos + i]) land 0xff)) done; let copy = r.scan - r.lenb - (r.lastscan + r.lenf) in Buffer.add_substring out.extra m.target (r.lastscan + r.lenf) copy; let seek = r.pos - r.lenb - (r.lastpos + r.lenf) in Wire.Codec.encode triple_codec { mix = r.lenf; copy; seek = encode_offt seek } out.tbuf 0; Buffer.add_bytes out.ctrl out.tbuf
(* Compress the three streams and frame them behind the BSDIFF40 header. *)let assemble_patch out ~new_size = let bz_ctrl = bz2_compress (Buffer.contents out.ctrl) in let bz_diff = bz2_compress (Buffer.contents out.diffb) in let bz_extra = bz2_compress (Buffer.contents out.extra) in let hbuf = Bytes.create header_size in Wire.Codec.encode header_codec { hdr_magic = magic_string; ctrl_len = String.length bz_ctrl; diff_len = String.length bz_diff; new_size; } hbuf 0; let patch = Buffer.create (header_size + String.length bz_ctrl + String.length bz_diff + String.length bz_extra) in Buffer.add_bytes patch hbuf; Buffer.add_string patch bz_ctrl; Buffer.add_string patch bz_diff; Buffer.add_string patch bz_extra; Buffer.contents patch
(* Traverse the target, emitting a control triple plus diff and extra bytes for each matched region, until the whole target is covered. *)let scan_all sa m out = let scan = ref 0 and len = ref 0 and pos = ref 0 in let lastscan = ref 0 and lastpos = ref 0 and lastoffset = ref 0 in while !scan < m.new_size do scan := !scan + !len; let s, l, p, oldscore = next_match sa m ~lastoffset:!lastoffset ~scan:!scan ~len:!len ~pos:!pos in scan := s; len := l; pos := p; if l <> oldscore || s = m.new_size then begin let lenf = forward_extent m ~lastscan:!lastscan ~lastpos:!lastpos ~scan:s in let lenb = if s < m.new_size then backward_extent m ~lastscan:!lastscan ~scan:s ~pos:p else 0 in let r = split_overlap m { lastscan = !lastscan; lastpos = !lastpos; lenf; scan = s; pos = p; lenb; } in emit_region m out r; lastscan := r.scan - r.lenb; lastpos := r.pos - r.lenb; lastoffset := r.pos - r.scan end done
let diff ~source ~target = let sa = Suffix_array.v source in let m = { source; target; old_size = String.length source; new_size = String.length target; } in let out = { ctrl = Buffer.create 256; diffb = Buffer.create 1024; extra = Buffer.create 1024; tbuf = Bytes.create triple_size; } in scan_all sa m out; assemble_patch out ~new_size:m.new_size