⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 decompress_bunzip2.c

📁 busybox最新版的源码:学习和应用的好东东,多的不说了,大家看后再说吧
💻 C
📖 第 1 页 / 共 2 页
字号:
/* vi: set sw=4 ts=4: *//* Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).   Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),   which also acknowledges contributions by Mike Burrows, David Wheeler,   Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,   Robert Sedgewick, and Jon L. Bentley.   Licensed under GPLv2 or later, see file LICENSE in this tarball for details.*//*	Size and speed optimizations by Manuel Novoa III  (mjn3@codepoet.org).	More efficient reading of Huffman codes, a streamlined read_bunzip()	function, and various other tweaks.  In (limited) tests, approximately	20% faster than bzcat on x86 and about 10% faster on arm.	Note that about 2/3 of the time is spent in read_unzip() reversing	the Burrows-Wheeler transformation.  Much of that time is delay	resulting from cache misses.	I would ask that anyone benefiting from this work, especially those	using it in commercial products, consider making a donation to my local	non-profit hospice organization (www.hospiceacadiana.com) in the name of	the woman I loved, Toni W. Hagan, who passed away Feb. 12, 2003.	Manuel */#include "libbb.h"#include "unarchive.h"/* Constants for Huffman coding */#define MAX_GROUPS          6#define GROUP_SIZE          50      /* 64 would have been more efficient */#define MAX_HUFCODE_BITS    20      /* Longest Huffman code allowed */#define MAX_SYMBOLS         258     /* 256 literals + RUNA + RUNB */#define SYMBOL_RUNA         0#define SYMBOL_RUNB         1/* Status return values */#define RETVAL_OK                       0#define RETVAL_LAST_BLOCK               (-1)#define RETVAL_NOT_BZIP_DATA            (-2)#define RETVAL_UNEXPECTED_INPUT_EOF     (-3)#define RETVAL_UNEXPECTED_OUTPUT_EOF    (-4)#define RETVAL_DATA_ERROR               (-5)#define RETVAL_OUT_OF_MEMORY            (-6)#define RETVAL_OBSOLETE_INPUT           (-7)/* Other housekeeping constants */#define IOBUF_SIZE          4096/* This is what we know about each Huffman coding group */struct group_data {	/* We have an extra slot at the end of limit[] for a sentinal value. */	int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];	int minLen, maxLen;};/* Structure holding all the housekeeping data, including IO buffers and   memory that persists between calls to bunzip */struct bunzip_data {	/* State for interrupting output loop */	int writeCopies, writePos, writeRunCountdown, writeCount, writeCurrent;	/* I/O tracking data (file handles, buffers, positions, etc.) */	int in_fd, out_fd, inbufCount, inbufPos /*, outbufPos*/;	unsigned char *inbuf /*,*outbuf*/;	unsigned inbufBitCount, inbufBits;	/* The CRC values stored in the block header and calculated from the data */	uint32_t headerCRC, totalCRC, writeCRC;	/* Intermediate buffer and its size (in bytes) */	unsigned *dbuf, dbufSize;	/* For I/O error handling */	jmp_buf jmpbuf;	/* Big things go last (register-relative addressing can be larger for big offsets */	uint32_t crc32Table[256];	unsigned char selectors[32768];			/* nSelectors=15 bits */	struct group_data groups[MAX_GROUPS];	/* Huffman coding tables */};/* typedef struct bunzip_data bunzip_data; -- done in .h file *//* Return the next nnn bits of input.  All reads from the compressed input   are done through this function.  All reads are big endian */static unsigned get_bits(bunzip_data *bd, char bits_wanted){	unsigned bits = 0;	/* If we need to get more data from the byte buffer, do so.  (Loop getting	   one byte at a time to enforce endianness and avoid unaligned access.) */	while (bd->inbufBitCount < bits_wanted) {		/* If we need to read more data from file into byte buffer, do so */		if (bd->inbufPos == bd->inbufCount) {			/* if "no input fd" case: in_fd == -1, read fails, we jump */			bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);			if (bd->inbufCount <= 0)				longjmp(bd->jmpbuf, RETVAL_UNEXPECTED_INPUT_EOF);			bd->inbufPos = 0;		}		/* Avoid 32-bit overflow (dump bit buffer to top of output) */		if (bd->inbufBitCount >= 24) {			bits = bd->inbufBits & ((1 << bd->inbufBitCount) - 1);			bits_wanted -= bd->inbufBitCount;			bits <<= bits_wanted;			bd->inbufBitCount = 0;		}		/* Grab next 8 bits of input from buffer. */		bd->inbufBits = (bd->inbufBits<<8) | bd->inbuf[bd->inbufPos++];		bd->inbufBitCount += 8;	}	/* Calculate result */	bd->inbufBitCount -= bits_wanted;	bits |= (bd->inbufBits >> bd->inbufBitCount) & ((1 << bits_wanted) - 1);	return bits;}/* Unpacks the next block and sets up for the inverse burrows-wheeler step. */static int get_next_block(bunzip_data *bd){	struct group_data *hufGroup;	int dbufCount, nextSym, dbufSize, groupCount, *base, *limit, selector,		i, j, k, t, runPos, symCount, symTotal, nSelectors, byteCount[256];	unsigned char uc, symToByte[256], mtfSymbol[256], *selectors;	unsigned *dbuf, origPtr;	dbuf = bd->dbuf;	dbufSize = bd->dbufSize;	selectors = bd->selectors;	/* Reset longjmp I/O error handling */	i = setjmp(bd->jmpbuf);	if (i) return i;	/* Read in header signature and CRC, then validate signature.	   (last block signature means CRC is for whole file, return now) */	i = get_bits(bd, 24);	j = get_bits(bd, 24);	bd->headerCRC = get_bits(bd, 32);	if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;	if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;	/* We can add support for blockRandomised if anybody complains.  There was	   some code for this in busybox 1.0.0-pre3, but nobody ever noticed that	   it didn't actually work. */	if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;	origPtr = get_bits(bd, 24);	if (origPtr > dbufSize) return RETVAL_DATA_ERROR;	/* mapping table: if some byte values are never used (encoding things	   like ascii text), the compression code removes the gaps to have fewer	   symbols to deal with, and writes a sparse bitfield indicating which	   values were present.  We make a translation table to convert the symbols	   back to the corresponding bytes. */	t = get_bits(bd, 16);	symTotal = 0;	for (i = 0; i < 16; i++) {		if (t & (1 << (15-i))) {			k = get_bits(bd, 16);			for (j = 0; j < 16; j++)				if (k & (1 << (15-j)))					symToByte[symTotal++] = (16*i) + j;		}	}	/* How many different Huffman coding groups does this block use? */	groupCount = get_bits(bd, 3);	if (groupCount < 2 || groupCount > MAX_GROUPS)		return RETVAL_DATA_ERROR;	/* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding	   group.  Read in the group selector list, which is stored as MTF encoded	   bit runs.  (MTF=Move To Front, as each value is used it's moved to the	   start of the list.) */	nSelectors = get_bits(bd, 15);	if (!nSelectors) return RETVAL_DATA_ERROR;	for (i = 0; i < groupCount; i++) mtfSymbol[i] = i;	for (i = 0; i < nSelectors; i++) {		/* Get next value */		for (j = 0; get_bits(bd, 1); j++)			if (j>=groupCount) return RETVAL_DATA_ERROR;		/* Decode MTF to get the next selector */		uc = mtfSymbol[j];		for (;j;j--) mtfSymbol[j] = mtfSymbol[j-1];		mtfSymbol[0] = selectors[i] = uc;	}	/* Read the Huffman coding tables for each group, which code for symTotal	   literal symbols, plus two run symbols (RUNA, RUNB) */	symCount = symTotal + 2;	for (j = 0; j < groupCount; j++) {		unsigned char length[MAX_SYMBOLS], temp[MAX_HUFCODE_BITS+1];		int minLen, maxLen, pp;		/* Read Huffman code lengths for each symbol.  They're stored in		   a way similar to mtf; record a starting value for the first symbol,		   and an offset from the previous value for everys symbol after that.		   (Subtracting 1 before the loop and then adding it back at the end is		   an optimization that makes the test inside the loop simpler: symbol		   length 0 becomes negative, so an unsigned inequality catches it.) */		t = get_bits(bd, 5) - 1;		for (i = 0; i < symCount; i++) {			for (;;) {				if ((unsigned)t > (MAX_HUFCODE_BITS-1))					return RETVAL_DATA_ERROR;				/* If first bit is 0, stop.  Else second bit indicates whether				   to increment or decrement the value.  Optimization: grab 2				   bits and unget the second if the first was 0. */				k = get_bits(bd, 2);				if (k < 2) {					bd->inbufBitCount++;					break;				}				/* Add one if second bit 1, else subtract 1.  Avoids if/else */				t += (((k+1) & 2) - 1);			}			/* Correct for the initial -1, to get the final symbol length */			length[i] = t + 1;		}		/* Find largest and smallest lengths in this group */		minLen = maxLen = length[0];		for (i = 1; i < symCount; i++) {			if (length[i] > maxLen) maxLen = length[i];			else if (length[i] < minLen) minLen = length[i];		}		/* Calculate permute[], base[], and limit[] tables from length[].		 *		 * permute[] is the lookup table for converting Huffman coded symbols		 * into decoded symbols.  base[] is the amount to subtract from the		 * value of a Huffman symbol of a given length when using permute[].		 *		 * limit[] indicates the largest numerical value a symbol with a given		 * number of bits can have.  This is how the Huffman codes can vary in		 * length: each code with a value>limit[length] needs another bit.		 */		hufGroup = bd->groups + j;		hufGroup->minLen = minLen;		hufGroup->maxLen = maxLen;		/* Note that minLen can't be smaller than 1, so we adjust the base		   and limit array pointers so we're not always wasting the first		   entry.  We do this again when using them (during symbol decoding).*/		base = hufGroup->base - 1;		limit = hufGroup->limit - 1;		/* Calculate permute[].  Concurently, initialize temp[] and limit[]. */		pp = 0;		for (i = minLen; i <= maxLen; i++) {			temp[i] = limit[i] = 0;			for (t = 0; t < symCount; t++)				if (length[t] == i)					hufGroup->permute[pp++] = t;		}		/* Count symbols coded for at each bit length */		for (i = 0; i < symCount; i++) temp[length[i]]++;		/* Calculate limit[] (the largest symbol-coding value at each bit		 * length, which is (previous limit<<1)+symbols at this level), and		 * base[] (number of symbols to ignore at each bit length, which is		 * limit minus the cumulative count of symbols coded for already). */		pp = t = 0;		for (i = minLen; i < maxLen; i++) {			pp += temp[i];			/* We read the largest possible symbol size and then unget bits			   after determining how many we need, and those extra bits could			   be set to anything.  (They're noise from future symbols.)  At			   each level we're really only interested in the first few bits,			   so here we set all the trailing to-be-ignored bits to 1 so they			   don't affect the value>limit[length] comparison. */			limit[i] = (pp << (maxLen - i)) - 1;			pp <<= 1;			t += temp[i];			base[i+1] = pp - t;		}		limit[maxLen+1] = INT_MAX; /* Sentinal value for reading next sym. */		limit[maxLen] = pp + temp[maxLen] - 1;		base[minLen] = 0;	}	/* We've finished reading and digesting the block header.  Now read this	   block's Huffman coded symbols from the file and undo the Huffman coding	   and run length encoding, saving the result into dbuf[dbufCount++]=uc */	/* Initialize symbol occurrence counters and symbol Move To Front table */	for (i = 0; i < 256; i++) {		byteCount[i] = 0;		mtfSymbol[i] = (unsigned char)i;	}	/* Loop through compressed symbols. */	runPos = dbufCount = selector = 0;	for (;;) {		/* fetch next Huffman coding group from list. */		symCount = GROUP_SIZE - 1;		if (selector >= nSelectors) return RETVAL_DATA_ERROR;		hufGroup = bd->groups + selectors[selector++];		base = hufGroup->base - 1;		limit = hufGroup->limit - 1; continue_this_group:		/* Read next Huffman-coded symbol. */		/* Note: It is far cheaper to read maxLen bits and back up than it is		   to read minLen bits and then an additional bit at a time, testing		   as we go.  Because there is a trailing last block (with file CRC),		   there is no danger of the overread causing an unexpected EOF for a		   valid compressed file.  As a further optimization, we do the read		   inline (falling back to a call to get_bits if the buffer runs		   dry).  The following (up to got_huff_bits:) is equivalent to		   j = get_bits(bd, hufGroup->maxLen);		 */		while (bd->inbufBitCount < hufGroup->maxLen) {			if (bd->inbufPos == bd->inbufCount) {				j = get_bits(bd, hufGroup->maxLen);				goto got_huff_bits;			}			bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];			bd->inbufBitCount += 8;		};		bd->inbufBitCount -= hufGroup->maxLen;		j = (bd->inbufBits >> bd->inbufBitCount) & ((1 << hufGroup->maxLen) - 1); got_huff_bits:		/* Figure how how many bits are in next symbol and unget extras */		i = hufGroup->minLen;		while (j > limit[i]) ++i;		bd->inbufBitCount += (hufGroup->maxLen - i);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -