1 ;;; bindat.el --- binary data structure packing and unpacking.
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Kim F. Storm <storm@cua.dk>
6 ;; Assignment name: struct.el
7 ;; Keywords: comm data processes
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; Packing and unpacking of (binary) data structures.
28 ;; The data formats used in binary files and network protocols are
29 ;; often structed data which can be described by a C-style structure
30 ;; such as the one shown below. Using the bindat package, decoding
31 ;; and encoding binary data formats like these is made simple using a
32 ;; structure specification which closely resembles the C style
33 ;; structure declarations.
35 ;; Encoded (binary) data is stored in a unibyte string or vector,
36 ;; while the decoded data is stored in an alist with (FIELD . VALUE)
41 ;; Consider the following C structures:
44 ;; unsigned long dest_ip;
45 ;; unsigned long src_ip;
46 ;; unsigned short dest_port;
47 ;; unsigned short src_port;
51 ;; unsigned char type;
52 ;; unsigned char opcode;
53 ;; unsigned long length; /* In little endian order */
54 ;; unsigned char id[8]; /* nul-terminated string */
55 ;; unsigned char data[/* (length + 3) & ~3 */];
59 ;; struct header header;
60 ;; unsigned char items;
61 ;; unsigned char filler[3];
62 ;; struct data item[/* items */];
65 ;; The corresponding Lisp bindat specification looks like this:
67 ;; (setq header-bindat-spec
73 ;; (setq data-bindat-spec
76 ;; (length u16r) ;; little endian order
78 ;; (data vec (length))
81 ;; (setq packet-bindat-spec
82 ;; '((header struct header-bindat-spec)
85 ;; (item repeat (items)
86 ;; (struct data-bindat-spec))))
89 ;; A binary data representation may look like
90 ;; [ 192 168 1 100 192 168 1 101 01 28 21 32 2 0 0 0
91 ;; 2 3 5 0 ?A ?B ?C ?D ?E ?F 0 0 1 2 3 4 5 0 0 0
92 ;; 1 4 7 0 ?B ?C ?D ?E ?F ?G 0 0 6 7 8 9 10 11 12 0 ]
94 ;; The corresponding decoded structure looks like
97 ;; (dest-ip . [192 168 1 100])
98 ;; (src-ip . [192 168 1 101])
100 ;; (src-port . 5408))
102 ;; (item ((data . [1 2 3 4 5])
107 ;; ((data . [6 7 8 9 10 11 12])
113 ;; To access a specific value in this structure, use the function
114 ;; bindat-get-field with the structure as first arg followed by a list
115 ;; of field names and array indexes, e.g. using the data above,
116 ;; (bindat-get-field decoded-structure 'item 1 'id)
119 ;; Binary Data Structure Specification Format
120 ;; ------------------------------------------
122 ;; We recommend using names that end in `-bindat-spec'; such names
123 ;; are recognized automatically as "risky" variables.
125 ;; The data specification is formatted as follows:
127 ;; SPEC ::= ( ITEM... )
129 ;; ITEM ::= ( [FIELD] TYPE )
130 ;; | ( [FIELD] eval FORM ) -- eval FORM for side-effect only
131 ;; | ( [FIELD] fill LEN ) -- skip LEN bytes
132 ;; | ( [FIELD] align LEN ) -- skip to next multiple of LEN bytes
133 ;; | ( [FIELD] struct SPEC_NAME )
134 ;; | ( [FIELD] union TAG_VAL (TAG SPEC)... [(t SPEC)] )
135 ;; | ( [FIELD] repeat COUNT ITEM... )
137 ;; -- In (eval EXPR), the value of the last field is available in
138 ;; the dynamically bound variable `last'.
140 ;; TYPE ::= ( eval EXPR ) -- interpret result as TYPE
141 ;; | u8 | byte -- length 1
142 ;; | u16 | word | short -- length 2, network byte order
143 ;; | u24 -- 3-byte value
144 ;; | u32 | dword | long -- length 4, network byte order
145 ;; | u16r | u24r | u32r -- little endian byte order.
146 ;; | str LEN -- LEN byte string
147 ;; | strz LEN -- LEN byte (zero-terminated) string
148 ;; | vec LEN [TYPE] -- vector of LEN items of TYPE (default: u8)
149 ;; | ip -- 4 byte vector
150 ;; | bits LEN -- List with bits set in LEN bytes.
152 ;; -- Note: 32 bit values may be limited by emacs' INTEGER
153 ;; implementation limits.
155 ;; -- Example: `bits 2' will unpack 0x28 0x1c to (2 3 4 11 13)
156 ;; and 0x1c 0x28 to (3 5 10 11 12).
158 ;; FIELD ::= ( eval EXPR ) -- use result as NAME
162 ;; | <omitted> | nil -- LEN = 1
167 ;; TAG ::= LISP_CONSTANT
168 ;; | ( eval EXPR ) -- return non-nil if tag match;
169 ;; current TAG_VAL in `tag'.
171 ;; ARG ::= ( eval EXPR ) -- interpret result as ARG
172 ;; | INTEGER_CONSTANT
175 ;; DEREF ::= ( [NAME | INTEGER]... ) -- Field NAME or Array index relative
176 ;; to current structure spec.
177 ;; -- see bindat-get-field
179 ;; A `union' specification
180 ;; ([FIELD] union TAG_VAL (TAG SPEC) ... [(t SPEC)])
181 ;; is interpreted by evalling TAG_VAL and then comparing that to
182 ;; each TAG using equal; if a match is found, the corresponding SPEC
184 ;; If TAG is a form (eval EXPR), EXPR is evalled with `tag' bound to the
185 ;; value of TAG_VAL; the corresponding SPEC is used if the result is non-nil.
186 ;; Finally, if TAG is t, the corresponding SPEC is used unconditionally.
188 ;; An `eval' specification
189 ;; ([FIELD] eval FORM)
190 ;; is interpreted by evalling FORM for its side effects only.
191 ;; If FIELD is specified, the value is bound to that field.
192 ;; The FORM may access and update `bindat-raw' and `bindat-idx' (see `bindat-unpack').
196 ;; Helper functions for structure unpacking.
197 ;; Relies on dynamic binding of BINDAT-RAW and BINDAT-IDX
202 (defun bindat--unpack-u8 ()
204 (aref bindat-raw bindat-idx
)
205 (setq bindat-idx
(1+ bindat-idx
))))
207 (defun bindat--unpack-u16 ()
208 (logior (lsh (bindat--unpack-u8) 8) (bindat--unpack-u8)))
210 (defun bindat--unpack-u24 ()
211 (logior (lsh (bindat--unpack-u16) 8) (bindat--unpack-u8)))
213 (defun bindat--unpack-u32 ()
214 (logior (lsh (bindat--unpack-u16) 16) (bindat--unpack-u16)))
216 (defun bindat--unpack-u16r ()
217 (logior (bindat--unpack-u8) (lsh (bindat--unpack-u8) 8)))
219 (defun bindat--unpack-u24r ()
220 (logior (bindat--unpack-u16r) (lsh (bindat--unpack-u8) 16)))
222 (defun bindat--unpack-u32r ()
223 (logior (bindat--unpack-u16r) (lsh (bindat--unpack-u16r) 16)))
225 (defun bindat--unpack-item (type len
&optional vectype
)
227 (setq type
'vec len
4))
229 ((memq type
'(u8 byte
))
231 ((memq type
'(u16 word short
))
232 (bindat--unpack-u16))
234 (bindat--unpack-u24))
235 ((memq type
'(u32 dword long
))
236 (bindat--unpack-u32))
238 (bindat--unpack-u16r))
240 (bindat--unpack-u24r))
242 (bindat--unpack-u32r))
244 (let ((bits nil
) (bnum (1- (* 8 len
))) j m
)
246 (if (= (setq m
(bindat--unpack-u8)) 0)
247 (setq bnum
(- bnum
8))
250 (if (/= 0 (logand m j
))
251 (setq bits
(cons bnum bits
)))
256 (let ((s (substring bindat-raw bindat-idx
(+ bindat-idx len
))))
257 (setq bindat-idx
(+ bindat-idx len
))
259 (string-make-unibyte (concat s
)))))
262 (while (and (< i len
) (/= (aref bindat-raw
(+ bindat-idx i
)) 0))
264 (setq s
(substring bindat-raw bindat-idx
(+ bindat-idx i
)))
265 (setq bindat-idx
(+ bindat-idx len
))
267 (string-make-unibyte (concat s
)))))
269 (let ((v (make-vector len
0)) (i 0) (vlen 1))
271 (setq vlen
(nth 1 vectype
)
272 vectype
(nth 2 vectype
))
273 (setq type
(or vectype
'u8
)
276 (aset v i
(bindat--unpack-item type vlen vectype
))
281 (defun bindat--unpack-group (spec)
284 (let* ((item (car spec
))
288 (vectype (and (eq type
'vec
) (nth 3 item
)))
291 (setq spec
(cdr spec
))
292 (if (and (consp field
) (eq (car field
) 'eval
))
293 (setq field
(eval (car (cdr field
)))))
294 (if (and type
(consp type
) (eq (car type
) 'eval
))
295 (setq type
(eval (car (cdr type
)))))
296 (if (and len
(consp len
) (eq (car len
) 'eval
))
297 (setq len
(eval (car (cdr len
)))))
298 (if (memq field
'(eval fill align struct union
))
303 (if (and (consp len
) (not (eq type
'eval
)))
304 (setq len
(apply 'bindat-get-field struct len
)))
310 (setq data
(eval len
))
313 (setq bindat-idx
(+ bindat-idx len
)))
315 (while (/= (% bindat-idx len
) 0)
316 (setq bindat-idx
(1+ bindat-idx
))))
318 (setq data
(bindat--unpack-group (eval len
))))
320 (let ((index 0) (count len
))
321 (while (< index count
)
322 (setq data
(cons (bindat--unpack-group (nthcdr tail item
)) data
))
323 (setq index
(1+ index
)))
324 (setq data
(nreverse data
))))
326 (let ((tag len
) (cases (nthcdr tail item
)) case cc
)
328 (setq case
(car cases
)
331 (if (or (equal cc tag
) (equal cc t
)
332 (and (consp cc
) (eval cc
)))
333 (setq data
(bindat--unpack-group (cdr case
))
336 (setq data
(bindat--unpack-item type len vectype
)
340 (setq struct
(cons (cons field data
) struct
))
341 (setq struct
(append data struct
))))))
344 (defun bindat-unpack (spec bindat-raw
&optional bindat-idx
)
345 "Return structured data according to SPEC for binary data in BINDAT-RAW.
346 BINDAT-RAW is a unibyte string or vector.
347 Optional third arg BINDAT-IDX specifies the starting offset in BINDAT-RAW."
348 (when (multibyte-string-p bindat-raw
)
349 (error "String is multibyte"))
350 (unless bindat-idx
(setq bindat-idx
0))
351 (bindat--unpack-group spec
))
353 (defun bindat-get-field (struct &rest field
)
354 "In structured data STRUCT, return value of field named FIELD.
355 If multiple field names are specified, use the field names to
356 lookup nested sub-structures in STRUCT, corresponding to the
357 C-language syntax STRUCT.FIELD1.FIELD2.FIELD3...
358 An integer value in the field list is taken as an array index,
359 e.g. corresponding to STRUCT.FIELD1[INDEX2].FIELD3..."
360 (while (and struct field
)
361 (setq struct
(if (integerp (car field
))
362 (nth (car field
) struct
)
363 (let ((val (assq (car field
) struct
)))
364 (if (consp val
) (cdr val
)))))
365 (setq field
(cdr field
)))
369 ;; Calculate bindat-raw length of structured data
371 (defvar bindat--fixed-length-alist
372 '((u8 .
1) (byte .
1)
373 (u16 .
2) (u16r .
2) (word .
2) (short .
2)
375 (u32 .
4) (u32r .
4) (dword .
4) (long .
4)
378 (defun bindat--length-group (struct spec
)
381 (let* ((item (car spec
))
385 (vectype (and (eq type
'vec
) (nth 3 item
)))
387 (setq spec
(cdr spec
))
388 (if (and (consp field
) (eq (car field
) 'eval
))
389 (setq field
(eval (car (cdr field
)))))
390 (if (and type
(consp type
) (eq (car type
) 'eval
))
391 (setq type
(eval (car (cdr type
)))))
392 (if (and len
(consp len
) (eq (car len
) 'eval
))
393 (setq len
(eval (car (cdr len
)))))
394 (if (memq field
'(eval fill align struct union
))
399 (if (and (consp len
) (not (eq type
'eval
)))
400 (setq len
(apply 'bindat-get-field struct len
)))
403 (while (eq type
'vec
)
406 (setq len
(* len
(nth 1 vectype
))
407 type
(nth 2 vectype
))
408 (setq type
(or vectype
'u8
)
413 (setq struct
(cons (cons field
(eval len
)) struct
))
416 (setq bindat-idx
(+ bindat-idx len
)))
418 (while (/= (% bindat-idx len
) 0)
419 (setq bindat-idx
(1+ bindat-idx
))))
421 (bindat--length-group
422 (if field
(bindat-get-field struct field
) struct
) (eval len
)))
424 (let ((index 0) (count len
))
425 (while (< index count
)
426 (bindat--length-group
427 (nth index
(bindat-get-field struct field
))
429 (setq index
(1+ index
)))))
431 (let ((tag len
) (cases (nthcdr tail item
)) case cc
)
433 (setq case
(car cases
)
436 (if (or (equal cc tag
) (equal cc t
)
437 (and (consp cc
) (eval cc
)))
439 (bindat--length-group struct
(cdr case
))
440 (setq cases nil
))))))
442 (if (setq type
(assq type bindat--fixed-length-alist
))
443 (setq len
(* len
(cdr type
))))
445 (setq last
(bindat-get-field struct field
)))
446 (setq bindat-idx
(+ bindat-idx len
))))))))
448 (defun bindat-length (spec struct
)
449 "Calculate bindat-raw length for STRUCT according to bindat SPEC."
450 (let ((bindat-idx 0))
451 (bindat--length-group struct spec
)
455 ;; Pack structured data into bindat-raw
457 (defun bindat--pack-u8 (v)
458 (aset bindat-raw bindat-idx
(logand v
255))
459 (setq bindat-idx
(1+ bindat-idx
)))
461 (defun bindat--pack-u16 (v)
462 (aset bindat-raw bindat-idx
(logand (lsh v -
8) 255))
463 (aset bindat-raw
(1+ bindat-idx
) (logand v
255))
464 (setq bindat-idx
(+ bindat-idx
2)))
466 (defun bindat--pack-u24 (v)
467 (bindat--pack-u8 (lsh v -
16))
468 (bindat--pack-u16 v
))
470 (defun bindat--pack-u32 (v)
471 (bindat--pack-u16 (lsh v -
16))
472 (bindat--pack-u16 v
))
474 (defun bindat--pack-u16r (v)
475 (aset bindat-raw
(1+ bindat-idx
) (logand (lsh v -
8) 255))
476 (aset bindat-raw bindat-idx
(logand v
255))
477 (setq bindat-idx
(+ bindat-idx
2)))
479 (defun bindat--pack-u24r (v)
480 (bindat--pack-u16r v
)
481 (bindat--pack-u8 (lsh v -
16)))
483 (defun bindat--pack-u32r (v)
484 (bindat--pack-u16r v
)
485 (bindat--pack-u16r (lsh v -
16)))
487 (defun bindat--pack-item (v type len
&optional vectype
)
489 (setq type
'vec len
4))
492 (setq bindat-idx
(+ bindat-idx len
)))
493 ((memq type
'(u8 byte
))
495 ((memq type
'(u16 word short
))
496 (bindat--pack-u16 v
))
498 (bindat--pack-u24 v
))
499 ((memq type
'(u32 dword long
))
500 (bindat--pack-u32 v
))
502 (bindat--pack-u16r v
))
504 (bindat--pack-u24r v
))
506 (bindat--pack-u32r v
))
508 (let ((bnum (1- (* 8 len
))) j m
)
512 (setq bnum
(- bnum
8))
516 (setq m
(logior m j
)))
519 (bindat--pack-u8 m
))))
520 ((memq type
'(str strz
))
521 (let ((l (length v
)) (i 0))
522 (if (> l len
) (setq l len
))
524 (aset bindat-raw
(+ bindat-idx i
) (aref v i
))
526 (setq bindat-idx
(+ bindat-idx len
))))
528 (let ((l (length v
)) (i 0) (vlen 1))
530 (setq vlen
(nth 1 vectype
)
531 vectype
(nth 2 vectype
))
532 (setq type
(or vectype
'u8
)
534 (if (> l len
) (setq l len
))
536 (bindat--pack-item (aref v i
) type vlen vectype
)
539 (setq bindat-idx
(+ bindat-idx len
)))))
541 (defun bindat--pack-group (struct spec
)
544 (let* ((item (car spec
))
548 (vectype (and (eq type
'vec
) (nth 3 item
)))
550 (setq spec
(cdr spec
))
551 (if (and (consp field
) (eq (car field
) 'eval
))
552 (setq field
(eval (car (cdr field
)))))
553 (if (and type
(consp type
) (eq (car type
) 'eval
))
554 (setq type
(eval (car (cdr type
)))))
555 (if (and len
(consp len
) (eq (car len
) 'eval
))
556 (setq len
(eval (car (cdr len
)))))
557 (if (memq field
'(eval fill align struct union
))
562 (if (and (consp len
) (not (eq type
'eval
)))
563 (setq len
(apply 'bindat-get-field struct len
)))
569 (setq struct
(cons (cons field
(eval len
)) struct
))
572 (setq bindat-idx
(+ bindat-idx len
)))
574 (while (/= (% bindat-idx len
) 0)
575 (setq bindat-idx
(1+ bindat-idx
))))
578 (if field
(bindat-get-field struct field
) struct
) (eval len
)))
580 (let ((index 0) (count len
))
581 (while (< index count
)
583 (nth index
(bindat-get-field struct field
))
585 (setq index
(1+ index
)))))
587 (let ((tag len
) (cases (nthcdr tail item
)) case cc
)
589 (setq case
(car cases
)
592 (if (or (equal cc tag
) (equal cc t
)
593 (and (consp cc
) (eval cc
)))
595 (bindat--pack-group struct
(cdr case
))
596 (setq cases nil
))))))
598 (setq last
(bindat-get-field struct field
))
599 (bindat--pack-item last type len vectype
)
602 (defun bindat-pack (spec struct
&optional bindat-raw bindat-idx
)
603 "Return binary data packed according to SPEC for structured data STRUCT.
604 Optional third arg BINDAT-RAW is a pre-allocated unibyte string or vector to
606 Optional fourth arg BINDAT-IDX is the starting offset into BINDAT-RAW."
607 (when (multibyte-string-p bindat-raw
)
608 (error "Pre-allocated string is multibyte"))
609 (let ((no-return bindat-raw
))
610 (unless bindat-idx
(setq bindat-idx
0))
612 (setq bindat-raw
(make-string (+ bindat-idx
(bindat-length spec struct
)) 0)))
613 (bindat--pack-group struct spec
)
614 (if no-return nil bindat-raw
)))
617 ;; Misc. format conversions
619 (defun bindat-format-vector (vect fmt sep
&optional len
)
620 "Format vector VECT using element format FMT and separator SEP.
621 Result is a string with each element of VECT formatted using FMT and
622 separated by the string SEP. If optional fourth arg LEN is given, use
623 only that many elements from VECT."
625 (setq len
(length vect
)))
626 (let ((i len
) (fmt2 (concat sep fmt
)) (s nil
))
629 s
(cons (format (if (= i
0) fmt fmt2
) (aref vect i
)) s
)))
632 (defun bindat-vector-to-dec (vect &optional sep
)
633 "Format vector VECT in decimal format separated by dots.
634 If optional second arg SEP is a string, use that as separator."
635 (bindat-format-vector vect
"%d" (if (stringp sep
) sep
".")))
637 (defun bindat-vector-to-hex (vect &optional sep
)
638 "Format vector VECT in hex format separated by dots.
639 If optional second arg SEP is a string, use that as separator."
640 (bindat-format-vector vect
"%02x" (if (stringp sep
) sep
":")))
642 (defun bindat-ip-to-string (ip)
643 "Format vector IP as an ip address in dotted notation.
644 The port (if any) is omitted. IP can be a string, as well."
646 (format-network-address ip t
)
647 (format "%d.%d.%d.%d"
648 (aref ip
0) (aref ip
1) (aref ip
2) (aref ip
3))))
652 ;; arch-tag: 5e6708c3-03e2-4ad7-9885-5041b779c3fb
653 ;;; bindat.el ends here