Avoid double quotes when possible.
[emacs.git] / lisp / emacs-lisp / bindat.el
blob1b37f3f772f2dbc6232d5cf0cff379936d6447dd
1 ;;; bindat.el --- binary data structure packing and unpacking.
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006 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 2, or (at your option)
14 ;; 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; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
26 ;;; Commentary:
28 ;; Packing and unpacking of (binary) data structures.
30 ;; The data formats used in binary files and network protocols are
31 ;; often structed data which can be described by a C-style structure
32 ;; such as the one shown below. Using the bindat package, decoding
33 ;; and encoding binary data formats like these is made simple using a
34 ;; structure specification which closely resembles the C style
35 ;; structure declarations.
37 ;; Encoded (binary) data is stored in a unibyte string or vector,
38 ;; while the decoded data is stored in an alist with (FIELD . VALUE)
39 ;; pairs.
41 ;; Example:
43 ;; Consider the following C structures:
45 ;; struct header {
46 ;; unsigned long dest_ip;
47 ;; unsigned long src_ip;
48 ;; unsigned short dest_port;
49 ;; unsigned short src_port;
50 ;; };
52 ;; struct data {
53 ;; unsigned char type;
54 ;; unsigned char opcode;
55 ;; unsigned long length; /* In little endian order */
56 ;; unsigned char id[8]; /* nul-terminated string */
57 ;; unsigned char data[/* (length + 3) & ~3 */];
58 ;; };
60 ;; struct packet {
61 ;; struct header header;
62 ;; unsigned char items;
63 ;; unsigned char filler[3];
64 ;; struct data item[/* items */];
65 ;; };
67 ;; The corresponding Lisp bindat specification looks like this:
69 ;; (setq header-spec
70 ;; '((dest-ip ip)
71 ;; (src-ip ip)
72 ;; (dest-port u16)
73 ;; (src-port u16)))
75 ;; (setq data-spec
76 ;; '((type u8)
77 ;; (opcode u8)
78 ;; (length u16r) ;; little endian order
79 ;; (id strz 8)
80 ;; (data vec (length))
81 ;; (align 4)))
83 ;; (setq packet-spec
84 ;; '((header struct header-spec)
85 ;; (items u8)
86 ;; (fill 3)
87 ;; (item repeat (items)
88 ;; (struct data-spec))))
91 ;; A binary data representation may look like
92 ;; [ 192 168 1 100 192 168 1 101 01 28 21 32 2 0 0 0
93 ;; 2 3 5 0 ?A ?B ?C ?D ?E ?F 0 0 1 2 3 4 5 0 0 0
94 ;; 1 4 7 0 ?B ?C ?D ?E ?F ?G 0 0 6 7 8 9 10 11 12 0 ]
96 ;; The corresponding decoded structure looks like
98 ;; ((header
99 ;; (dest-ip . [192 168 1 100])
100 ;; (src-ip . [192 168 1 101])
101 ;; (dest-port . 284)
102 ;; (src-port . 5408))
103 ;; (items . 2)
104 ;; (item ((data . [1 2 3 4 5])
105 ;; (id . "ABCDEF")
106 ;; (length . 5)
107 ;; (opcode . 3)
108 ;; (type . 2))
109 ;; ((data . [6 7 8 9 10 11 12])
110 ;; (id . "BCDEFG")
111 ;; (length . 7)
112 ;; (opcode . 4)
113 ;; (type . 1))))
115 ;; To access a specific value in this structure, use the function
116 ;; bindat-get-field with the structure as first arg followed by a list
117 ;; of field names and array indexes, e.g. using the data above,
118 ;; (bindat-get-field decoded-structure 'item 1 'id)
119 ;; returns "BCDEFG".
121 ;; Binary Data Structure Specification Format
122 ;; ------------------------------------------
124 ;; The data specification is formatted as follows:
126 ;; SPEC ::= ( ITEM... )
128 ;; ITEM ::= ( [FIELD] TYPE )
129 ;; | ( [FIELD] eval FORM ) -- eval FORM for side-effect only
130 ;; | ( [FIELD] fill LEN ) -- skip LEN bytes
131 ;; | ( [FIELD] align LEN ) -- skip to next multiple of LEN bytes
132 ;; | ( [FIELD] struct SPEC_NAME )
133 ;; | ( [FIELD] union TAG_VAL (TAG SPEC)... [(t SPEC)] )
134 ;; | ( [FIELD] repeat COUNT ITEM... )
136 ;; -- In (eval EXPR), the value of the last field is available in
137 ;; the dynamically bound variable `last'.
139 ;; TYPE ::= ( eval EXPR ) -- interpret result as TYPE
140 ;; | u8 | byte -- length 1
141 ;; | u16 | word | short -- length 2, network byte order
142 ;; | u24 -- 3-byte value
143 ;; | u32 | dword | long -- length 4, network byte order
144 ;; | u16r | u24r | u32r -- little endian byte order.
145 ;; | str LEN -- LEN byte string
146 ;; | strz LEN -- LEN byte (zero-terminated) string
147 ;; | vec LEN -- LEN byte vector
148 ;; | ip -- 4 byte vector
149 ;; | bits LEN -- List with bits set in LEN bytes.
151 ;; -- Note: 32 bit values may be limited by emacs' INTEGER
152 ;; implementation limits.
154 ;; -- Example: `bits 2' will unpack 0x28 0x1c to (2 3 4 11 13)
155 ;; and 0x1c 0x28 to (3 5 10 11 12).
157 ;; FIELD ::= ( eval EXPR ) -- use result as NAME
158 ;; | NAME
160 ;; LEN ::= ARG
161 ;; | <omitted> | nil -- LEN = 1
164 ;; TAG_VAL ::= ARG
166 ;; TAG ::= LISP_CONSTANT
167 ;; | ( eval EXPR ) -- return non-nil if tag match;
168 ;; current TAG_VAL in `tag'.
170 ;; ARG ::= ( eval EXPR ) -- interpret result as ARG
171 ;; | INTEGER_CONSTANT
172 ;; | DEREF
174 ;; DEREF ::= ( [NAME | INTEGER]... ) -- Field NAME or Array index relative
175 ;; to current structure spec.
176 ;; -- see bindat-get-field
178 ;; A `union' specification
179 ;; ([FIELD] union TAG_VAL (TAG SPEC) ... [(t SPEC)])
180 ;; is interpreted by evalling TAG_VAL and then comparing that to
181 ;; each TAG using equal; if a match is found, the corresponding SPEC
182 ;; is used.
183 ;; If TAG is a form (eval EXPR), EXPR is evalled with `tag' bound to the
184 ;; value of TAG_VAL; the corresponding SPEC is used if the result is non-nil.
185 ;; Finally, if TAG is t, the corresponding SPEC is used unconditionally.
187 ;; An `eval' specification
188 ;; ([FIELD] eval FORM)
189 ;; is interpreted by evalling FORM for its side effects only.
190 ;; If FIELD is specified, the value is bound to that field.
191 ;; The FORM may access and update `bindat-raw' and `bindat-idx' (see `bindat-unpack').
193 ;;; Code:
195 ;; Helper functions for structure unpacking.
196 ;; Relies on dynamic binding of BINDAT-RAW and BINDAT-IDX
198 (defvar bindat-raw)
199 (defvar bindat-idx)
201 (defun bindat--unpack-u8 ()
202 (prog1
203 (aref bindat-raw bindat-idx)
204 (setq bindat-idx (1+ bindat-idx))))
206 (defun bindat--unpack-u16 ()
207 (let* ((a (bindat--unpack-u8)) (b (bindat--unpack-u8)))
208 (logior (lsh a 8) b)))
210 (defun bindat--unpack-u24 ()
211 (let* ((a (bindat--unpack-u16)) (b (bindat--unpack-u8)))
212 (logior (lsh a 8) b)))
214 (defun bindat--unpack-u32 ()
215 (let* ((a (bindat--unpack-u16)) (b (bindat--unpack-u16)))
216 (logior (lsh a 16) b)))
218 (defun bindat--unpack-u16r ()
219 (let* ((a (bindat--unpack-u8)) (b (bindat--unpack-u8)))
220 (logior a (lsh b 8))))
222 (defun bindat--unpack-u24r ()
223 (let* ((a (bindat--unpack-u16r)) (b (bindat--unpack-u8)))
224 (logior a (lsh b 16))))
226 (defun bindat--unpack-u32r ()
227 (let* ((a (bindat--unpack-u16r)) (b (bindat--unpack-u16r)))
228 (logior a (lsh b 16))))
230 (defun bindat--unpack-item (type len)
231 (if (eq type 'ip)
232 (setq type 'vec len 4))
233 (cond
234 ((memq type '(u8 byte))
235 (bindat--unpack-u8))
236 ((memq type '(u16 word short))
237 (bindat--unpack-u16))
238 ((eq type 'u24)
239 (bindat--unpack-u24))
240 ((memq type '(u32 dword long))
241 (bindat--unpack-u32))
242 ((eq type 'u16r)
243 (bindat--unpack-u16r))
244 ((eq type 'u24r)
245 (bindat--unpack-u24r))
246 ((eq type 'u32r)
247 (bindat--unpack-u32r))
248 ((eq type 'bits)
249 (let ((bits nil) (bnum (1- (* 8 len))) j m)
250 (while (>= bnum 0)
251 (if (= (setq m (bindat--unpack-u8)) 0)
252 (setq bnum (- bnum 8))
253 (setq j 128)
254 (while (> j 0)
255 (if (/= 0 (logand m j))
256 (setq bits (cons bnum bits)))
257 (setq bnum (1- bnum)
258 j (lsh j -1)))))
259 bits))
260 ((eq type 'str)
261 (let ((s (substring bindat-raw bindat-idx (+ bindat-idx len))))
262 (setq bindat-idx (+ bindat-idx len))
263 (if (stringp s) s
264 (string-make-unibyte (concat s)))))
265 ((eq type 'strz)
266 (let ((i 0) s)
267 (while (and (< i len) (/= (aref bindat-raw (+ bindat-idx i)) 0))
268 (setq i (1+ i)))
269 (setq s (substring bindat-raw bindat-idx (+ bindat-idx i)))
270 (setq bindat-idx (+ bindat-idx len))
271 (if (stringp s) s
272 (string-make-unibyte (concat s)))))
273 ((eq type 'vec)
274 (let ((v (make-vector len 0)) (i 0))
275 (while (< i len)
276 (aset v i (bindat--unpack-u8))
277 (setq i (1+ i)))
279 (t nil)))
281 (defun bindat--unpack-group (spec)
282 (let (struct last)
283 (while spec
284 (let* ((item (car spec))
285 (field (car item))
286 (type (nth 1 item))
287 (len (nth 2 item))
288 (tail 3)
289 data)
290 (setq spec (cdr spec))
291 (if (and (consp field) (eq (car field) 'eval))
292 (setq field (eval (car (cdr field)))))
293 (if (and type (consp type) (eq (car type) 'eval))
294 (setq type (eval (car (cdr type)))))
295 (if (and len (consp len) (eq (car len) 'eval))
296 (setq len (eval (car (cdr len)))))
297 (if (memq field '(eval fill align struct union))
298 (setq tail 2
299 len type
300 type field
301 field nil))
302 (if (and (consp len) (not (eq type 'eval)))
303 (setq len (apply 'bindat-get-field struct len)))
304 (if (not len)
305 (setq len 1))
306 (cond
307 ((eq type 'eval)
308 (if field
309 (setq data (eval len))
310 (eval len)))
311 ((eq type 'fill)
312 (setq bindat-idx (+ bindat-idx len)))
313 ((eq type 'align)
314 (while (/= (% bindat-idx len) 0)
315 (setq bindat-idx (1+ bindat-idx))))
316 ((eq type 'struct)
317 (setq data (bindat--unpack-group (eval len))))
318 ((eq type 'repeat)
319 (let ((index 0))
320 (while (< index len)
321 (setq data (cons (bindat--unpack-group (nthcdr tail item)) data))
322 (setq index (1+ index)))
323 (setq data (nreverse data))))
324 ((eq type 'union)
325 (let ((tag len) (cases (nthcdr tail item)) case cc)
326 (while cases
327 (setq case (car cases)
328 cases (cdr cases)
329 cc (car case))
330 (if (or (equal cc tag) (equal cc t)
331 (and (consp cc) (eval cc)))
332 (setq data (bindat--unpack-group (cdr case))
333 cases nil)))))
335 (setq data (bindat--unpack-item type len)
336 last data)))
337 (if data
338 (if field
339 (setq struct (cons (cons field data) struct))
340 (setq struct (append data struct))))))
341 struct))
343 (defun bindat-unpack (spec bindat-raw &optional bindat-idx)
344 "Return structured data according to SPEC for binary data in BINDAT-RAW.
345 BINDAT-RAW is a unibyte string or vector. Optional third arg BINDAT-IDX specifies
346 the starting offset in BINDAT-RAW."
347 (when (multibyte-string-p bindat-raw)
348 (error "String is multibyte"))
349 (unless bindat-idx (setq bindat-idx 0))
350 (bindat--unpack-group spec))
352 (defun bindat-get-field (struct &rest field)
353 "In structured data STRUCT, return value of field named FIELD.
354 If multiple field names are specified, use the field names to
355 lookup nested sub-structures in STRUCT, corresponding to the
356 C-language syntax STRUCT.FIELD1.FIELD2.FIELD3...
357 An integer value in the field list is taken as an array index,
358 e.g. corresponding to STRUCT.FIELD1[INDEX2].FIELD3..."
359 (while (and struct field)
360 (setq struct (if (integerp (car field))
361 (nth (car field) struct)
362 (let ((val (assq (car field) struct)))
363 (if (consp val) (cdr val)))))
364 (setq field (cdr field)))
365 struct)
368 ;; Calculate bindat-raw length of structured data
370 (defvar bindat--fixed-length-alist
371 '((u8 . 1) (byte . 1)
372 (u16 . 2) (u16r . 2) (word . 2) (short . 2)
373 (u24 . 3) (u24r . 3)
374 (u32 . 4) (u32r . 4) (dword . 4) (long . 4)
375 (ip . 4)))
377 (defun bindat--length-group (struct spec)
378 (let (last)
379 (while spec
380 (let* ((item (car spec))
381 (field (car item))
382 (type (nth 1 item))
383 (len (nth 2 item))
384 (tail 3))
385 (setq spec (cdr spec))
386 (if (and (consp field) (eq (car field) 'eval))
387 (setq field (eval (car (cdr field)))))
388 (if (and type (consp type) (eq (car type) 'eval))
389 (setq type (eval (car (cdr type)))))
390 (if (and len (consp len) (eq (car len) 'eval))
391 (setq len (eval (car (cdr len)))))
392 (if (memq field '(eval fill align struct union))
393 (setq tail 2
394 len type
395 type field
396 field nil))
397 (if (and (consp len) (not (eq type 'eval)))
398 (setq len (apply 'bindat-get-field struct len)))
399 (if (not len)
400 (setq len 1))
401 (cond
402 ((eq type 'eval)
403 (if field
404 (setq struct (cons (cons field (eval len)) struct))
405 (eval len)))
406 ((eq type 'fill)
407 (setq bindat-idx (+ bindat-idx len)))
408 ((eq type 'align)
409 (while (/= (% bindat-idx len) 0)
410 (setq bindat-idx (1+ bindat-idx))))
411 ((eq type 'struct)
412 (bindat--length-group
413 (if field (bindat-get-field struct field) struct) (eval len)))
414 ((eq type 'repeat)
415 (let ((index 0))
416 (while (< index len)
417 (bindat--length-group
418 (nth index (bindat-get-field struct field))
419 (nthcdr tail item))
420 (setq index (1+ index)))))
421 ((eq type 'union)
422 (let ((tag len) (cases (nthcdr tail item)) case cc)
423 (while cases
424 (setq case (car cases)
425 cases (cdr cases)
426 cc (car case))
427 (if (or (equal cc tag) (equal cc t)
428 (and (consp cc) (eval cc)))
429 (progn
430 (bindat--length-group struct (cdr case))
431 (setq cases nil))))))
433 (if (setq type (assq type bindat--fixed-length-alist))
434 (setq len (cdr type)))
435 (if field
436 (setq last (bindat-get-field struct field)))
437 (setq bindat-idx (+ bindat-idx len))))))))
439 (defun bindat-length (spec struct)
440 "Calculate bindat-raw length for STRUCT according to bindat SPEC."
441 (let ((bindat-idx 0))
442 (bindat--length-group struct spec)
443 bindat-idx))
446 ;; Pack structured data into bindat-raw
448 (defun bindat--pack-u8 (v)
449 (aset bindat-raw bindat-idx (logand v 255))
450 (setq bindat-idx (1+ bindat-idx)))
452 (defun bindat--pack-u16 (v)
453 (aset bindat-raw bindat-idx (logand (lsh v -8) 255))
454 (aset bindat-raw (1+ bindat-idx) (logand v 255))
455 (setq bindat-idx (+ bindat-idx 2)))
457 (defun bindat--pack-u24 (v)
458 (bindat--pack-u8 (lsh v -16))
459 (bindat--pack-u16 v))
461 (defun bindat--pack-u32 (v)
462 (bindat--pack-u16 (lsh v -16))
463 (bindat--pack-u16 v))
465 (defun bindat--pack-u16r (v)
466 (aset bindat-raw (1+ bindat-idx) (logand (lsh v -8) 255))
467 (aset bindat-raw bindat-idx (logand v 255))
468 (setq bindat-idx (+ bindat-idx 2)))
470 (defun bindat--pack-u24r (v)
471 (bindat--pack-u16r v)
472 (bindat--pack-u8 (lsh v -16)))
474 (defun bindat--pack-u32r (v)
475 (bindat--pack-u16r v)
476 (bindat--pack-u16r (lsh v -16)))
478 (defun bindat--pack-item (v type len)
479 (if (eq type 'ip)
480 (setq type 'vec len 4))
481 (cond
482 ((null v)
483 (setq bindat-idx (+ bindat-idx len)))
484 ((memq type '(u8 byte))
485 (bindat--pack-u8 v))
486 ((memq type '(u16 word short))
487 (bindat--pack-u16 v))
488 ((eq type 'u24)
489 (bindat--pack-u24 v))
490 ((memq type '(u32 dword long))
491 (bindat--pack-u32 v))
492 ((eq type 'u16r)
493 (bindat--pack-u16r v))
494 ((eq type 'u24r)
495 (bindat--pack-u24r v))
496 ((eq type 'u32r)
497 (bindat--pack-u32r v))
498 ((eq type 'bits)
499 (let ((bnum (1- (* 8 len))) j m)
500 (while (>= bnum 0)
501 (setq m 0)
502 (if (null v)
503 (setq bnum (- bnum 8))
504 (setq j 128)
505 (while (> j 0)
506 (if (memq bnum v)
507 (setq m (logior m j)))
508 (setq bnum (1- bnum)
509 j (lsh j -1))))
510 (bindat--pack-u8 m))))
511 ((memq type '(str strz vec))
512 (let ((l (length v)) (i 0))
513 (if (> l len) (setq l len))
514 (while (< i l)
515 (aset bindat-raw (+ bindat-idx i) (aref v i))
516 (setq i (1+ i)))
517 (setq bindat-idx (+ bindat-idx len))))
519 (setq bindat-idx (+ bindat-idx len)))))
521 (defun bindat--pack-group (struct spec)
522 (let (last)
523 (while spec
524 (let* ((item (car spec))
525 (field (car item))
526 (type (nth 1 item))
527 (len (nth 2 item))
528 (tail 3))
529 (setq spec (cdr spec))
530 (if (and (consp field) (eq (car field) 'eval))
531 (setq field (eval (car (cdr field)))))
532 (if (and type (consp type) (eq (car type) 'eval))
533 (setq type (eval (car (cdr type)))))
534 (if (and len (consp len) (eq (car len) 'eval))
535 (setq len (eval (car (cdr len)))))
536 (if (memq field '(eval fill align struct union))
537 (setq tail 2
538 len type
539 type field
540 field nil))
541 (if (and (consp len) (not (eq type 'eval)))
542 (setq len (apply 'bindat-get-field struct len)))
543 (if (not len)
544 (setq len 1))
545 (cond
546 ((eq type 'eval)
547 (if field
548 (setq struct (cons (cons field (eval len)) struct))
549 (eval len)))
550 ((eq type 'fill)
551 (setq bindat-idx (+ bindat-idx len)))
552 ((eq type 'align)
553 (while (/= (% bindat-idx len) 0)
554 (setq bindat-idx (1+ bindat-idx))))
555 ((eq type 'struct)
556 (bindat--pack-group
557 (if field (bindat-get-field struct field) struct) (eval len)))
558 ((eq type 'repeat)
559 (let ((index 0))
560 (while (< index len)
561 (bindat--pack-group
562 (nth index (bindat-get-field struct field))
563 (nthcdr tail item))
564 (setq index (1+ index)))))
565 ((eq type 'union)
566 (let ((tag len) (cases (nthcdr tail item)) case cc)
567 (while cases
568 (setq case (car cases)
569 cases (cdr cases)
570 cc (car case))
571 (if (or (equal cc tag) (equal cc t)
572 (and (consp cc) (eval cc)))
573 (progn
574 (bindat--pack-group struct (cdr case))
575 (setq cases nil))))))
577 (setq last (bindat-get-field struct field))
578 (bindat--pack-item last type len)
579 ))))))
581 (defun bindat-pack (spec struct &optional bindat-raw bindat-idx)
582 "Return binary data packed according to SPEC for structured data STRUCT.
583 Optional third arg BINDAT-RAW is a pre-allocated unibyte string or vector to
584 pack into.
585 Optional fourth arg BINDAT-IDX is the starting offset into BINDAT-RAW."
586 (when (multibyte-string-p bindat-raw)
587 (error "Pre-allocated string is multibyte"))
588 (let ((no-return bindat-raw))
589 (unless bindat-idx (setq bindat-idx 0))
590 (unless bindat-raw
591 (setq bindat-raw (make-vector (+ bindat-idx (bindat-length spec struct)) 0)))
592 (bindat--pack-group struct spec)
593 (if no-return nil (concat bindat-raw))))
596 ;; Misc. format conversions
598 (defun bindat-format-vector (vect fmt sep &optional len)
599 "Format vector VECT using element format FMT and separator SEP.
600 Result is a string with each element of VECT formatted using FMT and
601 separated by the string SEP. If optional fourth arg LEN is given, use
602 only that many elements from VECT."
603 (unless len
604 (setq len (length vect)))
605 (let ((i len) (fmt2 (concat sep fmt)) (s nil))
606 (while (> i 0)
607 (setq i (1- i)
608 s (cons (format (if (= i 0) fmt fmt2) (aref vect i)) s)))
609 (apply 'concat s)))
611 (defun bindat-vector-to-dec (vect &optional sep)
612 "Format vector VECT in decimal format separated by dots.
613 If optional second arg SEP is a string, use that as separator."
614 (bindat-format-vector vect "%d" (if (stringp sep) sep ".")))
616 (defun bindat-vector-to-hex (vect &optional sep)
617 "Format vector VECT in hex format separated by dots.
618 If optional second arg SEP is a string, use that as separator."
619 (bindat-format-vector vect "%02x" (if (stringp sep) sep ":")))
621 (defun bindat-ip-to-string (ip)
622 "Format vector IP as an ip address in dotted notation.
623 The port (if any) is omitted. IP can be a string, as well."
624 (if (vectorp ip)
625 (format-network-address ip t)
626 (format "%d.%d.%d.%d"
627 (aref ip 0) (aref ip 1) (aref ip 2) (aref ip 3))))
629 (provide 'bindat)
631 ;;; arch-tag: 5e6708c3-03e2-4ad7-9885-5041b779c3fb
632 ;;; bindat.el ends here