2 * $Id: bitmatch.ml,v 1.5 2008-04-01 17:05:37 rjones Exp $
7 (* Enable runtime debug messages. Must also have been enabled
13 exception Construct_failure of string * string * int * int
15 (* A bitstring is simply the data itself (as a string), and the
16 * bitoffset and the bitlength within the string. Note offset/length
17 * are counted in bits, not bytes.
19 type bitstring = string * int * int
21 (* Functions to create and load bitstrings. *)
22 let empty_bitstring = "", 0, 0
24 let make_bitstring len c = String.make ((len+7) lsr 3) c, 0, len
26 let create_bitstring len = make_bitstring len '\000'
28 let bitstring_of_chan chan =
29 let tmpsize = 16384 in
30 let buf = Buffer.create tmpsize in
31 let tmp = String.create tmpsize in
33 while n := input chan tmp 0 tmpsize; !n > 0 do
34 Buffer.add_substring buf tmp 0 !n;
36 Buffer.contents buf, 0, Buffer.length buf lsl 3
38 let bitstring_of_file fname =
39 let chan = open_in_bin fname in
40 let bs = bitstring_of_chan chan in
44 let bitstring_length (_, _, len) = len
46 (*----------------------------------------------------------------------*)
47 (* Extraction functions.
49 * NB: internal functions, called from the generated macros, and
50 * the parameters should have been checked for sanity already).
54 let extract_bitstring data off len flen =
55 (data, off, flen), off+flen, len-flen
57 let extract_remainder data off len =
58 (data, off, len), off+len, 0
60 (* Extract and convert to numeric. A single bit is returned as
61 * a boolean. There are no endianness or signedness considerations.
63 let extract_bit data off len _ = (* final param is always 1 *)
64 let byteoff = off lsr 3 in
65 let bitmask = 1 lsl (7 - (off land 7)) in
66 let b = Char.code data.[byteoff] land bitmask <> 0 in
69 (* Returns 8 bit unsigned aligned bytes from the string.
70 * If the string ends then this returns 0's.
72 let _get_byte data byteoff strlen =
73 if strlen > byteoff then Char.code data.[byteoff] else 0
74 let _get_byte32 data byteoff strlen =
75 if strlen > byteoff then Int32.of_int (Char.code data.[byteoff]) else 0l
76 let _get_byte64 data byteoff strlen =
77 if strlen > byteoff then Int64.of_int (Char.code data.[byteoff]) else 0L
79 (* Extract [2..8] bits. Because the result fits into a single
80 * byte we don't have to worry about endianness, only signedness.
82 let extract_char_unsigned data off len flen =
83 let byteoff = off lsr 3 in
85 (* Optimize the common (byte-aligned) case. *)
86 if off land 7 = 0 then (
87 let byte = Char.code data.[byteoff] in
88 byte lsr (8 - flen), off+flen, len-flen
90 (* Extract the 16 bits at byteoff and byteoff+1 (note that the
91 * second byte might not exist in the original string).
93 let strlen = String.length data in
96 (_get_byte data byteoff strlen lsl 8) +
97 _get_byte data (byteoff+1) strlen in
99 (* Mask off the top bits. *)
100 let bitmask = (1 lsl (16 - (off land 7))) - 1 in
101 let word = word land bitmask in
102 (* Shift right to get rid of the bottom bits. *)
103 let shift = 16 - ((off land 7) + flen) in
104 let word = word lsr shift in
106 word, off+flen, len-flen
109 (* Extract [9..31] bits. We have to consider endianness and signedness. *)
110 let extract_int_be_unsigned data off len flen =
111 let byteoff = off lsr 3 in
113 let strlen = String.length data in
116 (* Optimize the common (byte-aligned) case. *)
117 if off land 7 = 0 then (
119 (_get_byte data byteoff strlen lsl 23) +
120 (_get_byte data (byteoff+1) strlen lsl 15) +
121 (_get_byte data (byteoff+2) strlen lsl 7) +
122 (_get_byte data (byteoff+3) strlen lsr 1) in
124 ) else if flen <= 24 then (
125 (* Extract the 31 bits at byteoff .. byteoff+3. *)
127 (_get_byte data byteoff strlen lsl 23) +
128 (_get_byte data (byteoff+1) strlen lsl 15) +
129 (_get_byte data (byteoff+2) strlen lsl 7) +
130 (_get_byte data (byteoff+3) strlen lsr 1) in
131 (* Mask off the top bits. *)
132 let bitmask = (1 lsl (31 - (off land 7))) - 1 in
133 let word = word land bitmask in
134 (* Shift right to get rid of the bottom bits. *)
135 let shift = 31 - ((off land 7) + flen) in
138 (* Extract the next 31 bits, slow method. *)
140 let c0, off, len = extract_char_unsigned data off len 8 in
141 let c1, off, len = extract_char_unsigned data off len 8 in
142 let c2, off, len = extract_char_unsigned data off len 8 in
143 let c3, off, len = extract_char_unsigned data off len 7 in
144 (c0 lsl 23) + (c1 lsl 15) + (c2 lsl 7) + c3 in
147 word, off+flen, len-flen
149 let _make_int32_be c0 c1 c2 c3 =
153 (Int32.shift_left c0 24)
154 (Int32.shift_left c1 16))
155 (Int32.shift_left c2 8))
158 (* Extract exactly 32 bits. We have to consider endianness and signedness. *)
159 let extract_int32_be_unsigned data off len flen =
160 let byteoff = off lsr 3 in
162 let strlen = String.length data in
165 (* Optimize the common (byte-aligned) case. *)
166 if off land 7 = 0 then (
168 let c0 = _get_byte32 data byteoff strlen in
169 let c1 = _get_byte32 data (byteoff+1) strlen in
170 let c2 = _get_byte32 data (byteoff+2) strlen in
171 let c3 = _get_byte32 data (byteoff+3) strlen in
172 _make_int32_be c0 c1 c2 c3 in
173 Int32.shift_right_logical word (32 - flen)
175 (* Extract the next 32 bits, slow method. *)
177 let c0, off, len = extract_char_unsigned data off len 8 in
178 let c1, off, len = extract_char_unsigned data off len 8 in
179 let c2, off, len = extract_char_unsigned data off len 8 in
180 let c3, _, _ = extract_char_unsigned data off len 8 in
181 let c0 = Int32.of_int c0 in
182 let c1 = Int32.of_int c1 in
183 let c2 = Int32.of_int c2 in
184 let c3 = Int32.of_int c3 in
185 _make_int32_be c0 c1 c2 c3 in
186 Int32.shift_right_logical word (32 - flen)
188 word, off+flen, len-flen
190 let _make_int64_be c0 c1 c2 c3 c4 c5 c6 c7 =
198 (Int64.shift_left c0 56)
199 (Int64.shift_left c1 48))
200 (Int64.shift_left c2 40))
201 (Int64.shift_left c3 32))
202 (Int64.shift_left c4 24))
203 (Int64.shift_left c5 16))
204 (Int64.shift_left c6 8))
207 (* Extract [1..64] bits. We have to consider endianness and signedness. *)
208 let extract_int64_be_unsigned data off len flen =
209 let byteoff = off lsr 3 in
211 let strlen = String.length data in
214 (* Optimize the common (byte-aligned) case. *)
215 if off land 7 = 0 then (
217 let c0 = _get_byte64 data byteoff strlen in
218 let c1 = _get_byte64 data (byteoff+1) strlen in
219 let c2 = _get_byte64 data (byteoff+2) strlen in
220 let c3 = _get_byte64 data (byteoff+3) strlen in
221 let c4 = _get_byte64 data (byteoff+4) strlen in
222 let c5 = _get_byte64 data (byteoff+5) strlen in
223 let c6 = _get_byte64 data (byteoff+6) strlen in
224 let c7 = _get_byte64 data (byteoff+7) strlen in
225 _make_int64_be c0 c1 c2 c3 c4 c5 c6 c7 in
226 Int64.shift_right_logical word (64 - flen)
228 (* Extract the next 64 bits, slow method. *)
230 let c0, off, len = extract_char_unsigned data off len 8 in
231 let c1, off, len = extract_char_unsigned data off len 8 in
232 let c2, off, len = extract_char_unsigned data off len 8 in
233 let c3, off, len = extract_char_unsigned data off len 8 in
234 let c4, off, len = extract_char_unsigned data off len 8 in
235 let c5, off, len = extract_char_unsigned data off len 8 in
236 let c6, off, len = extract_char_unsigned data off len 8 in
237 let c7, _, _ = extract_char_unsigned data off len 8 in
238 let c0 = Int64.of_int c0 in
239 let c1 = Int64.of_int c1 in
240 let c2 = Int64.of_int c2 in
241 let c3 = Int64.of_int c3 in
242 let c4 = Int64.of_int c4 in
243 let c5 = Int64.of_int c5 in
244 let c6 = Int64.of_int c6 in
245 let c7 = Int64.of_int c7 in
246 _make_int64_be c0 c1 c2 c3 c4 c5 c6 c7 in
247 Int64.shift_right_logical word (64 - flen)
249 word, off+flen, len-flen
251 (*----------------------------------------------------------------------*)
252 (* Constructor functions. *)
254 module Buffer = struct
257 mutable len : int; (* Length in bits. *)
258 (* Last byte in the buffer (if len is not aligned). We store
259 * it outside the buffer because buffers aren't mutable.
265 (* XXX We have almost enough information in the generator to
266 * choose a good initial size.
268 { buf = Buffer.create 128; len = 0; last = 0 }
270 let contents { buf = buf; len = len; last = last } =
272 if len land 7 = 0 then
275 Buffer.contents buf ^ (String.make 1 (Char.chr last)) in
278 (* Add exactly 8 bits. *)
279 let add_byte ({ buf = buf; len = len; last = last } as t) byte =
280 if byte < 0 || byte > 255 then invalid_arg "Bitmatch.Buffer.add_byte";
281 let shift = len land 7 in
283 (* Target buffer is byte-aligned. *)
284 Buffer.add_char buf (Char.chr byte)
286 (* Target buffer is unaligned. 'last' is meaningful. *)
287 let first = byte lsr shift in
288 let second = (byte lsl (8 - shift)) land 0xff in
289 Buffer.add_char buf (Char.chr (last lor first));
294 (* Add exactly 1 bit. *)
295 let add_bit ({ buf = buf; len = len; last = last } as t) bit =
296 let shift = 7 - (len land 7) in
298 (* Somewhere in the middle of 'last'. *)
299 t.last <- last lor ((if bit then 1 else 0) lsl shift)
301 (* Just a single spare bit in 'last'. *)
302 let last = last lor if bit then 1 else 0 in
303 Buffer.add_char buf (Char.chr last);
308 (* Add a small number of bits (definitely < 8). This uses a loop
309 * to call add_bit so it's slow.
311 let _add_bits t c slen =
312 if slen < 1 || slen >= 8 then invalid_arg "Bitmatch.Buffer._add_bits";
313 for i = slen-1 downto 0 do
314 let bit = c land (1 lsl i) <> 0 in
318 let add_bits ({ buf = buf; len = len } as t) str slen =
320 if len land 7 = 0 then (
321 if slen land 7 = 0 then
322 (* Common case - everything is byte-aligned. *)
323 Buffer.add_substring buf str 0 (slen lsr 3)
325 (* Target buffer is aligned. Copy whole bytes then leave the
326 * remaining bits in last.
328 let slenbytes = slen lsr 3 in
329 if slenbytes > 0 then Buffer.add_substring buf str 0 slenbytes;
330 t.last <- Char.code str.[slenbytes] lsl (8 - (slen land 7))
334 (* Target buffer is unaligned. Copy whole bytes using
335 * add_byte which knows how to deal with an unaligned
336 * target buffer, then call _add_bits for the remaining < 8 bits.
338 * XXX This is going to be dog-slow.
340 let slenbytes = slen lsr 3 in
341 for i = 0 to slenbytes-1 do
342 let byte = Char.code str.[i] in
345 _add_bits t (Char.code str.[slenbytes]) (slen - (slenbytes lsl 3))
350 (* Construct a single bit. *)
351 let construct_bit buf b _ =
354 (* Construct a field, flen = [2..8]. *)
355 let construct_char_unsigned buf v flen exn =
356 let max_val = 1 lsl flen in
357 if v < 0 || v >= max_val then raise exn;
359 Buffer.add_byte buf v
361 Buffer._add_bits buf v flen
363 (* Generate a mask with the lower 'bits' bits set. *)
365 if bits < 63 then Int64.pred (Int64.shift_left 1L bits)
366 else if bits = 63 then Int64.max_int
367 else if bits = 64 then -1L
368 else invalid_arg "Bitmatch.mask64"
370 (* Construct a field of up to 64 bits. *)
371 let construct_int64_be_unsigned buf v flen exn =
372 (* Check value is within range. *)
373 let m = Int64.lognot (mask64 flen) in
374 if Int64.logand v m <> 0L then raise exn;
377 let rec loop v flen =
379 loop (Int64.shift_right_logical v 8) (flen-8);
380 let lsb = Int64.to_int (Int64.logand v 0xffL) in
381 Buffer.add_byte buf lsb
382 ) else if flen > 0 then (
383 let lsb = Int64.to_int (Int64.logand v (mask64 flen)) in
384 Buffer._add_bits buf lsb flen
389 (*----------------------------------------------------------------------*)
390 (* Display functions. *)
393 let c = Char.code c in
396 let hexdump_bitstring chan (data, off, len) =
400 let linelen = ref 0 in
401 let linechars = String.make 16 ' ' in
403 fprintf chan "00000000 ";
406 let bits = min !len 8 in
407 let byte, off', len' = extract_char_unsigned data !off !len bits in
408 off := off'; len := len';
410 let byte = byte lsl (8-bits) in
411 fprintf chan "%02x " byte;
414 linechars.[!linelen] <-
415 (let c = Char.chr byte in
416 if isprint c then c else '.');
418 if !linelen = 8 then fprintf chan " ";
419 if !linelen = 16 then (
420 fprintf chan " |%s|\n%08x " linechars !count;
422 for i = 0 to 15 do linechars.[i] <- ' ' done
426 if !linelen > 0 then (
427 let skip = (16 - !linelen) * 3 + if !linelen < 8 then 1 else 0 in
428 for i = 0 to skip-1 do fprintf chan " " done;
429 fprintf chan " |%s|\n" linechars