aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/Kconfig17
-rw-r--r--lib/Makefile7
-rw-r--r--lib/decompress.c54
-rw-r--r--lib/decompress_bunzip2.c735
-rw-r--r--lib/decompress_inflate.c167
-rw-r--r--lib/decompress_unlzma.c647
-rw-r--r--lib/vsprintf.c1005
-rw-r--r--lib/zlib_inflate/inflate.h4
-rw-r--r--lib/zlib_inflate/inftrees.h4
9 files changed, 2412 insertions, 228 deletions
diff --git a/lib/Kconfig b/lib/Kconfig
index 03c2c24b9083..206f36a9efb4 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -2,6 +2,9 @@
2# Library configuration 2# Library configuration
3# 3#
4 4
5config BINARY_PRINTF
6 def_bool n
7
5menu "Library routines" 8menu "Library routines"
6 9
7config BITREVERSE 10config BITREVERSE
@@ -98,6 +101,20 @@ config LZO_DECOMPRESS
98 tristate 101 tristate
99 102
100# 103#
104# These all provide a common interface (hence the apparent duplication with
105# ZLIB_INFLATE; DECOMPRESS_GZIP is just a wrapper.)
106#
107config DECOMPRESS_GZIP
108 select ZLIB_INFLATE
109 tristate
110
111config DECOMPRESS_BZIP2
112 tristate
113
114config DECOMPRESS_LZMA
115 tristate
116
117#
101# Generic allocator support is selected if needed 118# Generic allocator support is selected if needed
102# 119#
103config GENERIC_ALLOCATOR 120config GENERIC_ALLOCATOR
diff --git a/lib/Makefile b/lib/Makefile
index 32b0e64ded27..790de7c25d0d 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -11,7 +11,8 @@ lib-y := ctype.o string.o vsprintf.o cmdline.o \
11 rbtree.o radix-tree.o dump_stack.o \ 11 rbtree.o radix-tree.o dump_stack.o \
12 idr.o int_sqrt.o extable.o prio_tree.o \ 12 idr.o int_sqrt.o extable.o prio_tree.o \
13 sha1.o irq_regs.o reciprocal_div.o argv_split.o \ 13 sha1.o irq_regs.o reciprocal_div.o argv_split.o \
14 proportions.o prio_heap.o ratelimit.o show_mem.o is_single_threaded.o 14 proportions.o prio_heap.o ratelimit.o show_mem.o \
15 is_single_threaded.o decompress.o
15 16
16lib-$(CONFIG_MMU) += ioremap.o 17lib-$(CONFIG_MMU) += ioremap.o
17lib-$(CONFIG_SMP) += cpumask.o 18lib-$(CONFIG_SMP) += cpumask.o
@@ -65,6 +66,10 @@ obj-$(CONFIG_REED_SOLOMON) += reed_solomon/
65obj-$(CONFIG_LZO_COMPRESS) += lzo/ 66obj-$(CONFIG_LZO_COMPRESS) += lzo/
66obj-$(CONFIG_LZO_DECOMPRESS) += lzo/ 67obj-$(CONFIG_LZO_DECOMPRESS) += lzo/
67 68
69lib-$(CONFIG_DECOMPRESS_GZIP) += decompress_inflate.o
70lib-$(CONFIG_DECOMPRESS_BZIP2) += decompress_bunzip2.o
71lib-$(CONFIG_DECOMPRESS_LZMA) += decompress_unlzma.o
72
68obj-$(CONFIG_TEXTSEARCH) += textsearch.o 73obj-$(CONFIG_TEXTSEARCH) += textsearch.o
69obj-$(CONFIG_TEXTSEARCH_KMP) += ts_kmp.o 74obj-$(CONFIG_TEXTSEARCH_KMP) += ts_kmp.o
70obj-$(CONFIG_TEXTSEARCH_BM) += ts_bm.o 75obj-$(CONFIG_TEXTSEARCH_BM) += ts_bm.o
diff --git a/lib/decompress.c b/lib/decompress.c
new file mode 100644
index 000000000000..d2842f571674
--- /dev/null
+++ b/lib/decompress.c
@@ -0,0 +1,54 @@
1/*
2 * decompress.c
3 *
4 * Detect the decompression method based on magic number
5 */
6
7#include <linux/decompress/generic.h>
8
9#include <linux/decompress/bunzip2.h>
10#include <linux/decompress/unlzma.h>
11#include <linux/decompress/inflate.h>
12
13#include <linux/types.h>
14#include <linux/string.h>
15
16#ifndef CONFIG_DECOMPRESS_GZIP
17# define gunzip NULL
18#endif
19#ifndef CONFIG_DECOMPRESS_BZIP2
20# define bunzip2 NULL
21#endif
22#ifndef CONFIG_DECOMPRESS_LZMA
23# define unlzma NULL
24#endif
25
26static const struct compress_format {
27 unsigned char magic[2];
28 const char *name;
29 decompress_fn decompressor;
30} compressed_formats[] = {
31 { {037, 0213}, "gzip", gunzip },
32 { {037, 0236}, "gzip", gunzip },
33 { {0x42, 0x5a}, "bzip2", bunzip2 },
34 { {0x5d, 0x00}, "lzma", unlzma },
35 { {0, 0}, NULL, NULL }
36};
37
38decompress_fn decompress_method(const unsigned char *inbuf, int len,
39 const char **name)
40{
41 const struct compress_format *cf;
42
43 if (len < 2)
44 return NULL; /* Need at least this much... */
45
46 for (cf = compressed_formats; cf->name; cf++) {
47 if (!memcmp(inbuf, cf->magic, 2))
48 break;
49
50 }
51 if (name)
52 *name = cf->name;
53 return cf->decompressor;
54}
diff --git a/lib/decompress_bunzip2.c b/lib/decompress_bunzip2.c
new file mode 100644
index 000000000000..5d3ddb5fcfd9
--- /dev/null
+++ b/lib/decompress_bunzip2.c
@@ -0,0 +1,735 @@
1/* vi: set sw = 4 ts = 4: */
2/* Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).
3
4 Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
5 which also acknowledges contributions by Mike Burrows, David Wheeler,
6 Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
7 Robert Sedgewick, and Jon L. Bentley.
8
9 This code is licensed under the LGPLv2:
10 LGPL (http://www.gnu.org/copyleft/lgpl.html
11*/
12
13/*
14 Size and speed optimizations by Manuel Novoa III (mjn3@codepoet.org).
15
16 More efficient reading of Huffman codes, a streamlined read_bunzip()
17 function, and various other tweaks. In (limited) tests, approximately
18 20% faster than bzcat on x86 and about 10% faster on arm.
19
20 Note that about 2/3 of the time is spent in read_unzip() reversing
21 the Burrows-Wheeler transformation. Much of that time is delay
22 resulting from cache misses.
23
24 I would ask that anyone benefiting from this work, especially those
25 using it in commercial products, consider making a donation to my local
26 non-profit hospice organization in the name of the woman I loved, who
27 passed away Feb. 12, 2003.
28
29 In memory of Toni W. Hagan
30
31 Hospice of Acadiana, Inc.
32 2600 Johnston St., Suite 200
33 Lafayette, LA 70503-3240
34
35 Phone (337) 232-1234 or 1-800-738-2226
36 Fax (337) 232-1297
37
38 http://www.hospiceacadiana.com/
39
40 Manuel
41 */
42
43/*
44 Made it fit for running in Linux Kernel by Alain Knaff (alain@knaff.lu)
45*/
46
47
48#ifndef STATIC
49#include <linux/decompress/bunzip2.h>
50#endif /* !STATIC */
51
52#include <linux/decompress/mm.h>
53
54#ifndef INT_MAX
55#define INT_MAX 0x7fffffff
56#endif
57
58/* Constants for Huffman coding */
59#define MAX_GROUPS 6
60#define GROUP_SIZE 50 /* 64 would have been more efficient */
61#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
62#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
63#define SYMBOL_RUNA 0
64#define SYMBOL_RUNB 1
65
66/* Status return values */
67#define RETVAL_OK 0
68#define RETVAL_LAST_BLOCK (-1)
69#define RETVAL_NOT_BZIP_DATA (-2)
70#define RETVAL_UNEXPECTED_INPUT_EOF (-3)
71#define RETVAL_UNEXPECTED_OUTPUT_EOF (-4)
72#define RETVAL_DATA_ERROR (-5)
73#define RETVAL_OUT_OF_MEMORY (-6)
74#define RETVAL_OBSOLETE_INPUT (-7)
75
76/* Other housekeeping constants */
77#define BZIP2_IOBUF_SIZE 4096
78
79/* This is what we know about each Huffman coding group */
80struct group_data {
81 /* We have an extra slot at the end of limit[] for a sentinal value. */
82 int limit[MAX_HUFCODE_BITS+1];
83 int base[MAX_HUFCODE_BITS];
84 int permute[MAX_SYMBOLS];
85 int minLen, maxLen;
86};
87
88/* Structure holding all the housekeeping data, including IO buffers and
89 memory that persists between calls to bunzip */
90struct bunzip_data {
91 /* State for interrupting output loop */
92 int writeCopies, writePos, writeRunCountdown, writeCount, writeCurrent;
93 /* I/O tracking data (file handles, buffers, positions, etc.) */
94 int (*fill)(void*, unsigned int);
95 int inbufCount, inbufPos /*, outbufPos*/;
96 unsigned char *inbuf /*,*outbuf*/;
97 unsigned int inbufBitCount, inbufBits;
98 /* The CRC values stored in the block header and calculated from the
99 data */
100 unsigned int crc32Table[256], headerCRC, totalCRC, writeCRC;
101 /* Intermediate buffer and its size (in bytes) */
102 unsigned int *dbuf, dbufSize;
103 /* These things are a bit too big to go on the stack */
104 unsigned char selectors[32768]; /* nSelectors = 15 bits */
105 struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */
106 int io_error; /* non-zero if we have IO error */
107};
108
109
110/* Return the next nnn bits of input. All reads from the compressed input
111 are done through this function. All reads are big endian */
112static unsigned int INIT get_bits(struct bunzip_data *bd, char bits_wanted)
113{
114 unsigned int bits = 0;
115
116 /* If we need to get more data from the byte buffer, do so.
117 (Loop getting one byte at a time to enforce endianness and avoid
118 unaligned access.) */
119 while (bd->inbufBitCount < bits_wanted) {
120 /* If we need to read more data from file into byte buffer, do
121 so */
122 if (bd->inbufPos == bd->inbufCount) {
123 if (bd->io_error)
124 return 0;
125 bd->inbufCount = bd->fill(bd->inbuf, BZIP2_IOBUF_SIZE);
126 if (bd->inbufCount <= 0) {
127 bd->io_error = RETVAL_UNEXPECTED_INPUT_EOF;
128 return 0;
129 }
130 bd->inbufPos = 0;
131 }
132 /* Avoid 32-bit overflow (dump bit buffer to top of output) */
133 if (bd->inbufBitCount >= 24) {
134 bits = bd->inbufBits&((1 << bd->inbufBitCount)-1);
135 bits_wanted -= bd->inbufBitCount;
136 bits <<= bits_wanted;
137 bd->inbufBitCount = 0;
138 }
139 /* Grab next 8 bits of input from buffer. */
140 bd->inbufBits = (bd->inbufBits << 8)|bd->inbuf[bd->inbufPos++];
141 bd->inbufBitCount += 8;
142 }
143 /* Calculate result */
144 bd->inbufBitCount -= bits_wanted;
145 bits |= (bd->inbufBits >> bd->inbufBitCount)&((1 << bits_wanted)-1);
146
147 return bits;
148}
149
150/* Unpacks the next block and sets up for the inverse burrows-wheeler step. */
151
152static int INIT get_next_block(struct bunzip_data *bd)
153{
154 struct group_data *hufGroup = NULL;
155 int *base = NULL;
156 int *limit = NULL;
157 int dbufCount, nextSym, dbufSize, groupCount, selector,
158 i, j, k, t, runPos, symCount, symTotal, nSelectors,
159 byteCount[256];
160 unsigned char uc, symToByte[256], mtfSymbol[256], *selectors;
161 unsigned int *dbuf, origPtr;
162
163 dbuf = bd->dbuf;
164 dbufSize = bd->dbufSize;
165 selectors = bd->selectors;
166
167 /* Read in header signature and CRC, then validate signature.
168 (last block signature means CRC is for whole file, return now) */
169 i = get_bits(bd, 24);
170 j = get_bits(bd, 24);
171 bd->headerCRC = get_bits(bd, 32);
172 if ((i == 0x177245) && (j == 0x385090))
173 return RETVAL_LAST_BLOCK;
174 if ((i != 0x314159) || (j != 0x265359))
175 return RETVAL_NOT_BZIP_DATA;
176 /* We can add support for blockRandomised if anybody complains.
177 There was some code for this in busybox 1.0.0-pre3, but nobody ever
178 noticed that it didn't actually work. */
179 if (get_bits(bd, 1))
180 return RETVAL_OBSOLETE_INPUT;
181 origPtr = get_bits(bd, 24);
182 if (origPtr > dbufSize)
183 return RETVAL_DATA_ERROR;
184 /* mapping table: if some byte values are never used (encoding things
185 like ascii text), the compression code removes the gaps to have fewer
186 symbols to deal with, and writes a sparse bitfield indicating which
187 values were present. We make a translation table to convert the
188 symbols back to the corresponding bytes. */
189 t = get_bits(bd, 16);
190 symTotal = 0;
191 for (i = 0; i < 16; i++) {
192 if (t&(1 << (15-i))) {
193 k = get_bits(bd, 16);
194 for (j = 0; j < 16; j++)
195 if (k&(1 << (15-j)))
196 symToByte[symTotal++] = (16*i)+j;
197 }
198 }
199 /* How many different Huffman coding groups does this block use? */
200 groupCount = get_bits(bd, 3);
201 if (groupCount < 2 || groupCount > MAX_GROUPS)
202 return RETVAL_DATA_ERROR;
203 /* nSelectors: Every GROUP_SIZE many symbols we select a new
204 Huffman coding group. Read in the group selector list,
205 which is stored as MTF encoded bit runs. (MTF = Move To
206 Front, as each value is used it's moved to the start of the
207 list.) */
208 nSelectors = get_bits(bd, 15);
209 if (!nSelectors)
210 return RETVAL_DATA_ERROR;
211 for (i = 0; i < groupCount; i++)
212 mtfSymbol[i] = i;
213 for (i = 0; i < nSelectors; i++) {
214 /* Get next value */
215 for (j = 0; get_bits(bd, 1); j++)
216 if (j >= groupCount)
217 return RETVAL_DATA_ERROR;
218 /* Decode MTF to get the next selector */
219 uc = mtfSymbol[j];
220 for (; j; j--)
221 mtfSymbol[j] = mtfSymbol[j-1];
222 mtfSymbol[0] = selectors[i] = uc;
223 }
224 /* Read the Huffman coding tables for each group, which code
225 for symTotal literal symbols, plus two run symbols (RUNA,
226 RUNB) */
227 symCount = symTotal+2;
228 for (j = 0; j < groupCount; j++) {
229 unsigned char length[MAX_SYMBOLS], temp[MAX_HUFCODE_BITS+1];
230 int minLen, maxLen, pp;
231 /* Read Huffman code lengths for each symbol. They're
232 stored in a way similar to mtf; record a starting
233 value for the first symbol, and an offset from the
234 previous value for everys symbol after that.
235 (Subtracting 1 before the loop and then adding it
236 back at the end is an optimization that makes the
237 test inside the loop simpler: symbol length 0
238 becomes negative, so an unsigned inequality catches
239 it.) */
240 t = get_bits(bd, 5)-1;
241 for (i = 0; i < symCount; i++) {
242 for (;;) {
243 if (((unsigned)t) > (MAX_HUFCODE_BITS-1))
244 return RETVAL_DATA_ERROR;
245
246 /* If first bit is 0, stop. Else
247 second bit indicates whether to
248 increment or decrement the value.
249 Optimization: grab 2 bits and unget
250 the second if the first was 0. */
251
252 k = get_bits(bd, 2);
253 if (k < 2) {
254 bd->inbufBitCount++;
255 break;
256 }
257 /* Add one if second bit 1, else
258 * subtract 1. Avoids if/else */
259 t += (((k+1)&2)-1);
260 }
261 /* Correct for the initial -1, to get the
262 * final symbol length */
263 length[i] = t+1;
264 }
265 /* Find largest and smallest lengths in this group */
266 minLen = maxLen = length[0];
267
268 for (i = 1; i < symCount; i++) {
269 if (length[i] > maxLen)
270 maxLen = length[i];
271 else if (length[i] < minLen)
272 minLen = length[i];
273 }
274
275 /* Calculate permute[], base[], and limit[] tables from
276 * length[].
277 *
278 * permute[] is the lookup table for converting
279 * Huffman coded symbols into decoded symbols. base[]
280 * is the amount to subtract from the value of a
281 * Huffman symbol of a given length when using
282 * permute[].
283 *
284 * limit[] indicates the largest numerical value a
285 * symbol with a given number of bits can have. This
286 * is how the Huffman codes can vary in length: each
287 * code with a value > limit[length] needs another
288 * bit.
289 */
290 hufGroup = bd->groups+j;
291 hufGroup->minLen = minLen;
292 hufGroup->maxLen = maxLen;
293 /* Note that minLen can't be smaller than 1, so we
294 adjust the base and limit array pointers so we're
295 not always wasting the first entry. We do this
296 again when using them (during symbol decoding).*/
297 base = hufGroup->base-1;
298 limit = hufGroup->limit-1;
299 /* Calculate permute[]. Concurently, initialize
300 * temp[] and limit[]. */
301 pp = 0;
302 for (i = minLen; i <= maxLen; i++) {
303 temp[i] = limit[i] = 0;
304 for (t = 0; t < symCount; t++)
305 if (length[t] == i)
306 hufGroup->permute[pp++] = t;
307 }
308 /* Count symbols coded for at each bit length */
309 for (i = 0; i < symCount; i++)
310 temp[length[i]]++;
311 /* Calculate limit[] (the largest symbol-coding value
312 *at each bit length, which is (previous limit <<
313 *1)+symbols at this level), and base[] (number of
314 *symbols to ignore at each bit length, which is limit
315 *minus the cumulative count of symbols coded for
316 *already). */
317 pp = t = 0;
318 for (i = minLen; i < maxLen; i++) {
319 pp += temp[i];
320 /* We read the largest possible symbol size
321 and then unget bits after determining how
322 many we need, and those extra bits could be
323 set to anything. (They're noise from
324 future symbols.) At each level we're
325 really only interested in the first few
326 bits, so here we set all the trailing
327 to-be-ignored bits to 1 so they don't
328 affect the value > limit[length]
329 comparison. */
330 limit[i] = (pp << (maxLen - i)) - 1;
331 pp <<= 1;
332 base[i+1] = pp-(t += temp[i]);
333 }
334 limit[maxLen+1] = INT_MAX; /* Sentinal value for
335 * reading next sym. */
336 limit[maxLen] = pp+temp[maxLen]-1;
337 base[minLen] = 0;
338 }
339 /* We've finished reading and digesting the block header. Now
340 read this block's Huffman coded symbols from the file and
341 undo the Huffman coding and run length encoding, saving the
342 result into dbuf[dbufCount++] = uc */
343
344 /* Initialize symbol occurrence counters and symbol Move To
345 * Front table */
346 for (i = 0; i < 256; i++) {
347 byteCount[i] = 0;
348 mtfSymbol[i] = (unsigned char)i;
349 }
350 /* Loop through compressed symbols. */
351 runPos = dbufCount = symCount = selector = 0;
352 for (;;) {
353 /* Determine which Huffman coding group to use. */
354 if (!(symCount--)) {
355 symCount = GROUP_SIZE-1;
356 if (selector >= nSelectors)
357 return RETVAL_DATA_ERROR;
358 hufGroup = bd->groups+selectors[selector++];
359 base = hufGroup->base-1;
360 limit = hufGroup->limit-1;
361 }
362 /* Read next Huffman-coded symbol. */
363 /* Note: It is far cheaper to read maxLen bits and
364 back up than it is to read minLen bits and then an
365 additional bit at a time, testing as we go.
366 Because there is a trailing last block (with file
367 CRC), there is no danger of the overread causing an
368 unexpected EOF for a valid compressed file. As a
369 further optimization, we do the read inline
370 (falling back to a call to get_bits if the buffer
371 runs dry). The following (up to got_huff_bits:) is
372 equivalent to j = get_bits(bd, hufGroup->maxLen);
373 */
374 while (bd->inbufBitCount < hufGroup->maxLen) {
375 if (bd->inbufPos == bd->inbufCount) {
376 j = get_bits(bd, hufGroup->maxLen);
377 goto got_huff_bits;
378 }
379 bd->inbufBits =
380 (bd->inbufBits << 8)|bd->inbuf[bd->inbufPos++];
381 bd->inbufBitCount += 8;
382 };
383 bd->inbufBitCount -= hufGroup->maxLen;
384 j = (bd->inbufBits >> bd->inbufBitCount)&
385 ((1 << hufGroup->maxLen)-1);
386got_huff_bits:
387 /* Figure how how many bits are in next symbol and
388 * unget extras */
389 i = hufGroup->minLen;
390 while (j > limit[i])
391 ++i;
392 bd->inbufBitCount += (hufGroup->maxLen - i);
393 /* Huffman decode value to get nextSym (with bounds checking) */
394 if ((i > hufGroup->maxLen)
395 || (((unsigned)(j = (j>>(hufGroup->maxLen-i))-base[i]))
396 >= MAX_SYMBOLS))
397 return RETVAL_DATA_ERROR;
398 nextSym = hufGroup->permute[j];
399 /* We have now decoded the symbol, which indicates
400 either a new literal byte, or a repeated run of the
401 most recent literal byte. First, check if nextSym
402 indicates a repeated run, and if so loop collecting
403 how many times to repeat the last literal. */
404 if (((unsigned)nextSym) <= SYMBOL_RUNB) { /* RUNA or RUNB */
405 /* If this is the start of a new run, zero out
406 * counter */
407 if (!runPos) {
408 runPos = 1;
409 t = 0;
410 }
411 /* Neat trick that saves 1 symbol: instead of
412 or-ing 0 or 1 at each bit position, add 1
413 or 2 instead. For example, 1011 is 1 << 0
414 + 1 << 1 + 2 << 2. 1010 is 2 << 0 + 2 << 1
415 + 1 << 2. You can make any bit pattern
416 that way using 1 less symbol than the basic
417 or 0/1 method (except all bits 0, which
418 would use no symbols, but a run of length 0
419 doesn't mean anything in this context).
420 Thus space is saved. */
421 t += (runPos << nextSym);
422 /* +runPos if RUNA; +2*runPos if RUNB */
423
424 runPos <<= 1;
425 continue;
426 }
427 /* When we hit the first non-run symbol after a run,
428 we now know how many times to repeat the last
429 literal, so append that many copies to our buffer
430 of decoded symbols (dbuf) now. (The last literal
431 used is the one at the head of the mtfSymbol
432 array.) */
433 if (runPos) {
434 runPos = 0;
435 if (dbufCount+t >= dbufSize)
436 return RETVAL_DATA_ERROR;
437
438 uc = symToByte[mtfSymbol[0]];
439 byteCount[uc] += t;
440 while (t--)
441 dbuf[dbufCount++] = uc;
442 }
443 /* Is this the terminating symbol? */
444 if (nextSym > symTotal)
445 break;
446 /* At this point, nextSym indicates a new literal
447 character. Subtract one to get the position in the
448 MTF array at which this literal is currently to be
449 found. (Note that the result can't be -1 or 0,
450 because 0 and 1 are RUNA and RUNB. But another
451 instance of the first symbol in the mtf array,
452 position 0, would have been handled as part of a
453 run above. Therefore 1 unused mtf position minus 2
454 non-literal nextSym values equals -1.) */
455 if (dbufCount >= dbufSize)
456 return RETVAL_DATA_ERROR;
457 i = nextSym - 1;
458 uc = mtfSymbol[i];
459 /* Adjust the MTF array. Since we typically expect to
460 *move only a small number of symbols, and are bound
461 *by 256 in any case, using memmove here would
462 *typically be bigger and slower due to function call
463 *overhead and other assorted setup costs. */
464 do {
465 mtfSymbol[i] = mtfSymbol[i-1];
466 } while (--i);
467 mtfSymbol[0] = uc;
468 uc = symToByte[uc];
469 /* We have our literal byte. Save it into dbuf. */
470 byteCount[uc]++;
471 dbuf[dbufCount++] = (unsigned int)uc;
472 }
473 /* At this point, we've read all the Huffman-coded symbols
474 (and repeated runs) for this block from the input stream,
475 and decoded them into the intermediate buffer. There are
476 dbufCount many decoded bytes in dbuf[]. Now undo the
477 Burrows-Wheeler transform on dbuf. See
478 http://dogma.net/markn/articles/bwt/bwt.htm
479 */
480 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
481 j = 0;
482 for (i = 0; i < 256; i++) {
483 k = j+byteCount[i];
484 byteCount[i] = j;
485 j = k;
486 }
487 /* Figure out what order dbuf would be in if we sorted it. */
488 for (i = 0; i < dbufCount; i++) {
489 uc = (unsigned char)(dbuf[i] & 0xff);
490 dbuf[byteCount[uc]] |= (i << 8);
491 byteCount[uc]++;
492 }
493 /* Decode first byte by hand to initialize "previous" byte.
494 Note that it doesn't get output, and if the first three
495 characters are identical it doesn't qualify as a run (hence
496 writeRunCountdown = 5). */
497 if (dbufCount) {
498 if (origPtr >= dbufCount)
499 return RETVAL_DATA_ERROR;
500 bd->writePos = dbuf[origPtr];
501 bd->writeCurrent = (unsigned char)(bd->writePos&0xff);
502 bd->writePos >>= 8;
503 bd->writeRunCountdown = 5;
504 }
505 bd->writeCount = dbufCount;
506
507 return RETVAL_OK;
508}
509
510/* Undo burrows-wheeler transform on intermediate buffer to produce output.
511 If start_bunzip was initialized with out_fd =-1, then up to len bytes of
512 data are written to outbuf. Return value is number of bytes written or
513 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
514 are ignored, data is written to out_fd and return is RETVAL_OK or error.
515*/
516
517static int INIT read_bunzip(struct bunzip_data *bd, char *outbuf, int len)
518{
519 const unsigned int *dbuf;
520 int pos, xcurrent, previous, gotcount;
521
522 /* If last read was short due to end of file, return last block now */
523 if (bd->writeCount < 0)
524 return bd->writeCount;
525
526 gotcount = 0;
527 dbuf = bd->dbuf;
528 pos = bd->writePos;
529 xcurrent = bd->writeCurrent;
530
531 /* We will always have pending decoded data to write into the output
532 buffer unless this is the very first call (in which case we haven't
533 Huffman-decoded a block into the intermediate buffer yet). */
534
535 if (bd->writeCopies) {
536 /* Inside the loop, writeCopies means extra copies (beyond 1) */
537 --bd->writeCopies;
538 /* Loop outputting bytes */
539 for (;;) {
540 /* If the output buffer is full, snapshot
541 * state and return */
542 if (gotcount >= len) {
543 bd->writePos = pos;
544 bd->writeCurrent = xcurrent;
545 bd->writeCopies++;
546 return len;
547 }
548 /* Write next byte into output buffer, updating CRC */
549 outbuf[gotcount++] = xcurrent;
550 bd->writeCRC = (((bd->writeCRC) << 8)
551 ^bd->crc32Table[((bd->writeCRC) >> 24)
552 ^xcurrent]);
553 /* Loop now if we're outputting multiple
554 * copies of this byte */
555 if (bd->writeCopies) {
556 --bd->writeCopies;
557 continue;
558 }
559decode_next_byte:
560 if (!bd->writeCount--)
561 break;
562 /* Follow sequence vector to undo
563 * Burrows-Wheeler transform */
564 previous = xcurrent;
565 pos = dbuf[pos];
566 xcurrent = pos&0xff;
567 pos >>= 8;
568 /* After 3 consecutive copies of the same
569 byte, the 4th is a repeat count. We count
570 down from 4 instead *of counting up because
571 testing for non-zero is faster */
572 if (--bd->writeRunCountdown) {
573 if (xcurrent != previous)
574 bd->writeRunCountdown = 4;
575 } else {
576 /* We have a repeated run, this byte
577 * indicates the count */
578 bd->writeCopies = xcurrent;
579 xcurrent = previous;
580 bd->writeRunCountdown = 5;
581 /* Sometimes there are just 3 bytes
582 * (run length 0) */
583 if (!bd->writeCopies)
584 goto decode_next_byte;
585 /* Subtract the 1 copy we'd output
586 * anyway to get extras */
587 --bd->writeCopies;
588 }
589 }
590 /* Decompression of this block completed successfully */
591 bd->writeCRC = ~bd->writeCRC;
592 bd->totalCRC = ((bd->totalCRC << 1) |
593 (bd->totalCRC >> 31)) ^ bd->writeCRC;
594 /* If this block had a CRC error, force file level CRC error. */
595 if (bd->writeCRC != bd->headerCRC) {
596 bd->totalCRC = bd->headerCRC+1;
597 return RETVAL_LAST_BLOCK;
598 }
599 }
600
601 /* Refill the intermediate buffer by Huffman-decoding next
602 * block of input */
603 /* (previous is just a convenient unused temp variable here) */
604 previous = get_next_block(bd);
605 if (previous) {
606 bd->writeCount = previous;
607 return (previous != RETVAL_LAST_BLOCK) ? previous : gotcount;
608 }
609 bd->writeCRC = 0xffffffffUL;
610 pos = bd->writePos;
611 xcurrent = bd->writeCurrent;
612 goto decode_next_byte;
613}
614
615static int INIT nofill(void *buf, unsigned int len)
616{
617 return -1;
618}
619
620/* Allocate the structure, read file header. If in_fd ==-1, inbuf must contain
621 a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are
622 ignored, and data is read from file handle into temporary buffer. */
623static int INIT start_bunzip(struct bunzip_data **bdp, void *inbuf, int len,
624 int (*fill)(void*, unsigned int))
625{
626 struct bunzip_data *bd;
627 unsigned int i, j, c;
628 const unsigned int BZh0 =
629 (((unsigned int)'B') << 24)+(((unsigned int)'Z') << 16)
630 +(((unsigned int)'h') << 8)+(unsigned int)'0';
631
632 /* Figure out how much data to allocate */
633 i = sizeof(struct bunzip_data);
634
635 /* Allocate bunzip_data. Most fields initialize to zero. */
636 bd = *bdp = malloc(i);
637 memset(bd, 0, sizeof(struct bunzip_data));
638 /* Setup input buffer */
639 bd->inbuf = inbuf;
640 bd->inbufCount = len;
641 if (fill != NULL)
642 bd->fill = fill;
643 else
644 bd->fill = nofill;
645
646 /* Init the CRC32 table (big endian) */
647 for (i = 0; i < 256; i++) {
648 c = i << 24;
649 for (j = 8; j; j--)
650 c = c&0x80000000 ? (c << 1)^0x04c11db7 : (c << 1);
651 bd->crc32Table[i] = c;
652 }
653
654 /* Ensure that file starts with "BZh['1'-'9']." */
655 i = get_bits(bd, 32);
656 if (((unsigned int)(i-BZh0-1)) >= 9)
657 return RETVAL_NOT_BZIP_DATA;
658
659 /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
660 uncompressed data. Allocate intermediate buffer for block. */
661 bd->dbufSize = 100000*(i-BZh0);
662
663 bd->dbuf = large_malloc(bd->dbufSize * sizeof(int));
664 return RETVAL_OK;
665}
666
667/* Example usage: decompress src_fd to dst_fd. (Stops at end of bzip2 data,
668 not end of file.) */
669STATIC int INIT bunzip2(unsigned char *buf, int len,
670 int(*fill)(void*, unsigned int),
671 int(*flush)(void*, unsigned int),
672 unsigned char *outbuf,
673 int *pos,
674 void(*error_fn)(char *x))
675{
676 struct bunzip_data *bd;
677 int i = -1;
678 unsigned char *inbuf;
679
680 set_error_fn(error_fn);
681 if (flush)
682 outbuf = malloc(BZIP2_IOBUF_SIZE);
683 else
684 len -= 4; /* Uncompressed size hack active in pre-boot
685 environment */
686 if (!outbuf) {
687 error("Could not allocate output bufer");
688 return -1;
689 }
690 if (buf)
691 inbuf = buf;
692 else
693 inbuf = malloc(BZIP2_IOBUF_SIZE);
694 if (!inbuf) {
695 error("Could not allocate input bufer");
696 goto exit_0;
697 }
698 i = start_bunzip(&bd, inbuf, len, fill);
699 if (!i) {
700 for (;;) {
701 i = read_bunzip(bd, outbuf, BZIP2_IOBUF_SIZE);
702 if (i <= 0)
703 break;
704 if (!flush)
705 outbuf += i;
706 else
707 if (i != flush(outbuf, i)) {
708 i = RETVAL_UNEXPECTED_OUTPUT_EOF;
709 break;
710 }
711 }
712 }
713 /* Check CRC and release memory */
714 if (i == RETVAL_LAST_BLOCK) {
715 if (bd->headerCRC != bd->totalCRC)
716 error("Data integrity error when decompressing.");
717 else
718 i = RETVAL_OK;
719 } else if (i == RETVAL_UNEXPECTED_OUTPUT_EOF) {
720 error("Compressed file ends unexpectedly");
721 }
722 if (bd->dbuf)
723 large_free(bd->dbuf);
724 if (pos)
725 *pos = bd->inbufPos;
726 free(bd);
727 if (!buf)
728 free(inbuf);
729exit_0:
730 if (flush)
731 free(outbuf);
732 return i;
733}
734
735#define decompress bunzip2
diff --git a/lib/decompress_inflate.c b/lib/decompress_inflate.c
new file mode 100644
index 000000000000..839a329b4fc4
--- /dev/null
+++ b/lib/decompress_inflate.c
@@ -0,0 +1,167 @@
1#ifdef STATIC
2/* Pre-boot environment: included */
3
4/* prevent inclusion of _LINUX_KERNEL_H in pre-boot environment: lots
5 * errors about console_printk etc... on ARM */
6#define _LINUX_KERNEL_H
7
8#include "zlib_inflate/inftrees.c"
9#include "zlib_inflate/inffast.c"
10#include "zlib_inflate/inflate.c"
11
12#else /* STATIC */
13/* initramfs et al: linked */
14
15#include <linux/zutil.h>
16
17#include "zlib_inflate/inftrees.h"
18#include "zlib_inflate/inffast.h"
19#include "zlib_inflate/inflate.h"
20
21#include "zlib_inflate/infutil.h"
22
23#endif /* STATIC */
24
25#include <linux/decompress/mm.h>
26
27#define INBUF_LEN (16*1024)
28
29/* Included from initramfs et al code */
30STATIC int INIT gunzip(unsigned char *buf, int len,
31 int(*fill)(void*, unsigned int),
32 int(*flush)(void*, unsigned int),
33 unsigned char *out_buf,
34 int *pos,
35 void(*error_fn)(char *x)) {
36 u8 *zbuf;
37 struct z_stream_s *strm;
38 int rc;
39 size_t out_len;
40
41 set_error_fn(error_fn);
42 rc = -1;
43 if (flush) {
44 out_len = 0x8000; /* 32 K */
45 out_buf = malloc(out_len);
46 } else {
47 out_len = 0x7fffffff; /* no limit */
48 }
49 if (!out_buf) {
50 error("Out of memory while allocating output buffer");
51 goto gunzip_nomem1;
52 }
53
54 if (buf)
55 zbuf = buf;
56 else {
57 zbuf = malloc(INBUF_LEN);
58 len = 0;
59 }
60 if (!zbuf) {
61 error("Out of memory while allocating input buffer");
62 goto gunzip_nomem2;
63 }
64
65 strm = malloc(sizeof(*strm));
66 if (strm == NULL) {
67 error("Out of memory while allocating z_stream");
68 goto gunzip_nomem3;
69 }
70
71 strm->workspace = malloc(flush ? zlib_inflate_workspacesize() :
72 sizeof(struct inflate_state));
73 if (strm->workspace == NULL) {
74 error("Out of memory while allocating workspace");
75 goto gunzip_nomem4;
76 }
77
78 if (len == 0)
79 len = fill(zbuf, INBUF_LEN);
80
81 /* verify the gzip header */
82 if (len < 10 ||
83 zbuf[0] != 0x1f || zbuf[1] != 0x8b || zbuf[2] != 0x08) {
84 if (pos)
85 *pos = 0;
86 error("Not a gzip file");
87 goto gunzip_5;
88 }
89
90 /* skip over gzip header (1f,8b,08... 10 bytes total +
91 * possible asciz filename)
92 */
93 strm->next_in = zbuf + 10;
94 /* skip over asciz filename */
95 if (zbuf[3] & 0x8) {
96 while (strm->next_in[0])
97 strm->next_in++;
98 strm->next_in++;
99 }
100 strm->avail_in = len - (strm->next_in - zbuf);
101
102 strm->next_out = out_buf;
103 strm->avail_out = out_len;
104
105 rc = zlib_inflateInit2(strm, -MAX_WBITS);
106
107 if (!flush) {
108 WS(strm)->inflate_state.wsize = 0;
109 WS(strm)->inflate_state.window = NULL;
110 }
111
112 while (rc == Z_OK) {
113 if (strm->avail_in == 0) {
114 /* TODO: handle case where both pos and fill are set */
115 len = fill(zbuf, INBUF_LEN);
116 if (len < 0) {
117 rc = -1;
118 error("read error");
119 break;
120 }
121 strm->next_in = zbuf;
122 strm->avail_in = len;
123 }
124 rc = zlib_inflate(strm, 0);
125
126 /* Write any data generated */
127 if (flush && strm->next_out > out_buf) {
128 int l = strm->next_out - out_buf;
129 if (l != flush(out_buf, l)) {
130 rc = -1;
131 error("write error");
132 break;
133 }
134 strm->next_out = out_buf;
135 strm->avail_out = out_len;
136 }
137
138 /* after Z_FINISH, only Z_STREAM_END is "we unpacked it all" */
139 if (rc == Z_STREAM_END) {
140 rc = 0;
141 break;
142 } else if (rc != Z_OK) {
143 error("uncompression error");
144 rc = -1;
145 }
146 }
147
148 zlib_inflateEnd(strm);
149 if (pos)
150 /* add + 8 to skip over trailer */
151 *pos = strm->next_in - zbuf+8;
152
153gunzip_5:
154 free(strm->workspace);
155gunzip_nomem4:
156 free(strm);
157gunzip_nomem3:
158 if (!buf)
159 free(zbuf);
160gunzip_nomem2:
161 if (flush)
162 free(out_buf);
163gunzip_nomem1:
164 return rc; /* returns Z_OK (0) if successful */
165}
166
167#define decompress gunzip
diff --git a/lib/decompress_unlzma.c b/lib/decompress_unlzma.c
new file mode 100644
index 000000000000..546f2f4c157e
--- /dev/null
+++ b/lib/decompress_unlzma.c
@@ -0,0 +1,647 @@
1/* Lzma decompressor for Linux kernel. Shamelessly snarfed
2 *from busybox 1.1.1
3 *
4 *Linux kernel adaptation
5 *Copyright (C) 2006 Alain < alain@knaff.lu >
6 *
7 *Based on small lzma deflate implementation/Small range coder
8 *implementation for lzma.
9 *Copyright (C) 2006 Aurelien Jacobs < aurel@gnuage.org >
10 *
11 *Based on LzmaDecode.c from the LZMA SDK 4.22 (http://www.7-zip.org/)
12 *Copyright (C) 1999-2005 Igor Pavlov
13 *
14 *Copyrights of the parts, see headers below.
15 *
16 *
17 *This program is free software; you can redistribute it and/or
18 *modify it under the terms of the GNU Lesser General Public
19 *License as published by the Free Software Foundation; either
20 *version 2.1 of the License, or (at your option) any later version.
21 *
22 *This program is distributed in the hope that it will be useful,
23 *but WITHOUT ANY WARRANTY; without even the implied warranty of
24 *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 *Lesser General Public License for more details.
26 *
27 *You should have received a copy of the GNU Lesser General Public
28 *License along with this library; if not, write to the Free Software
29 *Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
30 */
31
32#ifndef STATIC
33#include <linux/decompress/unlzma.h>
34#endif /* STATIC */
35
36#include <linux/decompress/mm.h>
37
38#define MIN(a, b) (((a) < (b)) ? (a) : (b))
39
40static long long INIT read_int(unsigned char *ptr, int size)
41{
42 int i;
43 long long ret = 0;
44
45 for (i = 0; i < size; i++)
46 ret = (ret << 8) | ptr[size-i-1];
47 return ret;
48}
49
50#define ENDIAN_CONVERT(x) \
51 x = (typeof(x))read_int((unsigned char *)&x, sizeof(x))
52
53
54/* Small range coder implementation for lzma.
55 *Copyright (C) 2006 Aurelien Jacobs < aurel@gnuage.org >
56 *
57 *Based on LzmaDecode.c from the LZMA SDK 4.22 (http://www.7-zip.org/)
58 *Copyright (c) 1999-2005 Igor Pavlov
59 */
60
61#include <linux/compiler.h>
62
63#define LZMA_IOBUF_SIZE 0x10000
64
65struct rc {
66 int (*fill)(void*, unsigned int);
67 uint8_t *ptr;
68 uint8_t *buffer;
69 uint8_t *buffer_end;
70 int buffer_size;
71 uint32_t code;
72 uint32_t range;
73 uint32_t bound;
74};
75
76
77#define RC_TOP_BITS 24
78#define RC_MOVE_BITS 5
79#define RC_MODEL_TOTAL_BITS 11
80
81
82/* Called twice: once at startup and once in rc_normalize() */
83static void INIT rc_read(struct rc *rc)
84{
85 rc->buffer_size = rc->fill((char *)rc->buffer, LZMA_IOBUF_SIZE);
86 if (rc->buffer_size <= 0)
87 error("unexpected EOF");
88 rc->ptr = rc->buffer;
89 rc->buffer_end = rc->buffer + rc->buffer_size;
90}
91
92/* Called once */
93static inline void INIT rc_init(struct rc *rc,
94 int (*fill)(void*, unsigned int),
95 char *buffer, int buffer_size)
96{
97 rc->fill = fill;
98 rc->buffer = (uint8_t *)buffer;
99 rc->buffer_size = buffer_size;
100 rc->buffer_end = rc->buffer + rc->buffer_size;
101 rc->ptr = rc->buffer;
102
103 rc->code = 0;
104 rc->range = 0xFFFFFFFF;
105}
106
107static inline void INIT rc_init_code(struct rc *rc)
108{
109 int i;
110
111 for (i = 0; i < 5; i++) {
112 if (rc->ptr >= rc->buffer_end)
113 rc_read(rc);
114 rc->code = (rc->code << 8) | *rc->ptr++;
115 }
116}
117
118
119/* Called once. TODO: bb_maybe_free() */
120static inline void INIT rc_free(struct rc *rc)
121{
122 free(rc->buffer);
123}
124
125/* Called twice, but one callsite is in inline'd rc_is_bit_0_helper() */
126static void INIT rc_do_normalize(struct rc *rc)
127{
128 if (rc->ptr >= rc->buffer_end)
129 rc_read(rc);
130 rc->range <<= 8;
131 rc->code = (rc->code << 8) | *rc->ptr++;
132}
133static inline void INIT rc_normalize(struct rc *rc)
134{
135 if (rc->range < (1 << RC_TOP_BITS))
136 rc_do_normalize(rc);
137}
138
139/* Called 9 times */
140/* Why rc_is_bit_0_helper exists?
141 *Because we want to always expose (rc->code < rc->bound) to optimizer
142 */
143static inline uint32_t INIT rc_is_bit_0_helper(struct rc *rc, uint16_t *p)
144{
145 rc_normalize(rc);
146 rc->bound = *p * (rc->range >> RC_MODEL_TOTAL_BITS);
147 return rc->bound;
148}
149static inline int INIT rc_is_bit_0(struct rc *rc, uint16_t *p)
150{
151 uint32_t t = rc_is_bit_0_helper(rc, p);
152 return rc->code < t;
153}
154
155/* Called ~10 times, but very small, thus inlined */
156static inline void INIT rc_update_bit_0(struct rc *rc, uint16_t *p)
157{
158 rc->range = rc->bound;
159 *p += ((1 << RC_MODEL_TOTAL_BITS) - *p) >> RC_MOVE_BITS;
160}
161static inline void rc_update_bit_1(struct rc *rc, uint16_t *p)
162{
163 rc->range -= rc->bound;
164 rc->code -= rc->bound;
165 *p -= *p >> RC_MOVE_BITS;
166}
167
168/* Called 4 times in unlzma loop */
169static int INIT rc_get_bit(struct rc *rc, uint16_t *p, int *symbol)
170{
171 if (rc_is_bit_0(rc, p)) {
172 rc_update_bit_0(rc, p);
173 *symbol *= 2;
174 return 0;
175 } else {
176 rc_update_bit_1(rc, p);
177 *symbol = *symbol * 2 + 1;
178 return 1;
179 }
180}
181
182/* Called once */
183static inline int INIT rc_direct_bit(struct rc *rc)
184{
185 rc_normalize(rc);
186 rc->range >>= 1;
187 if (rc->code >= rc->range) {
188 rc->code -= rc->range;
189 return 1;
190 }
191 return 0;
192}
193
194/* Called twice */
195static inline void INIT
196rc_bit_tree_decode(struct rc *rc, uint16_t *p, int num_levels, int *symbol)
197{
198 int i = num_levels;
199
200 *symbol = 1;
201 while (i--)
202 rc_get_bit(rc, p + *symbol, symbol);
203 *symbol -= 1 << num_levels;
204}
205
206
207/*
208 * Small lzma deflate implementation.
209 * Copyright (C) 2006 Aurelien Jacobs < aurel@gnuage.org >
210 *
211 * Based on LzmaDecode.c from the LZMA SDK 4.22 (http://www.7-zip.org/)
212 * Copyright (C) 1999-2005 Igor Pavlov
213 */
214
215
216struct lzma_header {
217 uint8_t pos;
218 uint32_t dict_size;
219 uint64_t dst_size;
220} __attribute__ ((packed)) ;
221
222
223#define LZMA_BASE_SIZE 1846
224#define LZMA_LIT_SIZE 768
225
226#define LZMA_NUM_POS_BITS_MAX 4
227
228#define LZMA_LEN_NUM_LOW_BITS 3
229#define LZMA_LEN_NUM_MID_BITS 3
230#define LZMA_LEN_NUM_HIGH_BITS 8
231
232#define LZMA_LEN_CHOICE 0
233#define LZMA_LEN_CHOICE_2 (LZMA_LEN_CHOICE + 1)
234#define LZMA_LEN_LOW (LZMA_LEN_CHOICE_2 + 1)
235#define LZMA_LEN_MID (LZMA_LEN_LOW \
236 + (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_LOW_BITS)))
237#define LZMA_LEN_HIGH (LZMA_LEN_MID \
238 +(1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_MID_BITS)))
239#define LZMA_NUM_LEN_PROBS (LZMA_LEN_HIGH + (1 << LZMA_LEN_NUM_HIGH_BITS))
240
241#define LZMA_NUM_STATES 12
242#define LZMA_NUM_LIT_STATES 7
243
244#define LZMA_START_POS_MODEL_INDEX 4
245#define LZMA_END_POS_MODEL_INDEX 14
246#define LZMA_NUM_FULL_DISTANCES (1 << (LZMA_END_POS_MODEL_INDEX >> 1))
247
248#define LZMA_NUM_POS_SLOT_BITS 6
249#define LZMA_NUM_LEN_TO_POS_STATES 4
250
251#define LZMA_NUM_ALIGN_BITS 4
252
253#define LZMA_MATCH_MIN_LEN 2
254
255#define LZMA_IS_MATCH 0
256#define LZMA_IS_REP (LZMA_IS_MATCH + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX))
257#define LZMA_IS_REP_G0 (LZMA_IS_REP + LZMA_NUM_STATES)
258#define LZMA_IS_REP_G1 (LZMA_IS_REP_G0 + LZMA_NUM_STATES)
259#define LZMA_IS_REP_G2 (LZMA_IS_REP_G1 + LZMA_NUM_STATES)
260#define LZMA_IS_REP_0_LONG (LZMA_IS_REP_G2 + LZMA_NUM_STATES)
261#define LZMA_POS_SLOT (LZMA_IS_REP_0_LONG \
262 + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX))
263#define LZMA_SPEC_POS (LZMA_POS_SLOT \
264 +(LZMA_NUM_LEN_TO_POS_STATES << LZMA_NUM_POS_SLOT_BITS))
265#define LZMA_ALIGN (LZMA_SPEC_POS \
266 + LZMA_NUM_FULL_DISTANCES - LZMA_END_POS_MODEL_INDEX)
267#define LZMA_LEN_CODER (LZMA_ALIGN + (1 << LZMA_NUM_ALIGN_BITS))
268#define LZMA_REP_LEN_CODER (LZMA_LEN_CODER + LZMA_NUM_LEN_PROBS)
269#define LZMA_LITERAL (LZMA_REP_LEN_CODER + LZMA_NUM_LEN_PROBS)
270
271
272struct writer {
273 uint8_t *buffer;
274 uint8_t previous_byte;
275 size_t buffer_pos;
276 int bufsize;
277 size_t global_pos;
278 int(*flush)(void*, unsigned int);
279 struct lzma_header *header;
280};
281
282struct cstate {
283 int state;
284 uint32_t rep0, rep1, rep2, rep3;
285};
286
287static inline size_t INIT get_pos(struct writer *wr)
288{
289 return
290 wr->global_pos + wr->buffer_pos;
291}
292
293static inline uint8_t INIT peek_old_byte(struct writer *wr,
294 uint32_t offs)
295{
296 if (!wr->flush) {
297 int32_t pos;
298 while (offs > wr->header->dict_size)
299 offs -= wr->header->dict_size;
300 pos = wr->buffer_pos - offs;
301 return wr->buffer[pos];
302 } else {
303 uint32_t pos = wr->buffer_pos - offs;
304 while (pos >= wr->header->dict_size)
305 pos += wr->header->dict_size;
306 return wr->buffer[pos];
307 }
308
309}
310
311static inline void INIT write_byte(struct writer *wr, uint8_t byte)
312{
313 wr->buffer[wr->buffer_pos++] = wr->previous_byte = byte;
314 if (wr->flush && wr->buffer_pos == wr->header->dict_size) {
315 wr->buffer_pos = 0;
316 wr->global_pos += wr->header->dict_size;
317 wr->flush((char *)wr->buffer, wr->header->dict_size);
318 }
319}
320
321
322static inline void INIT copy_byte(struct writer *wr, uint32_t offs)
323{
324 write_byte(wr, peek_old_byte(wr, offs));
325}
326
327static inline void INIT copy_bytes(struct writer *wr,
328 uint32_t rep0, int len)
329{
330 do {
331 copy_byte(wr, rep0);
332 len--;
333 } while (len != 0 && wr->buffer_pos < wr->header->dst_size);
334}
335
336static inline void INIT process_bit0(struct writer *wr, struct rc *rc,
337 struct cstate *cst, uint16_t *p,
338 int pos_state, uint16_t *prob,
339 int lc, uint32_t literal_pos_mask) {
340 int mi = 1;
341 rc_update_bit_0(rc, prob);
342 prob = (p + LZMA_LITERAL +
343 (LZMA_LIT_SIZE
344 * (((get_pos(wr) & literal_pos_mask) << lc)
345 + (wr->previous_byte >> (8 - lc))))
346 );
347
348 if (cst->state >= LZMA_NUM_LIT_STATES) {
349 int match_byte = peek_old_byte(wr, cst->rep0);
350 do {
351 int bit;
352 uint16_t *prob_lit;
353
354 match_byte <<= 1;
355 bit = match_byte & 0x100;
356 prob_lit = prob + 0x100 + bit + mi;
357 if (rc_get_bit(rc, prob_lit, &mi)) {
358 if (!bit)
359 break;
360 } else {
361 if (bit)
362 break;
363 }
364 } while (mi < 0x100);
365 }
366 while (mi < 0x100) {
367 uint16_t *prob_lit = prob + mi;
368 rc_get_bit(rc, prob_lit, &mi);
369 }
370 write_byte(wr, mi);
371 if (cst->state < 4)
372 cst->state = 0;
373 else if (cst->state < 10)
374 cst->state -= 3;
375 else
376 cst->state -= 6;
377}
378
379static inline void INIT process_bit1(struct writer *wr, struct rc *rc,
380 struct cstate *cst, uint16_t *p,
381 int pos_state, uint16_t *prob) {
382 int offset;
383 uint16_t *prob_len;
384 int num_bits;
385 int len;
386
387 rc_update_bit_1(rc, prob);
388 prob = p + LZMA_IS_REP + cst->state;
389 if (rc_is_bit_0(rc, prob)) {
390 rc_update_bit_0(rc, prob);
391 cst->rep3 = cst->rep2;
392 cst->rep2 = cst->rep1;
393 cst->rep1 = cst->rep0;
394 cst->state = cst->state < LZMA_NUM_LIT_STATES ? 0 : 3;
395 prob = p + LZMA_LEN_CODER;
396 } else {
397 rc_update_bit_1(rc, prob);
398 prob = p + LZMA_IS_REP_G0 + cst->state;
399 if (rc_is_bit_0(rc, prob)) {
400 rc_update_bit_0(rc, prob);
401 prob = (p + LZMA_IS_REP_0_LONG
402 + (cst->state <<
403 LZMA_NUM_POS_BITS_MAX) +
404 pos_state);
405 if (rc_is_bit_0(rc, prob)) {
406 rc_update_bit_0(rc, prob);
407
408 cst->state = cst->state < LZMA_NUM_LIT_STATES ?
409 9 : 11;
410 copy_byte(wr, cst->rep0);
411 return;
412 } else {
413 rc_update_bit_1(rc, prob);
414 }
415 } else {
416 uint32_t distance;
417
418 rc_update_bit_1(rc, prob);
419 prob = p + LZMA_IS_REP_G1 + cst->state;
420 if (rc_is_bit_0(rc, prob)) {
421 rc_update_bit_0(rc, prob);
422 distance = cst->rep1;
423 } else {
424 rc_update_bit_1(rc, prob);
425 prob = p + LZMA_IS_REP_G2 + cst->state;
426 if (rc_is_bit_0(rc, prob)) {
427 rc_update_bit_0(rc, prob);
428 distance = cst->rep2;
429 } else {
430 rc_update_bit_1(rc, prob);
431 distance = cst->rep3;
432 cst->rep3 = cst->rep2;
433 }
434 cst->rep2 = cst->rep1;
435 }
436 cst->rep1 = cst->rep0;
437 cst->rep0 = distance;
438 }
439 cst->state = cst->state < LZMA_NUM_LIT_STATES ? 8 : 11;
440 prob = p + LZMA_REP_LEN_CODER;
441 }
442
443 prob_len = prob + LZMA_LEN_CHOICE;
444 if (rc_is_bit_0(rc, prob_len)) {
445 rc_update_bit_0(rc, prob_len);
446 prob_len = (prob + LZMA_LEN_LOW
447 + (pos_state <<
448 LZMA_LEN_NUM_LOW_BITS));
449 offset = 0;
450 num_bits = LZMA_LEN_NUM_LOW_BITS;
451 } else {
452 rc_update_bit_1(rc, prob_len);
453 prob_len = prob + LZMA_LEN_CHOICE_2;
454 if (rc_is_bit_0(rc, prob_len)) {
455 rc_update_bit_0(rc, prob_len);
456 prob_len = (prob + LZMA_LEN_MID
457 + (pos_state <<
458 LZMA_LEN_NUM_MID_BITS));
459 offset = 1 << LZMA_LEN_NUM_LOW_BITS;
460 num_bits = LZMA_LEN_NUM_MID_BITS;
461 } else {
462 rc_update_bit_1(rc, prob_len);
463 prob_len = prob + LZMA_LEN_HIGH;
464 offset = ((1 << LZMA_LEN_NUM_LOW_BITS)
465 + (1 << LZMA_LEN_NUM_MID_BITS));
466 num_bits = LZMA_LEN_NUM_HIGH_BITS;
467 }
468 }
469
470 rc_bit_tree_decode(rc, prob_len, num_bits, &len);
471 len += offset;
472
473 if (cst->state < 4) {
474 int pos_slot;
475
476 cst->state += LZMA_NUM_LIT_STATES;
477 prob =
478 p + LZMA_POS_SLOT +
479 ((len <
480 LZMA_NUM_LEN_TO_POS_STATES ? len :
481 LZMA_NUM_LEN_TO_POS_STATES - 1)
482 << LZMA_NUM_POS_SLOT_BITS);
483 rc_bit_tree_decode(rc, prob,
484 LZMA_NUM_POS_SLOT_BITS,
485 &pos_slot);
486 if (pos_slot >= LZMA_START_POS_MODEL_INDEX) {
487 int i, mi;
488 num_bits = (pos_slot >> 1) - 1;
489 cst->rep0 = 2 | (pos_slot & 1);
490 if (pos_slot < LZMA_END_POS_MODEL_INDEX) {
491 cst->rep0 <<= num_bits;
492 prob = p + LZMA_SPEC_POS +
493 cst->rep0 - pos_slot - 1;
494 } else {
495 num_bits -= LZMA_NUM_ALIGN_BITS;
496 while (num_bits--)
497 cst->rep0 = (cst->rep0 << 1) |
498 rc_direct_bit(rc);
499 prob = p + LZMA_ALIGN;
500 cst->rep0 <<= LZMA_NUM_ALIGN_BITS;
501 num_bits = LZMA_NUM_ALIGN_BITS;
502 }
503 i = 1;
504 mi = 1;
505 while (num_bits--) {
506 if (rc_get_bit(rc, prob + mi, &mi))
507 cst->rep0 |= i;
508 i <<= 1;
509 }
510 } else
511 cst->rep0 = pos_slot;
512 if (++(cst->rep0) == 0)
513 return;
514 }
515
516 len += LZMA_MATCH_MIN_LEN;
517
518 copy_bytes(wr, cst->rep0, len);
519}
520
521
522
523STATIC inline int INIT unlzma(unsigned char *buf, int in_len,
524 int(*fill)(void*, unsigned int),
525 int(*flush)(void*, unsigned int),
526 unsigned char *output,
527 int *posp,
528 void(*error_fn)(char *x)
529 )
530{
531 struct lzma_header header;
532 int lc, pb, lp;
533 uint32_t pos_state_mask;
534 uint32_t literal_pos_mask;
535 uint16_t *p;
536 int num_probs;
537 struct rc rc;
538 int i, mi;
539 struct writer wr;
540 struct cstate cst;
541 unsigned char *inbuf;
542 int ret = -1;
543
544 set_error_fn(error_fn);
545 if (!flush)
546 in_len -= 4; /* Uncompressed size hack active in pre-boot
547 environment */
548 if (buf)
549 inbuf = buf;
550 else
551 inbuf = malloc(LZMA_IOBUF_SIZE);
552 if (!inbuf) {
553 error("Could not allocate input bufer");
554 goto exit_0;
555 }
556
557 cst.state = 0;
558 cst.rep0 = cst.rep1 = cst.rep2 = cst.rep3 = 1;
559
560 wr.header = &header;
561 wr.flush = flush;
562 wr.global_pos = 0;
563 wr.previous_byte = 0;
564 wr.buffer_pos = 0;
565
566 rc_init(&rc, fill, inbuf, in_len);
567
568 for (i = 0; i < sizeof(header); i++) {
569 if (rc.ptr >= rc.buffer_end)
570 rc_read(&rc);
571 ((unsigned char *)&header)[i] = *rc.ptr++;
572 }
573
574 if (header.pos >= (9 * 5 * 5))
575 error("bad header");
576
577 mi = 0;
578 lc = header.pos;
579 while (lc >= 9) {
580 mi++;
581 lc -= 9;
582 }
583 pb = 0;
584 lp = mi;
585 while (lp >= 5) {
586 pb++;
587 lp -= 5;
588 }
589 pos_state_mask = (1 << pb) - 1;
590 literal_pos_mask = (1 << lp) - 1;
591
592 ENDIAN_CONVERT(header.dict_size);
593 ENDIAN_CONVERT(header.dst_size);
594
595 if (header.dict_size == 0)
596 header.dict_size = 1;
597
598 if (output)
599 wr.buffer = output;
600 else {
601 wr.bufsize = MIN(header.dst_size, header.dict_size);
602 wr.buffer = large_malloc(wr.bufsize);
603 }
604 if (wr.buffer == NULL)
605 goto exit_1;
606
607 num_probs = LZMA_BASE_SIZE + (LZMA_LIT_SIZE << (lc + lp));
608 p = (uint16_t *) large_malloc(num_probs * sizeof(*p));
609 if (p == 0)
610 goto exit_2;
611 num_probs = LZMA_LITERAL + (LZMA_LIT_SIZE << (lc + lp));
612 for (i = 0; i < num_probs; i++)
613 p[i] = (1 << RC_MODEL_TOTAL_BITS) >> 1;
614
615 rc_init_code(&rc);
616
617 while (get_pos(&wr) < header.dst_size) {
618 int pos_state = get_pos(&wr) & pos_state_mask;
619 uint16_t *prob = p + LZMA_IS_MATCH +
620 (cst.state << LZMA_NUM_POS_BITS_MAX) + pos_state;
621 if (rc_is_bit_0(&rc, prob))
622 process_bit0(&wr, &rc, &cst, p, pos_state, prob,
623 lc, literal_pos_mask);
624 else {
625 process_bit1(&wr, &rc, &cst, p, pos_state, prob);
626 if (cst.rep0 == 0)
627 break;
628 }
629 }
630
631 if (posp)
632 *posp = rc.ptr-rc.buffer;
633 if (wr.flush)
634 wr.flush(wr.buffer, wr.buffer_pos);
635 ret = 0;
636 large_free(p);
637exit_2:
638 if (!output)
639 large_free(wr.buffer);
640exit_1:
641 if (!buf)
642 free(inbuf);
643exit_0:
644 return ret;
645}
646
647#define decompress unlzma
diff --git a/lib/vsprintf.c b/lib/vsprintf.c
index 0fbd0121d91d..dc1674377009 100644
--- a/lib/vsprintf.c
+++ b/lib/vsprintf.c
@@ -396,7 +396,38 @@ static noinline char* put_dec(char *buf, unsigned long long num)
396#define SMALL 32 /* Must be 32 == 0x20 */ 396#define SMALL 32 /* Must be 32 == 0x20 */
397#define SPECIAL 64 /* 0x */ 397#define SPECIAL 64 /* 0x */
398 398
399static char *number(char *buf, char *end, unsigned long long num, int base, int size, int precision, int type) 399enum format_type {
400 FORMAT_TYPE_NONE, /* Just a string part */
401 FORMAT_TYPE_WITDH,
402 FORMAT_TYPE_PRECISION,
403 FORMAT_TYPE_CHAR,
404 FORMAT_TYPE_STR,
405 FORMAT_TYPE_PTR,
406 FORMAT_TYPE_PERCENT_CHAR,
407 FORMAT_TYPE_INVALID,
408 FORMAT_TYPE_LONG_LONG,
409 FORMAT_TYPE_ULONG,
410 FORMAT_TYPE_LONG,
411 FORMAT_TYPE_USHORT,
412 FORMAT_TYPE_SHORT,
413 FORMAT_TYPE_UINT,
414 FORMAT_TYPE_INT,
415 FORMAT_TYPE_NRCHARS,
416 FORMAT_TYPE_SIZE_T,
417 FORMAT_TYPE_PTRDIFF
418};
419
420struct printf_spec {
421 enum format_type type;
422 int flags; /* flags to number() */
423 int field_width; /* width of output field */
424 int base;
425 int precision; /* # of digits/chars */
426 int qualifier;
427};
428
429static char *number(char *buf, char *end, unsigned long long num,
430 struct printf_spec spec)
400{ 431{
401 /* we are called with base 8, 10 or 16, only, thus don't need "G..." */ 432 /* we are called with base 8, 10 or 16, only, thus don't need "G..." */
402 static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */ 433 static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */
@@ -404,32 +435,32 @@ static char *number(char *buf, char *end, unsigned long long num, int base, int
404 char tmp[66]; 435 char tmp[66];
405 char sign; 436 char sign;
406 char locase; 437 char locase;
407 int need_pfx = ((type & SPECIAL) && base != 10); 438 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
408 int i; 439 int i;
409 440
410 /* locase = 0 or 0x20. ORing digits or letters with 'locase' 441 /* locase = 0 or 0x20. ORing digits or letters with 'locase'
411 * produces same digits or (maybe lowercased) letters */ 442 * produces same digits or (maybe lowercased) letters */
412 locase = (type & SMALL); 443 locase = (spec.flags & SMALL);
413 if (type & LEFT) 444 if (spec.flags & LEFT)
414 type &= ~ZEROPAD; 445 spec.flags &= ~ZEROPAD;
415 sign = 0; 446 sign = 0;
416 if (type & SIGN) { 447 if (spec.flags & SIGN) {
417 if ((signed long long) num < 0) { 448 if ((signed long long) num < 0) {
418 sign = '-'; 449 sign = '-';
419 num = - (signed long long) num; 450 num = - (signed long long) num;
420 size--; 451 spec.field_width--;
421 } else if (type & PLUS) { 452 } else if (spec.flags & PLUS) {
422 sign = '+'; 453 sign = '+';
423 size--; 454 spec.field_width--;
424 } else if (type & SPACE) { 455 } else if (spec.flags & SPACE) {
425 sign = ' '; 456 sign = ' ';
426 size--; 457 spec.field_width--;
427 } 458 }
428 } 459 }
429 if (need_pfx) { 460 if (need_pfx) {
430 size--; 461 spec.field_width--;
431 if (base == 16) 462 if (spec.base == 16)
432 size--; 463 spec.field_width--;
433 } 464 }
434 465
435 /* generate full string in tmp[], in reverse order */ 466 /* generate full string in tmp[], in reverse order */
@@ -441,10 +472,10 @@ static char *number(char *buf, char *end, unsigned long long num, int base, int
441 tmp[i++] = (digits[do_div(num,base)] | locase); 472 tmp[i++] = (digits[do_div(num,base)] | locase);
442 } while (num != 0); 473 } while (num != 0);
443 */ 474 */
444 else if (base != 10) { /* 8 or 16 */ 475 else if (spec.base != 10) { /* 8 or 16 */
445 int mask = base - 1; 476 int mask = spec.base - 1;
446 int shift = 3; 477 int shift = 3;
447 if (base == 16) shift = 4; 478 if (spec.base == 16) shift = 4;
448 do { 479 do {
449 tmp[i++] = (digits[((unsigned char)num) & mask] | locase); 480 tmp[i++] = (digits[((unsigned char)num) & mask] | locase);
450 num >>= shift; 481 num >>= shift;
@@ -454,12 +485,12 @@ static char *number(char *buf, char *end, unsigned long long num, int base, int
454 } 485 }
455 486
456 /* printing 100 using %2d gives "100", not "00" */ 487 /* printing 100 using %2d gives "100", not "00" */
457 if (i > precision) 488 if (i > spec.precision)
458 precision = i; 489 spec.precision = i;
459 /* leading space padding */ 490 /* leading space padding */
460 size -= precision; 491 spec.field_width -= spec.precision;
461 if (!(type & (ZEROPAD+LEFT))) { 492 if (!(spec.flags & (ZEROPAD+LEFT))) {
462 while(--size >= 0) { 493 while(--spec.field_width >= 0) {
463 if (buf < end) 494 if (buf < end)
464 *buf = ' '; 495 *buf = ' ';
465 ++buf; 496 ++buf;
@@ -476,23 +507,23 @@ static char *number(char *buf, char *end, unsigned long long num, int base, int
476 if (buf < end) 507 if (buf < end)
477 *buf = '0'; 508 *buf = '0';
478 ++buf; 509 ++buf;
479 if (base == 16) { 510 if (spec.base == 16) {
480 if (buf < end) 511 if (buf < end)
481 *buf = ('X' | locase); 512 *buf = ('X' | locase);
482 ++buf; 513 ++buf;
483 } 514 }
484 } 515 }
485 /* zero or space padding */ 516 /* zero or space padding */
486 if (!(type & LEFT)) { 517 if (!(spec.flags & LEFT)) {
487 char c = (type & ZEROPAD) ? '0' : ' '; 518 char c = (spec.flags & ZEROPAD) ? '0' : ' ';
488 while (--size >= 0) { 519 while (--spec.field_width >= 0) {
489 if (buf < end) 520 if (buf < end)
490 *buf = c; 521 *buf = c;
491 ++buf; 522 ++buf;
492 } 523 }
493 } 524 }
494 /* hmm even more zero padding? */ 525 /* hmm even more zero padding? */
495 while (i <= --precision) { 526 while (i <= --spec.precision) {
496 if (buf < end) 527 if (buf < end)
497 *buf = '0'; 528 *buf = '0';
498 ++buf; 529 ++buf;
@@ -504,7 +535,7 @@ static char *number(char *buf, char *end, unsigned long long num, int base, int
504 ++buf; 535 ++buf;
505 } 536 }
506 /* trailing space padding */ 537 /* trailing space padding */
507 while (--size >= 0) { 538 while (--spec.field_width >= 0) {
508 if (buf < end) 539 if (buf < end)
509 *buf = ' '; 540 *buf = ' ';
510 ++buf; 541 ++buf;
@@ -512,17 +543,17 @@ static char *number(char *buf, char *end, unsigned long long num, int base, int
512 return buf; 543 return buf;
513} 544}
514 545
515static char *string(char *buf, char *end, char *s, int field_width, int precision, int flags) 546static char *string(char *buf, char *end, char *s, struct printf_spec spec)
516{ 547{
517 int len, i; 548 int len, i;
518 549
519 if ((unsigned long)s < PAGE_SIZE) 550 if ((unsigned long)s < PAGE_SIZE)
520 s = "<NULL>"; 551 s = "<NULL>";
521 552
522 len = strnlen(s, precision); 553 len = strnlen(s, spec.precision);
523 554
524 if (!(flags & LEFT)) { 555 if (!(spec.flags & LEFT)) {
525 while (len < field_width--) { 556 while (len < spec.field_width--) {
526 if (buf < end) 557 if (buf < end)
527 *buf = ' '; 558 *buf = ' ';
528 ++buf; 559 ++buf;
@@ -533,7 +564,7 @@ static char *string(char *buf, char *end, char *s, int field_width, int precisio
533 *buf = *s; 564 *buf = *s;
534 ++buf; ++s; 565 ++buf; ++s;
535 } 566 }
536 while (len < field_width--) { 567 while (len < spec.field_width--) {
537 if (buf < end) 568 if (buf < end)
538 *buf = ' '; 569 *buf = ' ';
539 ++buf; 570 ++buf;
@@ -541,21 +572,24 @@ static char *string(char *buf, char *end, char *s, int field_width, int precisio
541 return buf; 572 return buf;
542} 573}
543 574
544static char *symbol_string(char *buf, char *end, void *ptr, int field_width, int precision, int flags) 575static char *symbol_string(char *buf, char *end, void *ptr,
576 struct printf_spec spec)
545{ 577{
546 unsigned long value = (unsigned long) ptr; 578 unsigned long value = (unsigned long) ptr;
547#ifdef CONFIG_KALLSYMS 579#ifdef CONFIG_KALLSYMS
548 char sym[KSYM_SYMBOL_LEN]; 580 char sym[KSYM_SYMBOL_LEN];
549 sprint_symbol(sym, value); 581 sprint_symbol(sym, value);
550 return string(buf, end, sym, field_width, precision, flags); 582 return string(buf, end, sym, spec);
551#else 583#else
552 field_width = 2*sizeof(void *); 584 spec.field_width = 2*sizeof(void *);
553 flags |= SPECIAL | SMALL | ZEROPAD; 585 spec.flags |= SPECIAL | SMALL | ZEROPAD;
554 return number(buf, end, value, 16, field_width, precision, flags); 586 spec.base = 16;
587 return number(buf, end, value, spec);
555#endif 588#endif
556} 589}
557 590
558static char *resource_string(char *buf, char *end, struct resource *res, int field_width, int precision, int flags) 591static char *resource_string(char *buf, char *end, struct resource *res,
592 struct printf_spec spec)
559{ 593{
560#ifndef IO_RSRC_PRINTK_SIZE 594#ifndef IO_RSRC_PRINTK_SIZE
561#define IO_RSRC_PRINTK_SIZE 4 595#define IO_RSRC_PRINTK_SIZE 4
@@ -564,7 +598,11 @@ static char *resource_string(char *buf, char *end, struct resource *res, int fie
564#ifndef MEM_RSRC_PRINTK_SIZE 598#ifndef MEM_RSRC_PRINTK_SIZE
565#define MEM_RSRC_PRINTK_SIZE 8 599#define MEM_RSRC_PRINTK_SIZE 8
566#endif 600#endif
567 601 struct printf_spec num_spec = {
602 .base = 16,
603 .precision = -1,
604 .flags = SPECIAL | SMALL | ZEROPAD,
605 };
568 /* room for the actual numbers, the two "0x", -, [, ] and the final zero */ 606 /* room for the actual numbers, the two "0x", -, [, ] and the final zero */
569 char sym[4*sizeof(resource_size_t) + 8]; 607 char sym[4*sizeof(resource_size_t) + 8];
570 char *p = sym, *pend = sym + sizeof(sym); 608 char *p = sym, *pend = sym + sizeof(sym);
@@ -576,17 +614,18 @@ static char *resource_string(char *buf, char *end, struct resource *res, int fie
576 size = MEM_RSRC_PRINTK_SIZE; 614 size = MEM_RSRC_PRINTK_SIZE;
577 615
578 *p++ = '['; 616 *p++ = '[';
579 p = number(p, pend, res->start, 16, size, -1, SPECIAL | SMALL | ZEROPAD); 617 num_spec.field_width = size;
618 p = number(p, pend, res->start, num_spec);
580 *p++ = '-'; 619 *p++ = '-';
581 p = number(p, pend, res->end, 16, size, -1, SPECIAL | SMALL | ZEROPAD); 620 p = number(p, pend, res->end, num_spec);
582 *p++ = ']'; 621 *p++ = ']';
583 *p = 0; 622 *p = 0;
584 623
585 return string(buf, end, sym, field_width, precision, flags); 624 return string(buf, end, sym, spec);
586} 625}
587 626
588static char *mac_address_string(char *buf, char *end, u8 *addr, int field_width, 627static char *mac_address_string(char *buf, char *end, u8 *addr,
589 int precision, int flags) 628 struct printf_spec spec)
590{ 629{
591 char mac_addr[6 * 3]; /* (6 * 2 hex digits), 5 colons and trailing zero */ 630 char mac_addr[6 * 3]; /* (6 * 2 hex digits), 5 colons and trailing zero */
592 char *p = mac_addr; 631 char *p = mac_addr;
@@ -594,16 +633,17 @@ static char *mac_address_string(char *buf, char *end, u8 *addr, int field_width,
594 633
595 for (i = 0; i < 6; i++) { 634 for (i = 0; i < 6; i++) {
596 p = pack_hex_byte(p, addr[i]); 635 p = pack_hex_byte(p, addr[i]);
597 if (!(flags & SPECIAL) && i != 5) 636 if (!(spec.flags & SPECIAL) && i != 5)
598 *p++ = ':'; 637 *p++ = ':';
599 } 638 }
600 *p = '\0'; 639 *p = '\0';
640 spec.flags &= ~SPECIAL;
601 641
602 return string(buf, end, mac_addr, field_width, precision, flags & ~SPECIAL); 642 return string(buf, end, mac_addr, spec);
603} 643}
604 644
605static char *ip6_addr_string(char *buf, char *end, u8 *addr, int field_width, 645static char *ip6_addr_string(char *buf, char *end, u8 *addr,
606 int precision, int flags) 646 struct printf_spec spec)
607{ 647{
608 char ip6_addr[8 * 5]; /* (8 * 4 hex digits), 7 colons and trailing zero */ 648 char ip6_addr[8 * 5]; /* (8 * 4 hex digits), 7 colons and trailing zero */
609 char *p = ip6_addr; 649 char *p = ip6_addr;
@@ -612,16 +652,17 @@ static char *ip6_addr_string(char *buf, char *end, u8 *addr, int field_width,
612 for (i = 0; i < 8; i++) { 652 for (i = 0; i < 8; i++) {
613 p = pack_hex_byte(p, addr[2 * i]); 653 p = pack_hex_byte(p, addr[2 * i]);
614 p = pack_hex_byte(p, addr[2 * i + 1]); 654 p = pack_hex_byte(p, addr[2 * i + 1]);
615 if (!(flags & SPECIAL) && i != 7) 655 if (!(spec.flags & SPECIAL) && i != 7)
616 *p++ = ':'; 656 *p++ = ':';
617 } 657 }
618 *p = '\0'; 658 *p = '\0';
659 spec.flags &= ~SPECIAL;
619 660
620 return string(buf, end, ip6_addr, field_width, precision, flags & ~SPECIAL); 661 return string(buf, end, ip6_addr, spec);
621} 662}
622 663
623static char *ip4_addr_string(char *buf, char *end, u8 *addr, int field_width, 664static char *ip4_addr_string(char *buf, char *end, u8 *addr,
624 int precision, int flags) 665 struct printf_spec spec)
625{ 666{
626 char ip4_addr[4 * 4]; /* (4 * 3 decimal digits), 3 dots and trailing zero */ 667 char ip4_addr[4 * 4]; /* (4 * 3 decimal digits), 3 dots and trailing zero */
627 char temp[3]; /* hold each IP quad in reverse order */ 668 char temp[3]; /* hold each IP quad in reverse order */
@@ -637,8 +678,9 @@ static char *ip4_addr_string(char *buf, char *end, u8 *addr, int field_width,
637 *p++ = '.'; 678 *p++ = '.';
638 } 679 }
639 *p = '\0'; 680 *p = '\0';
681 spec.flags &= ~SPECIAL;
640 682
641 return string(buf, end, ip4_addr, field_width, precision, flags & ~SPECIAL); 683 return string(buf, end, ip4_addr, spec);
642} 684}
643 685
644/* 686/*
@@ -663,41 +705,233 @@ static char *ip4_addr_string(char *buf, char *end, u8 *addr, int field_width,
663 * function pointers are really function descriptors, which contain a 705 * function pointers are really function descriptors, which contain a
664 * pointer to the real address. 706 * pointer to the real address.
665 */ 707 */
666static char *pointer(const char *fmt, char *buf, char *end, void *ptr, int field_width, int precision, int flags) 708static char *pointer(const char *fmt, char *buf, char *end, void *ptr,
709 struct printf_spec spec)
667{ 710{
668 if (!ptr) 711 if (!ptr)
669 return string(buf, end, "(null)", field_width, precision, flags); 712 return string(buf, end, "(null)", spec);
670 713
671 switch (*fmt) { 714 switch (*fmt) {
672 case 'F': 715 case 'F':
673 ptr = dereference_function_descriptor(ptr); 716 ptr = dereference_function_descriptor(ptr);
674 /* Fallthrough */ 717 /* Fallthrough */
675 case 'S': 718 case 'S':
676 return symbol_string(buf, end, ptr, field_width, precision, flags); 719 return symbol_string(buf, end, ptr, spec);
677 case 'R': 720 case 'R':
678 return resource_string(buf, end, ptr, field_width, precision, flags); 721 return resource_string(buf, end, ptr, spec);
679 case 'm': 722 case 'm':
680 flags |= SPECIAL; 723 spec.flags |= SPECIAL;
681 /* Fallthrough */ 724 /* Fallthrough */
682 case 'M': 725 case 'M':
683 return mac_address_string(buf, end, ptr, field_width, precision, flags); 726 return mac_address_string(buf, end, ptr, spec);
684 case 'i': 727 case 'i':
685 flags |= SPECIAL; 728 spec.flags |= SPECIAL;
686 /* Fallthrough */ 729 /* Fallthrough */
687 case 'I': 730 case 'I':
688 if (fmt[1] == '6') 731 if (fmt[1] == '6')
689 return ip6_addr_string(buf, end, ptr, field_width, precision, flags); 732 return ip6_addr_string(buf, end, ptr, spec);
690 if (fmt[1] == '4') 733 if (fmt[1] == '4')
691 return ip4_addr_string(buf, end, ptr, field_width, precision, flags); 734 return ip4_addr_string(buf, end, ptr, spec);
692 flags &= ~SPECIAL; 735 spec.flags &= ~SPECIAL;
736 break;
737 }
738 spec.flags |= SMALL;
739 if (spec.field_width == -1) {
740 spec.field_width = 2*sizeof(void *);
741 spec.flags |= ZEROPAD;
742 }
743 spec.base = 16;
744
745 return number(buf, end, (unsigned long) ptr, spec);
746}
747
748/*
749 * Helper function to decode printf style format.
750 * Each call decode a token from the format and return the
751 * number of characters read (or likely the delta where it wants
752 * to go on the next call).
753 * The decoded token is returned through the parameters
754 *
755 * 'h', 'l', or 'L' for integer fields
756 * 'z' support added 23/7/1999 S.H.
757 * 'z' changed to 'Z' --davidm 1/25/99
758 * 't' added for ptrdiff_t
759 *
760 * @fmt: the format string
761 * @type of the token returned
762 * @flags: various flags such as +, -, # tokens..
763 * @field_width: overwritten width
764 * @base: base of the number (octal, hex, ...)
765 * @precision: precision of a number
766 * @qualifier: qualifier of a number (long, size_t, ...)
767 */
768static int format_decode(const char *fmt, struct printf_spec *spec)
769{
770 const char *start = fmt;
771
772 /* we finished early by reading the field width */
773 if (spec->type == FORMAT_TYPE_WITDH) {
774 if (spec->field_width < 0) {
775 spec->field_width = -spec->field_width;
776 spec->flags |= LEFT;
777 }
778 spec->type = FORMAT_TYPE_NONE;
779 goto precision;
780 }
781
782 /* we finished early by reading the precision */
783 if (spec->type == FORMAT_TYPE_PRECISION) {
784 if (spec->precision < 0)
785 spec->precision = 0;
786
787 spec->type = FORMAT_TYPE_NONE;
788 goto qualifier;
789 }
790
791 /* By default */
792 spec->type = FORMAT_TYPE_NONE;
793
794 for (; *fmt ; ++fmt) {
795 if (*fmt == '%')
796 break;
797 }
798
799 /* Return the current non-format string */
800 if (fmt != start || !*fmt)
801 return fmt - start;
802
803 /* Process flags */
804 spec->flags = 0;
805
806 while (1) { /* this also skips first '%' */
807 bool found = true;
808
809 ++fmt;
810
811 switch (*fmt) {
812 case '-': spec->flags |= LEFT; break;
813 case '+': spec->flags |= PLUS; break;
814 case ' ': spec->flags |= SPACE; break;
815 case '#': spec->flags |= SPECIAL; break;
816 case '0': spec->flags |= ZEROPAD; break;
817 default: found = false;
818 }
819
820 if (!found)
821 break;
822 }
823
824 /* get field width */
825 spec->field_width = -1;
826
827 if (isdigit(*fmt))
828 spec->field_width = skip_atoi(&fmt);
829 else if (*fmt == '*') {
830 /* it's the next argument */
831 spec->type = FORMAT_TYPE_WITDH;
832 return ++fmt - start;
833 }
834
835precision:
836 /* get the precision */
837 spec->precision = -1;
838 if (*fmt == '.') {
839 ++fmt;
840 if (isdigit(*fmt)) {
841 spec->precision = skip_atoi(&fmt);
842 if (spec->precision < 0)
843 spec->precision = 0;
844 } else if (*fmt == '*') {
845 /* it's the next argument */
846 spec->type = FORMAT_TYPE_WITDH;
847 return ++fmt - start;
848 }
849 }
850
851qualifier:
852 /* get the conversion qualifier */
853 spec->qualifier = -1;
854 if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L' ||
855 *fmt == 'Z' || *fmt == 'z' || *fmt == 't') {
856 spec->qualifier = *fmt;
857 ++fmt;
858 if (spec->qualifier == 'l' && *fmt == 'l') {
859 spec->qualifier = 'L';
860 ++fmt;
861 }
862 }
863
864 /* default base */
865 spec->base = 10;
866 switch (*fmt) {
867 case 'c':
868 spec->type = FORMAT_TYPE_CHAR;
869 return ++fmt - start;
870
871 case 's':
872 spec->type = FORMAT_TYPE_STR;
873 return ++fmt - start;
874
875 case 'p':
876 spec->type = FORMAT_TYPE_PTR;
877 return fmt - start;
878 /* skip alnum */
879
880 case 'n':
881 spec->type = FORMAT_TYPE_NRCHARS;
882 return ++fmt - start;
883
884 case '%':
885 spec->type = FORMAT_TYPE_PERCENT_CHAR;
886 return ++fmt - start;
887
888 /* integer number formats - set up the flags and "break" */
889 case 'o':
890 spec->base = 8;
693 break; 891 break;
892
893 case 'x':
894 spec->flags |= SMALL;
895
896 case 'X':
897 spec->base = 16;
898 break;
899
900 case 'd':
901 case 'i':
902 spec->flags |= SIGN;
903 case 'u':
904 break;
905
906 default:
907 spec->type = FORMAT_TYPE_INVALID;
908 return fmt - start;
694 } 909 }
695 flags |= SMALL; 910
696 if (field_width == -1) { 911 if (spec->qualifier == 'L')
697 field_width = 2*sizeof(void *); 912 spec->type = FORMAT_TYPE_LONG_LONG;
698 flags |= ZEROPAD; 913 else if (spec->qualifier == 'l') {
914 if (spec->flags & SIGN)
915 spec->type = FORMAT_TYPE_LONG;
916 else
917 spec->type = FORMAT_TYPE_ULONG;
918 } else if (spec->qualifier == 'Z' || spec->qualifier == 'z') {
919 spec->type = FORMAT_TYPE_SIZE_T;
920 } else if (spec->qualifier == 't') {
921 spec->type = FORMAT_TYPE_PTRDIFF;
922 } else if (spec->qualifier == 'h') {
923 if (spec->flags & SIGN)
924 spec->type = FORMAT_TYPE_SHORT;
925 else
926 spec->type = FORMAT_TYPE_USHORT;
927 } else {
928 if (spec->flags & SIGN)
929 spec->type = FORMAT_TYPE_INT;
930 else
931 spec->type = FORMAT_TYPE_UINT;
699 } 932 }
700 return number(buf, end, (unsigned long) ptr, 16, field_width, precision, flags); 933
934 return ++fmt - start;
701} 935}
702 936
703/** 937/**
@@ -726,18 +960,9 @@ static char *pointer(const char *fmt, char *buf, char *end, void *ptr, int field
726int vsnprintf(char *buf, size_t size, const char *fmt, va_list args) 960int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
727{ 961{
728 unsigned long long num; 962 unsigned long long num;
729 int base;
730 char *str, *end, c; 963 char *str, *end, c;
731 964 int read;
732 int flags; /* flags to number() */ 965 struct printf_spec spec = {0};
733
734 int field_width; /* width of output field */
735 int precision; /* min. # of digits for integers; max
736 number of chars for from string */
737 int qualifier; /* 'h', 'l', or 'L' for integer fields */
738 /* 'z' support added 23/7/1999 S.H. */
739 /* 'z' changed to 'Z' --davidm 1/25/99 */
740 /* 't' added for ptrdiff_t */
741 966
742 /* Reject out-of-range values early. Large positive sizes are 967 /* Reject out-of-range values early. Large positive sizes are
743 used for unknown buffer sizes. */ 968 used for unknown buffer sizes. */
@@ -758,184 +983,144 @@ int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
758 size = end - buf; 983 size = end - buf;
759 } 984 }
760 985
761 for (; *fmt ; ++fmt) { 986 while (*fmt) {
762 if (*fmt != '%') { 987 const char *old_fmt = fmt;
763 if (str < end)
764 *str = *fmt;
765 ++str;
766 continue;
767 }
768 988
769 /* process flags */ 989 read = format_decode(fmt, &spec);
770 flags = 0;
771 repeat:
772 ++fmt; /* this also skips first '%' */
773 switch (*fmt) {
774 case '-': flags |= LEFT; goto repeat;
775 case '+': flags |= PLUS; goto repeat;
776 case ' ': flags |= SPACE; goto repeat;
777 case '#': flags |= SPECIAL; goto repeat;
778 case '0': flags |= ZEROPAD; goto repeat;
779 }
780 990
781 /* get field width */ 991 fmt += read;
782 field_width = -1;
783 if (isdigit(*fmt))
784 field_width = skip_atoi(&fmt);
785 else if (*fmt == '*') {
786 ++fmt;
787 /* it's the next argument */
788 field_width = va_arg(args, int);
789 if (field_width < 0) {
790 field_width = -field_width;
791 flags |= LEFT;
792 }
793 }
794 992
795 /* get the precision */ 993 switch (spec.type) {
796 precision = -1; 994 case FORMAT_TYPE_NONE: {
797 if (*fmt == '.') { 995 int copy = read;
798 ++fmt; 996 if (str < end) {
799 if (isdigit(*fmt)) 997 if (copy > end - str)
800 precision = skip_atoi(&fmt); 998 copy = end - str;
801 else if (*fmt == '*') { 999 memcpy(str, old_fmt, copy);
802 ++fmt;
803 /* it's the next argument */
804 precision = va_arg(args, int);
805 } 1000 }
806 if (precision < 0) 1001 str += read;
807 precision = 0; 1002 break;
808 } 1003 }
809 1004
810 /* get the conversion qualifier */ 1005 case FORMAT_TYPE_WITDH:
811 qualifier = -1; 1006 spec.field_width = va_arg(args, int);
812 if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L' || 1007 break;
813 *fmt =='Z' || *fmt == 'z' || *fmt == 't') {
814 qualifier = *fmt;
815 ++fmt;
816 if (qualifier == 'l' && *fmt == 'l') {
817 qualifier = 'L';
818 ++fmt;
819 }
820 }
821 1008
822 /* default base */ 1009 case FORMAT_TYPE_PRECISION:
823 base = 10; 1010 spec.precision = va_arg(args, int);
1011 break;
824 1012
825 switch (*fmt) { 1013 case FORMAT_TYPE_CHAR:
826 case 'c': 1014 if (!(spec.flags & LEFT)) {
827 if (!(flags & LEFT)) { 1015 while (--spec.field_width > 0) {
828 while (--field_width > 0) {
829 if (str < end)
830 *str = ' ';
831 ++str;
832 }
833 }
834 c = (unsigned char) va_arg(args, int);
835 if (str < end)
836 *str = c;
837 ++str;
838 while (--field_width > 0) {
839 if (str < end) 1016 if (str < end)
840 *str = ' '; 1017 *str = ' ';
841 ++str; 1018 ++str;
842 }
843 continue;
844
845 case 's':
846 str = string(str, end, va_arg(args, char *), field_width, precision, flags);
847 continue;
848
849 case 'p':
850 str = pointer(fmt+1, str, end,
851 va_arg(args, void *),
852 field_width, precision, flags);
853 /* Skip all alphanumeric pointer suffixes */
854 while (isalnum(fmt[1]))
855 fmt++;
856 continue;
857
858 case 'n':
859 /* FIXME:
860 * What does C99 say about the overflow case here? */
861 if (qualifier == 'l') {
862 long * ip = va_arg(args, long *);
863 *ip = (str - buf);
864 } else if (qualifier == 'Z' || qualifier == 'z') {
865 size_t * ip = va_arg(args, size_t *);
866 *ip = (str - buf);
867 } else {
868 int * ip = va_arg(args, int *);
869 *ip = (str - buf);
870 }
871 continue;
872 1019
873 case '%': 1020 }
1021 }
1022 c = (unsigned char) va_arg(args, int);
1023 if (str < end)
1024 *str = c;
1025 ++str;
1026 while (--spec.field_width > 0) {
874 if (str < end) 1027 if (str < end)
875 *str = '%'; 1028 *str = ' ';
876 ++str; 1029 ++str;
877 continue; 1030 }
1031 break;
878 1032
879 /* integer number formats - set up the flags and "break" */ 1033 case FORMAT_TYPE_STR:
880 case 'o': 1034 str = string(str, end, va_arg(args, char *), spec);
881 base = 8; 1035 break;
882 break;
883 1036
884 case 'x': 1037 case FORMAT_TYPE_PTR:
885 flags |= SMALL; 1038 str = pointer(fmt+1, str, end, va_arg(args, void *),
886 case 'X': 1039 spec);
887 base = 16; 1040 while (isalnum(*fmt))
888 break; 1041 fmt++;
1042 break;
889 1043
890 case 'd': 1044 case FORMAT_TYPE_PERCENT_CHAR:
891 case 'i': 1045 if (str < end)
892 flags |= SIGN; 1046 *str = '%';
893 case 'u': 1047 ++str;
894 break; 1048 break;
895 1049
896 default: 1050 case FORMAT_TYPE_INVALID:
1051 if (str < end)
1052 *str = '%';
1053 ++str;
1054 if (*fmt) {
897 if (str < end) 1055 if (str < end)
898 *str = '%'; 1056 *str = *fmt;
899 ++str; 1057 ++str;
900 if (*fmt) { 1058 } else {
901 if (str < end) 1059 --fmt;
902 *str = *fmt; 1060 }
903 ++str; 1061 break;
904 } else { 1062
905 --fmt; 1063 case FORMAT_TYPE_NRCHARS: {
906 } 1064 int qualifier = spec.qualifier;
907 continue; 1065
1066 if (qualifier == 'l') {
1067 long *ip = va_arg(args, long *);
1068 *ip = (str - buf);
1069 } else if (qualifier == 'Z' ||
1070 qualifier == 'z') {
1071 size_t *ip = va_arg(args, size_t *);
1072 *ip = (str - buf);
1073 } else {
1074 int *ip = va_arg(args, int *);
1075 *ip = (str - buf);
1076 }
1077 break;
908 } 1078 }
909 if (qualifier == 'L') 1079
910 num = va_arg(args, long long); 1080 default:
911 else if (qualifier == 'l') { 1081 switch (spec.type) {
912 num = va_arg(args, unsigned long); 1082 case FORMAT_TYPE_LONG_LONG:
913 if (flags & SIGN) 1083 num = va_arg(args, long long);
914 num = (signed long) num; 1084 break;
915 } else if (qualifier == 'Z' || qualifier == 'z') { 1085 case FORMAT_TYPE_ULONG:
916 num = va_arg(args, size_t); 1086 num = va_arg(args, unsigned long);
917 } else if (qualifier == 't') { 1087 break;
918 num = va_arg(args, ptrdiff_t); 1088 case FORMAT_TYPE_LONG:
919 } else if (qualifier == 'h') { 1089 num = va_arg(args, long);
920 num = (unsigned short) va_arg(args, int); 1090 break;
921 if (flags & SIGN) 1091 case FORMAT_TYPE_SIZE_T:
922 num = (signed short) num; 1092 num = va_arg(args, size_t);
923 } else { 1093 break;
924 num = va_arg(args, unsigned int); 1094 case FORMAT_TYPE_PTRDIFF:
925 if (flags & SIGN) 1095 num = va_arg(args, ptrdiff_t);
926 num = (signed int) num; 1096 break;
1097 case FORMAT_TYPE_USHORT:
1098 num = (unsigned short) va_arg(args, int);
1099 break;
1100 case FORMAT_TYPE_SHORT:
1101 num = (short) va_arg(args, int);
1102 break;
1103 case FORMAT_TYPE_INT:
1104 num = (int) va_arg(args, int);
1105 break;
1106 default:
1107 num = va_arg(args, unsigned int);
1108 }
1109
1110 str = number(str, end, num, spec);
927 } 1111 }
928 str = number(str, end, num, base,
929 field_width, precision, flags);
930 } 1112 }
1113
931 if (size > 0) { 1114 if (size > 0) {
932 if (str < end) 1115 if (str < end)
933 *str = '\0'; 1116 *str = '\0';
934 else 1117 else
935 end[-1] = '\0'; 1118 end[-1] = '\0';
936 } 1119 }
1120
937 /* the trailing null byte doesn't count towards the total */ 1121 /* the trailing null byte doesn't count towards the total */
938 return str-buf; 1122 return str-buf;
1123
939} 1124}
940EXPORT_SYMBOL(vsnprintf); 1125EXPORT_SYMBOL(vsnprintf);
941 1126
@@ -1058,6 +1243,372 @@ int sprintf(char * buf, const char *fmt, ...)
1058} 1243}
1059EXPORT_SYMBOL(sprintf); 1244EXPORT_SYMBOL(sprintf);
1060 1245
1246#ifdef CONFIG_BINARY_PRINTF
1247/*
1248 * bprintf service:
1249 * vbin_printf() - VA arguments to binary data
1250 * bstr_printf() - Binary data to text string
1251 */
1252
1253/**
1254 * vbin_printf - Parse a format string and place args' binary value in a buffer
1255 * @bin_buf: The buffer to place args' binary value
1256 * @size: The size of the buffer(by words(32bits), not characters)
1257 * @fmt: The format string to use
1258 * @args: Arguments for the format string
1259 *
1260 * The format follows C99 vsnprintf, except %n is ignored, and its argument
1261 * is skiped.
1262 *
1263 * The return value is the number of words(32bits) which would be generated for
1264 * the given input.
1265 *
1266 * NOTE:
1267 * If the return value is greater than @size, the resulting bin_buf is NOT
1268 * valid for bstr_printf().
1269 */
1270int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
1271{
1272 struct printf_spec spec = {0};
1273 char *str, *end;
1274 int read;
1275
1276 str = (char *)bin_buf;
1277 end = (char *)(bin_buf + size);
1278
1279#define save_arg(type) \
1280do { \
1281 if (sizeof(type) == 8) { \
1282 unsigned long long value; \
1283 str = PTR_ALIGN(str, sizeof(u32)); \
1284 value = va_arg(args, unsigned long long); \
1285 if (str + sizeof(type) <= end) { \
1286 *(u32 *)str = *(u32 *)&value; \
1287 *(u32 *)(str + 4) = *((u32 *)&value + 1); \
1288 } \
1289 } else { \
1290 unsigned long value; \
1291 str = PTR_ALIGN(str, sizeof(type)); \
1292 value = va_arg(args, int); \
1293 if (str + sizeof(type) <= end) \
1294 *(typeof(type) *)str = (type)value; \
1295 } \
1296 str += sizeof(type); \
1297} while (0)
1298
1299
1300 while (*fmt) {
1301 read = format_decode(fmt, &spec);
1302
1303 fmt += read;
1304
1305 switch (spec.type) {
1306 case FORMAT_TYPE_NONE:
1307 break;
1308
1309 case FORMAT_TYPE_WITDH:
1310 case FORMAT_TYPE_PRECISION:
1311 save_arg(int);
1312 break;
1313
1314 case FORMAT_TYPE_CHAR:
1315 save_arg(char);
1316 break;
1317
1318 case FORMAT_TYPE_STR: {
1319 const char *save_str = va_arg(args, char *);
1320 size_t len;
1321 if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
1322 || (unsigned long)save_str < PAGE_SIZE)
1323 save_str = "<NULL>";
1324 len = strlen(save_str);
1325 if (str + len + 1 < end)
1326 memcpy(str, save_str, len + 1);
1327 str += len + 1;
1328 break;
1329 }
1330
1331 case FORMAT_TYPE_PTR:
1332 save_arg(void *);
1333 /* skip all alphanumeric pointer suffixes */
1334 while (isalnum(*fmt))
1335 fmt++;
1336 break;
1337
1338 case FORMAT_TYPE_PERCENT_CHAR:
1339 break;
1340
1341 case FORMAT_TYPE_INVALID:
1342 if (!*fmt)
1343 --fmt;
1344 break;
1345
1346 case FORMAT_TYPE_NRCHARS: {
1347 /* skip %n 's argument */
1348 int qualifier = spec.qualifier;
1349 void *skip_arg;
1350 if (qualifier == 'l')
1351 skip_arg = va_arg(args, long *);
1352 else if (qualifier == 'Z' || qualifier == 'z')
1353 skip_arg = va_arg(args, size_t *);
1354 else
1355 skip_arg = va_arg(args, int *);
1356 break;
1357 }
1358
1359 default:
1360 switch (spec.type) {
1361
1362 case FORMAT_TYPE_LONG_LONG:
1363 save_arg(long long);
1364 break;
1365 case FORMAT_TYPE_ULONG:
1366 case FORMAT_TYPE_LONG:
1367 save_arg(unsigned long);
1368 break;
1369 case FORMAT_TYPE_SIZE_T:
1370 save_arg(size_t);
1371 break;
1372 case FORMAT_TYPE_PTRDIFF:
1373 save_arg(ptrdiff_t);
1374 break;
1375 case FORMAT_TYPE_USHORT:
1376 case FORMAT_TYPE_SHORT:
1377 save_arg(short);
1378 break;
1379 default:
1380 save_arg(int);
1381 }
1382 }
1383 }
1384 return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
1385
1386#undef save_arg
1387}
1388EXPORT_SYMBOL_GPL(vbin_printf);
1389
1390/**
1391 * bstr_printf - Format a string from binary arguments and place it in a buffer
1392 * @buf: The buffer to place the result into
1393 * @size: The size of the buffer, including the trailing null space
1394 * @fmt: The format string to use
1395 * @bin_buf: Binary arguments for the format string
1396 *
1397 * This function like C99 vsnprintf, but the difference is that vsnprintf gets
1398 * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
1399 * a binary buffer that generated by vbin_printf.
1400 *
1401 * The format follows C99 vsnprintf, but has some extensions:
1402 * %pS output the name of a text symbol
1403 * %pF output the name of a function pointer
1404 * %pR output the address range in a struct resource
1405 * %n is ignored
1406 *
1407 * The return value is the number of characters which would
1408 * be generated for the given input, excluding the trailing
1409 * '\0', as per ISO C99. If you want to have the exact
1410 * number of characters written into @buf as return value
1411 * (not including the trailing '\0'), use vscnprintf(). If the
1412 * return is greater than or equal to @size, the resulting
1413 * string is truncated.
1414 */
1415int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
1416{
1417 unsigned long long num;
1418 char *str, *end, c;
1419 const char *args = (const char *)bin_buf;
1420
1421 struct printf_spec spec = {0};
1422
1423 if (unlikely((int) size < 0)) {
1424 /* There can be only one.. */
1425 static char warn = 1;
1426 WARN_ON(warn);
1427 warn = 0;
1428 return 0;
1429 }
1430
1431 str = buf;
1432 end = buf + size;
1433
1434#define get_arg(type) \
1435({ \
1436 typeof(type) value; \
1437 if (sizeof(type) == 8) { \
1438 args = PTR_ALIGN(args, sizeof(u32)); \
1439 *(u32 *)&value = *(u32 *)args; \
1440 *((u32 *)&value + 1) = *(u32 *)(args + 4); \
1441 } else { \
1442 args = PTR_ALIGN(args, sizeof(type)); \
1443 value = *(typeof(type) *)args; \
1444 } \
1445 args += sizeof(type); \
1446 value; \
1447})
1448
1449 /* Make sure end is always >= buf */
1450 if (end < buf) {
1451 end = ((void *)-1);
1452 size = end - buf;
1453 }
1454
1455 while (*fmt) {
1456 int read;
1457 const char *old_fmt = fmt;
1458
1459 read = format_decode(fmt, &spec);
1460
1461 fmt += read;
1462
1463 switch (spec.type) {
1464 case FORMAT_TYPE_NONE: {
1465 int copy = read;
1466 if (str < end) {
1467 if (copy > end - str)
1468 copy = end - str;
1469 memcpy(str, old_fmt, copy);
1470 }
1471 str += read;
1472 break;
1473 }
1474
1475 case FORMAT_TYPE_WITDH:
1476 spec.field_width = get_arg(int);
1477 break;
1478
1479 case FORMAT_TYPE_PRECISION:
1480 spec.precision = get_arg(int);
1481 break;
1482
1483 case FORMAT_TYPE_CHAR:
1484 if (!(spec.flags & LEFT)) {
1485 while (--spec.field_width > 0) {
1486 if (str < end)
1487 *str = ' ';
1488 ++str;
1489 }
1490 }
1491 c = (unsigned char) get_arg(char);
1492 if (str < end)
1493 *str = c;
1494 ++str;
1495 while (--spec.field_width > 0) {
1496 if (str < end)
1497 *str = ' ';
1498 ++str;
1499 }
1500 break;
1501
1502 case FORMAT_TYPE_STR: {
1503 const char *str_arg = args;
1504 size_t len = strlen(str_arg);
1505 args += len + 1;
1506 str = string(str, end, (char *)str_arg, spec);
1507 break;
1508 }
1509
1510 case FORMAT_TYPE_PTR:
1511 str = pointer(fmt+1, str, end, get_arg(void *), spec);
1512 while (isalnum(*fmt))
1513 fmt++;
1514 break;
1515
1516 case FORMAT_TYPE_PERCENT_CHAR:
1517 if (str < end)
1518 *str = '%';
1519 ++str;
1520 break;
1521
1522 case FORMAT_TYPE_INVALID:
1523 if (str < end)
1524 *str = '%';
1525 ++str;
1526 if (*fmt) {
1527 if (str < end)
1528 *str = *fmt;
1529 ++str;
1530 } else {
1531 --fmt;
1532 }
1533 break;
1534
1535 case FORMAT_TYPE_NRCHARS:
1536 /* skip */
1537 break;
1538
1539 default:
1540 switch (spec.type) {
1541
1542 case FORMAT_TYPE_LONG_LONG:
1543 num = get_arg(long long);
1544 break;
1545 case FORMAT_TYPE_ULONG:
1546 num = get_arg(unsigned long);
1547 break;
1548 case FORMAT_TYPE_LONG:
1549 num = get_arg(unsigned long);
1550 break;
1551 case FORMAT_TYPE_SIZE_T:
1552 num = get_arg(size_t);
1553 break;
1554 case FORMAT_TYPE_PTRDIFF:
1555 num = get_arg(ptrdiff_t);
1556 break;
1557 case FORMAT_TYPE_USHORT:
1558 num = get_arg(unsigned short);
1559 break;
1560 case FORMAT_TYPE_SHORT:
1561 num = get_arg(short);
1562 break;
1563 case FORMAT_TYPE_UINT:
1564 num = get_arg(unsigned int);
1565 break;
1566 default:
1567 num = get_arg(int);
1568 }
1569
1570 str = number(str, end, num, spec);
1571 }
1572 }
1573
1574 if (size > 0) {
1575 if (str < end)
1576 *str = '\0';
1577 else
1578 end[-1] = '\0';
1579 }
1580
1581#undef get_arg
1582
1583 /* the trailing null byte doesn't count towards the total */
1584 return str - buf;
1585}
1586EXPORT_SYMBOL_GPL(bstr_printf);
1587
1588/**
1589 * bprintf - Parse a format string and place args' binary value in a buffer
1590 * @bin_buf: The buffer to place args' binary value
1591 * @size: The size of the buffer(by words(32bits), not characters)
1592 * @fmt: The format string to use
1593 * @...: Arguments for the format string
1594 *
1595 * The function returns the number of words(u32) written
1596 * into @bin_buf.
1597 */
1598int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
1599{
1600 va_list args;
1601 int ret;
1602
1603 va_start(args, fmt);
1604 ret = vbin_printf(bin_buf, size, fmt, args);
1605 va_end(args);
1606 return ret;
1607}
1608EXPORT_SYMBOL_GPL(bprintf);
1609
1610#endif /* CONFIG_BINARY_PRINTF */
1611
1061/** 1612/**
1062 * vsscanf - Unformat a buffer into a list of arguments 1613 * vsscanf - Unformat a buffer into a list of arguments
1063 * @buf: input buffer 1614 * @buf: input buffer
diff --git a/lib/zlib_inflate/inflate.h b/lib/zlib_inflate/inflate.h
index df8a6c92052d..3d17b3d1b21f 100644
--- a/lib/zlib_inflate/inflate.h
+++ b/lib/zlib_inflate/inflate.h
@@ -1,3 +1,6 @@
1#ifndef INFLATE_H
2#define INFLATE_H
3
1/* inflate.h -- internal inflate state definition 4/* inflate.h -- internal inflate state definition
2 * Copyright (C) 1995-2004 Mark Adler 5 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 6 * For conditions of distribution and use, see copyright notice in zlib.h
@@ -105,3 +108,4 @@ struct inflate_state {
105 unsigned short work[288]; /* work area for code table building */ 108 unsigned short work[288]; /* work area for code table building */
106 code codes[ENOUGH]; /* space for code tables */ 109 code codes[ENOUGH]; /* space for code tables */
107}; 110};
111#endif
diff --git a/lib/zlib_inflate/inftrees.h b/lib/zlib_inflate/inftrees.h
index 5f5219b1240e..b70b4731ac7a 100644
--- a/lib/zlib_inflate/inftrees.h
+++ b/lib/zlib_inflate/inftrees.h
@@ -1,3 +1,6 @@
1#ifndef INFTREES_H
2#define INFTREES_H
3
1/* inftrees.h -- header to use inftrees.c 4/* inftrees.h -- header to use inftrees.c
2 * Copyright (C) 1995-2005 Mark Adler 5 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 6 * For conditions of distribution and use, see copyright notice in zlib.h
@@ -53,3 +56,4 @@ typedef enum {
53extern int zlib_inflate_table (codetype type, unsigned short *lens, 56extern int zlib_inflate_table (codetype type, unsigned short *lens,
54 unsigned codes, code **table, 57 unsigned codes, code **table,
55 unsigned *bits, unsigned short *work); 58 unsigned *bits, unsigned short *work);
59#endif