]>
git.zerfleddert.de Git - proxmark3-svn/blob - client/reveng/poly.c
2 * Greg Cook, 9/Apr/2015
5 /* CRC RevEng, an arbitrary-precision CRC calculator and algorithm finder
6 * Copyright (C) 2010, 2011, 2012, 2013, 2014, 2015 Gregory Cook
8 * This file is part of CRC RevEng.
10 * CRC RevEng is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * CRC RevEng is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with CRC RevEng. If not, see <http://www.gnu.org/licenses/>.
24 /* 2015-04-03: added direct mode to strtop()
25 * 2014-01-11: added LOFS(), RNDUP()
26 * 2013-09-16: SIZE(), IDX(), OFS() macros bitshift if BMP_POF2
27 * 2013-02-07: conditional non-2^n fix, pmpar() return mask constant type
28 * 2013-01-17: fixed pfirst(), plast() for non-2^n BMP_BIT
29 * 2012-07-16: added pident()
30 * 2012-05-23: added pmpar()
31 * 2012-03-03: internal lookup tables stored better
32 * 2012-03-02: fixed full-width masking in filtop()
33 * 2011-09-06: added prevch()
34 * 2011-08-27: fixed zero test in piter()
35 * 2011-01-17: fixed ANSI C warnings, uses bmp_t type
36 * 2011-01-15: palloc() and praloc() gracefully handle lengths slightly
38 * 2011-01-15: strtop() error on invalid argument. pkchop() special case
39 * when argument all zeroes
40 * 2011-01-14: added pkchop()
41 * 2011-01-04: fixed bogus final length calculation in wide pcrc()
42 * 2011-01-02: faster, more robust prcp()
43 * 2011-01-01: commented functions, full const declarations, all-LUT rev()
44 * 2010-12-26: renamed CRC RevEng
45 * 2010-12-18: removed pmods(), finished pcrc(), added piter()
46 * 2010-12-17: roughed out pcrc(). difficult, etiam aberat musa heri :(
47 * 2010-12-15: added psnorm(), psncmp(); optimised pnorm(); fix to praloc()
48 * 2010-12-14: strtop() resets count between passes
49 * 2010-12-12: added pright()
50 * 2010-12-11: filtop won't read more than length bits
51 * 2010-12-10: finished filtop. 26 public functions
52 * 2010-12-05: finished strtop, pxsubs; unit tests
53 * 2010-12-02: project started
56 /* Note: WELL-FORMED poly_t objects have a valid bitmap pointer pointing
57 * to a malloc()-ed array of at least as many bits as stated in its
58 * length field. Any poly_t with a length of 0 is also a WELL-FORMED
59 * poly_t (whatever value the bitmap pointer has.)
60 * All poly_t objects passed to and from functions must be WELL-FORMED
61 * unless otherwise stated.
63 * CLEAN (or CANONICAL) poly_t objects are WELL-FORMED objects in which
64 * all spare bits in the bitmap word containing the last bit are zero.
65 * (Any excess allocated words will not be accessed.)
67 * SEMI-NORMALISED poly_t objects are CLEAN objects in which the last
68 * bit, at position (length - 1), is one.
70 * NORMALISED poly_t objects are SEMI-NORMALISED objects in which the
73 * pfree() should be called on every poly_t object (including
74 * those returned by functions) after its last use.
75 * As always, free() should be called on every malloc()-ed string after
84 static bmp_t
getwrd(const poly_t poly
, unsigned long iter
);
85 static bmp_t
rev(bmp_t accu
, int bits
);
86 static void prhex(char **spp
, bmp_t bits
, int flags
, int bperhx
);
88 static const poly_t pzero
= PZERO
;
90 /* word number (0..m-1) of var'th bit (0..n-1) */
92 # define IDX(var) ((var) >> BMP_POF2)
94 # define IDX(var) ((var) / BMP_BIT)
97 /* size of polynomial with var bits */
99 # define SIZE(var) ((BMP_BIT - 1UL + (var)) >> BMP_POF2)
101 # define SIZE(var) ((BMP_BIT - 1UL + (var)) / BMP_BIT)
104 /* polynomial length rounded up to BMP_BIT */
106 # define RNDUP(var) (~(BMP_BIT - 1UL) & (BMP_BIT - 1UL + (var)))
108 # define RNDUP(var) ((BMP_BIT - (var) % BMP_BIT) % BMP_BIT + (var))
111 /* bit offset (0..BMP_BIT-1, 0 = LSB) of var'th bit (0..n-1) */
113 # define OFS(var) ((int) ((BMP_BIT - 1UL) & ~(var)))
115 # define OFS(var) ((int) (BMP_BIT - 1UL - (var) % BMP_BIT))
118 /* bit offset (0..BMP_BIT-1, 0 = MSB) of var'th bit (0..n-1) */
120 # define LOFS(var) ((int) ((BMP_BIT - 1UL) & (var)))
122 # define LOFS(var) ((int) ((var) % BMP_BIT))
126 filtop(FILE *input
, unsigned long length
, int flags
, int bperhx
) {
127 /* reads binary data from input into a poly_t until EOF or until
128 * length bits are read. Characters are read until
129 * ceil(bperhx / CHAR_BIT) bits are collected; if P_LTLBYT is
130 * set in flags then the first character contains the LSB,
131 * otherwise the last one does. The least significant bperhx
132 * bits are taken, reflected (if P_REFIN) and appended to the
133 * result, then more characters are read. The maximum number of
135 * floor(length / bperhx) * ceil(bperhx / * CHAR_BIT).
136 * The returned poly_t is CLEAN.
139 bmp_t accu
= BMP_C(0);
140 bmp_t mask
= bperhx
== BMP_BIT
? ~BMP_C(0) : (BMP_C(1) << bperhx
) - BMP_C(1);
141 unsigned long iter
= 0UL, idx
;
142 int cmask
= ~(~0 << CHAR_BIT
), c
;
145 if(bperhx
== 0) return(poly
);
147 length
-= length
% bperhx
;
148 palloc(&poly
, length
); /* >= 0 */
150 while(iter
< length
&& (c
= fgetc(input
)) != EOF
) {
152 accu
|= (bmp_t
) (c
& cmask
) << count
;
154 accu
= (accu
<< CHAR_BIT
) | (bmp_t
) (c
& cmask
);
156 if(count
>= bperhx
) {
157 /* the low bperhx bits of accu contain bits of the poly.*/
161 accu
= rev(accu
, bperhx
);
164 /* iter >= bperhx > 0 */
165 idx
= IDX(iter
- 1UL);
166 ofs
= OFS(iter
- 1UL);
167 poly
.bitmap
[idx
] |= accu
<< ofs
;
168 if(ofs
+ bperhx
> BMP_BIT
) {
169 poly
.bitmap
[idx
-1] |= accu
>> (BMP_BIT
- ofs
);
171 accu
= BMP_C(0); /* only needed for P_LTLBYT */
179 strtop(const char *string
, int flags
, int bperhx
) {
180 /* Converts a hex or character string to a poly_t.
181 * Each character is converted to a hex nibble yielding 4 bits
182 * unless P_DIRECT, when each character yields CHAR_BIT bits.
183 * Nibbles and characters are accumulated left-to-right
184 * unless P_DIRECT && P_LTLBYT, when they are accumulated
185 * right-to-left without reflection.
186 * As soon as at least bperhx bits are accumulated, the
187 * rightmost bperhx bits are reflected (if P_REFIN)
188 * and appended to the poly. When !P_DIRECT:
189 * bperhx=8 reads hex nibbles in pairs
190 * bperhx=7 reads hex nibbles in pairs and discards
192 * bperhx=4 reads hex nibbles singly
193 * bperhx=3 reads octal
194 * bperhx=1 reads longhand binary
195 * in theory if !P_REFIN, bperhx can be any multiple of 4
197 * The returned poly_t is CLEAN.
200 /* make two passes, one to determine the poly size
201 * one to populate the bitmap
203 unsigned long length
= 1UL, idx
;
205 bmp_t mask
= bperhx
== BMP_BIT
? ~BMP_C(0) : (BMP_C(1) << bperhx
) - BMP_C(1);
206 int pass
, count
, ofs
;
207 int cmask
= ~(~0 << CHAR_BIT
), c
;
211 if(bperhx
> BMP_BIT
|| bperhx
<= 0 || string
== NULL
|| *string
== '\0')
214 for(pass
=0; pass
<2 && length
> 0UL; ++pass
) {
220 if(flags
& P_DIRECT
) {
222 accu
|= (bmp_t
) (c
& cmask
) << count
;
224 accu
= (accu
<< CHAR_BIT
) | (bmp_t
) (c
& cmask
);
227 if(c
== ' ' || c
== '\t' || c
== '\r' || c
== '\n') continue;
241 accu
|= (bmp_t
) c
- '0';
268 uerror("invalid character in hexadecimal argument");
272 if(count
>= bperhx
) {
273 /* the low bperhx bits of accu contain bits of the poly.
274 * in pass 0, increment length by bperhx.
275 * in pass 1, put the low bits of accu into the bitmap. */
280 accu
= rev(accu
, bperhx
);
283 /* length >= bperhx > 0 */
284 idx
= IDX(length
- 1);
285 ofs
= OFS(length
- 1);
286 poly
.bitmap
[idx
] |= accu
<< ofs
;
287 if(ofs
+ bperhx
> BMP_BIT
)
288 poly
.bitmap
[idx
-1] |= accu
>> (BMP_BIT
- ofs
);
289 accu
= BMP_C(0); /* only needed for P_LTLBYT */
293 if(pass
== 0) palloc(&poly
, length
);
299 ptostr(const poly_t poly
, int flags
, int bperhx
) {
300 /* Returns a malloc()-ed string containing a hexadecimal
301 * representation of poly. See phxsubs().
303 return(pxsubs(poly
, flags
, bperhx
, 0UL, poly
.length
));
307 pxsubs(const poly_t poly
, int flags
, int bperhx
, unsigned long start
, unsigned long end
) {
308 /* Returns a malloc()-ed string containing a hexadecimal
309 * representation of a portion of poly, from bit offset start to
310 * (end - 1) inclusive. The output is grouped into words of
311 * bperhx bits each. If P_RTJUST then the first word is padded
312 * with zeroes at the MSB end to make a whole number of words,
313 * otherwise the last word is padded at the LSB end. After
314 * justification the bperhx bits of each word are reversed (if
315 * P_REFOUT) and printed as a hex sequence, with words
316 * optionally separated by spaces (P_SPACE).
317 * If end exceeds the length of poly then zero bits are appended
318 * to make up the difference, in which case poly must be CLEAN.
321 unsigned long size
, iter
;
323 bmp_t mask
= bperhx
== BMP_BIT
? ~BMP_C(0) : (BMP_C(1) << bperhx
) - BMP_C(1);
326 if(bperhx
<= 0 || bperhx
> BMP_BIT
) return(NULL
);
328 if(start
> poly
.length
) start
= poly
.length
;
329 if(end
> poly
.length
) end
= poly
.length
;
330 if(end
< start
) end
= start
;
332 cperhx
= (bperhx
+ 3) >> 2;
333 if(flags
& P_SPACE
) ++cperhx
;
335 size
= (end
- start
+ bperhx
- 1UL) / bperhx
;
337 if(!size
|| ~flags
& P_SPACE
) ++size
; /* for trailing null */
339 if(!(sptr
= string
= (char *) malloc(size
)))
340 uerror("cannot allocate memory for string");
343 part
= (int) size
% bperhx
;
344 if(part
&& flags
& P_RTJUST
) {
346 accu
= getwrd(poly
, iter
- 1UL) & ((BMP_C(1) << part
) - BMP_C(1));
348 /* best to reverse over bperhx rather than part, I think
349 * e.g. converting a 7-bit poly to 8-bit little-endian hex
351 accu
= rev(accu
, bperhx
);
352 prhex(&sptr
, accu
, flags
, bperhx
);
353 if(flags
& P_SPACE
&& size
> iter
) *sptr
++ = ' ';
358 while((iter
+=bperhx
) <= end
) {
359 accu
= getwrd(poly
, iter
- 1UL) & mask
;
361 accu
= rev(accu
, bperhx
);
362 prhex(&sptr
, accu
, flags
, bperhx
);
363 if(flags
& P_SPACE
&& size
> iter
) *sptr
++ = ' ';
366 if(part
&& ~flags
& P_RTJUST
) {
367 accu
= getwrd(poly
, end
- 1UL);
369 accu
= rev(accu
, part
);
371 accu
= accu
<< (bperhx
- part
) & mask
;
372 prhex(&sptr
, accu
, flags
, bperhx
);
379 pclone(const poly_t poly
) {
380 /* Returns a freestanding copy of poly. Does not clean poly or
383 poly_t clone
= PZERO
;
390 pcpy(poly_t
*dest
, const poly_t src
) {
391 /* Assigns (copies) src into dest. Does not clean src or dest.
393 unsigned long iter
, idx
;
395 praloc(dest
, src
.length
);
396 for(iter
=0UL, idx
=0UL; iter
< src
.length
; iter
+= BMP_BIT
, ++idx
)
397 dest
->bitmap
[idx
] = src
.bitmap
[idx
];
401 pcanon(poly_t
*poly
) {
402 /* Converts poly into a CLEAN object by freeing unused bitmap words
403 * and clearing any bits in the last word beyond the last bit.
404 * The length field has absolute priority over the contents of the bitmap.
405 * Canonicalisation differs from normalisation in that leading and trailing
406 * zero terms are significant and preserved.
407 * poly may or may not be WELL-FORMED.
409 praloc(poly
, poly
->length
);
413 pnorm(poly_t
*poly
) {
414 /* Converts poly into a NORMALISED object by removing leading
415 * and trailing zeroes, so that the polynomial starts and ends
416 * with significant terms.
417 * poly may or may not be WELL-FORMED.
421 /* call pcanon() here so pfirst() and plast() return the correct
425 first
= pfirst(*poly
);
427 pshift(poly
, *poly
, 0UL, first
, plast(*poly
), 0UL);
429 praloc(poly
, plast(*poly
));
433 psnorm(poly_t
*poly
) {
434 /* Converts poly into a SEMI-NORMALISED object by removing
435 * trailing zeroes, so that the polynomial ends with a
437 * poly may or may not be WELL-FORMED.
440 /* call pcanon() here so plast() returns the correct result */
442 praloc(poly
, plast(*poly
));
446 pchop(poly_t
*poly
) {
447 /* Normalise poly, then chop off the highest significant term
448 * (produces a SEMI-NORMALISED object). poly becomes a suitable
449 * divisor for pcrc().
450 * poly may or may not be WELL-FORMED.
453 /* call pcanon() here so pfirst() and plast() return correct
457 pshift(poly
, *poly
, 0UL, pfirst(*poly
) + 1UL, plast(*poly
), 0UL);
461 pkchop(poly_t
*poly
) {
462 /* Convert poly from Koopman notation to chopped form (produces
463 * a SEMI-NORMALISED object). poly becomes a suitable divisor
465 * poly may or may not be WELL-FORMED.
469 /* call pcanon() here so pfirst() returns the correct result */
471 first
= pfirst(*poly
);
472 if(first
>= poly
->length
) {
476 pshift(poly
, *poly
, 0UL, first
+ 1UL, poly
->length
, 1UL);
481 plen(const poly_t poly
) {
482 /* Return length of polynomial.
483 * poly may or may not be WELL-FORMED.
489 pcmp(const poly_t
*a
, const poly_t
*b
) {
490 /* Compares poly_t objects for identical sizes and contents.
491 * a and b must be CLEAN.
492 * Defines a total order relation for sorting, etc. although
493 * mathematically, polynomials of equal degree are no greater or
494 * less than one another.
499 if(!a
|| !b
) return(!b
- !a
);
500 if(a
->length
< b
->length
) return(-1);
501 if(a
->length
> b
->length
) return(1);
504 for(iter
=0UL; iter
< a
->length
; iter
+= BMP_BIT
) {
507 if(*aptr
++ > *bptr
++)
514 psncmp(const poly_t
*a
, const poly_t
*b
) {
515 /* Compares polys for identical effect, i.e. as though the
516 * shorter poly were padded with zeroes to the length of the
518 * a and b must still be CLEAN, therefore psncmp() is *not*
519 * identical to pcmp() on semi-normalised polys as psnorm()
520 * clears the slack space.
522 unsigned long length
, iter
, idx
;
524 if(!a
|| !b
) return(!b
- !a
);
525 length
= (a
->length
> b
->length
) ? a
->length
: b
->length
;
526 for(iter
= 0UL, idx
= 0UL; iter
< length
; iter
+= BMP_BIT
, ++idx
) {
527 aword
= (iter
< a
->length
) ? a
->bitmap
[idx
] : BMP_C(0);
528 bword
= (iter
< b
->length
) ? b
->bitmap
[idx
] : BMP_C(0);
539 ptst(const poly_t poly
) {
540 /* Tests whether a polynomial equals zero. Returns 0 if equal,
541 * a nonzero value otherwise.
542 * poly must be CLEAN.
546 if(!poly
.bitmap
) return(0);
547 for(iter
= 0UL, bptr
= poly
.bitmap
; iter
< poly
.length
; iter
+= BMP_BIT
)
548 if(*bptr
++) return(1);
553 pfirst(const poly_t poly
) {
554 /* Returns the index of the first nonzero term in poly. If none
555 * is found, returns the length of poly.
556 * poly must be CLEAN.
558 unsigned long idx
= 0UL, size
= SIZE(poly
.length
);
559 bmp_t accu
= BMP_C(0); /* initialiser for Acorn C */
560 unsigned int probe
= BMP_SUB
, ofs
= 0;
562 while(idx
< size
&& !(accu
= poly
.bitmap
[idx
])) ++idx
;
563 if(idx
>= size
) return(poly
.length
);
566 while((ofs
| probe
) >= (unsigned int) BMP_BIT
) probe
>>= 1;
568 if(accu
>> (ofs
| probe
)) ofs
|= probe
;
572 return(BMP_BIT
- 1UL - ofs
+ idx
* BMP_BIT
);
576 plast(const poly_t poly
) {
577 /* Returns 1 plus the index of the last nonzero term in poly.
578 * If none is found, returns zero.
579 * poly must be CLEAN.
581 unsigned long idx
, size
= SIZE(poly
.length
);
583 unsigned int probe
= BMP_SUB
, ofs
= 0;
585 if(!poly
.length
) return(0UL);
587 while(idx
&& !(accu
= poly
.bitmap
[idx
])) --idx
;
588 if(!idx
&& !(accu
= poly
.bitmap
[idx
])) return(0UL);
589 /* now accu == poly.bitmap[idx] and contains last significant term */
592 while((ofs
| probe
) >= (unsigned int) BMP_BIT
) probe
>>= 1;
594 if(accu
<< (ofs
| probe
)) ofs
|= probe
;
598 return(idx
* BMP_BIT
+ ofs
+ 1UL);
602 psubs(const poly_t src
, unsigned long head
, unsigned long start
, unsigned long end
, unsigned long tail
) {
604 pshift(&dest
, src
, head
, start
, end
, tail
);
609 pright(poly_t
*poly
, unsigned long length
) {
610 /* Trims or extends poly to length at the left edge, prepending
611 * zeroes if necessary. Analogous to praloc() except the
612 * rightmost terms of poly are preserved.
613 * On entry, poly may or may not be WELL-FORMED.
614 * On exit, poly is CLEAN.
617 if(length
> poly
->length
)
618 pshift(poly
, *poly
, length
- poly
->length
, 0UL, poly
->length
, 0UL);
619 else if(length
< poly
->length
)
620 pshift(poly
, *poly
, 0UL, poly
->length
- length
, poly
->length
, 0UL);
622 praloc(poly
, poly
->length
);
626 pshift(poly_t
*dest
, const poly_t src
, unsigned long head
, unsigned long start
, unsigned long end
, unsigned long tail
) {
627 /* copies bits start to end-1 of src to dest, plus the number of leading and trailing zeroes given by head and tail.
628 * end may exceed the length of src in which case more zeroes are appended.
629 * dest may point to src, in which case the poly is edited in place.
630 * On exit, dest is CLEAN.
633 unsigned long length
, fulllength
, size
, fullsize
, iter
, idx
, datidx
;
634 /* condition inputs; end, head and tail may be any value */
635 if(end
< start
) end
= start
;
637 length
= end
- start
+ head
;
638 fulllength
= length
+ tail
;
639 if(fulllength
> src
.length
)
640 praloc(dest
, fulllength
);
642 praloc(dest
, src
.length
);
644 /* number of words in new poly */
646 fullsize
= SIZE(fulllength
);
647 /* array index of first word ending up with source material */
650 if(head
> start
&& end
> start
) {
651 /* shifting right, size > 0 */
652 /* index of the source bit ending up in the LSB of the last word
653 * size * BMP_BIT >= length > head > 0 */
654 iter
= size
* BMP_BIT
- head
- 1UL;
655 for(idx
= size
- 1UL; idx
> datidx
; iter
-= BMP_BIT
, --idx
)
656 dest
->bitmap
[idx
] = getwrd(src
, iter
);
657 dest
->bitmap
[idx
] = getwrd(src
, iter
);
658 /* iter == size * BMP_BIT - head - 1 - BMP_BIT * (size - 1 - datidx)
659 * == BMP_BIT * (size - size + 1 + datidx) - head - 1
660 * == BMP_BIT * (1 + head / BMP_BIT) - head - 1
661 * == BMP_BIT + head - head % BMP_BIT - head - 1
662 * == BMP_BIT - head % BMP_BIT - 1
665 } else if(head
<= start
) {
666 /* shifting left or copying */
667 /* index of the source bit ending up in the LSB of bitmap[idx] */
668 iter
= start
- head
+ BMP_BIT
- 1UL;
669 for(idx
= datidx
; idx
< size
; iter
+= BMP_BIT
, ++idx
)
670 dest
->bitmap
[idx
] = getwrd(src
, iter
);
674 for(idx
= 0UL; idx
< datidx
; ++idx
)
675 dest
->bitmap
[idx
] = BMP_C(0);
677 dest
->bitmap
[datidx
] &= ~BMP_C(0) >> LOFS(head
);
681 dest
->bitmap
[size
- 1UL] &= ~(~BMP_C(0) >> LOFS(length
));
682 for(idx
= size
; idx
< fullsize
; ++idx
)
683 dest
->bitmap
[idx
] = BMP_C(0);
685 /* call praloc to shrink poly if required */
686 if(dest
->length
> fulllength
)
687 praloc(dest
, fulllength
);
691 ppaste(poly_t
*dest
, const poly_t src
, unsigned long skip
, unsigned long seek
, unsigned long end
, unsigned long fulllength
) {
692 /* pastes terms of src, starting from skip, to positions seek to end-1 of dest
693 * then sets length of dest to fulllength (>= end)
694 * to paste n terms of src, give end = seek + n
695 * to truncate dest at end of paste, set fulllength = end
696 * to avoid truncating, set fulllength = plen(*dest)
697 * dest may point to src, in which case the poly is edited in place.
698 * src must be CLEAN in the case that the end is overrun.
699 * On exit, dest is CLEAN.
702 unsigned long seekidx
, endidx
, iter
;
704 if(end
< seek
) end
= seek
;
705 if(fulllength
< end
) fulllength
= end
;
707 /* expand dest if necessary. don't shrink as dest may be src */
708 if(fulllength
> dest
->length
)
709 praloc(dest
, fulllength
);
713 /* index of the source bit ending up in the LSB of the first modified word */
714 iter
= skip
+ seekofs
;
715 if(seekidx
== endidx
) {
716 /* paste affects one word (traps end = seek case) */
717 mask
= ((BMP_C(1) << seekofs
) - (BMP_C(1) << OFS(end
))) << 1;
718 dest
->bitmap
[seekidx
] = (dest
->bitmap
[seekidx
] & ~mask
) | (getwrd(src
, iter
) & mask
);
719 } else if(seek
> skip
) {
721 /* index of the source bit ending up in the LSB of the last modified word */
722 iter
+= (endidx
- seekidx
) * BMP_BIT
;
723 mask
= ~BMP_C(0) >> LOFS(end
);
724 dest
->bitmap
[endidx
] = (dest
->bitmap
[endidx
] & mask
) | (getwrd(src
, iter
) & ~mask
);
725 for(iter
-= BMP_BIT
, --endidx
; endidx
> seekidx
; iter
-= BMP_BIT
, --endidx
)
726 dest
->bitmap
[endidx
] = getwrd(src
, iter
);
727 mask
= ~BMP_C(0) >> LOFS(seek
);
728 dest
->bitmap
[endidx
] = (dest
->bitmap
[endidx
] & ~mask
) | (getwrd(src
, iter
) & mask
);
729 /* iter == skip + seekofs + (endidx - seekidx) * BMP_BIT - BMP_BIT * (endidx - seekidx)
730 * == skip + seekofs + BMP_BIT * (endidx - seekidx - endidx + seekidx)
735 /* shifting left or copying */
736 mask
= ~BMP_C(0) >> LOFS(seek
);
737 dest
->bitmap
[seekidx
] = (dest
->bitmap
[seekidx
] & ~mask
) | (getwrd(src
, iter
) & mask
);
738 for(iter
+= BMP_BIT
, ++seekidx
; seekidx
< endidx
; iter
+= BMP_BIT
, ++seekidx
)
739 dest
->bitmap
[seekidx
] = getwrd(src
, iter
);
740 mask
= ~BMP_C(0) >> LOFS(end
);
741 dest
->bitmap
[seekidx
] = (dest
->bitmap
[seekidx
] & mask
) | (getwrd(src
, iter
) & ~mask
);
743 /* shrink poly if required */
744 if(dest
->length
> fulllength
)
745 praloc(dest
, fulllength
);
749 pdiff(poly_t
*dest
, const poly_t src
, unsigned long ofs
) {
750 /* Subtract src from dest (modulo 2) at offset ofs.
751 * In modulo 2 arithmetic, subtraction is equivalent to addition
752 * We include an alias for those who wish to retain the distinction
753 * src and dest must be CLEAN.
755 psum(dest
, src
, ofs
);
759 psum(poly_t
*dest
, const poly_t src
, unsigned long ofs
) {
760 /* Adds src to dest (modulo 2) at offset ofs.
761 * When ofs == dest->length, catenates src on to dest.
762 * src and dest must be CLEAN.
764 unsigned long fulllength
, idx
, iter
, end
;
766 fulllength
= ofs
+ src
.length
;
767 if(fulllength
> dest
->length
)
768 praloc(dest
, fulllength
);
769 /* array index of first word in dest to be modified */
771 /* index of bit in src to be added to LSB of dest->bitmap[idx] */
773 /* stop value for iter */
774 end
= BMP_BIT
- 1UL + src
.length
;
775 for(; iter
< end
; iter
+= BMP_BIT
, ++idx
)
776 dest
->bitmap
[idx
] ^= getwrd(src
, iter
);
781 /* Reverse or reciprocate a polynomial.
782 * On exit, poly is CLEAN.
784 unsigned long leftidx
= 0UL, rightidx
= SIZE(poly
->length
);
785 unsigned long ofs
= LOFS(BMP_BIT
- LOFS(poly
->length
));
786 unsigned long fulllength
= poly
->length
+ ofs
;
790 /* removable optimisation */
791 if(poly
->length
< (unsigned long) BMP_BIT
) {
792 *poly
->bitmap
= rev(*poly
->bitmap
>> ofs
, (int) poly
->length
) << ofs
;
796 /* claim remaining bits of last word (as we use public function pshift()) */
797 poly
->length
= fulllength
;
799 /* reverse and swap words in the array, leaving it right-justified */
800 while(leftidx
< rightidx
) {
802 accu
= rev(poly
->bitmap
[--rightidx
], BMP_BIT
);
803 poly
->bitmap
[rightidx
] = rev(poly
->bitmap
[leftidx
], BMP_BIT
);
804 poly
->bitmap
[leftidx
++] = accu
;
806 /* shift polynomial to left edge if required */
808 pshift(poly
, *poly
, 0UL, ofs
, fulllength
, 0UL);
812 prevch(poly_t
*poly
, int bperhx
) {
813 /* Reverse each group of bperhx bits in a polynomial.
814 * Does not clean poly.
816 unsigned long iter
= 0, idx
, ofs
;
819 if(bperhx
< 2 || bperhx
> BMP_BIT
)
821 if(poly
->length
% bperhx
)
822 praloc(poly
, bperhx
- (poly
->length
% bperhx
) + poly
->length
);
823 mask
= ~BMP_C(0) >> (BMP_BIT
- bperhx
);
824 for(iter
= (unsigned long) (bperhx
- 1); iter
< poly
->length
; iter
+= bperhx
) {
825 accu
= getwrd(*poly
, iter
) & mask
;
826 accu
^= rev(accu
, bperhx
);
829 poly
->bitmap
[idx
] ^= accu
<< ofs
;
830 if(ofs
+ bperhx
> (unsigned int) BMP_BIT
)
831 /* (BMP_BIT - 1UL - (iter) % BMP_BIT) + bperhx > BMP_BIT
832 * (-1UL - (iter) % BMP_BIT) + bperhx > 0
833 * (- (iter % BMP_BIT)) + bperhx > 1
834 * - (iter % BMP_BIT) > 1 - bperhx
835 * iter % BMP_BIT < bperhx - 1, iter >= bperhx - 1
839 poly
->bitmap
[idx
-1] ^= accu
>> (BMP_BIT
- ofs
);
845 /* Reciprocate a chopped polynomial. Use prev() on whole
847 * On exit, poly is SEMI-NORMALISED.
851 praloc(poly
, RNDUP(poly
->length
));
853 first
= pfirst(*poly
);
854 if(first
>= poly
->length
) {
858 pshift(poly
, *poly
, 0UL, first
+ 1UL, poly
->length
, 1UL);
864 /* Invert a polynomial, i.e. add 1 (modulo 2) to the coefficient of each term
865 * on exit, poly is CLEAN.
867 unsigned long idx
, size
= SIZE(poly
->length
);
869 for(idx
= 0UL; idx
<size
; ++idx
)
870 poly
->bitmap
[idx
] = ~poly
->bitmap
[idx
];
871 if(LOFS(poly
->length
))
872 poly
->bitmap
[size
- 1UL] &= ~(~BMP_C(0) >> LOFS(poly
->length
));
876 pmod(const poly_t dividend
, const poly_t divisor
) {
877 /* Divide dividend by normalised divisor and return the remainder
878 * This function generates a temporary 'chopped' divisor for pcrc()
879 * If calling repeatedly with a constant divisor, produce a chopped copy
880 * with pchop() and call pcrc() directly for higher efficiency.
881 * dividend and divisor must be CLEAN.
884 /* perhaps generate an error if divisor is zero */
885 poly_t subdivisor
= psubs(divisor
, 0UL, pfirst(divisor
) + 1UL, plast(divisor
), 0UL);
886 poly_t result
= pcrc(dividend
, subdivisor
, pzero
, pzero
, 0);
892 pcrc(const poly_t message
, const poly_t divisor
, const poly_t init
, const poly_t xorout
, int flags
) {
893 /* Divide message by divisor and return the remainder.
894 * init is added to divisor, highest terms aligned, before
896 * xorout is added to the remainder, highest terms aligned.
897 * If P_MULXN is set in flags, message is multiplied by x^n
898 * (i.e. trailing zeroes equal to the CRC width are appended)
899 * before adding init and division. Set P_MULXN for most CRC
901 * All inputs must be CLEAN.
902 * If all inputs are CLEAN, the returned poly_t will be CLEAN.
904 unsigned long max
= 0UL, iter
, ofs
, resiter
;
905 bmp_t probe
, rem
, dvsr
, *rptr
, *sptr
;
906 const bmp_t
*bptr
, *eptr
;
907 poly_t result
= PZERO
;
910 max
= message
.length
;
911 else if(message
.length
> divisor
.length
)
912 max
= message
.length
- divisor
.length
;
914 eptr
=message
.bitmap
+SIZE(message
.length
);
915 probe
=~(~BMP_C(0) >> 1);
916 if(divisor
.length
<= (unsigned long) BMP_BIT
917 && init
.length
<= (unsigned long) BMP_BIT
) {
918 rem
= init
.length
? *init
.bitmap
: BMP_C(0);
919 dvsr
= divisor
.length
? *divisor
.bitmap
: BMP_C(0);
920 for(iter
= 0UL, ofs
= 0UL; iter
< max
; ++iter
, --ofs
) {
926 rem
= (rem
<< 1) ^ dvsr
;
931 /* max < message.length */
932 rem
^= *bptr
>> OFS(BMP_BIT
- 1UL + max
);
933 if(init
.length
> max
&& init
.length
- max
> divisor
.length
) {
934 palloc(&result
, init
.length
- max
);
935 *result
.bitmap
= rem
;
936 } else if(divisor
.length
) {
937 palloc(&result
, divisor
.length
);
938 *result
.bitmap
= rem
;
941 /* allocate maximum size plus one word for shifted divisors and one word containing zero.
942 * This also ensures that result[1] exists
944 palloc(&result
, (init
.length
> divisor
.length
? init
.length
: divisor
.length
) + (unsigned long) (BMP_BIT
<< 1));
945 /*if there is content in init, there will be an extra word in result to clear it */
946 psum(&result
, init
, 0UL);
948 *result
.bitmap
^= *bptr
++;
949 for(iter
= 0UL, ofs
= 0UL; iter
< max
; ++iter
, probe
>>= 1) {
951 probe
= ~(~BMP_C(0) >> 1);
953 sptr
= rptr
= result
.bitmap
;
955 /* iter < max <= message.length, so bptr is valid
956 * shift result one word to the left, splicing in a message word
957 * and clearing the last active word
959 *rptr
++ = *sptr
++ ^ *bptr
++;
960 for(resiter
= (unsigned long) (BMP_BIT
<< 1); resiter
< result
.length
; resiter
+= BMP_BIT
)
964 if(*result
.bitmap
& probe
)
965 psum(&result
, divisor
, ofs
);
967 rptr
= result
.bitmap
;
971 /* 0 <= ofs <= BMP_BIT, location of the first bit of the result */
972 pshift(&result
, result
, 0UL, ofs
, (init
.length
> max
+ divisor
.length
? init
.length
- max
- divisor
.length
: 0UL) + divisor
.length
+ ofs
, 0UL);
974 psum(&result
, xorout
, 0UL);
979 piter(poly_t
*poly
) {
980 /* Replace poly with the 'next' polynomial of equal length.
981 * Returns zero if the next polynomial is all zeroes, a nonzero
983 * Does not clean poly.
986 if(!poly
->length
) return(0);
988 bptr
= poly
->bitmap
+ IDX(poly
->length
- 1UL);
989 *bptr
+= BMP_C(1) << OFS(poly
->length
- 1UL);
990 while(bptr
!= poly
->bitmap
&& !*bptr
)
992 return(*bptr
!= BMP_C(0));
996 palloc(poly_t
*poly
, unsigned long length
) {
997 /* Replaces poly with a CLEAN object of the specified length,
998 * consisting of all zeroes.
999 * It is safe to call with length = 0, in which case the object
1001 * poly may or may not be WELL-FORMED.
1002 * On exit, poly is CLEAN.
1004 unsigned long size
= SIZE(length
);
1008 poly
->bitmap
= NULL
;
1011 size
= IDX(length
) + 1UL;
1012 poly
->bitmap
= (bmp_t
*) calloc(size
, sizeof(bmp_t
));
1014 poly
->length
= length
;
1016 uerror("cannot allocate memory for poly");
1020 pfree(poly_t
*poly
) {
1021 /* Frees poly's bitmap storage and sets poly equal to the empty
1022 * polynomial (PZERO).
1023 * poly may or may not be WELL-FORMED.
1024 * On exit, poly is CLEAN.
1027 /* palloc(poly, 0UL); */
1031 poly
->bitmap
= NULL
;
1035 praloc(poly_t
*poly
, unsigned long length
) {
1036 /* Trims or extends poly to length at the right edge, appending
1037 * zeroes if necessary.
1038 * On entry, poly may or may not be WELL-FORMED.
1039 * On exit, poly is CLEAN.
1041 unsigned long oldsize
, size
= SIZE(length
);
1046 poly
->bitmap
= NULL
;
1050 size
= IDX(length
) + 1UL;
1053 oldsize
= SIZE(poly
->length
);
1055 /* reallocate if array pointer is null or array resized */
1056 poly
->bitmap
= (bmp_t
*) realloc((void *)poly
->bitmap
, size
* sizeof(bmp_t
));
1058 if(poly
->length
< length
) {
1059 /* poly->length >= 0, length > 0, size > 0.
1060 * poly expanded. clear old last word and all new words
1062 if(LOFS(poly
->length
))
1063 poly
->bitmap
[oldsize
- 1UL] &= ~(~BMP_C(0) >> LOFS(poly
->length
));
1064 while(oldsize
< size
)
1065 poly
->bitmap
[oldsize
++] = BMP_C(0);
1066 } else if(LOFS(length
))
1067 /* poly->length >= length > 0.
1068 * poly shrunk. clear new last word
1070 poly
->bitmap
[size
- 1UL] &= ~(~BMP_C(0) >> LOFS(length
));
1071 poly
->length
= length
;
1073 uerror("cannot reallocate memory for poly");
1077 pmpar(const poly_t poly
, const poly_t mask
) {
1078 /* Return even parity of poly masked with mask.
1079 * Poly and mask must be CLEAN.
1081 bmp_t res
= BMP_C(0);
1083 const bmp_t
*pptr
= poly
.bitmap
, *mptr
= mask
.bitmap
;
1084 const bmp_t
*const pend
= poly
.bitmap
+ SIZE(poly
.length
);
1085 const bmp_t
*const mend
= mask
.bitmap
+ SIZE(mask
.length
);
1087 while(pptr
< pend
&& mptr
< mend
)
1088 res
^= *pptr
++ & *mptr
++;
1093 return((int) (res
& BMP_C(1)));
1097 pident(const poly_t a
, const poly_t b
) {
1098 /* Return nonzero if a and b have the same length
1099 * and point to the same bitmap.
1100 * a and b need not be CLEAN.
1102 return(a
.length
== b
.length
&& a
.bitmap
== b
.bitmap
);
1105 /* Private functions */
1108 getwrd(const poly_t poly
, unsigned long iter
) {
1109 /* Fetch unaligned word from poly where LSB of result is
1110 * bit iter of the bitmap (counting from zero). If iter exceeds
1111 * the length of poly then zeroes are appended as necessary.
1112 * Factored from ptostr().
1113 * poly must be CLEAN.
1115 bmp_t accu
= BMP_C(0);
1116 unsigned long idx
, size
;
1121 size
= SIZE(poly
.length
);
1124 accu
|= poly
.bitmap
[idx
] >> ofs
;
1125 if(idx
&& idx
<= size
&& ofs
> 0)
1126 accu
|= poly
.bitmap
[idx
- 1UL] << (BMP_BIT
- ofs
);
1131 rev(bmp_t accu
, int bits
) {
1132 /* Returns the bitmap word argument with the given number of
1133 * least significant bits reversed and the rest cleared.
1135 static const unsigned char revtab
[256] = {
1136 0x00,0x80,0x40,0xc0,0x20,0xa0,0x60,0xe0,
1137 0x10,0x90,0x50,0xd0,0x30,0xb0,0x70,0xf0,
1138 0x08,0x88,0x48,0xc8,0x28,0xa8,0x68,0xe8,
1139 0x18,0x98,0x58,0xd8,0x38,0xb8,0x78,0xf8,
1140 0x04,0x84,0x44,0xc4,0x24,0xa4,0x64,0xe4,
1141 0x14,0x94,0x54,0xd4,0x34,0xb4,0x74,0xf4,
1142 0x0c,0x8c,0x4c,0xcc,0x2c,0xac,0x6c,0xec,
1143 0x1c,0x9c,0x5c,0xdc,0x3c,0xbc,0x7c,0xfc,
1144 0x02,0x82,0x42,0xc2,0x22,0xa2,0x62,0xe2,
1145 0x12,0x92,0x52,0xd2,0x32,0xb2,0x72,0xf2,
1146 0x0a,0x8a,0x4a,0xca,0x2a,0xaa,0x6a,0xea,
1147 0x1a,0x9a,0x5a,0xda,0x3a,0xba,0x7a,0xfa,
1148 0x06,0x86,0x46,0xc6,0x26,0xa6,0x66,0xe6,
1149 0x16,0x96,0x56,0xd6,0x36,0xb6,0x76,0xf6,
1150 0x0e,0x8e,0x4e,0xce,0x2e,0xae,0x6e,0xee,
1151 0x1e,0x9e,0x5e,0xde,0x3e,0xbe,0x7e,0xfe,
1152 0x01,0x81,0x41,0xc1,0x21,0xa1,0x61,0xe1,
1153 0x11,0x91,0x51,0xd1,0x31,0xb1,0x71,0xf1,
1154 0x09,0x89,0x49,0xc9,0x29,0xa9,0x69,0xe9,
1155 0x19,0x99,0x59,0xd9,0x39,0xb9,0x79,0xf9,
1156 0x05,0x85,0x45,0xc5,0x25,0xa5,0x65,0xe5,
1157 0x15,0x95,0x55,0xd5,0x35,0xb5,0x75,0xf5,
1158 0x0d,0x8d,0x4d,0xcd,0x2d,0xad,0x6d,0xed,
1159 0x1d,0x9d,0x5d,0xdd,0x3d,0xbd,0x7d,0xfd,
1160 0x03,0x83,0x43,0xc3,0x23,0xa3,0x63,0xe3,
1161 0x13,0x93,0x53,0xd3,0x33,0xb3,0x73,0xf3,
1162 0x0b,0x8b,0x4b,0xcb,0x2b,0xab,0x6b,0xeb,
1163 0x1b,0x9b,0x5b,0xdb,0x3b,0xbb,0x7b,0xfb,
1164 0x07,0x87,0x47,0xc7,0x27,0xa7,0x67,0xe7,
1165 0x17,0x97,0x57,0xd7,0x37,0xb7,0x77,0xf7,
1166 0x0f,0x8f,0x4f,0xcf,0x2f,0xaf,0x6f,0xef,
1167 0x1f,0x9f,0x5f,0xdf,0x3f,0xbf,0x7f,0xff
1169 bmp_t result
= BMP_C(0);
1172 result
= result
<< 8 | revtab
[accu
& 0xff];
1175 result
= result
<< bits
| (bmp_t
) (revtab
[accu
& 0xff] >> (8 - bits
));
1180 prhex(char **spp
, bmp_t bits
, int flags
, int bperhx
) {
1181 /* Appends a hexadecimal string representing the bperhx least
1182 * significant bits of bits to an external string.
1183 * spp points to a character pointer that in turn points to the
1184 * end of a hex string being built. prhex() advances this
1185 * second pointer by the number of characters written.
1186 * The unused MSBs of bits MUST be cleared.
1187 * Set P_UPPER in flags to write A-F in uppercase.
1189 static const char hex
[] = "0123456789abcdef0123456789ABCDEF";
1190 const int upper
= (flags
& P_UPPER
? 0x10 : 0);
1192 bperhx
-= ((bperhx
+ 3) & 3) + 1;
1193 *(*spp
)++ = hex
[(bits
>> bperhx
& BMP_C(0xf)) | upper
];