2 * LZ4 - Fast LZ compression algorithm
3 * Copyright (C) 2011 - 2016, Yann Collet.
4 * BSD 2 - Clause License (http://www.opensource.org/licenses/bsd - license.php)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 * You can contact the author at :
26 * - LZ4 homepage : http://www.lz4.org
27 * - LZ4 source repository : https://github.com/lz4/lz4
29 * Changed for kernel usage by:
33 /*-************************************
35 **************************************/
37 #include <linux/init.h>
38 #include <linux/module.h>
39 #include <linux/kernel.h>
40 #include <linux/unaligned.h>
42 /*-*****************************
43 * Decompression functions
44 *******************************/
46 #define DEBUGLOG(l, ...) {} /* disabled */
49 #define assert(condition) ((void)0)
53 * LZ4_decompress_generic() :
54 * This generic decompression function covers all use cases.
55 * It shall be instantiated several times, using different sets of directives.
56 * Note that it is important for performance that this function really get inlined,
57 * in order to remove useless branches during compilation optimization.
59 static FORCE_INLINE int LZ4_decompress_generic(
60 const char * const src,
64 * If endOnInput == endOnInputSize,
65 * this value is `dstCapacity`
68 /* endOnOutputSize, endOnInputSize */
69 endCondition_directive endOnInput,
71 earlyEnd_directive partialDecoding,
72 /* noDict, withPrefix64k, usingExtDict */
74 /* always <= dst, == dst when no prefix */
75 const BYTE * const lowPrefix,
76 /* only if dict == usingExtDict */
77 const BYTE * const dictStart,
78 /* note : = 0 if noDict */
82 const BYTE *ip = (const BYTE *) src;
83 const BYTE * const iend = ip + srcSize;
85 BYTE *op = (BYTE *) dst;
86 BYTE * const oend = op + outputSize;
89 const BYTE * const dictEnd = (const BYTE *)dictStart + dictSize;
90 static const unsigned int inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};
91 static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};
93 const int safeDecode = (endOnInput == endOnInputSize);
94 const int checkOffset = ((safeDecode) && (dictSize < (int)(64 * KB)));
96 /* Set up the "end" pointers for the shortcut. */
97 const BYTE *const shortiend = iend -
98 (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
99 const BYTE *const shortoend = oend -
100 (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
102 DEBUGLOG(5, "%s (srcSize:%i, dstSize:%i)", __func__,
103 srcSize, outputSize);
106 assert(lowPrefix <= op);
109 /* Empty output buffer */
110 if ((endOnInput) && (unlikely(outputSize == 0)))
111 return ((srcSize == 1) && (*ip == 0)) ? 0 : -1;
113 if ((!endOnInput) && (unlikely(outputSize == 0)))
114 return (*ip == 0 ? 1 : -1);
116 if ((endOnInput) && unlikely(srcSize == 0))
119 /* Main Loop : decode sequences */
125 /* get literal length */
126 unsigned int const token = *ip++;
127 length = token>>ML_BITS;
129 /* ip < iend before the increment */
130 assert(!endOnInput || ip <= iend);
133 * A two-stage shortcut for the most common case:
134 * 1) If the literal length is 0..14, and there is enough
135 * space, enter the shortcut and copy 16 bytes on behalf
136 * of the literals (in the fast mode, only 8 bytes can be
137 * safely copied this way).
138 * 2) Further if the match length is 4..18, copy 18 bytes
139 * in a similar manner; but we ensure that there's enough
140 * space in the output for those 18 bytes earlier, upon
141 * entering the shortcut (in other words, there is a
142 * combined check for both stages).
144 * The & in the likely() below is intentionally not && so that
145 * some compilers can produce better parallelized runtime code
147 if ((endOnInput ? length != RUN_MASK : length <= 8)
149 * strictly "less than" on input, to re-enter
150 * the loop with at least one byte
152 && likely((endOnInput ? ip < shortiend : 1) &
153 (op <= shortoend))) {
154 /* Copy the literals */
155 LZ4_memcpy(op, ip, endOnInput ? 16 : 8);
156 op += length; ip += length;
160 * prepare for match copying, decode full info.
161 * If it doesn't work out, the info won't be wasted.
163 length = token & ML_MASK; /* match length */
164 offset = LZ4_readLE16(ip);
167 assert(match <= op); /* check overflow */
169 /* Do not deal with overlapping matches. */
170 if ((length != ML_MASK) &&
172 (dict == withPrefix64k || match >= lowPrefix)) {
173 /* Copy the match. */
174 LZ4_memcpy(op + 0, match + 0, 8);
175 LZ4_memcpy(op + 8, match + 8, 8);
176 LZ4_memcpy(op + 16, match + 16, 2);
177 op += length + MINMATCH;
178 /* Both stages worked, load the next token. */
183 * The second stage didn't work out, but the info
184 * is ready. Propel it right to the point of match
190 /* decode literal length */
191 if (length == RUN_MASK) {
194 if (unlikely(endOnInput ? ip >= iend - RUN_MASK : 0)) {
195 /* overflow detection */
201 } while (likely(endOnInput
202 ? ip < iend - RUN_MASK
206 && unlikely((uptrval)(op) +
207 length < (uptrval)(op))) {
208 /* overflow detection */
212 && unlikely((uptrval)(ip) +
213 length < (uptrval)(ip))) {
214 /* overflow detection */
221 LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
223 if (((endOnInput) && ((cpy > oend - MFLIMIT)
224 || (ip + length > iend - (2 + 1 + LASTLITERALS))))
225 || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) {
226 if (partialDecoding) {
230 * stop in the middle of literal segment
236 && (ip + length > iend)) {
239 * read attempt beyond
240 * end of input buffer
249 * block decoding must
255 && ((ip + length != iend)
259 * input must be consumed
266 * supports overlapping memory regions; only matters
267 * for in-place decompression scenarios
269 LZ4_memmove(op, ip, length);
273 /* Necessarily EOF when !partialDecoding.
274 * When partialDecoding, it is EOF if we've either
275 * filled the output buffer or
276 * can't proceed with reading an offset for following match.
278 if (!partialDecoding || (cpy == oend) || (ip >= (iend - 2)))
281 /* may overwrite up to WILDCOPYLENGTH beyond cpy */
282 LZ4_wildCopy(op, ip, cpy);
288 offset = LZ4_readLE16(ip);
292 /* get matchlength */
293 length = token & ML_MASK;
296 if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) {
297 /* Error : offset outside buffers */
301 /* costs ~1%; silence an msan warning when offset == 0 */
303 * note : when partialDecoding, there is no guarantee that
304 * at least 4 bytes remain available in output buffer
306 if (!partialDecoding) {
308 assert(oend - op >= 4);
310 LZ4_write32(op, (U32)offset);
313 if (length == ML_MASK) {
319 if ((endOnInput) && (ip > iend - LASTLITERALS))
327 (uptrval)(op) + length < (uptrval)op)) {
328 /* overflow detection */
335 /* match starting within external dictionary */
336 if ((dict == usingExtDict) && (match < lowPrefix)) {
337 if (unlikely(op + length > oend - LASTLITERALS)) {
338 /* doesn't respect parsing restriction */
339 if (!partialDecoding)
341 length = min(length, (size_t)(oend - op));
344 if (length <= (size_t)(lowPrefix - match)) {
346 * match fits entirely within external
347 * dictionary : just copy
349 memmove(op, dictEnd - (lowPrefix - match),
354 * match stretches into both external
355 * dictionary and current block
357 size_t const copySize = (size_t)(lowPrefix - match);
358 size_t const restSize = length - copySize;
360 LZ4_memcpy(op, dictEnd - copySize, copySize);
362 if (restSize > (size_t)(op - lowPrefix)) {
364 BYTE * const endOfMatch = op + restSize;
365 const BYTE *copyFrom = lowPrefix;
367 while (op < endOfMatch)
370 LZ4_memcpy(op, lowPrefix, restSize);
377 /* copy match within block */
382 * may not respect endBlock parsing restrictions
385 if (partialDecoding &&
386 (cpy > oend - MATCH_SAFEGUARD_DISTANCE)) {
387 size_t const mlen = min(length, (size_t)(oend - op));
388 const BYTE * const matchEnd = match + mlen;
389 BYTE * const copyEnd = op + mlen;
396 LZ4_memcpy(op, match, mlen);
404 if (unlikely(offset < 8)) {
409 match += inc32table[offset];
410 LZ4_memcpy(op + 4, match, 4);
411 match -= dec64table[offset];
413 LZ4_copy8(op, match);
419 if (unlikely(cpy > oend - MATCH_SAFEGUARD_DISTANCE)) {
420 BYTE * const oCopyLimit = oend - (WILDCOPYLENGTH - 1);
422 if (cpy > oend - LASTLITERALS) {
424 * Error : last LASTLITERALS bytes
425 * must be literals (uncompressed)
430 if (op < oCopyLimit) {
431 LZ4_wildCopy(op, match, oCopyLimit);
432 match += oCopyLimit - op;
438 LZ4_copy8(op, match);
440 LZ4_wildCopy(op + 8, match + 8, cpy);
442 op = cpy; /* wildcopy correction */
445 /* end of decoding */
447 /* Nb of output bytes decoded */
448 return (int) (((char *)op) - dst);
450 /* Nb of input bytes read */
451 return (int) (((const char *)ip) - src);
454 /* Overflow error detected */
456 return (int) (-(((const char *)ip) - src)) - 1;
459 int LZ4_decompress_safe(const char *source, char *dest,
460 int compressedSize, int maxDecompressedSize)
462 return LZ4_decompress_generic(source, dest,
463 compressedSize, maxDecompressedSize,
464 endOnInputSize, decode_full_block,
465 noDict, (BYTE *)dest, NULL, 0);
468 int LZ4_decompress_safe_partial(const char *src, char *dst,
469 int compressedSize, int targetOutputSize, int dstCapacity)
471 dstCapacity = min(targetOutputSize, dstCapacity);
472 return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
473 endOnInputSize, partial_decode,
474 noDict, (BYTE *)dst, NULL, 0);
477 int LZ4_decompress_fast(const char *source, char *dest, int originalSize)
479 return LZ4_decompress_generic(source, dest, 0, originalSize,
480 endOnOutputSize, decode_full_block,
482 (BYTE *)dest - 64 * KB, NULL, 0);
485 /* ===== Instantiate a few more decoding cases, used more than once. ===== */
487 static int LZ4_decompress_safe_withPrefix64k(const char *source, char *dest,
488 int compressedSize, int maxOutputSize)
490 return LZ4_decompress_generic(source, dest,
491 compressedSize, maxOutputSize,
492 endOnInputSize, decode_full_block,
494 (BYTE *)dest - 64 * KB, NULL, 0);
497 static int LZ4_decompress_safe_withSmallPrefix(const char *source, char *dest,
502 return LZ4_decompress_generic(source, dest,
503 compressedSize, maxOutputSize,
504 endOnInputSize, decode_full_block,
506 (BYTE *)dest - prefixSize, NULL, 0);
509 static int LZ4_decompress_safe_forceExtDict(const char *source, char *dest,
510 int compressedSize, int maxOutputSize,
511 const void *dictStart, size_t dictSize)
513 return LZ4_decompress_generic(source, dest,
514 compressedSize, maxOutputSize,
515 endOnInputSize, decode_full_block,
516 usingExtDict, (BYTE *)dest,
517 (const BYTE *)dictStart, dictSize);
520 static int LZ4_decompress_fast_extDict(const char *source, char *dest,
522 const void *dictStart, size_t dictSize)
524 return LZ4_decompress_generic(source, dest,
526 endOnOutputSize, decode_full_block,
527 usingExtDict, (BYTE *)dest,
528 (const BYTE *)dictStart, dictSize);
532 * The "double dictionary" mode, for use with e.g. ring buffers: the first part
533 * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
534 * These routines are used only once, in LZ4_decompress_*_continue().
537 int LZ4_decompress_safe_doubleDict(const char *source, char *dest,
538 int compressedSize, int maxOutputSize,
540 const void *dictStart, size_t dictSize)
542 return LZ4_decompress_generic(source, dest,
543 compressedSize, maxOutputSize,
544 endOnInputSize, decode_full_block,
545 usingExtDict, (BYTE *)dest - prefixSize,
546 (const BYTE *)dictStart, dictSize);
550 int LZ4_decompress_fast_doubleDict(const char *source, char *dest,
551 int originalSize, size_t prefixSize,
552 const void *dictStart, size_t dictSize)
554 return LZ4_decompress_generic(source, dest,
556 endOnOutputSize, decode_full_block,
557 usingExtDict, (BYTE *)dest - prefixSize,
558 (const BYTE *)dictStart, dictSize);
561 /* ===== streaming decompression functions ===== */
563 int LZ4_setStreamDecode(LZ4_streamDecode_t *LZ4_streamDecode,
564 const char *dictionary, int dictSize)
566 LZ4_streamDecode_t_internal *lz4sd =
567 &LZ4_streamDecode->internal_donotuse;
569 lz4sd->prefixSize = (size_t) dictSize;
570 lz4sd->prefixEnd = (const BYTE *) dictionary + dictSize;
571 lz4sd->externalDict = NULL;
572 lz4sd->extDictSize = 0;
578 * These decoding functions allow decompression of multiple blocks
579 * in "streaming" mode.
580 * Previously decoded blocks must still be available at the memory
581 * position where they were decoded.
582 * If it's not possible, save the relevant part of
583 * decoded data into a safe buffer,
584 * and indicate where it stands using LZ4_setStreamDecode()
586 int LZ4_decompress_safe_continue(LZ4_streamDecode_t *LZ4_streamDecode,
587 const char *source, char *dest, int compressedSize, int maxOutputSize)
589 LZ4_streamDecode_t_internal *lz4sd =
590 &LZ4_streamDecode->internal_donotuse;
593 if (lz4sd->prefixSize == 0) {
594 /* The first call, no dictionary yet. */
595 assert(lz4sd->extDictSize == 0);
596 result = LZ4_decompress_safe(source, dest,
597 compressedSize, maxOutputSize);
600 lz4sd->prefixSize = result;
601 lz4sd->prefixEnd = (BYTE *)dest + result;
602 } else if (lz4sd->prefixEnd == (BYTE *)dest) {
603 /* They're rolling the current segment. */
604 if (lz4sd->prefixSize >= 64 * KB - 1)
605 result = LZ4_decompress_safe_withPrefix64k(source, dest,
606 compressedSize, maxOutputSize);
607 else if (lz4sd->extDictSize == 0)
608 result = LZ4_decompress_safe_withSmallPrefix(source,
609 dest, compressedSize, maxOutputSize,
612 result = LZ4_decompress_safe_doubleDict(source, dest,
613 compressedSize, maxOutputSize,
615 lz4sd->externalDict, lz4sd->extDictSize);
618 lz4sd->prefixSize += result;
619 lz4sd->prefixEnd += result;
622 * The buffer wraps around, or they're
623 * switching to another buffer.
625 lz4sd->extDictSize = lz4sd->prefixSize;
626 lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
627 result = LZ4_decompress_safe_forceExtDict(source, dest,
628 compressedSize, maxOutputSize,
629 lz4sd->externalDict, lz4sd->extDictSize);
632 lz4sd->prefixSize = result;
633 lz4sd->prefixEnd = (BYTE *)dest + result;
639 int LZ4_decompress_fast_continue(LZ4_streamDecode_t *LZ4_streamDecode,
640 const char *source, char *dest, int originalSize)
642 LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse;
645 if (lz4sd->prefixSize == 0) {
646 assert(lz4sd->extDictSize == 0);
647 result = LZ4_decompress_fast(source, dest, originalSize);
650 lz4sd->prefixSize = originalSize;
651 lz4sd->prefixEnd = (BYTE *)dest + originalSize;
652 } else if (lz4sd->prefixEnd == (BYTE *)dest) {
653 if (lz4sd->prefixSize >= 64 * KB - 1 ||
654 lz4sd->extDictSize == 0)
655 result = LZ4_decompress_fast(source, dest,
658 result = LZ4_decompress_fast_doubleDict(source, dest,
659 originalSize, lz4sd->prefixSize,
660 lz4sd->externalDict, lz4sd->extDictSize);
663 lz4sd->prefixSize += originalSize;
664 lz4sd->prefixEnd += originalSize;
666 lz4sd->extDictSize = lz4sd->prefixSize;
667 lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
668 result = LZ4_decompress_fast_extDict(source, dest,
669 originalSize, lz4sd->externalDict, lz4sd->extDictSize);
672 lz4sd->prefixSize = originalSize;
673 lz4sd->prefixEnd = (BYTE *)dest + originalSize;
678 int LZ4_decompress_safe_usingDict(const char *source, char *dest,
679 int compressedSize, int maxOutputSize,
680 const char *dictStart, int dictSize)
683 return LZ4_decompress_safe(source, dest,
684 compressedSize, maxOutputSize);
685 if (dictStart+dictSize == dest) {
686 if (dictSize >= 64 * KB - 1)
687 return LZ4_decompress_safe_withPrefix64k(source, dest,
688 compressedSize, maxOutputSize);
689 return LZ4_decompress_safe_withSmallPrefix(source, dest,
690 compressedSize, maxOutputSize, dictSize);
692 return LZ4_decompress_safe_forceExtDict(source, dest,
693 compressedSize, maxOutputSize, dictStart, dictSize);
696 int LZ4_decompress_fast_usingDict(const char *source, char *dest,
698 const char *dictStart, int dictSize)
700 if (dictSize == 0 || dictStart + dictSize == dest)
701 return LZ4_decompress_fast(source, dest, originalSize);
703 return LZ4_decompress_fast_extDict(source, dest, originalSize,
704 dictStart, dictSize);
708 EXPORT_SYMBOL(LZ4_decompress_safe);
709 EXPORT_SYMBOL(LZ4_decompress_safe_partial);
710 EXPORT_SYMBOL(LZ4_decompress_fast);
711 EXPORT_SYMBOL(LZ4_setStreamDecode);
712 EXPORT_SYMBOL(LZ4_decompress_safe_continue);
713 EXPORT_SYMBOL(LZ4_decompress_fast_continue);
714 EXPORT_SYMBOL(LZ4_decompress_safe_usingDict);
715 EXPORT_SYMBOL(LZ4_decompress_fast_usingDict);
717 MODULE_LICENSE("Dual BSD/GPL");
718 MODULE_DESCRIPTION("LZ4 decompressor");