blob: c718659c590a727f9838fa2e3da1a0d1dddc1242 [file] [log] [blame]
Huang Jianan24a0c502022-02-26 15:05:48 +08001// SPDX-License-Identifier: GPL 2.0+ OR BSD-2-Clause
Julius Wernerf41a3ca2015-10-06 20:03:53 -07002/*
Huang Jianan24a0c502022-02-26 15:05:48 +08003 * LZ4 - Fast LZ compression algorithm
4 * Copyright (C) 2011 - 2016, Yann Collet.
5 * BSD 2 - Clause License (http://www.opensource.org/licenses/bsd - license.php)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
14 * distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 * You can contact the author at :
27 * - LZ4 homepage : http://www.lz4.org
28 * - LZ4 source repository : https://github.com/lz4/lz4
29 */
Huang Jianan24a0c502022-02-26 15:05:48 +080030#include <compiler.h>
31#include <linux/kernel.h>
32#include <linux/types.h>
33#include <linux/bug.h>
34#include <asm/unaligned.h>
35#include <u-boot/lz4.h>
Simon Glassbb1492e2025-01-26 11:43:22 -070036#include <asm/sections.h>
Huang Jianan24a0c502022-02-26 15:05:48 +080037
38#define FORCE_INLINE inline __attribute__((always_inline))
Julius Wernerf41a3ca2015-10-06 20:03:53 -070039
Simon Glassbb1492e2025-01-26 11:43:22 -070040__rcode static FORCE_INLINE u16 LZ4_readLE16(const void *src)
Huang Jianan24a0c502022-02-26 15:05:48 +080041{
42 return get_unaligned_le16(src);
43}
Julius Wernerf41a3ca2015-10-06 20:03:53 -070044
Simon Glassbb1492e2025-01-26 11:43:22 -070045__rcode static FORCE_INLINE void LZ4_copy8(void *dst, const void *src)
Huang Jianan24a0c502022-02-26 15:05:48 +080046{
47 put_unaligned(get_unaligned((const u64 *)src), (u64 *)dst);
48}
49
50typedef uint8_t BYTE;
51typedef uint16_t U16;
52typedef uint32_t U32;
53typedef int32_t S32;
54typedef uint64_t U64;
55typedef uintptr_t uptrval;
56
Simon Glassbb1492e2025-01-26 11:43:22 -070057__rcode static FORCE_INLINE void LZ4_write32(void *memPtr, U32 value)
Huang Jianan24a0c502022-02-26 15:05:48 +080058{
59 put_unaligned(value, (U32 *)memPtr);
60}
Julius Wernerf41a3ca2015-10-06 20:03:53 -070061
62/**************************************
63* Reading and writing into memory
64**************************************/
65
66/* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */
Simon Glassbb1492e2025-01-26 11:43:22 -070067__rcode static void LZ4_wildCopy(void *dstPtr, const void *srcPtr, void *dstEnd)
Julius Wernerf41a3ca2015-10-06 20:03:53 -070068{
69 BYTE* d = (BYTE*)dstPtr;
70 const BYTE* s = (const BYTE*)srcPtr;
71 BYTE* e = (BYTE*)dstEnd;
72 do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);
73}
74
Julius Wernerf41a3ca2015-10-06 20:03:53 -070075/**************************************
76* Common Constants
77**************************************/
78#define MINMATCH 4
79
Huang Jianan24a0c502022-02-26 15:05:48 +080080#define WILDCOPYLENGTH 8
Julius Wernerf41a3ca2015-10-06 20:03:53 -070081#define LASTLITERALS 5
Huang Jianan24a0c502022-02-26 15:05:48 +080082#define MFLIMIT (WILDCOPYLENGTH + MINMATCH)
83
84/*
85 * ensure it's possible to write 2 x wildcopyLength
86 * without overflowing output buffer
87 */
88#define MATCH_SAFEGUARD_DISTANCE ((2 * WILDCOPYLENGTH) - MINMATCH)
Julius Wernerf41a3ca2015-10-06 20:03:53 -070089
Huang Jianan24a0c502022-02-26 15:05:48 +080090#define KB (1 <<10)
Julius Wernerf41a3ca2015-10-06 20:03:53 -070091
92#define MAXD_LOG 16
93#define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
94
95#define ML_BITS 4
96#define ML_MASK ((1U<<ML_BITS)-1)
97#define RUN_BITS (8-ML_BITS)
98#define RUN_MASK ((1U<<RUN_BITS)-1)
99
Huang Jianan24a0c502022-02-26 15:05:48 +0800100#define LZ4_STATIC_ASSERT(c) BUILD_BUG_ON(!(c))
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700101
102/**************************************
103* Local Structures and types
104**************************************/
105typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
106typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
Huang Jianan24a0c502022-02-26 15:05:48 +0800107typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700108
Huang Jianan24a0c502022-02-26 15:05:48 +0800109#define DEBUGLOG(l, ...) {} /* disabled */
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700110
Huang Jianan24a0c502022-02-26 15:05:48 +0800111#ifndef assert
112#define assert(condition) ((void)0)
113#endif
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700114
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700115/*
Simon Glassbb1492e2025-01-26 11:43:22 -0700116 * spl_reloc needs all necessary data to be set up within its code, since the
117 * code is relocated at runtime. Unfortunately this increase code-size slightly
118 * so only do it if spl_reloc is enabled
119 */
120#if CONFIG_IS_ENABLED(RELOC_LOADER)
121#define STATIC
122#else
123#define STATIC static
124#endif
125
126/*
Huang Jianan24a0c502022-02-26 15:05:48 +0800127 * LZ4_decompress_generic() :
128 * This generic decompression function covers all use cases.
129 * It shall be instantiated several times, using different sets of directives.
130 * Note that it is important for performance that this function really get inlined,
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700131 * in order to remove useless branches during compilation optimization.
132 */
Simon Glassbb1492e2025-01-26 11:43:22 -0700133__rcode static FORCE_INLINE int LZ4_decompress_generic(
Huang Jianan24a0c502022-02-26 15:05:48 +0800134 const char * const src,
135 char * const dst,
136 int srcSize,
137 /*
138 * If endOnInput == endOnInputSize,
139 * this value is `dstCapacity`
140 */
141 int outputSize,
142 /* endOnOutputSize, endOnInputSize */
143 endCondition_directive endOnInput,
144 /* full, partial */
145 earlyEnd_directive partialDecoding,
146 /* noDict, withPrefix64k, usingExtDict */
147 dict_directive dict,
148 /* always <= dst, == dst when no prefix */
149 const BYTE * const lowPrefix,
150 /* only if dict == usingExtDict */
151 const BYTE * const dictStart,
152 /* note : = 0 if noDict */
153 const size_t dictSize
154 )
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700155{
Simon Glassbb1492e2025-01-26 11:43:22 -0700156 STATIC const unsigned int inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};
157 STATIC const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};
Huang Jianan24a0c502022-02-26 15:05:48 +0800158 const BYTE *ip = (const BYTE *) src;
159 const BYTE * const iend = ip + srcSize;
160
161 BYTE *op = (BYTE *) dst;
162 BYTE * const oend = op + outputSize;
163 BYTE *cpy;
164
165 const BYTE * const dictEnd = (const BYTE *)dictStart + dictSize;
Huang Jianan24a0c502022-02-26 15:05:48 +0800166
167 const int safeDecode = (endOnInput == endOnInputSize);
168 const int checkOffset = ((safeDecode) && (dictSize < (int)(64 * KB)));
169
170 /* Set up the "end" pointers for the shortcut. */
171 const BYTE *const shortiend = iend -
172 (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
173 const BYTE *const shortoend = oend -
174 (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
175
176 DEBUGLOG(5, "%s (srcSize:%i, dstSize:%i)", __func__,
177 srcSize, outputSize);
178
179 /* Special cases */
180 assert(lowPrefix <= op);
181 assert(src != NULL);
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700182
Huang Jianan24a0c502022-02-26 15:05:48 +0800183 /* Empty output buffer */
184 if ((endOnInput) && (unlikely(outputSize == 0)))
185 return ((srcSize == 1) && (*ip == 0)) ? 0 : -1;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700186
Huang Jianan24a0c502022-02-26 15:05:48 +0800187 if ((!endOnInput) && (unlikely(outputSize == 0)))
188 return (*ip == 0 ? 1 : -1);
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700189
Huang Jianan24a0c502022-02-26 15:05:48 +0800190 if ((endOnInput) && unlikely(srcSize == 0))
191 return -1;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700192
Huang Jianan24a0c502022-02-26 15:05:48 +0800193 /* Main Loop : decode sequences */
194 while (1) {
195 size_t length;
196 const BYTE *match;
197 size_t offset;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700198
Huang Jianan24a0c502022-02-26 15:05:48 +0800199 /* get literal length */
200 unsigned int const token = *ip++;
201 length = token>>ML_BITS;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700202
Huang Jianan24a0c502022-02-26 15:05:48 +0800203 /* ip < iend before the increment */
204 assert(!endOnInput || ip <= iend);
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700205
Huang Jianan24a0c502022-02-26 15:05:48 +0800206 /*
207 * A two-stage shortcut for the most common case:
208 * 1) If the literal length is 0..14, and there is enough
209 * space, enter the shortcut and copy 16 bytes on behalf
210 * of the literals (in the fast mode, only 8 bytes can be
211 * safely copied this way).
212 * 2) Further if the match length is 4..18, copy 18 bytes
213 * in a similar manner; but we ensure that there's enough
214 * space in the output for those 18 bytes earlier, upon
215 * entering the shortcut (in other words, there is a
216 * combined check for both stages).
217 *
218 * The & in the likely() below is intentionally not && so that
219 * some compilers can produce better parallelized runtime code
220 */
221 if ((endOnInput ? length != RUN_MASK : length <= 8)
222 /*
223 * strictly "less than" on input, to re-enter
224 * the loop with at least one byte
225 */
226 && likely((endOnInput ? ip < shortiend : 1) &
227 (op <= shortoend))) {
228 /* Copy the literals */
229 memcpy(op, ip, endOnInput ? 16 : 8);
230 op += length; ip += length;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700231
Huang Jianan24a0c502022-02-26 15:05:48 +0800232 /*
233 * The second stage:
234 * prepare for match copying, decode full info.
235 * If it doesn't work out, the info won't be wasted.
236 */
237 length = token & ML_MASK; /* match length */
238 offset = LZ4_readLE16(ip);
239 ip += 2;
240 match = op - offset;
241 assert(match <= op); /* check overflow */
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700242
Huang Jianan24a0c502022-02-26 15:05:48 +0800243 /* Do not deal with overlapping matches. */
244 if ((length != ML_MASK) &&
245 (offset >= 8) &&
246 (dict == withPrefix64k || match >= lowPrefix)) {
247 /* Copy the match. */
248 memcpy(op + 0, match + 0, 8);
249 memcpy(op + 8, match + 8, 8);
250 memcpy(op + 16, match + 16, 2);
251 op += length + MINMATCH;
252 /* Both stages worked, load the next token. */
253 continue;
254 }
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700255
Huang Jianan24a0c502022-02-26 15:05:48 +0800256 /*
257 * The second stage didn't work out, but the info
258 * is ready. Propel it right to the point of match
259 * copying.
260 */
261 goto _copy_match;
262 }
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700263
Huang Jianan24a0c502022-02-26 15:05:48 +0800264 /* decode literal length */
265 if (length == RUN_MASK) {
266 unsigned int s;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700267
Huang Jianan24a0c502022-02-26 15:05:48 +0800268 if (unlikely(endOnInput ? ip >= iend - RUN_MASK : 0)) {
269 /* overflow detection */
270 goto _output_error;
271 }
272 do {
273 s = *ip++;
274 length += s;
275 } while (likely(endOnInput
276 ? ip < iend - RUN_MASK
277 : 1) & (s == 255));
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700278
Huang Jianan24a0c502022-02-26 15:05:48 +0800279 if ((safeDecode)
280 && unlikely((uptrval)(op) +
281 length < (uptrval)(op))) {
282 /* overflow detection */
283 goto _output_error;
284 }
285 if ((safeDecode)
286 && unlikely((uptrval)(ip) +
287 length < (uptrval)(ip))) {
288 /* overflow detection */
289 goto _output_error;
290 }
291 }
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700292
Huang Jianan24a0c502022-02-26 15:05:48 +0800293 /* copy literals */
294 cpy = op + length;
295 LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700296
Huang Jianan24a0c502022-02-26 15:05:48 +0800297 if (((endOnInput) && ((cpy > oend - MFLIMIT)
298 || (ip + length > iend - (2 + 1 + LASTLITERALS))))
299 || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) {
300 if (partialDecoding) {
301 if (cpy > oend) {
302 /*
303 * Partial decoding :
304 * stop in the middle of literal segment
305 */
306 cpy = oend;
307 length = oend - op;
308 }
309 if ((endOnInput)
310 && (ip + length > iend)) {
311 /*
312 * Error :
313 * read attempt beyond
314 * end of input buffer
315 */
316 goto _output_error;
317 }
318 } else {
319 if ((!endOnInput)
320 && (cpy != oend)) {
321 /*
322 * Error :
323 * block decoding must
324 * stop exactly there
325 */
326 goto _output_error;
327 }
328 if ((endOnInput)
329 && ((ip + length != iend)
330 || (cpy > oend))) {
331 /*
332 * Error :
333 * input must be consumed
334 */
335 goto _output_error;
336 }
337 }
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700338
Huang Jianan24a0c502022-02-26 15:05:48 +0800339 /*
340 * supports overlapping memory regions; only matters
341 * for in-place decompression scenarios
342 */
343 memmove(op, ip, length);
344 ip += length;
345 op += length;
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700346
Huang Jianan24a0c502022-02-26 15:05:48 +0800347 /* Necessarily EOF, due to parsing restrictions */
348 if (!partialDecoding || (cpy == oend))
349 break;
350 } else {
351 /* may overwrite up to WILDCOPYLENGTH beyond cpy */
352 LZ4_wildCopy(op, ip, cpy);
353 ip += length;
354 op = cpy;
355 }
356
357 /* get offset */
358 offset = LZ4_readLE16(ip);
359 ip += 2;
360 match = op - offset;
361
362 /* get matchlength */
363 length = token & ML_MASK;
364
365_copy_match:
366 if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) {
367 /* Error : offset outside buffers */
368 goto _output_error;
369 }
370
371 /* costs ~1%; silence an msan warning when offset == 0 */
372 /*
373 * note : when partialDecoding, there is no guarantee that
374 * at least 4 bytes remain available in output buffer
375 */
376 if (!partialDecoding) {
377 assert(oend > op);
378 assert(oend - op >= 4);
379
380 LZ4_write32(op, (U32)offset);
381 }
382
383 if (length == ML_MASK) {
384 unsigned int s;
385
386 do {
387 s = *ip++;
388
389 if ((endOnInput) && (ip > iend - LASTLITERALS))
390 goto _output_error;
391
392 length += s;
393 } while (s == 255);
394
395 if ((safeDecode)
396 && unlikely(
397 (uptrval)(op) + length < (uptrval)op)) {
398 /* overflow detection */
399 goto _output_error;
400 }
401 }
402
403 length += MINMATCH;
404
405 /* match starting within external dictionary */
406 if ((dict == usingExtDict) && (match < lowPrefix)) {
407 if (unlikely(op + length > oend - LASTLITERALS)) {
408 /* doesn't respect parsing restriction */
409 if (!partialDecoding)
410 goto _output_error;
411 length = min(length, (size_t)(oend - op));
412 }
413
414 if (length <= (size_t)(lowPrefix - match)) {
415 /*
416 * match fits entirely within external
417 * dictionary : just copy
418 */
419 memmove(op, dictEnd - (lowPrefix - match),
420 length);
421 op += length;
422 } else {
423 /*
424 * match stretches into both external
425 * dictionary and current block
426 */
427 size_t const copySize = (size_t)(lowPrefix - match);
428 size_t const restSize = length - copySize;
429
430 memcpy(op, dictEnd - copySize, copySize);
431 op += copySize;
432 if (restSize > (size_t)(op - lowPrefix)) {
433 /* overlap copy */
434 BYTE * const endOfMatch = op + restSize;
435 const BYTE *copyFrom = lowPrefix;
436
437 while (op < endOfMatch)
438 *op++ = *copyFrom++;
439 } else {
440 memcpy(op, lowPrefix, restSize);
441 op += restSize;
442 }
443 }
444 continue;
445 }
446
447 /* copy match within block */
448 cpy = op + length;
449
450 /*
451 * partialDecoding :
452 * may not respect endBlock parsing restrictions
453 */
454 assert(op <= oend);
455 if (partialDecoding &&
456 (cpy > oend - MATCH_SAFEGUARD_DISTANCE)) {
457 size_t const mlen = min(length, (size_t)(oend - op));
458 const BYTE * const matchEnd = match + mlen;
459 BYTE * const copyEnd = op + mlen;
460
461 if (matchEnd > op) {
462 /* overlap copy */
463 while (op < copyEnd)
464 *op++ = *match++;
465 } else {
466 memcpy(op, match, mlen);
467 }
468 op = copyEnd;
469 if (op == oend)
470 break;
471 continue;
472 }
473
474 if (unlikely(offset < 8)) {
475 op[0] = match[0];
476 op[1] = match[1];
477 op[2] = match[2];
478 op[3] = match[3];
479 match += inc32table[offset];
480 memcpy(op + 4, match, 4);
481 match -= dec64table[offset];
482 } else {
483 LZ4_copy8(op, match);
484 match += 8;
485 }
486
487 op += 8;
488
489 if (unlikely(cpy > oend - MATCH_SAFEGUARD_DISTANCE)) {
490 BYTE * const oCopyLimit = oend - (WILDCOPYLENGTH - 1);
491
492 if (cpy > oend - LASTLITERALS) {
493 /*
494 * Error : last LASTLITERALS bytes
495 * must be literals (uncompressed)
496 */
497 goto _output_error;
498 }
499
500 if (op < oCopyLimit) {
501 LZ4_wildCopy(op, match, oCopyLimit);
502 match += oCopyLimit - op;
503 op = oCopyLimit;
504 }
505 while (op < cpy)
506 *op++ = *match++;
507 } else {
508 LZ4_copy8(op, match);
509 if (length > 16)
510 LZ4_wildCopy(op + 8, match + 8, cpy);
511 }
512 op = cpy; /* wildcopy correction */
513 }
514
515 /* end of decoding */
516 if (endOnInput) {
517 /* Nb of output bytes decoded */
518 return (int) (((char *)op) - dst);
519 } else {
520 /* Nb of input bytes read */
521 return (int) (((const char *)ip) - src);
522 }
523
524 /* Overflow error detected */
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700525_output_error:
Huang Jianan24a0c502022-02-26 15:05:48 +0800526 return (int) (-(((const char *)ip) - src)) - 1;
527}
528
Simon Glassbb1492e2025-01-26 11:43:22 -0700529#ifndef CONFIG_SPL_BUILD
530__rcode int LZ4_decompress_safe(const char *source, char *dest,
531 int compressedSize, int maxDecompressedSize)
Huang Jianan24a0c502022-02-26 15:05:48 +0800532{
533 return LZ4_decompress_generic(source, dest,
534 compressedSize, maxDecompressedSize,
535 endOnInputSize, decode_full_block,
536 noDict, (BYTE *)dest, NULL, 0);
537}
538
Simon Glassbb1492e2025-01-26 11:43:22 -0700539__rcode int LZ4_decompress_safe_partial(const char *src, char *dst,
540 int compressedSize,
541 int targetOutputSize, int dstCapacity)
Huang Jianan24a0c502022-02-26 15:05:48 +0800542{
543 dstCapacity = min(targetOutputSize, dstCapacity);
544 return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
545 endOnInputSize, partial_decode,
546 noDict, (BYTE *)dst, NULL, 0);
Julius Wernerf41a3ca2015-10-06 20:03:53 -0700547}
Simon Glassbb1492e2025-01-26 11:43:22 -0700548#endif