xref: /freebsd/sbin/hastd/lzf.c (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1 /*
2  * Copyright (c) 2000-2008 Marc Alexander Lehmann <schmorp@schmorp.de>
3  *
4  * Redistribution and use in source and binary forms, with or without modifica-
5  * tion, are permitted provided that the following conditions are met:
6  *
7  *   1.  Redistributions of source code must retain the above copyright notice,
8  *       this list of conditions and the following disclaimer.
9  *
10  *   2.  Redistributions in binary form must reproduce the above copyright
11  *       notice, this list of conditions and the following disclaimer in the
12  *       documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
15  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
16  * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
17  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
18  * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
20  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
21  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
22  * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
23  * OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  * Alternatively, the contents of this file may be used under the terms of
26  * the GNU General Public License ("GPL") version 2 or any later version,
27  * in which case the provisions of the GPL are applicable instead of
28  * the above. If you wish to allow the use of your version of this file
29  * only under the terms of the GPL and not to allow others to use your
30  * version of this file under the BSD license, indicate your decision
31  * by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL. If you do not delete the
33  * provisions above, a recipient may use your version of this file under
34  * either the BSD or the GPL.
35  */
36 
37 #include "lzf.h"
38 
39 #define HSIZE (1 << (HLOG))
40 
41 /*
42  * don't play with this unless you benchmark!
43  * decompression is not dependent on the hash function
44  * the hashing function might seem strange, just believe me
45  * it works ;)
46  */
47 #ifndef FRST
48 # define FRST(p) (((p[0]) << 8) | p[1])
49 # define NEXT(v,p) (((v) << 8) | p[2])
50 # if ULTRA_FAST
51 #  define IDX(h) ((( h             >> (3*8 - HLOG)) - h  ) & (HSIZE - 1))
52 # elif VERY_FAST
53 #  define IDX(h) ((( h             >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))
54 # else
55 #  define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))
56 # endif
57 #endif
58 /*
59  * IDX works because it is very similar to a multiplicative hash, e.g.
60  * ((h * 57321 >> (3*8 - HLOG)) & (HSIZE - 1))
61  * the latter is also quite fast on newer CPUs, and compresses similarly.
62  *
63  * the next one is also quite good, albeit slow ;)
64  * (int)(cos(h & 0xffffff) * 1e6)
65  */
66 
67 #if 0
68 /* original lzv-like hash function, much worse and thus slower */
69 # define FRST(p) (p[0] << 5) ^ p[1]
70 # define NEXT(v,p) ((v) << 5) ^ p[2]
71 # define IDX(h) ((h) & (HSIZE - 1))
72 #endif
73 
74 #define        MAX_LIT        (1 <<  5)
75 #define        MAX_OFF        (1 << 13)
76 #define        MAX_REF        ((1 << 8) + (1 << 3))
77 
78 #if __GNUC__ >= 3
79 # define expect(expr,value)         __builtin_expect ((expr),(value))
80 # define inline                     inline
81 #else
82 # define expect(expr,value)         (expr)
83 # define inline                     static
84 #endif
85 
86 #define expect_false(expr) expect ((expr) != 0, 0)
87 #define expect_true(expr)  expect ((expr) != 0, 1)
88 
89 /*
90  * compressed format
91  *
92  * 000LLLLL <L+1>    ; literal
93  * LLLooooo oooooooo ; backref L
94  * 111ooooo LLLLLLLL oooooooo ; backref L+7
95  *
96  */
97 
98 unsigned int
99 lzf_compress (const void *const in_data, unsigned int in_len,
100 	      void *out_data, unsigned int out_len
101 #if LZF_STATE_ARG
102               , LZF_STATE htab
103 #endif
104               )
105 {
106 #if !LZF_STATE_ARG
107   LZF_STATE htab;
108 #endif
109   const u8 **hslot;
110   const u8 *ip = (const u8 *)in_data;
111         u8 *op = (u8 *)out_data;
112   const u8 *in_end  = ip + in_len;
113         u8 *out_end = op + out_len;
114   const u8 *ref;
115 
116   /* off requires a type wide enough to hold a general pointer difference.
117    * ISO C doesn't have that (size_t might not be enough and ptrdiff_t only
118    * works for differences within a single object). We also assume that no
119    * no bit pattern traps. Since the only platform that is both non-POSIX
120    * and fails to support both assumptions is windows 64 bit, we make a
121    * special workaround for it.
122    */
123 #if defined (WIN32) && defined (_M_X64)
124   unsigned _int64 off; /* workaround for missing POSIX compliance */
125 #else
126   unsigned long off;
127 #endif
128   unsigned int hval;
129   int lit;
130 
131   if (!in_len || !out_len)
132     return 0;
133 
134 #if INIT_HTAB
135   memset (htab, 0, sizeof (htab));
136 # if 0
137   for (hslot = htab; hslot < htab + HSIZE; hslot++)
138     *hslot++ = ip;
139 # endif
140 #endif
141 
142   lit = 0; op++; /* start run */
143 
144   hval = FRST (ip);
145   while (ip < in_end - 2)
146     {
147       hval = NEXT (hval, ip);
148       hslot = htab + IDX (hval);
149       ref = *hslot; *hslot = ip;
150 
151       if (1
152 #if INIT_HTAB
153           && ref < ip /* the next test will actually take care of this, but this is faster */
154 #endif
155           && (off = ip - ref - 1) < MAX_OFF
156           && ip + 4 < in_end
157           && ref > (const u8 *)in_data
158 #if STRICT_ALIGN
159           && ref[0] == ip[0]
160           && ref[1] == ip[1]
161           && ref[2] == ip[2]
162 #else
163           && *(const u16 *)ref == *(const u16 *)ip
164           && ref[2] == ip[2]
165 #endif
166         )
167         {
168           /* match found at *ref++ */
169           unsigned int len = 2;
170           unsigned int maxlen = in_end - ip - len;
171           maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;
172 
173           if (expect_false (op + 3 + 1 >= out_end)) /* first a faster conservative test */
174             if (op - !lit + 3 + 1 >= out_end) /* second the exact but rare test */
175               return 0;
176 
177           op [- lit - 1] = lit - 1; /* stop run */
178           op -= !lit; /* undo run if length is zero */
179 
180           for (;;)
181             {
182               if (expect_true (maxlen > 16))
183                 {
184                   len++; if (ref [len] != ip [len]) break;
185                   len++; if (ref [len] != ip [len]) break;
186                   len++; if (ref [len] != ip [len]) break;
187                   len++; if (ref [len] != ip [len]) break;
188 
189                   len++; if (ref [len] != ip [len]) break;
190                   len++; if (ref [len] != ip [len]) break;
191                   len++; if (ref [len] != ip [len]) break;
192                   len++; if (ref [len] != ip [len]) break;
193 
194                   len++; if (ref [len] != ip [len]) break;
195                   len++; if (ref [len] != ip [len]) break;
196                   len++; if (ref [len] != ip [len]) break;
197                   len++; if (ref [len] != ip [len]) break;
198 
199                   len++; if (ref [len] != ip [len]) break;
200                   len++; if (ref [len] != ip [len]) break;
201                   len++; if (ref [len] != ip [len]) break;
202                   len++; if (ref [len] != ip [len]) break;
203                 }
204 
205               do
206                 len++;
207               while (len < maxlen && ref[len] == ip[len]);
208 
209               break;
210             }
211 
212           len -= 2; /* len is now #octets - 1 */
213           ip++;
214 
215           if (len < 7)
216             {
217               *op++ = (off >> 8) + (len << 5);
218             }
219           else
220             {
221               *op++ = (off >> 8) + (  7 << 5);
222               *op++ = len - 7;
223             }
224 
225           *op++ = off;
226           lit = 0; op++; /* start run */
227 
228           ip += len + 1;
229 
230           if (expect_false (ip >= in_end - 2))
231             break;
232 
233 #if ULTRA_FAST || VERY_FAST
234           --ip;
235 # if VERY_FAST && !ULTRA_FAST
236           --ip;
237 # endif
238           hval = FRST (ip);
239 
240           hval = NEXT (hval, ip);
241           htab[IDX (hval)] = ip;
242           ip++;
243 
244 # if VERY_FAST && !ULTRA_FAST
245           hval = NEXT (hval, ip);
246           htab[IDX (hval)] = ip;
247           ip++;
248 # endif
249 #else
250           ip -= len + 1;
251 
252           do
253             {
254               hval = NEXT (hval, ip);
255               htab[IDX (hval)] = ip;
256               ip++;
257             }
258           while (len--);
259 #endif
260         }
261       else
262         {
263           /* one more literal byte we must copy */
264           if (expect_false (op >= out_end))
265             return 0;
266 
267           lit++; *op++ = *ip++;
268 
269           if (expect_false (lit == MAX_LIT))
270             {
271               op [- lit - 1] = lit - 1; /* stop run */
272               lit = 0; op++; /* start run */
273             }
274         }
275     }
276 
277   if (op + 3 > out_end) /* at most 3 bytes can be missing here */
278     return 0;
279 
280   while (ip < in_end)
281     {
282       lit++; *op++ = *ip++;
283 
284       if (expect_false (lit == MAX_LIT))
285         {
286           op [- lit - 1] = lit - 1; /* stop run */
287           lit = 0; op++; /* start run */
288         }
289     }
290 
291   op [- lit - 1] = lit - 1; /* end run */
292   op -= !lit; /* undo run if length is zero */
293 
294   return op - (u8 *)out_data;
295 }
296 
297 #if AVOID_ERRNO
298 # define SET_ERRNO(n)
299 #else
300 # include <errno.h>
301 # define SET_ERRNO(n) errno = (n)
302 #endif
303 
304 #if (__i386 || __amd64) && __GNUC__ >= 3
305 # define lzf_movsb(dst, src, len)                \
306    asm ("rep movsb"                              \
307         : "=D" (dst), "=S" (src), "=c" (len)     \
308         :  "0" (dst),  "1" (src),  "2" (len));
309 #endif
310 
311 unsigned int
312 lzf_decompress (const void *const in_data,  unsigned int in_len,
313                 void             *out_data, unsigned int out_len)
314 {
315   u8 const *ip = (const u8 *)in_data;
316   u8       *op = (u8 *)out_data;
317   u8 const *const in_end  = ip + in_len;
318   u8       *const out_end = op + out_len;
319 
320   do
321     {
322       unsigned int ctrl = *ip++;
323 
324       if (ctrl < (1 << 5)) /* literal run */
325         {
326           ctrl++;
327 
328           if (op + ctrl > out_end)
329             {
330               SET_ERRNO (E2BIG);
331               return 0;
332             }
333 
334 #if CHECK_INPUT
335           if (ip + ctrl > in_end)
336             {
337               SET_ERRNO (EINVAL);
338               return 0;
339             }
340 #endif
341 
342 #ifdef lzf_movsb
343           lzf_movsb (op, ip, ctrl);
344 #else
345           do
346             *op++ = *ip++;
347           while (--ctrl);
348 #endif
349         }
350       else /* back reference */
351         {
352           unsigned int len = ctrl >> 5;
353 
354           u8 *ref = op - ((ctrl & 0x1f) << 8) - 1;
355 
356 #if CHECK_INPUT
357           if (ip >= in_end)
358             {
359               SET_ERRNO (EINVAL);
360               return 0;
361             }
362 #endif
363           if (len == 7)
364             {
365               len += *ip++;
366 #if CHECK_INPUT
367               if (ip >= in_end)
368                 {
369                   SET_ERRNO (EINVAL);
370                   return 0;
371                 }
372 #endif
373             }
374 
375           ref -= *ip++;
376 
377           if (op + len + 2 > out_end)
378             {
379               SET_ERRNO (E2BIG);
380               return 0;
381             }
382 
383           if (ref < (u8 *)out_data)
384             {
385               SET_ERRNO (EINVAL);
386               return 0;
387             }
388 
389 #ifdef lzf_movsb
390           len += 2;
391           lzf_movsb (op, ref, len);
392 #else
393           *op++ = *ref++;
394           *op++ = *ref++;
395 
396           do
397             *op++ = *ref++;
398           while (--len);
399 #endif
400         }
401     }
402   while (ip < in_end);
403 
404   return op - (u8 *)out_data;
405 }
406 
407