f5e06b54bef8727938dce98d8ace83dd77f331ed
[oweals/busybox.git] / archival / lzop.c
1 /*
2    This file is part of the lzop file compressor.
3
4    Copyright (C) 1996..2003 Markus Franz Xaver Johannes Oberhumer
5    All Rights Reserved.
6
7    Markus F.X.J. Oberhumer <markus@oberhumer.com>
8    http://www.oberhumer.com/opensource/lzop/
9
10    lzop and the LZO library are free software; you can redistribute them
11    and/or modify them under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2 of
13    the License, or (at your option) any later version.
14
15    This program 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.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; see the file COPYING.
22    If not, write to the Free Software Foundation, Inc.,
23    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24
25    "Minimalized" for busybox by Alain Knaff
26 */
27
28 //usage:#define lzop_trivial_usage
29 //usage:       "[-cfvd123456789CF] [FILE]..."
30 //usage:#define lzop_full_usage "\n\n"
31 //usage:       "        -1..9   Compression level"
32 //usage:     "\n        -d      Decompress"
33 //usage:     "\n        -c      Write to stdout"
34 //usage:     "\n        -f      Force"
35 //usage:     "\n        -v      Verbose"
36 //usage:     "\n        -F      Don't store or verify checksum"
37 //usage:     "\n        -C      Also write checksum of compressed block"
38 //usage:
39 //usage:#define lzopcat_trivial_usage
40 //usage:       "[-vCF] [FILE]..."
41 //usage:#define lzopcat_full_usage "\n\n"
42 //usage:       "        -v      Verbose"
43 //usage:     "\n        -F      Don't store or verify checksum"
44 //usage:
45 //usage:#define unlzop_trivial_usage
46 //usage:       "[-cfvCF] [FILE]..."
47 //usage:#define unlzop_full_usage "\n\n"
48 //usage:       "        -c      Write to stdout"
49 //usage:     "\n        -f      Force"
50 //usage:     "\n        -v      Verbose"
51 //usage:     "\n        -F      Don't store or verify checksum"
52
53 #include "libbb.h"
54 #include "bb_archive.h"
55 #include "liblzo_interface.h"
56
57 /* lzo-2.03/src/lzo_ptr.h */
58 #define pd(a,b)  ((unsigned)((a)-(b)))
59
60 #define lzo_version()                   LZO_VERSION
61 #define lzo_sizeof_dict_t               (sizeof(uint8_t*))
62
63 /* lzo-2.03/include/lzo/lzo1x.h */
64 #define LZO1X_1_MEM_COMPRESS    (16384 * lzo_sizeof_dict_t)
65 #define LZO1X_1_15_MEM_COMPRESS (32768 * lzo_sizeof_dict_t)
66 #define LZO1X_999_MEM_COMPRESS  (14 * 16384 * sizeof(short))
67
68 /* lzo-2.03/src/lzo1x_oo.c */
69 #define NO_LIT UINT_MAX
70
71 /**********************************************************************/
72 static void copy2(uint8_t* ip, const uint8_t* m_pos, unsigned off)
73 {
74         ip[0] = m_pos[0];
75         if (off == 1)
76                 ip[1] = m_pos[0];
77         else
78                 ip[1] = m_pos[1];
79 }
80
81 static void copy3(uint8_t* ip, const uint8_t* m_pos, unsigned off)
82 {
83         ip[0] = m_pos[0];
84         if (off == 1) {
85                 ip[2] = ip[1] = m_pos[0];
86         }
87         else if (off == 2) {
88                 ip[1] = m_pos[1];
89                 ip[2] = m_pos[0];
90         }
91         else {
92                 ip[1] = m_pos[1];
93                 ip[2] = m_pos[2];
94         }
95 }
96
97 /**********************************************************************/
98 // optimize a block of data.
99 /**********************************************************************/
100 #define TEST_IP         (ip < ip_end)
101 #define TEST_OP         (op <= op_end)
102
103 static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
104                 uint8_t *out, unsigned *out_len,
105                 void* wrkmem UNUSED_PARAM)
106 {
107         uint8_t* op;
108         uint8_t* ip;
109         unsigned t;
110         uint8_t* m_pos;
111         uint8_t* const ip_end = in + in_len;
112         uint8_t* const op_end = out + *out_len;
113         uint8_t* litp = NULL;
114         unsigned lit = 0;
115         unsigned next_lit = NO_LIT;
116         unsigned nl;
117         unsigned long o_m1_a = 0, o_m1_b = 0, o_m2 = 0, o_m3_a = 0, o_m3_b = 0;
118
119 //      LZO_UNUSED(wrkmem);
120
121         *out_len = 0;
122
123         op = out;
124         ip = in;
125
126         if (*ip > 17) {
127                 t = *ip++ - 17;
128                 if (t < 4)
129                         goto match_next;
130                 goto first_literal_run;
131         }
132
133         while (TEST_IP && TEST_OP) {
134                 t = *ip++;
135                 if (t >= 16)
136                         goto match;
137                 /* a literal run */
138                 litp = ip - 1;
139                 if (t == 0) {
140                         t = 15;
141                         while (*ip == 0)
142                                 t += 255, ip++;
143                         t += *ip++;
144                 }
145                 lit = t + 3;
146                 /* copy literals */
147  copy_literal_run:
148                 *op++ = *ip++;
149                 *op++ = *ip++;
150                 *op++ = *ip++;
151  first_literal_run:
152                 do *op++ = *ip++; while (--t > 0);
153
154                 t = *ip++;
155
156                 if (t >= 16)
157                         goto match;
158 #if defined(LZO1X)
159                 m_pos = op - 1 - 0x800;
160 #elif defined(LZO1Y)
161                 m_pos = op - 1 - 0x400;
162 #endif
163                 m_pos -= t >> 2;
164                 m_pos -= *ip++ << 2;
165                 *op++ = *m_pos++;
166                 *op++ = *m_pos++;
167                 *op++ = *m_pos++;
168                 lit = 0;
169                 goto match_done;
170
171
172                 /* handle matches */
173                 do {
174                         if (t < 16) { /* a M1 match */
175                                 m_pos = op - 1;
176                                 m_pos -= t >> 2;
177                                 m_pos -= *ip++ << 2;
178
179                                 if (litp == NULL)
180                                         goto copy_m1;
181
182                                 nl = ip[-2] & 3;
183                                 /* test if a match follows */
184                                 if (nl == 0 && lit == 1 && ip[0] >= 16) {
185                                         next_lit = nl;
186                                         /* adjust length of previous short run */
187                                         lit += 2;
188                                         *litp = (unsigned char)((*litp & ~3) | lit);
189                                         /* copy over the 2 literals that replace the match */
190                                         copy2(ip-2, m_pos, pd(op, m_pos));
191                                         o_m1_a++;
192                                 }
193                                 /* test if a literal run follows */
194                                 else
195                                 if (nl == 0
196                                  && ip[0] < 16
197                                  && ip[0] != 0
198                                  && (lit + 2 + ip[0] < 16)
199                                 ) {
200                                         t = *ip++;
201                                         /* remove short run */
202                                         *litp &= ~3;
203                                         /* copy over the 2 literals that replace the match */
204                                         copy2(ip-3+1, m_pos, pd(op, m_pos));
205                                         /* move literals 1 byte ahead */
206                                         litp += 2;
207                                         if (lit > 0)
208                                                 memmove(litp+1, litp, lit);
209                                         /* insert new length of long literal run */
210                                         lit += 2 + t + 3;
211                                         *litp = (unsigned char)(lit - 3);
212
213                                         o_m1_b++;
214                                         *op++ = *m_pos++;
215                                         *op++ = *m_pos++;
216                                         goto copy_literal_run;
217                                 }
218  copy_m1:
219                                 *op++ = *m_pos++;
220                                 *op++ = *m_pos++;
221                         } else {
222  match:
223                                 if (t >= 64) {                          /* a M2 match */
224                                         m_pos = op - 1;
225 #if defined(LZO1X)
226                                         m_pos -= (t >> 2) & 7;
227                                         m_pos -= *ip++ << 3;
228                                         t = (t >> 5) - 1;
229 #elif defined(LZO1Y)
230                                         m_pos -= (t >> 2) & 3;
231                                         m_pos -= *ip++ << 2;
232                                         t = (t >> 4) - 3;
233 #endif
234                                         if (litp == NULL)
235                                                 goto copy_m;
236
237                                         nl = ip[-2] & 3;
238                                         /* test if in beetween two long literal runs */
239                                         if (t == 1 && lit > 3 && nl == 0
240                                          && ip[0] < 16 && ip[0] != 0 && (lit + 3 + ip[0] < 16)
241                                         ) {
242                                                 t = *ip++;
243                                                 /* copy over the 3 literals that replace the match */
244                                                 copy3(ip-1-2, m_pos, pd(op, m_pos));
245                                                 /* set new length of previous literal run */
246                                                 lit += 3 + t + 3;
247                                                 *litp = (unsigned char)(lit - 3);
248                                                 o_m2++;
249                                                 *op++ = *m_pos++;
250                                                 *op++ = *m_pos++;
251                                                 *op++ = *m_pos++;
252                                                 goto copy_literal_run;
253                                         }
254                                 } else {
255                                         if (t >= 32) {                  /* a M3 match */
256                                                 t &= 31;
257                                                 if (t == 0) {
258                                                         t = 31;
259                                                         while (*ip == 0)
260                                                                 t += 255, ip++;
261                                                         t += *ip++;
262                                                 }
263                                                 m_pos = op - 1;
264                                                 m_pos -= *ip++ >> 2;
265                                                 m_pos -= *ip++ << 6;
266                                         } else {                                        /* a M4 match */
267                                                 m_pos = op;
268                                                 m_pos -= (t & 8) << 11;
269                                                 t &= 7;
270                                                 if (t == 0) {
271                                                         t = 7;
272                                                         while (*ip == 0)
273                                                                 t += 255, ip++;
274                                                         t += *ip++;
275                                                 }
276                                                 m_pos -= *ip++ >> 2;
277                                                 m_pos -= *ip++ << 6;
278                                                 if (m_pos == op)
279                                                         goto eof_found;
280                                                 m_pos -= 0x4000;
281                                         }
282                                         if (litp == NULL)
283                                                 goto copy_m;
284
285                                         nl = ip[-2] & 3;
286                                         /* test if in beetween two matches */
287                                         if (t == 1 && lit == 0 && nl == 0 && ip[0] >= 16) {
288                                                 next_lit = nl;
289                                                 /* make a previous short run */
290                                                 lit += 3;
291                                                 *litp = (unsigned char)((*litp & ~3) | lit);
292                                                 /* copy over the 3 literals that replace the match */
293                                                 copy3(ip-3, m_pos, pd(op, m_pos));
294                                                 o_m3_a++;
295                                         }
296                                         /* test if a literal run follows */
297                                         else if (t == 1 && lit <= 3 && nl == 0
298                                          && ip[0] < 16 && ip[0] != 0 && (lit + 3 + ip[0] < 16)
299                                         ) {
300                                                 t = *ip++;
301                                                 /* remove short run */
302                                                 *litp &= ~3;
303                                                 /* copy over the 3 literals that replace the match */
304                                                 copy3(ip-4+1, m_pos, pd(op, m_pos));
305                                                 /* move literals 1 byte ahead */
306                                                 litp += 2;
307                                                 if (lit > 0)
308                                                         memmove(litp+1,litp,lit);
309                                                 /* insert new length of long literal run */
310                                                 lit += 3 + t + 3;
311                                                 *litp = (unsigned char)(lit - 3);
312
313                                                 o_m3_b++;
314                                                 *op++ = *m_pos++;
315                                                 *op++ = *m_pos++;
316                                                 *op++ = *m_pos++;
317                                                 goto copy_literal_run;
318                                         }
319                                 }
320  copy_m:
321                                 *op++ = *m_pos++;
322                                 *op++ = *m_pos++;
323                                 do *op++ = *m_pos++; while (--t > 0);
324                         }
325
326  match_done:
327                         if (next_lit == NO_LIT) {
328                                 t = ip[-2] & 3;
329                                 lit = t;
330                                 litp = ip - 2;
331                         }
332                         else
333                                 t = next_lit;
334                         next_lit = NO_LIT;
335                         if (t == 0)
336                                 break;
337                         /* copy literals */
338  match_next:
339                         do *op++ = *ip++; while (--t > 0);
340                         t = *ip++;
341                 } while (TEST_IP && TEST_OP);
342         }
343
344         /* no EOF code was found */
345         *out_len = pd(op, out);
346         return LZO_E_EOF_NOT_FOUND;
347
348  eof_found:
349 //      LZO_UNUSED(o_m1_a); LZO_UNUSED(o_m1_b); LZO_UNUSED(o_m2);
350 //      LZO_UNUSED(o_m3_a); LZO_UNUSED(o_m3_b);
351         *out_len = pd(op, out);
352         return (ip == ip_end ? LZO_E_OK :
353                 (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN));
354 }
355
356 /**********************************************************************/
357 #define F_OS F_OS_UNIX
358 #define F_CS F_CS_NATIVE
359
360 /**********************************************************************/
361 #define ADLER32_INIT_VALUE 1
362 #define CRC32_INIT_VALUE   0
363
364 /**********************************************************************/
365 enum {
366         M_LZO1X_1    = 1,
367         M_LZO1X_1_15 = 2,
368         M_LZO1X_999  = 3,
369 };
370
371 /**********************************************************************/
372 /* header flags */
373 #define F_ADLER32_D     0x00000001L
374 #define F_ADLER32_C     0x00000002L
375 #define F_H_EXTRA_FIELD 0x00000040L
376 #define F_H_GMTDIFF     0x00000080L
377 #define F_CRC32_D       0x00000100L
378 #define F_CRC32_C       0x00000200L
379 #define F_H_FILTER      0x00000800L
380 #define F_H_CRC32       0x00001000L
381 #define F_MASK          0x00003FFFL
382
383 /* operating system & file system that created the file [mostly unused] */
384 #define F_OS_UNIX       0x03000000L
385 #define F_OS_SHIFT      24
386 #define F_OS_MASK       0xff000000L
387
388 /* character set for file name encoding [mostly unused] */
389 #define F_CS_NATIVE     0x00000000L
390 #define F_CS_SHIFT      20
391 #define F_CS_MASK       0x00f00000L
392
393 /* these bits must be zero */
394 #define F_RESERVED      ((F_MASK | F_OS_MASK | F_CS_MASK) ^ 0xffffffffL)
395
396 typedef struct chksum_t {
397         uint32_t f_adler32;
398         uint32_t f_crc32;
399 } chksum_t;
400
401 typedef struct header_t {
402         unsigned version;
403         unsigned lib_version;
404         unsigned version_needed_to_extract;
405         uint32_t flags;
406         uint32_t mode;
407         uint32_t mtime;
408         uint32_t gmtdiff;
409         uint32_t header_checksum;
410
411         uint32_t extra_field_len;
412         uint32_t extra_field_checksum;
413
414         unsigned char method;
415         unsigned char level;
416
417         /* info */
418         char name[255+1];
419 } header_t;
420
421 struct globals {
422         /*const uint32_t *lzo_crc32_table;*/
423         chksum_t chksum_in;
424         chksum_t chksum_out;
425 } FIX_ALIASING;
426 #define G (*(struct globals*)&bb_common_bufsiz1)
427 #define INIT_G() do { } while (0)
428 //#define G (*ptr_to_globals)
429 //#define INIT_G() do {
430 //      SET_PTR_TO_GLOBALS(xzalloc(sizeof(G)));
431 //} while (0)
432
433
434 /**********************************************************************/
435 #define LZOP_VERSION            0x1010
436 //#define LZOP_VERSION_STRING     "1.01"
437 //#define LZOP_VERSION_DATE       "Apr 27th 2003"
438
439 #define OPTION_STRING "cfvqdt123456789CF"
440
441 enum {
442         OPT_STDOUT      = (1 << 0),
443         OPT_FORCE       = (1 << 1),
444         OPT_VERBOSE     = (1 << 2),
445         OPT_QUIET       = (1 << 3),
446         OPT_DECOMPRESS  = (1 << 4),
447         OPT_TEST        = (1 << 5),
448         OPT_1           = (1 << 6),
449         OPT_2           = (1 << 7),
450         OPT_3           = (1 << 8),
451         OPT_4           = (1 << 9),
452         OPT_5           = (1 << 10),
453         OPT_6           = (1 << 11),
454         OPT_789         = (7 << 12),
455         OPT_7           = (1 << 13),
456         OPT_8           = (1 << 14),
457         OPT_C           = (1 << 15),
458         OPT_F           = (1 << 16),
459 };
460
461 /**********************************************************************/
462 // adler32 checksum
463 // adapted from free code by Mark Adler <madler@alumni.caltech.edu>
464 // see http://www.zlib.org/
465 /**********************************************************************/
466 static FAST_FUNC uint32_t
467 lzo_adler32(uint32_t adler, const uint8_t* buf, unsigned len)
468 {
469         enum {
470                 LZO_BASE = 65521, /* largest prime smaller than 65536 */
471                 /* NMAX is the largest n such that
472                  * 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
473                 LZO_NMAX = 5552,
474         };
475         uint32_t s1 = adler & 0xffff;
476         uint32_t s2 = (adler >> 16) & 0xffff;
477         unsigned k;
478
479         if (buf == NULL)
480                 return 1;
481
482         while (len > 0) {
483                 k = len < LZO_NMAX ? (unsigned) len : LZO_NMAX;
484                 len -= k;
485                 if (k != 0) do {
486                         s1 += *buf++;
487                         s2 += s1;
488                 } while (--k > 0);
489                 s1 %= LZO_BASE;
490                 s2 %= LZO_BASE;
491         }
492         return (s2 << 16) | s1;
493 }
494
495 static FAST_FUNC uint32_t
496 lzo_crc32(uint32_t c, const uint8_t* buf, unsigned len)
497 {
498         //if (buf == NULL) - impossible
499         //      return 0;
500
501         return ~crc32_block_endian0(~c, buf, len, global_crc32_table);
502 }
503
504 /**********************************************************************/
505 static void init_chksum(chksum_t *ct)
506 {
507         ct->f_adler32 = ADLER32_INIT_VALUE;
508         ct->f_crc32 = CRC32_INIT_VALUE;
509 }
510
511 static void add_bytes_to_chksum(chksum_t *ct, const void* buf, int cnt)
512 {
513         /* We need to handle the two checksums at once, because at the
514          * beginning of the header, we don't know yet which one we'll
515          * eventually need */
516         ct->f_adler32 = lzo_adler32(ct->f_adler32, (const uint8_t*)buf, cnt);
517         ct->f_crc32 = lzo_crc32(ct->f_crc32, (const uint8_t*)buf, cnt);
518 }
519
520 static uint32_t chksum_getresult(chksum_t *ct, const header_t *h)
521 {
522         return (h->flags & F_H_CRC32) ? ct->f_crc32 : ct->f_adler32;
523 }
524
525 /**********************************************************************/
526 static uint32_t read32(void)
527 {
528         uint32_t v;
529         xread(0, &v, 4);
530         return ntohl(v);
531 }
532
533 static void write32(uint32_t v)
534 {
535         v = htonl(v);
536         xwrite(1, &v, 4);
537 }
538
539 static void f_write(const void* buf, int cnt)
540 {
541         xwrite(1, buf, cnt);
542         add_bytes_to_chksum(&G.chksum_out, buf, cnt);
543 }
544
545 static void f_read(void* buf, int cnt)
546 {
547         xread(0, buf, cnt);
548         add_bytes_to_chksum(&G.chksum_in, buf, cnt);
549 }
550
551 static int f_read8(void)
552 {
553         uint8_t v;
554         f_read(&v, 1);
555         return v;
556 }
557
558 static void f_write8(uint8_t v)
559 {
560         f_write(&v, 1);
561 }
562
563 static unsigned f_read16(void)
564 {
565         uint16_t v;
566         f_read(&v, 2);
567         return ntohs(v);
568 }
569
570 static void f_write16(uint16_t v)
571 {
572         v = htons(v);
573         f_write(&v, 2);
574 }
575
576 static uint32_t f_read32(void)
577 {
578         uint32_t v;
579         f_read(&v, 4);
580         return ntohl(v);
581 }
582
583 static void f_write32(uint32_t v)
584 {
585         v = htonl(v);
586         f_write(&v, 4);
587 }
588
589 /**********************************************************************/
590 static int lzo_get_method(header_t *h)
591 {
592         /* check method */
593         if (h->method == M_LZO1X_1) {
594                 if (h->level == 0)
595                         h->level = 3;
596         } else if (h->method == M_LZO1X_1_15) {
597                 if (h->level == 0)
598                         h->level = 1;
599         } else if (h->method == M_LZO1X_999) {
600                 if (h->level == 0)
601                         h->level = 9;
602         } else
603                 return -1;              /* not a LZO method */
604
605         /* check compression level */
606         if (h->level < 1 || h->level > 9)
607                 return 15;
608
609         return 0;
610 }
611
612 /**********************************************************************/
613 #define LZO_BLOCK_SIZE  (256 * 1024l)
614 #define MAX_BLOCK_SIZE  (64 * 1024l * 1024l)    /* DO NOT CHANGE */
615
616 /* LZO may expand uncompressible data by a small amount */
617 #define MAX_COMPRESSED_SIZE(x)  ((x) + (x) / 16 + 64 + 3)
618
619 /**********************************************************************/
620 // compress a file
621 /**********************************************************************/
622 static NOINLINE smallint lzo_compress(const header_t *h)
623 {
624         unsigned block_size = LZO_BLOCK_SIZE;
625         int r = 0; /* LZO_E_OK */
626         uint8_t *const b1 = xzalloc(block_size);
627         uint8_t *const b2 = xzalloc(MAX_COMPRESSED_SIZE(block_size));
628         unsigned src_len = 0, dst_len = 0;
629         uint32_t d_adler32 = ADLER32_INIT_VALUE;
630         uint32_t d_crc32 = CRC32_INIT_VALUE;
631         int l;
632         smallint ok = 1;
633         uint8_t *wrk_mem = NULL;
634
635         if (h->method == M_LZO1X_1)
636                 wrk_mem = xzalloc(LZO1X_1_MEM_COMPRESS);
637         else if (h->method == M_LZO1X_1_15)
638                 wrk_mem = xzalloc(LZO1X_1_15_MEM_COMPRESS);
639         else if (h->method == M_LZO1X_999)
640                 wrk_mem = xzalloc(LZO1X_999_MEM_COMPRESS);
641
642         for (;;) {
643                 /* read a block */
644                 l = full_read(0, b1, block_size);
645                 src_len = (l > 0 ? l : 0);
646
647                 /* write uncompressed block size */
648                 write32(src_len);
649
650                 /* exit if last block */
651                 if (src_len == 0)
652                         break;
653
654                 /* compute checksum of uncompressed block */
655                 if (h->flags & F_ADLER32_D)
656                         d_adler32 = lzo_adler32(ADLER32_INIT_VALUE, b1, src_len);
657                 if (h->flags & F_CRC32_D)
658                         d_crc32 = lzo_crc32(CRC32_INIT_VALUE, b1, src_len);
659
660                 /* compress */
661                 if (h->method == M_LZO1X_1)
662                         r = lzo1x_1_compress(b1, src_len, b2, &dst_len, wrk_mem);
663                 else if (h->method == M_LZO1X_1_15)
664                         r = lzo1x_1_15_compress(b1, src_len, b2, &dst_len, wrk_mem);
665 #if ENABLE_LZOP_COMPR_HIGH
666                 else if (h->method == M_LZO1X_999)
667                         r = lzo1x_999_compress_level(b1, src_len, b2, &dst_len,
668                                                 wrk_mem, h->level);
669 #endif
670                 else
671                         bb_error_msg_and_die("internal error");
672
673                 if (r != 0) /* not LZO_E_OK */
674                         bb_error_msg_and_die("internal error - compression failed");
675
676                 /* write compressed block size */
677                 if (dst_len < src_len) {
678                         /* optimize */
679                         if (h->method == M_LZO1X_999) {
680                                 unsigned new_len = src_len;
681                                 r = lzo1x_optimize(b2, dst_len, b1, &new_len, NULL);
682                                 if (r != 0 /*LZO_E_OK*/ || new_len != src_len)
683                                         bb_error_msg_and_die("internal error - optimization failed");
684                         }
685                         write32(dst_len);
686                 } else {
687                         /* data actually expanded => store data uncompressed */
688                         write32(src_len);
689                 }
690
691                 /* write checksum of uncompressed block */
692                 if (h->flags & F_ADLER32_D)
693                         write32(d_adler32);
694                 if (h->flags & F_CRC32_D)
695                         write32(d_crc32);
696
697                 if (dst_len < src_len) {
698                         /* write checksum of compressed block */
699                         if (h->flags & F_ADLER32_C)
700                                 write32(lzo_adler32(ADLER32_INIT_VALUE, b2, dst_len));
701                         if (h->flags & F_CRC32_C)
702                                 write32(lzo_crc32(CRC32_INIT_VALUE, b2, dst_len));
703                         /* write compressed block data */
704                         xwrite(1, b2, dst_len);
705                 } else {
706                         /* write uncompressed block data */
707                         xwrite(1, b1, src_len);
708                 }
709         }
710
711         free(wrk_mem);
712         free(b1);
713         free(b2);
714         return ok;
715 }
716
717 static FAST_FUNC void lzo_check(
718                 uint32_t init,
719                 uint8_t* buf, unsigned len,
720                 uint32_t FAST_FUNC (*fn)(uint32_t, const uint8_t*, unsigned),
721                 uint32_t ref)
722 {
723         /* This function, by having the same order of parameters
724          * as fn, and by being marked FAST_FUNC (same as fn),
725          * saves a dozen bytes of code.
726          */
727         uint32_t c = fn(init, buf, len);
728         if (c != ref)
729                 bb_error_msg_and_die("checksum error");
730 }
731
732 /**********************************************************************/
733 // decompress a file
734 /**********************************************************************/
735 static NOINLINE smallint lzo_decompress(const header_t *h)
736 {
737         unsigned block_size = LZO_BLOCK_SIZE;
738         int r;
739         uint32_t src_len, dst_len;
740         uint32_t c_adler32 = ADLER32_INIT_VALUE;
741         uint32_t d_adler32 = ADLER32_INIT_VALUE;
742         uint32_t c_crc32 = CRC32_INIT_VALUE, d_crc32 = CRC32_INIT_VALUE;
743         smallint ok = 1;
744         uint8_t *b1;
745         uint32_t mcs_block_size = MAX_COMPRESSED_SIZE(block_size);
746         uint8_t *b2 = NULL;
747
748         for (;;) {
749                 uint8_t *dst;
750
751                 /* read uncompressed block size */
752                 dst_len = read32();
753
754                 /* exit if last block */
755                 if (dst_len == 0)
756                         break;
757
758                 /* error if split file */
759                 if (dst_len == 0xffffffffL)
760                         /* should not happen - not yet implemented */
761                         bb_error_msg_and_die("this file is a split lzop file");
762
763                 if (dst_len > MAX_BLOCK_SIZE)
764                         bb_error_msg_and_die("corrupted data");
765
766                 /* read compressed block size */
767                 src_len = read32();
768                 if (src_len <= 0 || src_len > dst_len)
769                         bb_error_msg_and_die("corrupted data");
770
771                 if (dst_len > block_size) {
772                         if (b2) {
773                                 free(b2);
774                                 b2 = NULL;
775                         }
776                         block_size = dst_len;
777                         mcs_block_size = MAX_COMPRESSED_SIZE(block_size);
778                 }
779
780                 /* read checksum of uncompressed block */
781                 if (h->flags & F_ADLER32_D)
782                         d_adler32 = read32();
783                 if (h->flags & F_CRC32_D)
784                         d_crc32 = read32();
785
786                 /* read checksum of compressed block */
787                 if (src_len < dst_len) {
788                         if (h->flags & F_ADLER32_C)
789                                 c_adler32 = read32();
790                         if (h->flags & F_CRC32_C)
791                                 c_crc32 = read32();
792                 }
793
794                 if (b2 == NULL)
795                         b2 = xzalloc(mcs_block_size);
796                 /* read the block into the end of our buffer */
797                 b1 = b2 + mcs_block_size - src_len;
798                 xread(0, b1, src_len);
799
800                 if (src_len < dst_len) {
801                         unsigned d = dst_len;
802
803                         if (!(option_mask32 & OPT_F)) {
804                                 /* verify checksum of compressed block */
805                                 if (h->flags & F_ADLER32_C)
806                                         lzo_check(ADLER32_INIT_VALUE,
807                                                         b1, src_len,
808                                                         lzo_adler32, c_adler32);
809                                 if (h->flags & F_CRC32_C)
810                                         lzo_check(CRC32_INIT_VALUE,
811                                                         b1, src_len,
812                                                         lzo_crc32, c_crc32);
813                         }
814
815                         /* decompress */
816 //                      if (option_mask32 & OPT_F)
817 //                              r = lzo1x_decompress(b1, src_len, b2, &d, NULL);
818 //                      else
819                                 r = lzo1x_decompress_safe(b1, src_len, b2, &d, NULL);
820
821                         if (r != 0 /*LZO_E_OK*/ || dst_len != d) {
822                                 bb_error_msg_and_die("corrupted data");
823                         }
824                         dst = b2;
825                 } else {
826                         /* "stored" block => no decompression */
827                         dst = b1;
828                 }
829
830                 if (!(option_mask32 & OPT_F)) {
831                         /* verify checksum of uncompressed block */
832                         if (h->flags & F_ADLER32_D)
833                                 lzo_check(ADLER32_INIT_VALUE,
834                                         dst, dst_len,
835                                         lzo_adler32, d_adler32);
836                         if (h->flags & F_CRC32_D)
837                                 lzo_check(CRC32_INIT_VALUE,
838                                         dst, dst_len,
839                                         lzo_crc32, d_crc32);
840                 }
841
842                 /* write uncompressed block data */
843                 xwrite(1, dst, dst_len);
844         }
845
846         free(b2);
847         return ok;
848 }
849
850 /**********************************************************************/
851 // lzop file signature (shamelessly borrowed from PNG)
852 /**********************************************************************/
853 /*
854  * The first nine bytes of a lzop file always contain the following values:
855  *
856  *                                 0   1   2   3   4   5   6   7   8
857  *                               --- --- --- --- --- --- --- --- ---
858  * (hex)                          89  4c  5a  4f  00  0d  0a  1a  0a
859  * (decimal)                     137  76  90  79   0  13  10  26  10
860  * (C notation - ASCII)         \211   L   Z   O  \0  \r  \n \032 \n
861  */
862
863 /* (vda) comparison with lzop v1.02rc1 ("lzop -1 <FILE" cmd):
864  * Only slight differences in header:
865  * -00000000  89 4c 5a 4f 00 0d 0a 1a 0a 10 20 20 20 09 40 02
866  * +00000000  89 4c 5a 4f 00 0d 0a 1a 0a 10 10 20 30 09 40 02
867  *                                       ^^^^^ ^^^^^
868  *                                     version lib_version
869  * -00000010  01 03 00 00 0d 00 00 81 a4 49 f7 a6 3f 00 00 00
870  * +00000010  01 03 00 00 01 00 00 00 00 00 00 00 00 00 00 00
871  *               ^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^
872  *               flags       mode        mtime
873  * -00000020  00 00 2d 67 04 17 00 04 00 00 00 03 ed ec 9d 6d
874  * +00000020  00 00 10 5f 00 c1 00 04 00 00 00 03 ed ec 9d 6d
875  *                  ^^^^^^^^^^^
876  *                  chksum_out
877  * The rest is identical.
878 */
879 static const unsigned char lzop_magic[9] = {
880         0x89, 0x4c, 0x5a, 0x4f, 0x00, 0x0d, 0x0a, 0x1a, 0x0a
881 };
882
883 /* This coding is derived from Alexander Lehmann's pngcheck code. */
884 static void check_magic(void)
885 {
886         unsigned char magic[sizeof(lzop_magic)];
887         xread(0, magic, sizeof(magic));
888         if (memcmp(magic, lzop_magic, sizeof(lzop_magic)) != 0)
889                 bb_error_msg_and_die("bad magic number");
890 }
891
892 /**********************************************************************/
893 // lzop file header
894 /**********************************************************************/
895 static void write_header(const header_t *h)
896 {
897         int l;
898
899         xwrite(1, lzop_magic, sizeof(lzop_magic));
900
901         init_chksum(&G.chksum_out);
902
903         f_write16(h->version);
904         f_write16(h->lib_version);
905         f_write16(h->version_needed_to_extract);
906         f_write8(h->method);
907         f_write8(h->level);
908         f_write32(h->flags);
909         f_write32(h->mode);
910         f_write32(h->mtime);
911         f_write32(h->gmtdiff);
912
913         l = (int) strlen(h->name);
914         f_write8(l);
915         if (l)
916                 f_write(h->name, l);
917
918         f_write32(chksum_getresult(&G.chksum_out, h));
919 }
920
921 static int read_header(header_t *h)
922 {
923         int r;
924         int l;
925         uint32_t checksum;
926
927         memset(h, 0, sizeof(*h));
928         h->version_needed_to_extract = 0x0900;  /* first lzop version */
929         h->level = 0;
930
931         init_chksum(&G.chksum_in);
932
933         h->version = f_read16();
934         if (h->version < 0x0900)
935                 return 3;
936         h->lib_version = f_read16();
937         if (h->version >= 0x0940) {
938                 h->version_needed_to_extract = f_read16();
939                 if (h->version_needed_to_extract > LZOP_VERSION)
940                         return 16;
941                 if (h->version_needed_to_extract < 0x0900)
942                         return 3;
943         }
944         h->method = f_read8();
945         if (h->version >= 0x0940)
946                 h->level = f_read8();
947         h->flags = f_read32();
948         if (h->flags & F_H_FILTER)
949                 return 16; /* filter not supported */
950         h->mode = f_read32();
951         h->mtime = f_read32();
952         if (h->version >= 0x0940)
953                 h->gmtdiff = f_read32();
954
955         l = f_read8();
956         if (l > 0)
957                 f_read(h->name, l);
958         h->name[l] = 0;
959
960         checksum = chksum_getresult(&G.chksum_in, h);
961         h->header_checksum = f_read32();
962         if (h->header_checksum != checksum)
963                 return 2;
964
965         if (h->method <= 0)
966                 return 14;
967         r = lzo_get_method(h);
968         if (r != 0)
969                 return r;
970
971         /* check reserved flags */
972         if (h->flags & F_RESERVED)
973                 return -13;
974
975         /* skip extra field [not used yet] */
976         if (h->flags & F_H_EXTRA_FIELD) {
977                 uint32_t k;
978
979                 /* note: the checksum also covers the length */
980                 init_chksum(&G.chksum_in);
981                 h->extra_field_len = f_read32();
982                 for (k = 0; k < h->extra_field_len; k++)
983                         f_read8();
984                 checksum = chksum_getresult(&G.chksum_in, h);
985                 h->extra_field_checksum = f_read32();
986                 if (h->extra_field_checksum != checksum)
987                         return 3;
988         }
989
990         return 0;
991 }
992
993 static void p_header(header_t *h)
994 {
995         int r;
996
997         r = read_header(h);
998         if (r == 0)
999                 return;
1000         bb_error_msg_and_die("header_error %d", r);
1001 }
1002
1003 /**********************************************************************/
1004 // compress
1005 /**********************************************************************/
1006 static void lzo_set_method(header_t *h)
1007 {
1008         int level = 1;
1009
1010         if (option_mask32 & OPT_1) {
1011                 h->method = M_LZO1X_1_15;
1012         } else if (option_mask32 & OPT_789) {
1013 #if ENABLE_LZOP_COMPR_HIGH
1014                 h->method = M_LZO1X_999;
1015                 if (option_mask32 & OPT_7)
1016                         level = 7;
1017                 else if (option_mask32 & OPT_8)
1018                         level = 8;
1019                 else
1020                         level = 9;
1021 #else
1022                 bb_error_msg_and_die("high compression not compiled in");
1023 #endif
1024         } else { /* levels 2..6 or none (defaults to level 3) */
1025                 h->method = M_LZO1X_1;
1026                 level = 5; /* levels 2-6 are actually the same */
1027         }
1028
1029         h->level = level;
1030 }
1031
1032 static smallint do_lzo_compress(void)
1033 {
1034         header_t header;
1035
1036 #define h (&header)
1037         memset(h, 0, sizeof(*h));
1038
1039         lzo_set_method(h);
1040
1041         h->version = (LZOP_VERSION & 0xffff);
1042         h->version_needed_to_extract = 0x0940;
1043         h->lib_version = lzo_version() & 0xffff;
1044
1045         h->flags = (F_OS & F_OS_MASK) | (F_CS & F_CS_MASK);
1046
1047         if (!(option_mask32 & OPT_F) || h->method == M_LZO1X_999) {
1048                 h->flags |= F_ADLER32_D;
1049                 if (option_mask32 & OPT_C)
1050                         h->flags |= F_ADLER32_C;
1051         }
1052         write_header(h);
1053         return lzo_compress(h);
1054 #undef h
1055 }
1056
1057 /**********************************************************************/
1058 // decompress
1059 /**********************************************************************/
1060 static smallint do_lzo_decompress(void)
1061 {
1062         header_t header;
1063
1064         check_magic();
1065         p_header(&header);
1066         return lzo_decompress(&header);
1067 }
1068
1069 static char* FAST_FUNC make_new_name_lzop(char *filename, const char *expected_ext UNUSED_PARAM)
1070 {
1071         if (option_mask32 & OPT_DECOMPRESS) {
1072                 char *extension = strrchr(filename, '.');
1073                 if (!extension || strcmp(extension + 1, "lzo") != 0)
1074                         return xasprintf("%s.out", filename);
1075                 *extension = '\0';
1076                 return filename;
1077         }
1078         return xasprintf("%s.lzo", filename);
1079 }
1080
1081 static IF_DESKTOP(long long) int FAST_FUNC pack_lzop(transformer_aux_data_t *aux UNUSED_PARAM)
1082 {
1083         if (option_mask32 & OPT_DECOMPRESS)
1084                 return do_lzo_decompress();
1085         return do_lzo_compress();
1086 }
1087
1088 int lzop_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1089 int lzop_main(int argc UNUSED_PARAM, char **argv)
1090 {
1091         getopt32(argv, OPTION_STRING);
1092         argv += optind;
1093         /* lzopcat? */
1094         if (applet_name[4] == 'c')
1095                 option_mask32 |= (OPT_STDOUT | OPT_DECOMPRESS);
1096         /* unlzop? */
1097         if (applet_name[4] == 'o')
1098                 option_mask32 |= OPT_DECOMPRESS;
1099
1100         global_crc32_table = crc32_filltable(NULL, 0);
1101         return bbunpack(argv, pack_lzop, make_new_name_lzop, /*unused:*/ NULL);
1102 }