bzcat.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /* bzcat.c - bzip2 decompression
  2. *
  3. * Copyright 2003, 2007 Rob Landley <rob@landley.net>
  4. *
  5. * Based on a close reading (but not the actual code) of the original bzip2
  6. * decompression code by Julian R Seward (jseward@acm.org), which also
  7. * acknowledges contributions by Mike Burrows, David Wheeler, Peter Fenwick,
  8. * Alistair Moffat, Radford Neal, Ian H. Witten, Robert Sedgewick, and
  9. * Jon L. Bentley.
  10. *
  11. * No standard.
  12. USE_BZCAT(NEWTOY(bzcat, NULL, TOYFLAG_USR|TOYFLAG_BIN))
  13. USE_BUNZIP2(NEWTOY(bunzip2, "cftkv", TOYFLAG_USR|TOYFLAG_BIN))
  14. config BUNZIP2
  15. bool "bunzip2"
  16. default y
  17. help
  18. usage: bunzip2 [-cftkv] [FILE...]
  19. Decompress listed files (file.bz becomes file) deleting archive file(s).
  20. Read from stdin if no files listed.
  21. -c Force output to stdout
  22. -f Force decompression (if FILE doesn't end in .bz, replace original)
  23. -k Keep input files (-c and -t imply this)
  24. -t Test integrity
  25. -v Verbose
  26. config BZCAT
  27. bool "bzcat"
  28. default y
  29. help
  30. usage: bzcat [FILE...]
  31. Decompress listed files to stdout. Use stdin if no files listed.
  32. */
  33. #define FOR_bunzip2
  34. #include "toys.h"
  35. #define THREADS 1
  36. // Constants for huffman coding
  37. #define MAX_GROUPS 6
  38. #define GROUP_SIZE 50 /* 64 would have been more efficient */
  39. #define MAX_HUFCODE_BITS 20 /* Longest huffman code allowed */
  40. #define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
  41. #define SYMBOL_RUNA 0
  42. #define SYMBOL_RUNB 1
  43. // Other housekeeping constants
  44. #define IOBUF_SIZE 4096
  45. // Status return values
  46. #define RETVAL_LAST_BLOCK (-100)
  47. #define RETVAL_NOT_BZIP_DATA (-1)
  48. #define RETVAL_DATA_ERROR (-2)
  49. #define RETVAL_OBSOLETE_INPUT (-3)
  50. // This is what we know about each huffman coding group
  51. struct group_data {
  52. int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
  53. char minLen, maxLen;
  54. };
  55. // Data for burrows wheeler transform
  56. struct bwdata {
  57. unsigned int origPtr;
  58. int byteCount[256];
  59. // State saved when interrupting output
  60. int writePos, writeRun, writeCount, writeCurrent;
  61. unsigned int dataCRC, headerCRC;
  62. unsigned int *dbuf;
  63. };
  64. // Structure holding all the housekeeping data, including IO buffers and
  65. // memory that persists between calls to bunzip
  66. struct bunzip_data {
  67. // Input stream, input buffer, input bit buffer
  68. int in_fd, inbufCount, inbufPos;
  69. char *inbuf;
  70. unsigned int inbufBitCount, inbufBits;
  71. // Output buffer
  72. char outbuf[IOBUF_SIZE];
  73. int outbufPos;
  74. unsigned int totalCRC;
  75. // First pass decompression data (Huffman and MTF decoding)
  76. char selectors[32768]; // nSelectors=15 bits
  77. struct group_data groups[MAX_GROUPS]; // huffman coding tables
  78. int symTotal, groupCount, nSelectors;
  79. unsigned char symToByte[256], mtfSymbol[256];
  80. // The CRC values stored in the block header and calculated from the data
  81. unsigned int crc32Table[256];
  82. // Second pass decompression data (burrows-wheeler transform)
  83. unsigned int dbufSize;
  84. struct bwdata bwdata[THREADS];
  85. };
  86. // Return the next nnn bits of input. All reads from the compressed input
  87. // are done through this function. All reads are big endian.
  88. static unsigned int get_bits(struct bunzip_data *bd, char bits_wanted)
  89. {
  90. unsigned int bits = 0;
  91. // If we need to get more data from the byte buffer, do so. (Loop getting
  92. // one byte at a time to enforce endianness and avoid unaligned access.)
  93. while (bd->inbufBitCount < bits_wanted) {
  94. // If we need to read more data from file into byte buffer, do so
  95. if (bd->inbufPos == bd->inbufCount) {
  96. if (0 >= (bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE)))
  97. error_exit("input EOF");
  98. bd->inbufPos = 0;
  99. }
  100. // Avoid 32-bit overflow (dump bit buffer to top of output)
  101. if (bd->inbufBitCount>=24) {
  102. bits = bd->inbufBits&((1<<bd->inbufBitCount)-1);
  103. bits_wanted -= bd->inbufBitCount;
  104. bits <<= bits_wanted;
  105. bd->inbufBitCount = 0;
  106. }
  107. // Grab next 8 bits of input from buffer.
  108. bd->inbufBits = (bd->inbufBits<<8) | bd->inbuf[bd->inbufPos++];
  109. bd->inbufBitCount += 8;
  110. }
  111. // Calculate result
  112. bd->inbufBitCount -= bits_wanted;
  113. bits |= (bd->inbufBits>>bd->inbufBitCount) & ((1<<bits_wanted)-1);
  114. return bits;
  115. }
  116. /* Read block header at start of a new compressed data block. Consists of:
  117. *
  118. * 48 bits : Block signature, either pi (data block) or e (EOF block).
  119. * 32 bits : bw->headerCRC
  120. * 1 bit : obsolete feature flag.
  121. * 24 bits : origPtr (Burrows-wheeler unwind index, only 20 bits ever used)
  122. * 16 bits : Mapping table index.
  123. *[16 bits]: symToByte[symTotal] (Mapping table. For each bit set in mapping
  124. * table index above, read another 16 bits of mapping table data.
  125. * If correspondig bit is unset, all bits in that mapping table
  126. * section are 0.)
  127. * 3 bits : groupCount (how many huffman tables used to encode, anywhere
  128. * from 2 to MAX_GROUPS)
  129. * variable: hufGroup[groupCount] (MTF encoded huffman table data.)
  130. */
  131. static int read_block_header(struct bunzip_data *bd, struct bwdata *bw)
  132. {
  133. struct group_data *hufGroup;
  134. int hh, ii, jj, kk, symCount, *base, *limit;
  135. unsigned char uc;
  136. // Read in header signature and CRC (which is stored big endian)
  137. ii = get_bits(bd, 24);
  138. jj = get_bits(bd, 24);
  139. bw->headerCRC = get_bits(bd,32);
  140. // Is this the EOF block with CRC for whole file? (Constant is "e")
  141. if (ii==0x177245 && jj==0x385090) return RETVAL_LAST_BLOCK;
  142. // Is this a valid data block? (Constant is "pi".)
  143. if (ii!=0x314159 || jj!=0x265359) return RETVAL_NOT_BZIP_DATA;
  144. // We can add support for blockRandomised if anybody complains.
  145. if (get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
  146. if ((bw->origPtr = get_bits(bd,24)) > bd->dbufSize) return RETVAL_DATA_ERROR;
  147. // mapping table: if some byte values are never used (encoding things
  148. // like ascii text), the compression code removes the gaps to have fewer
  149. // symbols to deal with, and writes a sparse bitfield indicating which
  150. // values were present. We make a translation table to convert the symbols
  151. // back to the corresponding bytes.
  152. hh = get_bits(bd, 16);
  153. bd->symTotal = 0;
  154. for (ii=0; ii<16; ii++) {
  155. if (hh & (1 << (15 - ii))) {
  156. kk = get_bits(bd, 16);
  157. for (jj=0; jj<16; jj++)
  158. if (kk & (1 << (15 - jj)))
  159. bd->symToByte[bd->symTotal++] = (16 * ii) + jj;
  160. }
  161. }
  162. // How many different huffman coding groups does this block use?
  163. bd->groupCount = get_bits(bd,3);
  164. if (bd->groupCount<2 || bd->groupCount>MAX_GROUPS) return RETVAL_DATA_ERROR;
  165. // nSelectors: Every GROUP_SIZE many symbols we switch huffman coding
  166. // tables. Each group has a selector, which is an index into the huffman
  167. // coding table arrays.
  168. //
  169. // Read in the group selector array, which is stored as MTF encoded
  170. // bit runs. (MTF = Move To Front. Every time a symbol occurs it's moved
  171. // to the front of the table, so it has a shorter encoding next time.)
  172. if (!(bd->nSelectors = get_bits(bd, 15))) return RETVAL_DATA_ERROR;
  173. for (ii=0; ii<bd->groupCount; ii++) bd->mtfSymbol[ii] = ii;
  174. for (ii=0; ii<bd->nSelectors; ii++) {
  175. // Get next value
  176. for(jj=0;get_bits(bd,1);jj++)
  177. if (jj>=bd->groupCount) return RETVAL_DATA_ERROR;
  178. // Decode MTF to get the next selector, and move it to the front.
  179. uc = bd->mtfSymbol[jj];
  180. memmove(bd->mtfSymbol+1, bd->mtfSymbol, jj);
  181. bd->mtfSymbol[0] = bd->selectors[ii] = uc;
  182. }
  183. // Read the huffman coding tables for each group, which code for symTotal
  184. // literal symbols, plus two run symbols (RUNA, RUNB)
  185. symCount = bd->symTotal+2;
  186. for (jj=0; jj<bd->groupCount; jj++) {
  187. unsigned char length[MAX_SYMBOLS];
  188. unsigned temp[MAX_HUFCODE_BITS+1];
  189. int minLen, maxLen, pp;
  190. // Read lengths
  191. hh = get_bits(bd, 5);
  192. for (ii = 0; ii < symCount; ii++) {
  193. for(;;) {
  194. // !hh || hh > MAX_HUFCODE_BITS in one test.
  195. if (MAX_HUFCODE_BITS-1 < (unsigned)hh-1) return RETVAL_DATA_ERROR;
  196. // Grab 2 bits instead of 1 (slightly smaller/faster). Stop if
  197. // first bit is 0, otherwise second bit says whether to
  198. // increment or decrement.
  199. kk = get_bits(bd, 2);
  200. if (kk & 2) hh += 1 - ((kk&1)<<1);
  201. else {
  202. bd->inbufBitCount++;
  203. break;
  204. }
  205. }
  206. length[ii] = hh;
  207. }
  208. // Find largest and smallest lengths in this group
  209. minLen = maxLen = length[0];
  210. for (ii = 1; ii < symCount; ii++) {
  211. if(length[ii] > maxLen) maxLen = length[ii];
  212. else if(length[ii] < minLen) minLen = length[ii];
  213. }
  214. /* Calculate permute[], base[], and limit[] tables from length[].
  215. *
  216. * permute[] is the lookup table for converting huffman coded symbols
  217. * into decoded symbols. It contains symbol values sorted by length.
  218. *
  219. * base[] is the amount to subtract from the value of a huffman symbol
  220. * of a given length when using permute[].
  221. *
  222. * limit[] indicates the largest numerical value a symbol with a given
  223. * number of bits can have. It lets us know when to stop reading.
  224. *
  225. * To use these, keep reading bits until value <= limit[bitcount] or
  226. * you've read over 20 bits (error). Then the decoded symbol
  227. * equals permute[hufcode_value - base[hufcode_bitcount]].
  228. */
  229. hufGroup = bd->groups+jj;
  230. hufGroup->minLen = minLen;
  231. hufGroup->maxLen = maxLen;
  232. // Note that minLen can't be smaller than 1, so we adjust the base
  233. // and limit array pointers so we're not always wasting the first
  234. // entry. We do this again when using them (during symbol decoding).
  235. base = hufGroup->base-1;
  236. limit = hufGroup->limit-1;
  237. // zero temp[] and limit[], and calculate permute[]
  238. pp = 0;
  239. for (ii = minLen; ii <= maxLen; ii++) {
  240. temp[ii] = limit[ii] = 0;
  241. for (hh = 0; hh < symCount; hh++)
  242. if (length[hh] == ii) hufGroup->permute[pp++] = hh;
  243. }
  244. // Count symbols coded for at each bit length
  245. for (ii = 0; ii < symCount; ii++) temp[length[ii]]++;
  246. /* Calculate limit[] (the largest symbol-coding value at each bit
  247. * length, which is (previous limit<<1)+symbols at this level), and
  248. * base[] (number of symbols to ignore at each bit length, which is
  249. * limit minus the cumulative count of symbols coded for already). */
  250. pp = hh = 0;
  251. for (ii = minLen; ii < maxLen; ii++) {
  252. pp += temp[ii];
  253. limit[ii] = pp-1;
  254. pp <<= 1;
  255. base[ii+1] = pp-(hh+=temp[ii]);
  256. }
  257. limit[maxLen] = pp+temp[maxLen]-1;
  258. limit[maxLen+1] = INT_MAX;
  259. base[minLen] = 0;
  260. }
  261. return 0;
  262. }
  263. /* First pass, read block's symbols into dbuf[dbufCount].
  264. *
  265. * This undoes three types of compression: huffman coding, run length encoding,
  266. * and move to front encoding. We have to undo all those to know when we've
  267. * read enough input.
  268. */
  269. static int read_huffman_data(struct bunzip_data *bd, struct bwdata *bw)
  270. {
  271. struct group_data *hufGroup;
  272. int ii, jj, kk, runPos, dbufCount, symCount, selector, nextSym,
  273. *byteCount, *base, *limit;
  274. unsigned hh, *dbuf = bw->dbuf;
  275. unsigned char uc;
  276. // We've finished reading and digesting the block header. Now read this
  277. // block's huffman coded symbols from the file and undo the huffman coding
  278. // and run length encoding, saving the result into dbuf[dbufCount++] = uc
  279. // Initialize symbol occurrence counters and symbol mtf table
  280. byteCount = bw->byteCount;
  281. for(ii=0; ii<256; ii++) {
  282. byteCount[ii] = 0;
  283. bd->mtfSymbol[ii] = ii;
  284. }
  285. // Loop through compressed symbols. This is the first "tight inner loop"
  286. // that needs to be micro-optimized for speed. (This one fills out dbuf[]
  287. // linearly, staying in cache more, so isn't as limited by DRAM access.)
  288. runPos = dbufCount = symCount = selector = 0;
  289. // Some unnecessary initializations to shut gcc up.
  290. base = limit = 0;
  291. hufGroup = 0;
  292. hh = 0;
  293. for (;;) {
  294. // Have we reached the end of this huffman group?
  295. if (!(symCount--)) {
  296. // Determine which huffman coding group to use.
  297. symCount = GROUP_SIZE-1;
  298. if (selector >= bd->nSelectors) return RETVAL_DATA_ERROR;
  299. hufGroup = bd->groups + bd->selectors[selector++];
  300. base = hufGroup->base-1;
  301. limit = hufGroup->limit-1;
  302. }
  303. // Read next huffman-coded symbol (into jj).
  304. ii = hufGroup->minLen;
  305. jj = get_bits(bd, ii);
  306. while (jj > limit[ii]) {
  307. // if (ii > hufGroup->maxLen) return RETVAL_DATA_ERROR;
  308. ii++;
  309. // Unroll get_bits() to avoid a function call when the data's in
  310. // the buffer already.
  311. kk = bd->inbufBitCount
  312. ? (bd->inbufBits >> --(bd->inbufBitCount)) & 1 : get_bits(bd, 1);
  313. jj = (jj << 1) | kk;
  314. }
  315. // Huffman decode jj into nextSym (with bounds checking)
  316. jj-=base[ii];
  317. if (ii > hufGroup->maxLen || (unsigned)jj >= MAX_SYMBOLS)
  318. return RETVAL_DATA_ERROR;
  319. nextSym = hufGroup->permute[jj];
  320. // If this is a repeated run, loop collecting data
  321. if ((unsigned)nextSym <= SYMBOL_RUNB) {
  322. // If this is the start of a new run, zero out counter
  323. if(!runPos) {
  324. runPos = 1;
  325. hh = 0;
  326. }
  327. /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
  328. each bit position, add 1 or 2 instead. For example,
  329. 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
  330. You can make any bit pattern that way using 1 less symbol than
  331. the basic or 0/1 method (except all bits 0, which would use no
  332. symbols, but a run of length 0 doesn't mean anything in this
  333. context). Thus space is saved. */
  334. hh += (runPos << nextSym); // +runPos if RUNA; +2*runPos if RUNB
  335. runPos <<= 1;
  336. continue;
  337. }
  338. /* When we hit the first non-run symbol after a run, we now know
  339. how many times to repeat the last literal, so append that many
  340. copies to our buffer of decoded symbols (dbuf) now. (The last
  341. literal used is the one at the head of the mtfSymbol array.) */
  342. if (runPos) {
  343. runPos = 0;
  344. // Check for integer overflow
  345. if (hh>bd->dbufSize || dbufCount+hh>bd->dbufSize)
  346. return RETVAL_DATA_ERROR;
  347. uc = bd->symToByte[bd->mtfSymbol[0]];
  348. byteCount[uc] += hh;
  349. while (hh--) dbuf[dbufCount++] = uc;
  350. }
  351. // Is this the terminating symbol?
  352. if (nextSym>bd->symTotal) break;
  353. /* At this point, the symbol we just decoded indicates a new literal
  354. character. Subtract one to get the position in the MTF array
  355. at which this literal is currently to be found. (Note that the
  356. result can't be -1 or 0, because 0 and 1 are RUNA and RUNB.
  357. Another instance of the first symbol in the mtf array, position 0,
  358. would have been handled as part of a run.) */
  359. if (dbufCount>=bd->dbufSize) return RETVAL_DATA_ERROR;
  360. ii = nextSym - 1;
  361. uc = bd->mtfSymbol[ii];
  362. // On my laptop, unrolling this memmove() into a loop shaves 3.5% off
  363. // the total running time.
  364. while(ii--) bd->mtfSymbol[ii+1] = bd->mtfSymbol[ii];
  365. bd->mtfSymbol[0] = uc;
  366. uc = bd->symToByte[uc];
  367. // We have our literal byte. Save it into dbuf.
  368. byteCount[uc]++;
  369. dbuf[dbufCount++] = (unsigned int)uc;
  370. }
  371. // Now we know what dbufCount is, do a better sanity check on origPtr.
  372. if (bw->origPtr >= (bw->writeCount = dbufCount)) return RETVAL_DATA_ERROR;
  373. return 0;
  374. }
  375. // Flush output buffer to disk
  376. static void flush_bunzip_outbuf(struct bunzip_data *bd, int out_fd)
  377. {
  378. if (bd->outbufPos) {
  379. if (write(out_fd, bd->outbuf, bd->outbufPos) != bd->outbufPos)
  380. error_exit("output EOF");
  381. bd->outbufPos = 0;
  382. }
  383. }
  384. static void burrows_wheeler_prep(struct bunzip_data *bd, struct bwdata *bw)
  385. {
  386. int ii, jj;
  387. unsigned int *dbuf = bw->dbuf;
  388. int *byteCount = bw->byteCount;
  389. // Turn byteCount into cumulative occurrence counts of 0 to n-1.
  390. jj = 0;
  391. for (ii=0; ii<256; ii++) {
  392. int kk = jj + byteCount[ii];
  393. byteCount[ii] = jj;
  394. jj = kk;
  395. }
  396. // Use occurrence counts to quickly figure out what order dbuf would be in
  397. // if we sorted it.
  398. for (ii=0; ii < bw->writeCount; ii++) {
  399. unsigned char uc = dbuf[ii];
  400. dbuf[byteCount[uc]] |= (ii << 8);
  401. byteCount[uc]++;
  402. }
  403. // blockRandomised support would go here.
  404. // Using ii as position, jj as previous character, hh as current character,
  405. // and uc as run count.
  406. bw->dataCRC = 0xffffffffL;
  407. /* Decode first byte by hand to initialize "previous" byte. Note that it
  408. doesn't get output, and if the first three characters are identical
  409. it doesn't qualify as a run (hence uc=255, which will either wrap
  410. to 1 or get reset). */
  411. if (bw->writeCount) {
  412. bw->writePos = dbuf[bw->origPtr];
  413. bw->writeCurrent = (unsigned char)bw->writePos;
  414. bw->writePos >>= 8;
  415. bw->writeRun = -1;
  416. }
  417. }
  418. // Decompress a block of text to intermediate buffer
  419. static int read_bunzip_data(struct bunzip_data *bd)
  420. {
  421. int rc = read_block_header(bd, bd->bwdata);
  422. if (!rc) rc=read_huffman_data(bd, bd->bwdata);
  423. // First thing that can be done by a background thread.
  424. burrows_wheeler_prep(bd, bd->bwdata);
  425. return rc;
  426. }
  427. // Undo burrows-wheeler transform on intermediate buffer to produce output.
  428. // If !len, write up to len bytes of data to buf. Otherwise write to out_fd.
  429. // Returns len ? bytes written : 0. Notice all errors are negative #'s.
  430. //
  431. // Burrows-wheeler transform is described at:
  432. // http://dogma.net/markn/articles/bwt/bwt.htm
  433. // http://marknelson.us/1996/09/01/bwt/
  434. static int write_bunzip_data(struct bunzip_data *bd, struct bwdata *bw,
  435. int out_fd, char *outbuf, int len)
  436. {
  437. unsigned int *dbuf = bw->dbuf;
  438. int count, pos, current, run, copies, outbyte, previous, gotcount = 0;
  439. for (;;) {
  440. // If last read was short due to end of file, return last block now
  441. if (bw->writeCount < 0) return bw->writeCount;
  442. // If we need to refill dbuf, do it.
  443. if (!bw->writeCount) {
  444. int i = read_bunzip_data(bd);
  445. if (i) {
  446. if (i == RETVAL_LAST_BLOCK) {
  447. bw->writeCount = i;
  448. return gotcount;
  449. } else return i;
  450. }
  451. }
  452. // loop generating output
  453. count = bw->writeCount;
  454. pos = bw->writePos;
  455. current = bw->writeCurrent;
  456. run = bw->writeRun;
  457. while (count) {
  458. // If somebody (like tar) wants a certain number of bytes of
  459. // data from memory instead of written to a file, humor them.
  460. if (len && bd->outbufPos >= len) goto dataus_interruptus;
  461. count--;
  462. // Follow sequence vector to undo Burrows-Wheeler transform.
  463. previous = current;
  464. pos = dbuf[pos];
  465. current = pos&0xff;
  466. pos >>= 8;
  467. // Whenever we see 3 consecutive copies of the same byte,
  468. // the 4th is a repeat count
  469. if (run++ == 3) {
  470. copies = current;
  471. outbyte = previous;
  472. current = -1;
  473. } else {
  474. copies = 1;
  475. outbyte = current;
  476. }
  477. // Output bytes to buffer, flushing to file if necessary
  478. while (copies--) {
  479. if (bd->outbufPos == IOBUF_SIZE) flush_bunzip_outbuf(bd, out_fd);
  480. bd->outbuf[bd->outbufPos++] = outbyte;
  481. bw->dataCRC = (bw->dataCRC << 8)
  482. ^ bd->crc32Table[(bw->dataCRC >> 24) ^ outbyte];
  483. }
  484. if (current != previous) run=0;
  485. }
  486. // decompression of this block completed successfully
  487. bw->dataCRC = ~(bw->dataCRC);
  488. bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bw->dataCRC;
  489. // if this block had a crc error, force file level crc error.
  490. if (bw->dataCRC != bw->headerCRC) {
  491. bd->totalCRC = bw->headerCRC+1;
  492. return RETVAL_LAST_BLOCK;
  493. }
  494. dataus_interruptus:
  495. bw->writeCount = count;
  496. if (len) {
  497. gotcount += bd->outbufPos;
  498. memcpy(outbuf, bd->outbuf, len);
  499. // If we got enough data, checkpoint loop state and return
  500. if ((len -= bd->outbufPos)<1) {
  501. bd->outbufPos -= len;
  502. if (bd->outbufPos) memmove(bd->outbuf, bd->outbuf+len, bd->outbufPos);
  503. bw->writePos = pos;
  504. bw->writeCurrent = current;
  505. bw->writeRun = run;
  506. return gotcount;
  507. }
  508. }
  509. }
  510. }
  511. // Allocate the structure, read file header. If !len, src_fd contains
  512. // filehandle to read from. Else inbuf contains data.
  513. static int start_bunzip(struct bunzip_data **bdp, int src_fd, char *inbuf,
  514. int len)
  515. {
  516. struct bunzip_data *bd;
  517. unsigned int i;
  518. // Figure out how much data to allocate.
  519. i = sizeof(struct bunzip_data);
  520. if (!len) i += IOBUF_SIZE;
  521. // Allocate bunzip_data. Most fields initialize to zero.
  522. bd = *bdp = xzalloc(i);
  523. if (len) {
  524. bd->inbuf = inbuf;
  525. bd->inbufCount = len;
  526. bd->in_fd = -1;
  527. } else {
  528. bd->inbuf = (char *)(bd+1);
  529. bd->in_fd = src_fd;
  530. }
  531. crc_init(bd->crc32Table, 0);
  532. // Ensure that file starts with "BZh".
  533. for (i=0;i<3;i++) if (get_bits(bd,8)!="BZh"[i]) return RETVAL_NOT_BZIP_DATA;
  534. // Next byte ascii '1'-'9', indicates block size in units of 100k of
  535. // uncompressed data. Allocate intermediate buffer for block.
  536. i = get_bits(bd, 8);
  537. if (i<'1' || i>'9') return RETVAL_NOT_BZIP_DATA;
  538. bd->dbufSize = 100000*(i-'0')*THREADS;
  539. for (i=0; i<THREADS; i++)
  540. bd->bwdata[i].dbuf = xmalloc(bd->dbufSize * sizeof(int));
  541. return 0;
  542. }
  543. // Example usage: decompress src_fd to dst_fd. (Stops at end of bzip data,
  544. // not end of file.)
  545. static char *bunzipStream(int src_fd, int dst_fd)
  546. {
  547. struct bunzip_data *bd;
  548. char *bunzip_errors[] = {0, "not bzip", "bad data", "old format"};
  549. int i, j;
  550. if (!(i = start_bunzip(&bd,src_fd, 0, 0))) {
  551. i = write_bunzip_data(bd,bd->bwdata, dst_fd, 0, 0);
  552. if (i==RETVAL_LAST_BLOCK) {
  553. if (bd->bwdata[0].headerCRC==bd->totalCRC) i = 0;
  554. else i = RETVAL_DATA_ERROR;
  555. }
  556. }
  557. flush_bunzip_outbuf(bd, dst_fd);
  558. for (j=0; j<THREADS; j++) free(bd->bwdata[j].dbuf);
  559. free(bd);
  560. return bunzip_errors[-i];
  561. }
  562. static void do_bzcat(int fd, char *name)
  563. {
  564. char *err = bunzipStream(fd, 1);
  565. if (err) error_exit_raw(err);
  566. }
  567. void bzcat_main(void)
  568. {
  569. loopfiles(toys.optargs, do_bzcat);
  570. }
  571. static void do_bunzip2(int fd, char *name)
  572. {
  573. int outfd = 1, rename = 0, len = strlen(name);
  574. char *tmp, *err, *dotbz = 0;
  575. // Trim off .bz or .bz2 extension
  576. dotbz = name+len-3;
  577. if ((len>3 && !strcmp(dotbz, ".bz")) || (len>4 && !strcmp(--dotbz, ".bz2")))
  578. dotbz = 0;
  579. // For - no replace
  580. if (toys.optflags&FLAG_t) outfd = xopen("/dev/null", O_WRONLY);
  581. else if ((fd || strcmp(name, "-")) && !(toys.optflags&FLAG_c)) {
  582. if (toys.optflags&FLAG_k) {
  583. if (!dotbz || !access(name, X_OK)) {
  584. error_msg("%s exists", name);
  585. return;
  586. }
  587. }
  588. outfd = copy_tempfile(fd, name, &tmp);
  589. rename++;
  590. }
  591. if (toys.optflags&FLAG_v) printf("%s:", name);
  592. err = bunzipStream(fd, outfd);
  593. if (toys.optflags&FLAG_v) {
  594. printf("%s\n", err ? err : "ok");
  595. toys.exitval |= !!err;
  596. } else if (err) error_msg_raw(err);
  597. // can't test outfd==1 because may have been called with stdin+stdout closed
  598. if (rename) {
  599. if (toys.optflags&FLAG_k) {
  600. free(tmp);
  601. tmp = 0;
  602. } else {
  603. if (dotbz) *dotbz = '.';
  604. if (!unlink(name)) perror_msg_raw(name);
  605. }
  606. (err ? delete_tempfile : replace_tempfile)(-1, outfd, &tmp);
  607. }
  608. }
  609. void bunzip2_main(void)
  610. {
  611. loopfiles(toys.optargs, do_bunzip2);
  612. }