(* Copyright (c) 2024-2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) type entry = { commit : Object_hash.t; bits : Ewah.t; flags : int } type t = { pack_checksum : Object_hash.t; commits : Ewah.t; trees : Ewah.t; blobs : Ewah.t; tags : Ewah.t; entries : entry list; } let pp ppf t = Fmt.pf ppf "@[Bitmap{pack=%a;@ entries=%d;@ commits=%d}@]" Object_hash.pp t.pack_checksum (List.length t.entries) (Ewah.cardinal t.commits) let flag_full_dag = 0x1 let flag_hash_cache = 0x4 let flag_lookup_table = 0x10 exception Parse_error of string let fail fmt = Fmt.kstr (fun s -> raise (Parse_error s)) fmt let err_msg fmt = Fmt.kstr (fun s -> Error (`Msg s)) fmt let pack_order index = let n = Pack_index.count index in let order = Array.init n (fun i -> i) in Array.sort (fun a b -> Optint.Int63.compare (Pack_index.offset_at index a) (Pack_index.offset_at index b)) order; Array.map (fun i -> Pack_index.hash_at index i) order let ewah_xor a b = Ewah.union (Ewah.diff a b) (Ewah.diff b a) (* Fixed headers and variable-length chunks are decoded with wire's direct interpreter; EWAH payloads use the ewah codec. *) (* Every bitmap header number is a count, a commit position or a flag word bounded far below 2^31, so it decodes to a native int. *) let i32be_int = Wire.map ~decode:Wire.SInt32.to_int ~encode:Wire.SInt32.of_int Wire.int32be let u16be_int = Wire.map ~decode:Wire.UInt16.to_int ~encode:Wire.UInt16.v Wire.uint16be let u8_int = Wire.map ~decode:Wire.UInt8.to_int ~encode:Wire.UInt8.v Wire.uint8 let u32 data pos = Wire.of_string_exn i32be_int (String.sub data pos 4) let u16x2 data pos = match Wire.of_string_exn (Wire.array ~len:(Wire.int 2) u16be_int) (String.sub data pos 4) with | [ a; b ] -> (a, b) | _ -> assert false (* Whole 64-bit words are EWAH's unit, and a bitmap's declared bit count is read in them. *) let words bits = (bits + 63) / 64 (* A bit position names an object in the pack, so a bitmap spans no more words than the pack has objects. The declared size is checked first, so a short chunk cannot declare an arbitrarily wide bitmap; the set bits are then checked against the object count, since the final word's padding is not an object. *) let read_ewah ~count data pos = if pos + 8 > String.length data then fail "truncated bitmap at %d" pos; let bit_size = u32 data pos in let wc = u32 data (pos + 4) in if bit_size < 0 || words bit_size > words count then fail "bitmap at %d spans %d bit(s), the pack has %d objects" pos bit_size count; if wc < 0 then fail "bitmap at %d declares %d compressed word(s)" pos wc; let len = 8 + (wc * 8) + 4 in if pos + len > String.length data then fail "truncated bitmap at %d" pos; match Ewah.of_bytes (Bytes.of_string (String.sub data pos len)) with | Ok e -> for bit = count to Ewah.length e - 1 do if Ewah.mem e bit then fail "bitmap at %d sets bit %d, the pack has %d objects" pos bit count done; (e, pos + len) | Error (`Msg m) -> fail "bad bitmap chunk at %d: %s" pos m let parse_header ~index data = if String.length data < 32 then fail "too short: %d bytes" (String.length data); if String.sub data 0 4 <> "BITM" then fail "bad magic"; let version, flags = u16x2 data 4 in if version <> 1 then fail "unsupported version %d" version; if flags land flag_full_dag = 0 then fail "bitmap without the full-DAG flag"; let entry_count = u32 data 8 in let count = Pack_index.count index in if entry_count < 0 || entry_count > count then fail "%d bitmap entries, the pack has %d objects" entry_count count; let pack_checksum = Object_hash.of_raw_string (String.sub data 12 20) in if not (Object_hash.equal pack_checksum (Pack_index.pack_checksum index)) then fail "bitmap is for pack %s, index is for pack %s" (Object_hash.to_hex pack_checksum) (Object_hash.to_hex (Pack_index.pack_checksum index)); (flags, entry_count, pack_checksum) let parse_entries ~index ~entry_count data pos = let n = Pack_index.count index in let decoded = Array.make entry_count Ewah.empty in let entries = ref [] in let pos = ref pos in for i = 0 to entry_count - 1 do if !pos + 6 > String.length data then fail "truncated entry %d" i; let commit_pos = u32 data !pos in let xor_offset = Wire.of_string_exn u8_int (String.sub data (!pos + 4) 1) in let flags = Wire.of_string_exn u8_int (String.sub data (!pos + 5) 1) in if commit_pos < 0 || commit_pos >= n then fail "entry %d: commit position %d out of range" i commit_pos; let stored, next = read_ewah ~count:n data (!pos + 6) in pos := next; let bits = if xor_offset = 0 then stored else if xor_offset > i then fail "entry %d: xor offset %d reaches before the first entry" i xor_offset else ewah_xor stored decoded.(i - xor_offset) in decoded.(i) <- bits; entries := { commit = Pack_index.hash_at index commit_pos; bits; flags } :: !entries done; (List.rev !entries, !pos) let of_string ~index data = try let flags, entry_count, pack_checksum = parse_header ~index data in let total = String.length data in let count = Pack_index.count index in let commits, pos = read_ewah ~count data 32 in let trees, pos = read_ewah ~count data pos in let blobs, pos = read_ewah ~count data pos in let tags, pos = read_ewah ~count data pos in let entries, pos = parse_entries ~index ~entry_count data pos in (* Optional sections sit between the entries and the trailing checksum. *) let trailer = total - 20 in let pos = if flags land flag_hash_cache <> 0 then pos + (4 * Pack_index.count index) else pos in if pos > trailer then fail "sections overrun the trailer"; if flags land flag_lookup_table = 0 && pos <> trailer then fail "%d unexpected bytes before the trailer" (trailer - pos); let expected = Hash.SHA1.(to_raw_string (digest_string (String.sub data 0 trailer))) in if String.sub data trailer 20 <> expected then fail "checksum mismatch"; Ok { pack_checksum; commits; trees; blobs; tags; entries } with | Parse_error m -> Error (`Msg m) | Invalid_argument m -> Error (`Msg m) | Wire.Parse_error e -> err_msg "%a" Wire.pp_parse_error e let to_string ~index ~commits ~trees ~blobs ~tags ~entries = try let w_u32 = Wire.to_string i32be_int in let w_u16 = Wire.to_string u16be_int in let w_u8 = Wire.to_string u8_int in let buf = Buffer.create 4096 in Buffer.add_string buf "BITM"; Buffer.add_string buf (w_u16 1); Buffer.add_string buf (w_u16 flag_full_dag); Buffer.add_string buf (w_u32 (List.length entries)); Buffer.add_string buf (Object_hash.to_raw_string (Pack_index.pack_checksum index)); List.iter (fun e -> Buffer.add_bytes buf (Ewah.to_bytes e)) [ commits; trees; blobs; tags ]; List.iter (fun (commit, bits) -> let pos = match Pack_index.index index commit with | Some p -> p | None -> fail "commit %s is not in the pack" (Object_hash.to_hex commit) in Buffer.add_string buf (w_u32 pos); Buffer.add_string buf (w_u8 0); Buffer.add_string buf (w_u8 0); Buffer.add_bytes buf (Ewah.to_bytes bits)) entries; let body = Buffer.contents buf in let trailer = Hash.SHA1.(to_raw_string (digest_string body)) in Ok (body ^ trailer) with Parse_error m -> Error (`Msg m)