Line | Count | Source |
1 | | /* |
2 | | * LZ4 auto-framing library |
3 | | * Copyright (c) Yann Collet. All rights reserved. |
4 | | * |
5 | | * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) |
6 | | * |
7 | | * Redistribution and use in source and binary forms, with or without |
8 | | * modification, are permitted provided that the following conditions are |
9 | | * met: |
10 | | * |
11 | | * - Redistributions of source code must retain the above copyright |
12 | | * notice, this list of conditions and the following disclaimer. |
13 | | * - Redistributions in binary form must reproduce the above |
14 | | * copyright notice, this list of conditions and the following disclaimer |
15 | | * in the documentation and/or other materials provided with the |
16 | | * distribution. |
17 | | * |
18 | | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
19 | | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
20 | | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
21 | | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
22 | | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
23 | | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
24 | | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
25 | | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
26 | | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
27 | | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
28 | | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
29 | | * |
30 | | * You can contact the author at : |
31 | | * - LZ4 homepage : http://www.lz4.org |
32 | | * - LZ4 source repository : https://github.com/lz4/lz4 |
33 | | */ |
34 | | |
35 | | /* LZ4F is a stand-alone API to create LZ4-compressed Frames |
36 | | * in full conformance with specification v1.6.1 . |
37 | | * This library rely upon memory management capabilities (malloc, free) |
38 | | * provided either by <stdlib.h>, |
39 | | * or redirected towards another library of user's choice |
40 | | * (see Memory Routines below). |
41 | | */ |
42 | | |
43 | | |
44 | | /*-************************************ |
45 | | * Compiler Options |
46 | | **************************************/ |
47 | | #include <limits.h> |
48 | | #ifdef _MSC_VER /* Visual Studio */ |
49 | | # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ |
50 | | #endif |
51 | | |
52 | | |
53 | | /*-************************************ |
54 | | * Tuning parameters |
55 | | **************************************/ |
56 | | /* |
57 | | * LZ4F_HEAPMODE : |
58 | | * Control how LZ4F_compressFrame allocates the Compression State, |
59 | | * either on stack (0:default, fastest), or in memory heap (1:requires malloc()). |
60 | | */ |
61 | | #ifndef LZ4F_HEAPMODE |
62 | | # define LZ4F_HEAPMODE 0 |
63 | | #endif |
64 | | |
65 | | /* |
66 | | * LZ4F_MULTITHREAD : |
67 | | * Enables multi-threaded compression, requested with LZ4F_preferences_t.nbWorkers. |
68 | | * Requires <pthread.h> on POSIX systems (compile and link with -pthread), or Windows threads. |
69 | | * Default is 0 : no threading code is compiled, |
70 | | * and multi-threaded requests are served serially by the calling thread, producing the same output. |
71 | | */ |
72 | | #ifndef LZ4F_MULTITHREAD |
73 | | # define LZ4F_MULTITHREAD 0 |
74 | | #endif |
75 | | #if defined(LZ4_FREESTANDING) && (LZ4_FREESTANDING == 1) |
76 | | # undef LZ4F_MULTITHREAD |
77 | | # define LZ4F_MULTITHREAD 0 |
78 | | #endif |
79 | | #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) /* MinGW.org, unlike mingw-w64, lacks Windows Vista API (condition variables) */ |
80 | | # undef LZ4F_MULTITHREAD |
81 | | # define LZ4F_MULTITHREAD 0 |
82 | | #endif |
83 | | |
84 | | |
85 | | /*-************************************ |
86 | | * Library declarations |
87 | | **************************************/ |
88 | | #define LZ4F_STATIC_LINKING_ONLY |
89 | | #include "lz4frame.h" |
90 | | #define LZ4_STATIC_LINKING_ONLY |
91 | | #include "lz4.h" |
92 | | #define LZ4_HC_STATIC_LINKING_ONLY |
93 | | #include "lz4hc.h" |
94 | | #define XXH_STATIC_LINKING_ONLY |
95 | | #include "xxhash.h" |
96 | | |
97 | | |
98 | | /*-************************************ |
99 | | * Memory routines |
100 | | **************************************/ |
101 | | /* |
102 | | * Default allocation functions, employed when LZ4F_CustomMem doesn't define them : |
103 | | * malloc(), calloc() and free(), or LZ4_malloc(), LZ4_calloc() and LZ4_free() |
104 | | * when lz4 is compiled with LZ4_USER_MEMORY_FUNCTIONS (see lz4.c). |
105 | | * None with LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION (implied by LZ4_FREESTANDING) : allocation then fails without LZ4F_CustomMem. |
106 | | **/ |
107 | | |
108 | | #if !LZ4_FREESTANDING |
109 | | # include <string.h> /* memset, memcpy, memmove */ |
110 | | #endif |
111 | | /* defined by the user with LZ4_FREESTANDING, or by lz4.c when sources are coalesced */ |
112 | | #ifndef LZ4_memcpy |
113 | 0 | # define LZ4_memcpy(d,s,n) memcpy((d),(s),(n)) |
114 | | #endif |
115 | | #ifndef LZ4_memmove |
116 | 0 | # define LZ4_memmove(d,s,n) memmove((d),(s),(n)) |
117 | | #endif |
118 | | #ifndef LZ4_memset |
119 | 0 | # define LZ4_memset(p,v,n) memset((p),(v),(n)) |
120 | | #endif |
121 | | #ifndef LZ4_SRC_INCLUDED /* avoid redefinition when sources are coalesced */ |
122 | 0 | # define MEM_INIT(p,v,s) LZ4_memset((p),(v),(s)) |
123 | | #endif |
124 | | |
125 | | #ifndef LZ4_SRC_INCLUDED /* avoid redefinition when sources are coalesced */ |
126 | | # if defined(LZ4_USER_MEMORY_FUNCTIONS) |
127 | | void* LZ4_malloc(size_t s); |
128 | | void* LZ4_calloc(size_t n, size_t s); |
129 | | void LZ4_free(void* p); |
130 | | # define ALLOC(s) LZ4_malloc(s) |
131 | | # define ALLOC_AND_ZERO(s) LZ4_calloc(1,(s)) |
132 | | # define FREEMEM(p) LZ4_free(p) |
133 | | # elif defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) |
134 | | # define ALLOC(s) NULL /* no default allocator */ |
135 | | # define ALLOC_AND_ZERO(s) NULL |
136 | | # define FREEMEM(p) ((void)(p)) |
137 | | # else |
138 | | # include <stdlib.h> /* malloc, calloc, free */ |
139 | 0 | # define ALLOC(s) malloc(s) |
140 | 0 | # define ALLOC_AND_ZERO(s) calloc(1,(s)) |
141 | 0 | # define FREEMEM(p) free(p) |
142 | | # endif |
143 | | #endif |
144 | | |
145 | | static void* LZ4F_calloc(size_t s, LZ4F_CustomMem cmem) |
146 | 0 | { |
147 | | /* custom calloc defined : use it */ |
148 | 0 | if (cmem.customCalloc != NULL) { |
149 | 0 | return cmem.customCalloc(cmem.opaqueState, s); |
150 | 0 | } |
151 | | /* nothing defined : use default calloc(), if any */ |
152 | 0 | if (cmem.customAlloc == NULL) { |
153 | 0 | return ALLOC_AND_ZERO(s); |
154 | 0 | } |
155 | | /* only custom alloc defined : use it, and combine it with LZ4_memset() */ |
156 | 0 | { void* const p = cmem.customAlloc(cmem.opaqueState, s); |
157 | 0 | if (p != NULL) MEM_INIT(p, 0, s); |
158 | 0 | return p; |
159 | 0 | } } |
160 | | |
161 | | static void* LZ4F_malloc(size_t s, LZ4F_CustomMem cmem) |
162 | 0 | { |
163 | | /* custom malloc defined : use it */ |
164 | 0 | if (cmem.customAlloc != NULL) { |
165 | 0 | return cmem.customAlloc(cmem.opaqueState, s); |
166 | 0 | } |
167 | | /* nothing defined : use default malloc(), if any */ |
168 | 0 | return ALLOC(s); |
169 | 0 | } |
170 | | |
171 | | static void LZ4F_free(void* p, LZ4F_CustomMem cmem) |
172 | 0 | { |
173 | 0 | if (p == NULL) return; |
174 | 0 | if (cmem.customFree != NULL) { |
175 | | /* custom allocation defined : use it */ |
176 | 0 | cmem.customFree(cmem.opaqueState, p); |
177 | 0 | return; |
178 | 0 | } |
179 | | /* nothing defined : use default free(), if any */ |
180 | 0 | FREEMEM(p); |
181 | 0 | } |
182 | | |
183 | | |
184 | | /*-************************************ |
185 | | * Debug |
186 | | **************************************/ |
187 | | #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1) |
188 | | # include <assert.h> |
189 | | #else |
190 | | # ifndef assert |
191 | | # define assert(condition) ((void)0) |
192 | | # endif |
193 | | #endif |
194 | | |
195 | 0 | #define LZ4F_STATIC_ASSERT(c) { enum { LZ4F_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ |
196 | | |
197 | | #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) && !defined(DEBUGLOG) |
198 | | # include <stdio.h> |
199 | | static int g_debuglog_enable = 1; |
200 | | # define DEBUGLOG(l, ...) { \ |
201 | | if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ |
202 | | fprintf(stderr, __FILE__ " %i: ", __LINE__ ); \ |
203 | | fprintf(stderr, __VA_ARGS__); \ |
204 | | fprintf(stderr, " \n"); \ |
205 | | } } |
206 | | #endif |
207 | | #ifndef DEBUGLOG /* may already be defined, e.g. by lz4.c in an amalgamated build */ |
208 | 0 | # define DEBUGLOG(l, ...) {} /* disabled */ |
209 | | #endif |
210 | | |
211 | | |
212 | | /*-************************************ |
213 | | * Basic Types |
214 | | **************************************/ |
215 | | #ifndef LZ4_SRC_INCLUDED |
216 | | # if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) |
217 | | # include <stdint.h> |
218 | | typedef uint8_t BYTE; |
219 | | typedef uint16_t U16; |
220 | | typedef uint32_t U32; |
221 | | typedef int32_t S32; |
222 | | typedef uint64_t U64; |
223 | | # else |
224 | | typedef unsigned char BYTE; |
225 | | typedef unsigned short U16; |
226 | | typedef unsigned int U32; |
227 | | typedef signed int S32; |
228 | | typedef unsigned long long U64; |
229 | | # endif |
230 | | #endif |
231 | | |
232 | | |
233 | | /* unoptimized version; solves endianness & alignment issues */ |
234 | | static U32 LZ4F_readLE32 (const void* src) |
235 | 0 | { |
236 | 0 | const BYTE* const srcPtr = (const BYTE*)src; |
237 | 0 | U32 value32 = srcPtr[0]; |
238 | 0 | value32 |= ((U32)srcPtr[1])<< 8; |
239 | 0 | value32 |= ((U32)srcPtr[2])<<16; |
240 | 0 | value32 |= ((U32)srcPtr[3])<<24; |
241 | 0 | return value32; |
242 | 0 | } |
243 | | |
244 | | static void LZ4F_writeLE32 (void* dst, U32 value32) |
245 | 0 | { |
246 | 0 | BYTE* const dstPtr = (BYTE*)dst; |
247 | 0 | dstPtr[0] = (BYTE)value32; |
248 | 0 | dstPtr[1] = (BYTE)(value32 >> 8); |
249 | 0 | dstPtr[2] = (BYTE)(value32 >> 16); |
250 | 0 | dstPtr[3] = (BYTE)(value32 >> 24); |
251 | 0 | } |
252 | | |
253 | | static U64 LZ4F_readLE64 (const void* src) |
254 | 0 | { |
255 | 0 | const BYTE* const srcPtr = (const BYTE*)src; |
256 | 0 | U64 value64 = srcPtr[0]; |
257 | 0 | value64 |= ((U64)srcPtr[1]<<8); |
258 | 0 | value64 |= ((U64)srcPtr[2]<<16); |
259 | 0 | value64 |= ((U64)srcPtr[3]<<24); |
260 | 0 | value64 |= ((U64)srcPtr[4]<<32); |
261 | 0 | value64 |= ((U64)srcPtr[5]<<40); |
262 | 0 | value64 |= ((U64)srcPtr[6]<<48); |
263 | 0 | value64 |= ((U64)srcPtr[7]<<56); |
264 | 0 | return value64; |
265 | 0 | } |
266 | | |
267 | | static void LZ4F_writeLE64 (void* dst, U64 value64) |
268 | 0 | { |
269 | 0 | BYTE* const dstPtr = (BYTE*)dst; |
270 | 0 | dstPtr[0] = (BYTE)value64; |
271 | 0 | dstPtr[1] = (BYTE)(value64 >> 8); |
272 | 0 | dstPtr[2] = (BYTE)(value64 >> 16); |
273 | 0 | dstPtr[3] = (BYTE)(value64 >> 24); |
274 | 0 | dstPtr[4] = (BYTE)(value64 >> 32); |
275 | 0 | dstPtr[5] = (BYTE)(value64 >> 40); |
276 | 0 | dstPtr[6] = (BYTE)(value64 >> 48); |
277 | 0 | dstPtr[7] = (BYTE)(value64 >> 56); |
278 | 0 | } |
279 | | |
280 | | |
281 | | /*-************************************ |
282 | | * Constants |
283 | | **************************************/ |
284 | | #ifndef LZ4_SRC_INCLUDED /* avoid double definition */ |
285 | 0 | # define KB *(1<<10) |
286 | 0 | # define MB *(1<<20) |
287 | 0 | # define GB *(1<<30) |
288 | | #endif |
289 | | |
290 | 0 | #define _1BIT 0x01 |
291 | 0 | #define _2BITS 0x03 |
292 | 0 | #define _3BITS 0x07 |
293 | 0 | #define _4BITS 0x0F |
294 | | #define _8BITS 0xFF |
295 | | |
296 | 0 | #define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U |
297 | 0 | #define LZ4F_BLOCKSIZEID_DEFAULT LZ4F_max64KB |
298 | | |
299 | | static const size_t minFHSize = LZ4F_HEADER_SIZE_MIN; /* 7 */ |
300 | | static const size_t maxFHSize = LZ4F_HEADER_SIZE_MAX; /* 19 */ |
301 | | static const size_t BHSize = LZ4F_BLOCK_HEADER_SIZE; /* block header : size, and compress flag */ |
302 | | static const size_t BFSize = LZ4F_BLOCK_CHECKSUM_SIZE; /* block footer : checksum (optional) */ |
303 | | |
304 | | |
305 | | /*-************************************ |
306 | | * Structures and local types |
307 | | **************************************/ |
308 | | |
309 | | typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_BlockCompressMode_e; |
310 | | typedef enum { ctxNone, ctxFast, ctxHC } LZ4F_CtxType_e; |
311 | | |
312 | | struct LZ4F_CDict_s { |
313 | | LZ4F_CustomMem cmem; |
314 | | void* dictContent; |
315 | | LZ4_stream_t* fastCtx; |
316 | | LZ4_streamHC_t* HCCtx; |
317 | | }; /* typedef'd to LZ4F_CDict within lz4frame_static.h */ |
318 | | |
319 | | typedef struct LZ4F_cctx_s |
320 | | { |
321 | | LZ4F_CustomMem cmem; |
322 | | LZ4F_preferences_t prefs; |
323 | | U32 version; |
324 | | U32 cStage; /* 0 : compression uninitialized ; 1 : initialized, can compress ; 2 : frame ending (LZ4F_compressEnd() in progress) */ |
325 | | const LZ4F_CDict* cdict; |
326 | | size_t maxBlockSize; |
327 | | size_t tmpBuffCapacity; |
328 | | BYTE* tmpBuff; /* internal buffer, for streaming */ |
329 | | BYTE* tmpIn; /* starting position of data compress within internal buffer (>= tmpBuff) */ |
330 | | size_t tmpInSize; /* amount of data to compress after tmpIn */ |
331 | | U64 totalInSize; |
332 | | XXH32_state_t xxh; |
333 | | void* lz4CtxPtr; |
334 | | U16 lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */ |
335 | | U16 lz4CtxType; /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */ |
336 | | LZ4F_BlockCompressMode_e blockCompressMode; |
337 | | struct LZ4F_mtCtx_s* mt; /* multi-threading resources, kept across frames; NULL when never needed */ |
338 | | U32 mtActive; /* current frame is cut into jobs (prefs.nbWorkers >= 1) */ |
339 | | /* LZ4F_flush() and LZ4F_compressEnd() : output not fitting into dstBuffer yet, see LZ4F_emitPending() */ |
340 | | U32 flushStage; /* 0 : none ; 1 : flush point set, emitting ; LZ4F_compressEnd() only : 2 : footer ; 3 : completed */ |
341 | | const BYTE* pending; /* remaining output of a block (stageBuff), or of the frame footer */ |
342 | | size_t pendingSize; |
343 | | BYTE* stageBuff; /* a block not fitting into dstBuffer : allocated on first need */ |
344 | | size_t stageCapacity; |
345 | | BYTE footer[8]; /* endMark + optional content checksum */ |
346 | | /* raw dictionary (LZ4F_compressBegin_usingDict()) digested for current frame, then employed as a CDict */ |
347 | | struct LZ4F_CDict_s rawDict; /* fastCtx or HCCtx, the other one NULL ; no dictContent : not owned */ |
348 | | LZ4_stream_t* rawDictFast; /* allocated on first need */ |
349 | | LZ4_streamHC_t* rawDictHC; /* allocated on first need */ |
350 | | } LZ4F_cctx_t; |
351 | | |
352 | | /* multi-threaded compression, see LZ4F_preferences_t.nbWorkers */ |
353 | | typedef struct LZ4F_mtCtx_s LZ4F_mtCtx_t; |
354 | | static void LZ4F_mt_abort(LZ4F_mtCtx_t* mt); |
355 | | static size_t LZ4F_mt_begin(LZ4F_cctx_t* cctx); |
356 | | static void LZ4F_mt_free(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem); |
357 | | static size_t LZ4F_mt_sizeof(const LZ4F_mtCtx_t* mt); |
358 | | |
359 | | |
360 | | /*-************************************ |
361 | | * Error management |
362 | | **************************************/ |
363 | | #define LZ4F_GENERATE_STRING(STRING) #STRING, |
364 | | static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) }; |
365 | | |
366 | | |
367 | | unsigned LZ4F_isError(LZ4F_errorCode_t code) |
368 | 0 | { |
369 | 0 | return (code > (LZ4F_errorCode_t)(-LZ4F_ERROR_maxCode)); |
370 | 0 | } |
371 | | |
372 | | const char* LZ4F_getErrorName(LZ4F_errorCode_t code) |
373 | 0 | { |
374 | 0 | static const char* codeError = "Unspecified error code"; |
375 | 0 | if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)]; |
376 | 0 | return codeError; |
377 | 0 | } |
378 | | |
379 | | LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult) |
380 | 0 | { |
381 | 0 | if (!LZ4F_isError(functionResult)) return LZ4F_OK_NoError; |
382 | 0 | return (LZ4F_errorCodes)(-(ptrdiff_t)functionResult); |
383 | 0 | } |
384 | | |
385 | | static LZ4F_errorCode_t LZ4F_returnErrorCode(LZ4F_errorCodes code) |
386 | 0 | { |
387 | | /* A compilation error here means sizeof(ptrdiff_t) is not large enough */ |
388 | 0 | LZ4F_STATIC_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t)); |
389 | 0 | return (LZ4F_errorCode_t)-(ptrdiff_t)code; |
390 | 0 | } |
391 | | |
392 | 0 | #define RETURN_ERROR(e) return LZ4F_returnErrorCode(LZ4F_ERROR_ ## e) |
393 | | |
394 | 0 | #define RETURN_ERROR_IF(c,e) do { \ |
395 | 0 | if (c) { \ |
396 | 0 | DEBUGLOG(3, "Error: " #c); \ |
397 | 0 | RETURN_ERROR(e); \ |
398 | 0 | } \ |
399 | 0 | } while (0) |
400 | | |
401 | | /* note : @r is evaluated only once, so it can be an expression with side effects */ |
402 | 0 | #define FORWARD_IF_ERROR(r) do { \ |
403 | 0 | size_t const err_code = (r); \ |
404 | 0 | if (LZ4F_isError(err_code)) return err_code; \ |
405 | 0 | } while (0) |
406 | | |
407 | | /* a failed operation invalidates the frame, and discards its jobs (multi-threaded mode) : |
408 | | * next operations fail with compressionState_uninitialized, until LZ4F_compressBegin(). |
409 | | * Idempotent : also employed to forward errors of functions which already invalidated the frame */ |
410 | | static void LZ4F_invalidateFrame(LZ4F_cctx_t* cctx) |
411 | 0 | { |
412 | 0 | if (cctx->mtActive) LZ4F_mt_abort(cctx->mt); |
413 | 0 | cctx->cStage = 0; |
414 | 0 | } |
415 | | |
416 | 0 | #define FORWARD_IF_ERROR_INVALIDATE(r, cctx) do { \ |
417 | 0 | size_t const err_code = (r); \ |
418 | 0 | if (LZ4F_isError(err_code)) { \ |
419 | 0 | LZ4F_invalidateFrame(cctx); \ |
420 | 0 | return err_code; \ |
421 | 0 | } \ |
422 | 0 | } while (0) |
423 | | |
424 | 0 | unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; } |
425 | | |
426 | 0 | int LZ4F_compressionLevel_max(void) { return LZ4HC_CLEVEL_MAX; } |
427 | | |
428 | | size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID) |
429 | 0 | { |
430 | 0 | static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB }; |
431 | |
|
432 | 0 | if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT; |
433 | 0 | if (blockSizeID < LZ4F_max64KB || blockSizeID > LZ4F_max4MB) |
434 | 0 | RETURN_ERROR(maxBlockSize_invalid); |
435 | 0 | { int const blockSizeIdx = (int)blockSizeID - (int)LZ4F_max64KB; |
436 | 0 | return blockSizes[blockSizeIdx]; |
437 | 0 | } } |
438 | | |
439 | | /*-************************************ |
440 | | * Private functions |
441 | | **************************************/ |
442 | | #undef MIN |
443 | 0 | #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) |
444 | | |
445 | | static BYTE LZ4F_headerChecksum (const void* header, size_t length) |
446 | 0 | { |
447 | 0 | U32 const xxh = XXH32(header, length, 0); |
448 | 0 | return (BYTE)(xxh >> 8); |
449 | 0 | } |
450 | | |
451 | | |
452 | | /*-************************************ |
453 | | * Simple-pass compression functions |
454 | | **************************************/ |
455 | | static LZ4F_blockSizeID_t LZ4F_optimalBSID(const LZ4F_blockSizeID_t requestedBSID, |
456 | | const size_t srcSize) |
457 | 0 | { |
458 | 0 | LZ4F_blockSizeID_t proposedBSID = LZ4F_max64KB; |
459 | 0 | size_t maxBlockSize = 64 KB; |
460 | 0 | while (requestedBSID > proposedBSID) { |
461 | 0 | if (srcSize <= maxBlockSize) |
462 | 0 | return proposedBSID; |
463 | 0 | proposedBSID = (LZ4F_blockSizeID_t)((int)proposedBSID + 1); |
464 | 0 | maxBlockSize <<= 2; |
465 | 0 | } |
466 | 0 | return requestedBSID; |
467 | 0 | } |
468 | | |
469 | | /*! LZ4F_compressBound_autoFlush() : |
470 | | * worst case : @srcSize as blocks stored uncompressed, the last one partial, then the frame footer. |
471 | | * Also bounds one-shot compression (LZ4F_compressFrameBound()), which compresses all its input at once. |
472 | | * When srcSize==0, it bounds LZ4F_flush() and LZ4F_compressEnd() operations. |
473 | | */ |
474 | | static size_t LZ4F_compressBound_autoFlush(size_t srcSize, const LZ4F_preferences_t* prefsPtr) |
475 | 0 | { |
476 | 0 | size_t const blockSize = LZ4F_getBlockSize(prefsPtr->frameInfo.blockSizeID); |
477 | 0 | size_t const nbFullBlocks = srcSize / blockSize; |
478 | 0 | size_t const lastBlockSize = srcSize & (blockSize-1); |
479 | 0 | size_t const nbBlocks = nbFullBlocks + (lastBlockSize>0); |
480 | 0 | size_t const blockCRCSize = BFSize * prefsPtr->frameInfo.blockChecksumFlag; |
481 | 0 | size_t const frameEnd = BHSize + (prefsPtr->frameInfo.contentChecksumFlag*BFSize); |
482 | 0 | assert(prefsPtr->autoFlush); |
483 | 0 | return ((BHSize + blockCRCSize) * nbBlocks) + |
484 | 0 | (blockSize * nbFullBlocks) + lastBlockSize + frameEnd; |
485 | 0 | } |
486 | | |
487 | | size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr) |
488 | 0 | { |
489 | 0 | LZ4F_preferences_t prefs; |
490 | 0 | size_t const headerSize = maxFHSize; /* max header size, including optional fields */ |
491 | |
|
492 | 0 | if (preferencesPtr!=NULL) prefs = *preferencesPtr; |
493 | 0 | else MEM_INIT(&prefs, 0, sizeof(prefs)); |
494 | 0 | prefs.autoFlush = 1; |
495 | |
|
496 | 0 | return headerSize + LZ4F_compressBound_autoFlush(srcSize, &prefs); |
497 | 0 | } |
498 | | |
499 | | |
500 | | /*-************************************ |
501 | | * Multi-threading parameters |
502 | | **************************************/ |
503 | | /* see LZ4F_preferences_t.nbWorkers */ |
504 | | /* sanity limit (ex: uninitialized preferences) ; on 32-bit systems, keeps LZ4F_compressBound() within address space */ |
505 | | #ifndef LZ4F_NBWORKERS_MAX |
506 | | # define LZ4F_NBWORKERS_MAX ((sizeof(size_t) >= 8) ? 1024u : 128u) |
507 | | #endif |
508 | 0 | #define LZ4F_MT_PREFIX_SIZE (64 KB) /* history employed by linked blocks */ |
509 | | |
510 | | /* Job size : |
511 | | * Input is cut into jobs at fixed positions of the frame's content (restarting after each flush) : |
512 | | * a whole nb of blocks, up to LZ4F_MT_JOBSIZE (lz4frame.h), or a single block when larger. |
513 | | * With linked blocks, each job restarts the stream, using previous 64 KB as dictionary. |
514 | | * Job boundaries are therefore part of the output definition : changing this size changes output of linked blocks. |
515 | | * With independent blocks, output only depends on block boundaries, not on job boundaries. |
516 | | * Small jobs balance load among threads, engage multi-threading on smaller inputs, and lower latency. */ |
517 | | static size_t LZ4F_mtJobSize(size_t blockSize) |
518 | 0 | { |
519 | 0 | if (blockSize >= LZ4F_MT_JOBSIZE) return blockSize; |
520 | 0 | return (LZ4F_MT_JOBSIZE / blockSize) * blockSize; /* whole nb of blocks */ |
521 | 0 | } |
522 | | |
523 | | unsigned LZ4F_getMaxNbWorkers(void) |
524 | 0 | { |
525 | | #if LZ4F_MULTITHREAD |
526 | | return LZ4F_NBWORKERS_MAX; |
527 | | #else |
528 | 0 | return 0; |
529 | 0 | #endif |
530 | 0 | } |
531 | | |
532 | | /* frames are cut into jobs only with valid block modes, see LZ4F_mt_begin() */ |
533 | | static int LZ4F_mtEligible(const LZ4F_preferences_t* prefs) |
534 | 0 | { |
535 | 0 | if (prefs->nbWorkers == 0) return 0; |
536 | | /* linked blocks : jobs define the output, so frames are cut into jobs even without threads */ |
537 | 0 | if (prefs->frameInfo.blockMode == LZ4F_blockLinked) return 1; |
538 | | #if LZ4F_MULTITHREAD |
539 | | return (prefs->frameInfo.blockMode == LZ4F_blockIndependent); |
540 | | #else |
541 | | /* independent blocks : the output is identical to single-threaded mode, which is faster without threads */ |
542 | 0 | return 0; |
543 | 0 | #endif |
544 | 0 | } |
545 | | |
546 | | /* nb of job slots for @nbThreads worker threads : |
547 | | * one being filled, one per worker, plus room for jobs completed out of order, |
548 | | * since their outputs are emitted in order */ |
549 | | #ifndef LZ4F_MT_SLOTS_PER_THREAD |
550 | 0 | # define LZ4F_MT_SLOTS_PER_THREAD 2 |
551 | | #endif |
552 | 0 | #define LZ4F_MT_NBSLOTS(nbThreads) ((size_t)(nbThreads) * LZ4F_MT_SLOTS_PER_THREAD + 1) |
553 | | #ifndef LZ4F_MT_EXTRA_INBUFFS |
554 | 0 | # define LZ4F_MT_EXTRA_INBUFFS 1 |
555 | | #endif |
556 | | |
557 | | |
558 | | /*! LZ4F_blocksBound() : |
559 | | * @return worst case size of LZ4F_compressBlocks_internal() output */ |
560 | | static size_t LZ4F_blocksBound(size_t srcSize, size_t blockSize, LZ4F_blockChecksum_t crcFlag) |
561 | 0 | { |
562 | 0 | size_t const nbBlocks = (srcSize + blockSize - 1) / blockSize; |
563 | 0 | return srcSize + nbBlocks * (BHSize + (size_t)crcFlag * BFSize); |
564 | 0 | } |
565 | | |
566 | | /*! LZ4F_mtCompressBound() : |
567 | | * LZ4F_compressBound() for frames cut into jobs, without autoFlush : the job is the unit, instead of the block. |
568 | | * LZ4F_compressUpdate() defers completed jobs not fitting into dstBuffer : |
569 | | * output is only required to start a job while all slots are busy (the oldest one), |
570 | | * and an invocation starts at most ceil(srcSize / jobSize) jobs, since the job being filled holds < jobSize bytes. |
571 | | * @srcSize == 0 : LZ4F_flush() and LZ4F_compressEnd() emit at least one whole job per invocation, then the frame footer. |
572 | | * The frame footer is always included, so that the bound grows with @srcSize. */ |
573 | | static size_t LZ4F_mtCompressBound(size_t srcSize, const LZ4F_preferences_t* prefs) |
574 | 0 | { |
575 | 0 | size_t const bs = LZ4F_getBlockSize(prefs->frameInfo.blockSizeID); |
576 | 0 | size_t const blockSize = LZ4F_isError(bs) ? 4 MB : bs; |
577 | 0 | size_t const jobSize = LZ4F_mtJobSize(blockSize); |
578 | 0 | size_t const nbJobs = srcSize ? (srcSize / jobSize) + ((srcSize % jobSize) != 0) : 1; |
579 | 0 | size_t const frameEnd = BHSize + (prefs->frameInfo.contentChecksumFlag*BFSize); |
580 | 0 | return nbJobs * LZ4F_blocksBound(jobSize, blockSize, prefs->frameInfo.blockChecksumFlag) + frameEnd; |
581 | 0 | } |
582 | | |
583 | | /*! LZ4F_compressFrame_usingCDict() : |
584 | | * Compress srcBuffer using a dictionary, in a single step. |
585 | | * cdict can be NULL, in which case, no dictionary is used. |
586 | | * Success is guaranteed when dstCapacity >= LZ4F_compressFrameBound(srcSize, preferencesPtr). |
587 | | * Otherwise, compression fails with dstCapacity_tooSmall if the frame doesn't fit. |
588 | | * The LZ4F_preferences_t structure is optional : you may provide NULL as argument, |
589 | | * however, it's the only way to provide a dictID, so it's not recommended. |
590 | | * @return : number of bytes written into dstBuffer, |
591 | | * or an error code if it fails (can be tested using LZ4F_isError()) |
592 | | */ |
593 | | size_t LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx, |
594 | | void* dstBuffer, size_t dstCapacity, |
595 | | const void* srcBuffer, size_t srcSize, |
596 | | const LZ4F_CDict* cdict, |
597 | | const LZ4F_preferences_t* preferencesPtr) |
598 | 0 | { |
599 | 0 | LZ4F_preferences_t prefs; |
600 | 0 | LZ4F_compressOptions_t options; |
601 | 0 | BYTE* const dstStart = (BYTE*) dstBuffer; |
602 | 0 | BYTE* dstPtr = dstStart; |
603 | 0 | BYTE* const dstEnd = dstStart + dstCapacity; |
604 | |
|
605 | 0 | DEBUGLOG(4, "LZ4F_compressFrame_usingCDict (srcSize=%u)", (unsigned)srcSize); |
606 | 0 | if (preferencesPtr!=NULL) |
607 | 0 | prefs = *preferencesPtr; |
608 | 0 | else |
609 | 0 | MEM_INIT(&prefs, 0, sizeof(prefs)); |
610 | 0 | if (prefs.frameInfo.contentSize != 0) |
611 | 0 | prefs.frameInfo.contentSize = (U64)srcSize; /* auto-correct content size if selected (!=0) */ |
612 | |
|
613 | 0 | FORWARD_IF_ERROR(LZ4F_getBlockSize(prefs.frameInfo.blockSizeID)); /* invalid blockSizeID */ |
614 | 0 | prefs.frameInfo.blockSizeID = LZ4F_optimalBSID(prefs.frameInfo.blockSizeID, srcSize); |
615 | 0 | prefs.autoFlush = 1; |
616 | 0 | if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID)) |
617 | 0 | prefs.frameInfo.blockMode = LZ4F_blockIndependent; /* only one block => no need for inter-block link */ |
618 | |
|
619 | 0 | if (LZ4F_mtEligible(&prefs)) { |
620 | | /* a single job produces the same output as single-threaded compression, without the setup cost */ |
621 | 0 | size_t const blockSize = LZ4F_getBlockSize(prefs.frameInfo.blockSizeID); |
622 | 0 | if (LZ4F_isError(blockSize) || srcSize <= LZ4F_mtJobSize(blockSize)) |
623 | 0 | prefs.nbWorkers = 0; |
624 | 0 | } |
625 | |
|
626 | 0 | MEM_INIT(&options, 0, sizeof(options)); |
627 | 0 | options.stableSrc = LZ4F_srcStableUntilFlush; /* src remains until LZ4F_compressEnd() below */ |
628 | |
|
629 | 0 | { size_t const headerSize = LZ4F_compressBegin_usingCDict(cctx, dstBuffer, dstCapacity, cdict, &prefs); /* write header */ |
630 | 0 | FORWARD_IF_ERROR(headerSize); |
631 | 0 | dstPtr += headerSize; /* header size */ } |
632 | | |
633 | 0 | assert(dstEnd >= dstPtr); |
634 | 0 | { size_t const cSize = LZ4F_compressUpdate(cctx, dstPtr, (size_t)(dstEnd-dstPtr), srcBuffer, srcSize, &options); |
635 | 0 | FORWARD_IF_ERROR(cSize); |
636 | 0 | dstPtr += cSize; } |
637 | | |
638 | 0 | assert(dstEnd >= dstPtr); |
639 | 0 | { size_t const tailSize = LZ4F_compressEnd(cctx, dstPtr, (size_t)(dstEnd-dstPtr), &options); /* flush last block, and generate suffix */ |
640 | 0 | int const completed = !LZ4F_isError(tailSize) && ((cctx->cStage == 0) || (cctx->flushStage == 3)); |
641 | 0 | if (!completed) { |
642 | | /* the frame doesn't fit */ |
643 | 0 | LZ4F_invalidateFrame(cctx); |
644 | 0 | return LZ4F_isError(tailSize) ? tailSize : LZ4F_returnErrorCode(LZ4F_ERROR_dstCapacity_tooSmall); |
645 | 0 | } |
646 | 0 | cctx->cStage = 0; |
647 | 0 | cctx->flushStage = 0; |
648 | 0 | dstPtr += tailSize; } |
649 | | |
650 | 0 | assert(dstEnd >= dstStart); |
651 | 0 | return (size_t)(dstPtr - dstStart); |
652 | 0 | } |
653 | | |
654 | | |
655 | | /*! LZ4F_compressFrame() : |
656 | | * Compress an entire srcBuffer into a valid LZ4 frame, in a single step. |
657 | | * Success is guaranteed when dstCapacity >= LZ4F_compressFrameBound(srcSize, preferencesPtr). |
658 | | * Otherwise, compression fails with dstCapacity_tooSmall if the frame doesn't fit. |
659 | | * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. |
660 | | * @return : number of bytes written into dstBuffer. |
661 | | * or an error code if it fails (can be tested using LZ4F_isError()) |
662 | | */ |
663 | | size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity, |
664 | | const void* srcBuffer, size_t srcSize, |
665 | | const LZ4F_preferences_t* preferencesPtr) |
666 | 0 | { |
667 | 0 | size_t result; |
668 | | #if (LZ4F_HEAPMODE) |
669 | | LZ4F_cctx_t* const cctxPtr = LZ4F_createCompressionContext_advanced(LZ4F_defaultCMem, LZ4F_VERSION); |
670 | | RETURN_ERROR_IF(cctxPtr == NULL, allocation_failed); |
671 | | #else |
672 | 0 | LZ4F_cctx_t cctx; |
673 | 0 | LZ4_stream_t lz4ctx; |
674 | 0 | LZ4F_cctx_t* const cctxPtr = &cctx; |
675 | |
|
676 | 0 | MEM_INIT(&cctx, 0, sizeof(cctx)); |
677 | 0 | cctx.version = LZ4F_VERSION; |
678 | 0 | cctx.tmpBuffCapacity = 5 MB; /* mess with real buffer size to prevent dynamic allocation; works only because autoflush==1 & stableSrc */ |
679 | 0 | if ( preferencesPtr == NULL |
680 | 0 | || preferencesPtr->compressionLevel < LZ4HC_CLEVEL_MIN ) { |
681 | 0 | LZ4_initStream(&lz4ctx, sizeof(lz4ctx)); |
682 | 0 | cctxPtr->lz4CtxPtr = &lz4ctx; |
683 | 0 | cctxPtr->lz4CtxAlloc = ctxFast; |
684 | 0 | cctxPtr->lz4CtxType = ctxFast; |
685 | 0 | } |
686 | 0 | #endif |
687 | 0 | DEBUGLOG(4, "LZ4F_compressFrame"); |
688 | |
|
689 | 0 | result = LZ4F_compressFrame_usingCDict(cctxPtr, dstBuffer, dstCapacity, |
690 | 0 | srcBuffer, srcSize, |
691 | 0 | NULL, preferencesPtr); |
692 | |
|
693 | | #if (LZ4F_HEAPMODE) |
694 | | LZ4F_freeCompressionContext(cctxPtr); |
695 | | #else |
696 | 0 | if ( preferencesPtr != NULL |
697 | 0 | && preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN ) { |
698 | 0 | LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem); |
699 | 0 | } |
700 | 0 | LZ4F_mt_free(cctxPtr->mt, cctxPtr->cmem); |
701 | 0 | LZ4F_free(cctxPtr->stageBuff, cctxPtr->cmem); |
702 | 0 | #endif |
703 | 0 | return result; |
704 | 0 | } |
705 | | |
706 | | |
707 | | /*-*************************************************** |
708 | | * Dictionary compression |
709 | | *****************************************************/ |
710 | | |
711 | | LZ4F_CDict* |
712 | | LZ4F_createCDict_advanced(LZ4F_CustomMem cmem, const void* dictBuffer, size_t dictSize) |
713 | 0 | { |
714 | 0 | const char* dictStart = (const char*)dictBuffer; |
715 | 0 | LZ4F_CDict* cdict = NULL; |
716 | |
|
717 | 0 | DEBUGLOG(4, "LZ4F_createCDict_advanced"); |
718 | |
|
719 | 0 | if (!dictStart) |
720 | 0 | return NULL; |
721 | 0 | cdict = (LZ4F_CDict*)LZ4F_malloc(sizeof(*cdict), cmem); |
722 | 0 | if (!cdict) |
723 | 0 | return NULL; |
724 | | |
725 | 0 | cdict->cmem = cmem; |
726 | 0 | if (dictSize > 64 KB) { |
727 | 0 | dictStart += dictSize - 64 KB; |
728 | 0 | dictSize = 64 KB; |
729 | 0 | } |
730 | 0 | cdict->dictContent = LZ4F_malloc(dictSize, cmem); |
731 | | /* note: using @cmem to allocate => can't use default create */ |
732 | 0 | cdict->fastCtx = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cmem); |
733 | 0 | cdict->HCCtx = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cmem); |
734 | 0 | if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) { |
735 | 0 | LZ4F_freeCDict(cdict); |
736 | 0 | return NULL; |
737 | 0 | } |
738 | 0 | LZ4_memcpy(cdict->dictContent, dictStart, dictSize); |
739 | 0 | LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t)); |
740 | 0 | LZ4_loadDictSlow(cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize); |
741 | 0 | LZ4_initStreamHC(cdict->HCCtx, sizeof(LZ4_streamHC_t)); |
742 | | /* note: we don't know at this point which compression level is going to be used |
743 | | * as a consequence, HCCtx is created for the more common HC mode */ |
744 | 0 | LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT); |
745 | 0 | LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize); |
746 | 0 | return cdict; |
747 | 0 | } |
748 | | |
749 | | /*! LZ4F_createCDict() : |
750 | | * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once. |
751 | | * LZ4F_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. |
752 | | * LZ4F_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. |
753 | | * @dictBuffer can be released after LZ4F_CDict creation, since its content is copied within CDict |
754 | | * @return : digested dictionary for compression, or NULL if failed */ |
755 | | LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize) |
756 | 0 | { |
757 | 0 | DEBUGLOG(4, "LZ4F_createCDict"); |
758 | 0 | return LZ4F_createCDict_advanced(LZ4F_defaultCMem, dictBuffer, dictSize); |
759 | 0 | } |
760 | | |
761 | | void LZ4F_freeCDict(LZ4F_CDict* cdict) |
762 | 0 | { |
763 | 0 | if (cdict==NULL) return; /* support free on NULL */ |
764 | 0 | LZ4F_free(cdict->dictContent, cdict->cmem); |
765 | 0 | LZ4F_free(cdict->fastCtx, cdict->cmem); |
766 | 0 | LZ4F_free(cdict->HCCtx, cdict->cmem); |
767 | 0 | LZ4F_free(cdict, cdict->cmem); |
768 | 0 | } |
769 | | |
770 | | |
771 | | /*-********************************* |
772 | | * Advanced compression functions |
773 | | ***********************************/ |
774 | | |
775 | | LZ4F_cctx* |
776 | | LZ4F_createCompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version) |
777 | 0 | { |
778 | 0 | LZ4F_cctx* const cctxPtr = |
779 | 0 | (LZ4F_cctx*)LZ4F_calloc(sizeof(LZ4F_cctx), customMem); |
780 | 0 | if (cctxPtr==NULL) return NULL; |
781 | | |
782 | 0 | cctxPtr->cmem = customMem; |
783 | 0 | cctxPtr->version = version; |
784 | 0 | cctxPtr->cStage = 0; /* Uninitialized. Next stage : init cctx */ |
785 | |
|
786 | 0 | return cctxPtr; |
787 | 0 | } |
788 | | |
789 | | /*! LZ4F_createCompressionContext() : |
790 | | * The first thing to do is to create a compressionContext object, which will be used in all compression operations. |
791 | | * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure. |
792 | | * The version provided MUST be LZ4F_VERSION. It is intended to track potential incompatible differences between different binaries. |
793 | | * The function will provide a pointer to an allocated LZ4F_compressionContext_t object. |
794 | | * If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation. |
795 | | * Object can release its memory using LZ4F_freeCompressionContext(); |
796 | | **/ |
797 | | LZ4F_errorCode_t |
798 | | LZ4F_createCompressionContext(LZ4F_cctx** LZ4F_compressionContextPtr, unsigned version) |
799 | 0 | { |
800 | 0 | assert(LZ4F_compressionContextPtr != NULL); /* considered a violation of narrow contract */ |
801 | | /* in case it nonetheless happen in production */ |
802 | 0 | RETURN_ERROR_IF(LZ4F_compressionContextPtr == NULL, parameter_null); |
803 | | |
804 | 0 | *LZ4F_compressionContextPtr = LZ4F_createCompressionContext_advanced(LZ4F_defaultCMem, version); |
805 | 0 | RETURN_ERROR_IF(*LZ4F_compressionContextPtr==NULL, allocation_failed); |
806 | 0 | return LZ4F_OK_NoError; |
807 | 0 | } |
808 | | |
809 | | LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctxPtr) |
810 | 0 | { |
811 | 0 | if (cctxPtr != NULL) { /* support free on NULL */ |
812 | 0 | LZ4F_mt_free(cctxPtr->mt, cctxPtr->cmem); /* first : waits for jobs still in flight */ |
813 | 0 | LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem); /* note: LZ4_streamHC_t and LZ4_stream_t are simple POD types */ |
814 | 0 | LZ4F_free(cctxPtr->tmpBuff, cctxPtr->cmem); |
815 | 0 | LZ4F_free(cctxPtr->stageBuff, cctxPtr->cmem); |
816 | 0 | LZ4F_free(cctxPtr->rawDictFast, cctxPtr->cmem); |
817 | 0 | LZ4F_free(cctxPtr->rawDictHC, cctxPtr->cmem); |
818 | 0 | LZ4F_free(cctxPtr, cctxPtr->cmem); |
819 | 0 | } |
820 | 0 | return LZ4F_OK_NoError; |
821 | 0 | } |
822 | | |
823 | | |
824 | | /** |
825 | | * This function prepares the internal LZ4(HC) stream for a new compression, |
826 | | * resetting the context and attaching the dictionary, if there is one. |
827 | | * |
828 | | * It needs to be called at the beginning of each independent compression |
829 | | * stream (i.e., at the beginning of a frame in blockLinked mode, or at the |
830 | | * beginning of each block in blockIndependent mode). |
831 | | */ |
832 | | static void LZ4F_initStream(void* ctx, |
833 | | const LZ4F_CDict* cdict, |
834 | | int level, |
835 | 0 | LZ4F_blockMode_t blockMode) { |
836 | 0 | if (level < LZ4HC_CLEVEL_MIN) { |
837 | | /* In these cases, we will call LZ4_compress_fast_continue(), |
838 | | * which needs an already reset context. Otherwise, we'll call a |
839 | | * one-shot API. The non-continued APIs internally perform their own |
840 | | * resets at the beginning of their calls, where they know what |
841 | | * tableType they need the context to be in. So in that case this |
842 | | * would be misguided / wasted work. */ |
843 | 0 | if (cdict) { |
844 | 0 | LZ4_resetStream_fast((LZ4_stream_t*)ctx); |
845 | 0 | LZ4_attach_dictionary((LZ4_stream_t*)ctx, cdict->fastCtx); |
846 | 0 | } else if (blockMode == LZ4F_blockLinked) { |
847 | | /* Clear the table, rather than LZ4_resetStream_fast() : |
848 | | * output doesn't depend on the context's history, |
849 | | * and it's faster, unless the frame is tiny. */ |
850 | 0 | LZ4_initStream(ctx, sizeof(LZ4_stream_t)); |
851 | 0 | } |
852 | | /* In these cases, we'll call a one-shot API. |
853 | | * The non-continued APIs internally perform their own resets |
854 | | * at the beginning of their calls, where they know |
855 | | * which tableType they need the context to be in. |
856 | | * Therefore, a reset here would be wasted work. */ |
857 | 0 | } else { |
858 | 0 | LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level); |
859 | 0 | if (cdict) |
860 | 0 | LZ4_attach_HC_dictionary((LZ4_streamHC_t*)ctx, cdict->HCCtx); |
861 | 0 | } |
862 | 0 | } |
863 | | |
864 | | /* LZ4F_startStream() : |
865 | | * starts the LZ4 stream @ctx at the compression level of @prefs : for a frame, a job, or after uncompressed blocks. |
866 | | * With linked blocks, the stream starts from dictionary @cdict, or from history @dict (@dictSize bytes) ; |
867 | | * independent blocks start their own stream (see LZ4F_compressBlock()). */ |
868 | | static void LZ4F_startStream(void* ctx, const LZ4F_preferences_t* prefs, |
869 | | const LZ4F_CDict* cdict, const void* dict, size_t dictSize) |
870 | 0 | { |
871 | 0 | int const level = prefs->compressionLevel; |
872 | 0 | if (prefs->frameInfo.blockMode == LZ4F_blockLinked) |
873 | 0 | LZ4F_initStream(ctx, cdict, level, LZ4F_blockLinked); |
874 | 0 | if (level >= LZ4HC_CLEVEL_MIN) |
875 | 0 | LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)ctx, (int)prefs->favorDecSpeed); |
876 | 0 | if (dict) { |
877 | 0 | assert(cdict == NULL); |
878 | 0 | assert(prefs->frameInfo.blockMode == LZ4F_blockLinked); |
879 | 0 | assert(dictSize <= INT_MAX); |
880 | 0 | if (level < LZ4HC_CLEVEL_MIN) { |
881 | 0 | LZ4_loadDict((LZ4_stream_t*)ctx, (const char*)dict, (int)dictSize); |
882 | 0 | } else { |
883 | 0 | LZ4_loadDictHC((LZ4_streamHC_t*)ctx, (const char*)dict, (int)dictSize); |
884 | 0 | } |
885 | 0 | } |
886 | 0 | } |
887 | | |
888 | | /* LZ4F_sizeofLZ4State() : |
889 | | * @return the size of the inner LZ4 state (pointed by lz4CtxPtr) for @ctxType : |
890 | | * LZ4_stream_t for fast levels, LZ4_streamHC_t for HC levels. |
891 | | * ctxNone means no state allocated, hence a size of 0. |
892 | | * Note : the larger of fast and HC states depends on LZ4_MEMORY_USAGE, |
893 | | * so reusing an allocated state requires comparing sizes. */ |
894 | | static size_t LZ4F_sizeofLZ4State(LZ4F_CtxType_e ctxType) |
895 | 0 | { |
896 | 0 | switch (ctxType) { |
897 | 0 | case ctxNone: return 0; |
898 | 0 | case ctxFast: return sizeof(LZ4_stream_t); |
899 | 0 | case ctxHC: return LZ4_STREAMHC_EXTSIZE; /* extended : levels >= 10 allocate nothing */ |
900 | 0 | } |
901 | 0 | assert(0); /* invalid ctxType */ |
902 | 0 | return 0; |
903 | 0 | } |
904 | | |
905 | | /* LZ4F_initLZ4State() : |
906 | | * initializes the inner LZ4 state @state for @ctxType (fast or HC), at compression @level */ |
907 | | static void LZ4F_initLZ4State(void* state, LZ4F_CtxType_e ctxType, int level) |
908 | 0 | { |
909 | 0 | if (ctxType == ctxFast) { |
910 | 0 | LZ4_initStream(state, sizeof(LZ4_stream_t)); |
911 | 0 | } else { |
912 | 0 | assert(ctxType == ctxHC); |
913 | 0 | LZ4_initStreamHC(state, LZ4_STREAMHC_EXTSIZE); |
914 | 0 | LZ4_setCompressionLevel((LZ4_streamHC_t*)state, level); |
915 | 0 | } |
916 | 0 | } |
917 | | |
918 | 0 | size_t LZ4F_cctx_size(const LZ4F_cctx* cctx) { |
919 | 0 | if (cctx == NULL) { |
920 | 0 | return 0; |
921 | 0 | } |
922 | 0 | return sizeof(*cctx) + cctx->tmpBuffCapacity + cctx->stageCapacity + LZ4F_sizeofLZ4State((LZ4F_CtxType_e)cctx->lz4CtxAlloc) |
923 | 0 | + (cctx->rawDictFast ? sizeof(LZ4_stream_t) : 0) + (cctx->rawDictHC ? sizeof(LZ4_streamHC_t) : 0) |
924 | 0 | + LZ4F_mt_sizeof(cctx->mt); |
925 | 0 | } |
926 | | |
927 | | /* LZ4F_digestRawDict() : |
928 | | * digests @dictBuffer within states owned by @cctx, without copying it (it must outlive the compression session), |
929 | | * for the compression level of current frame, which then employs it as a CDict. |
930 | | * Since it's done for each frame, fast levels employ LZ4_loadDict(), faster than LZ4F_createCDict()'s LZ4_loadDictSlow(). |
931 | | * HC levels digest it for the frame's level : level 2 (lz4mid) has its own format, |
932 | | * which a CDict (digested at default level) lacks. |
933 | | * @return : CDict, or NULL if allocation failed */ |
934 | | static const LZ4F_CDict* LZ4F_digestRawDict(LZ4F_cctx_t* cctx, const void* dictBuffer, size_t dictSize) |
935 | 0 | { |
936 | 0 | const char* dictStart = (const char*)dictBuffer; |
937 | 0 | if (dictSize > 64 KB) { |
938 | 0 | dictStart += dictSize - 64 KB; |
939 | 0 | dictSize = 64 KB; |
940 | 0 | } |
941 | 0 | cctx->rawDict.cmem = cctx->cmem; |
942 | 0 | cctx->rawDict.dictContent = NULL; |
943 | 0 | cctx->rawDict.fastCtx = NULL; |
944 | 0 | cctx->rawDict.HCCtx = NULL; |
945 | 0 | if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) { |
946 | 0 | if (cctx->rawDictFast == NULL) cctx->rawDictFast = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cctx->cmem); |
947 | 0 | if (cctx->rawDictFast == NULL) return NULL; |
948 | 0 | LZ4_initStream(cctx->rawDictFast, sizeof(LZ4_stream_t)); |
949 | 0 | LZ4_loadDict(cctx->rawDictFast, dictStart, (int)dictSize); |
950 | 0 | cctx->rawDict.fastCtx = cctx->rawDictFast; |
951 | 0 | } else { |
952 | 0 | if (cctx->rawDictHC == NULL) cctx->rawDictHC = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cctx->cmem); |
953 | 0 | if (cctx->rawDictHC == NULL) return NULL; |
954 | 0 | LZ4_initStreamHC(cctx->rawDictHC, sizeof(LZ4_streamHC_t)); |
955 | 0 | LZ4_setCompressionLevel(cctx->rawDictHC, cctx->prefs.compressionLevel); |
956 | 0 | LZ4_loadDictHC(cctx->rawDictHC, dictStart, (int)dictSize); |
957 | 0 | cctx->rawDict.HCCtx = cctx->rawDictHC; |
958 | 0 | } |
959 | 0 | return &cctx->rawDict; |
960 | 0 | } |
961 | | |
962 | | /* LZ4F_compressBegin_internal() |
963 | | * Note: only accepts @cdict _or_ @dictBuffer as non NULL. |
964 | | */ |
965 | | static size_t LZ4F_compressBegin_internal(LZ4F_cctx* cctx, |
966 | | void* dstBuffer, size_t dstCapacity, |
967 | | const void* dictBuffer, size_t dictSize, |
968 | | const LZ4F_CDict* cdict, |
969 | | const LZ4F_preferences_t* preferencesPtr) |
970 | 0 | { |
971 | 0 | LZ4F_preferences_t const prefNull = LZ4F_INIT_PREFERENCES; |
972 | 0 | BYTE* const dstStart = (BYTE*)dstBuffer; |
973 | 0 | BYTE* dstPtr = dstStart; |
974 | 0 | int mtFrame; /* frame cut into jobs (multi-threaded compression) */ |
975 | |
|
976 | 0 | if (preferencesPtr == NULL) preferencesPtr = &prefNull; |
977 | | /* validate arguments before modifying @cctx : when they are rejected, a frame in progress continues */ |
978 | 0 | { size_t const headerSize = minFHSize |
979 | 0 | + (preferencesPtr->frameInfo.contentSize ? 8 : 0) |
980 | 0 | + (preferencesPtr->frameInfo.dictID ? 4 : 0); |
981 | 0 | RETURN_ERROR_IF(dstCapacity < headerSize, dstCapacity_tooSmall); |
982 | 0 | } |
983 | 0 | FORWARD_IF_ERROR( LZ4F_getBlockSize(preferencesPtr->frameInfo.blockSizeID) ); |
984 | 0 | RETURN_ERROR_IF(dictSize > INT_MAX, parameter_invalid); |
985 | | /* from now on, a failure (allocation) leaves no frame in progress */ |
986 | 0 | LZ4F_invalidateFrame(cctx); /* jobs of an abandoned frame : must complete before @cctx is modified */ |
987 | 0 | cctx->mtActive = 0; |
988 | 0 | cctx->flushStage = 0; |
989 | 0 | cctx->pendingSize = 0; |
990 | 0 | cctx->prefs = *preferencesPtr; |
991 | 0 | mtFrame = LZ4F_mtEligible(&cctx->prefs); |
992 | 0 | DEBUGLOG(5, "LZ4F_compressBegin_internal: Independent_blocks=%u", cctx->prefs.frameInfo.blockMode); |
993 | | |
994 | | /* cctx Management */ |
995 | 0 | { LZ4F_CtxType_e const ctxType = (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? ctxFast : ctxHC; |
996 | 0 | size_t const requiredSize = LZ4F_sizeofLZ4State(ctxType); |
997 | 0 | size_t const allocatedSize = LZ4F_sizeofLZ4State((LZ4F_CtxType_e)cctx->lz4CtxAlloc); |
998 | 0 | if (allocatedSize < requiredSize) { |
999 | | /* not enough space allocated : must take ownership of memory allocation, |
1000 | | * in order to respect custom allocator contract */ |
1001 | 0 | LZ4F_free(cctx->lz4CtxPtr, cctx->cmem); |
1002 | 0 | cctx->lz4CtxAlloc = (U16)ctxNone; /* in case allocation fails */ |
1003 | 0 | cctx->lz4CtxPtr = LZ4F_malloc(requiredSize, cctx->cmem); |
1004 | 0 | RETURN_ERROR_IF(cctx->lz4CtxPtr == NULL, allocation_failed); |
1005 | 0 | cctx->lz4CtxAlloc = (U16)ctxType; |
1006 | 0 | cctx->lz4CtxType = (U16)ctxNone; /* not initialized yet */ |
1007 | 0 | } |
1008 | 0 | if (cctx->lz4CtxType != ctxType) { |
1009 | | /* initialize the state for the correct context type */ |
1010 | 0 | LZ4F_initLZ4State(cctx->lz4CtxPtr, ctxType, cctx->prefs.compressionLevel); |
1011 | 0 | cctx->lz4CtxType = (U16)ctxType; |
1012 | 0 | } } |
1013 | | |
1014 | | /* raw dictionary : employed by each block as a CDict (independent blocks, or jobs of multi-threaded frames) ; |
1015 | | * single-threaded linked blocks keep the historical behavior : dictionary loaded as history, preceding the first block, |
1016 | | * from a copy within @tmpBuff (see below) */ |
1017 | 0 | if ( dictBuffer |
1018 | 0 | && ((cctx->prefs.frameInfo.blockMode == LZ4F_blockIndependent) || mtFrame) ) { |
1019 | 0 | assert(cdict == NULL); |
1020 | 0 | cdict = LZ4F_digestRawDict(cctx, dictBuffer, dictSize); |
1021 | 0 | RETURN_ERROR_IF(cdict == NULL, allocation_failed); |
1022 | 0 | dictBuffer = NULL; |
1023 | 0 | dictSize = 0; |
1024 | 0 | } |
1025 | | |
1026 | | /* Buffer Management */ |
1027 | 0 | if (cctx->prefs.frameInfo.blockSizeID == 0) |
1028 | 0 | cctx->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT; |
1029 | 0 | cctx->maxBlockSize = LZ4F_getBlockSize(cctx->prefs.frameInfo.blockSizeID); |
1030 | |
|
1031 | 0 | { size_t const requiredBuffSize = mtFrame ? 0 : /* jobs employ their own buffers */ |
1032 | 0 | preferencesPtr->autoFlush ? |
1033 | 0 | ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0) : /* history, then inputs < 64 KB (see LZ4F_st_update()) */ |
1034 | 0 | cctx->maxBlockSize + ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0); |
1035 | |
|
1036 | 0 | if (cctx->tmpBuffCapacity < requiredBuffSize) { |
1037 | 0 | cctx->tmpBuffCapacity = 0; |
1038 | 0 | LZ4F_free(cctx->tmpBuff, cctx->cmem); |
1039 | 0 | cctx->tmpBuff = (BYTE*)LZ4F_malloc(requiredBuffSize, cctx->cmem); |
1040 | 0 | RETURN_ERROR_IF(cctx->tmpBuff == NULL, allocation_failed); |
1041 | 0 | cctx->tmpBuffCapacity = requiredBuffSize; |
1042 | 0 | } } |
1043 | 0 | cctx->tmpIn = cctx->tmpBuff; |
1044 | 0 | cctx->tmpInSize = 0; |
1045 | 0 | if (dictBuffer) { |
1046 | | /* single-threaded linked blocks : the dictionary is copied into @tmpBuff, as saved history : |
1047 | | * buffered input follows it, and references it in prefix mode |
1048 | | * (faster than an external dictionary, which fast levels also lose after the first block) */ |
1049 | 0 | if (dictSize > 64 KB) { |
1050 | 0 | dictBuffer = (const BYTE*)dictBuffer + dictSize - 64 KB; |
1051 | 0 | dictSize = 64 KB; |
1052 | 0 | } |
1053 | 0 | assert(cctx->tmpBuffCapacity >= 128 KB); |
1054 | 0 | LZ4_memcpy(cctx->tmpBuff, dictBuffer, dictSize); |
1055 | 0 | dictBuffer = cctx->tmpBuff; |
1056 | 0 | cctx->tmpIn = cctx->tmpBuff + dictSize; |
1057 | 0 | } |
1058 | 0 | (void)XXH32_reset(&(cctx->xxh), 0); |
1059 | | |
1060 | | /* context init */ |
1061 | 0 | cctx->cdict = cdict; |
1062 | 0 | cctx->blockCompressMode = LZ4B_COMPRESSED; /* a frame starts with the LZ4 state just initialized (dictionary included) */ |
1063 | 0 | LZ4F_startStream(cctx->lz4CtxPtr, &cctx->prefs, cdict, dictBuffer, dictSize); |
1064 | | |
1065 | | /* Stage 2 : Write Frame Header */ |
1066 | | |
1067 | | /* Magic Number */ |
1068 | 0 | LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER); |
1069 | 0 | dstPtr += 4; |
1070 | 0 | { BYTE* const headerStart = dstPtr; |
1071 | | |
1072 | | /* FLG Byte */ |
1073 | 0 | *dstPtr++ = (BYTE)(((1 & _2BITS) << 6) /* Version('01') */ |
1074 | 0 | + ((cctx->prefs.frameInfo.blockMode & _1BIT ) << 5) |
1075 | 0 | + ((cctx->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4) |
1076 | 0 | + ((unsigned)(cctx->prefs.frameInfo.contentSize > 0) << 3) |
1077 | 0 | + ((cctx->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2) |
1078 | 0 | + (cctx->prefs.frameInfo.dictID > 0) ); |
1079 | | /* BD Byte */ |
1080 | 0 | *dstPtr++ = (BYTE)((cctx->prefs.frameInfo.blockSizeID & _3BITS) << 4); |
1081 | | /* Optional Frame content size field */ |
1082 | 0 | if (cctx->prefs.frameInfo.contentSize) { |
1083 | 0 | LZ4F_writeLE64(dstPtr, cctx->prefs.frameInfo.contentSize); |
1084 | 0 | dstPtr += 8; |
1085 | 0 | cctx->totalInSize = 0; |
1086 | 0 | } |
1087 | | /* Optional dictionary ID field */ |
1088 | 0 | if (cctx->prefs.frameInfo.dictID) { |
1089 | 0 | LZ4F_writeLE32(dstPtr, cctx->prefs.frameInfo.dictID); |
1090 | 0 | dstPtr += 4; |
1091 | 0 | } |
1092 | | /* Header CRC Byte */ |
1093 | 0 | *dstPtr = LZ4F_headerChecksum(headerStart, (size_t)(dstPtr - headerStart)); |
1094 | 0 | dstPtr++; |
1095 | 0 | } |
1096 | |
|
1097 | 0 | if (mtFrame) { |
1098 | 0 | assert(dictBuffer == NULL); |
1099 | 0 | FORWARD_IF_ERROR( LZ4F_mt_begin(cctx) ); |
1100 | 0 | } |
1101 | | |
1102 | 0 | cctx->cStage = 1; /* header written, now request input data block */ |
1103 | 0 | return (size_t)(dstPtr - dstStart); |
1104 | 0 | } |
1105 | | |
1106 | | size_t LZ4F_compressBegin(LZ4F_cctx* cctx, |
1107 | | void* dstBuffer, size_t dstCapacity, |
1108 | | const LZ4F_preferences_t* preferencesPtr) |
1109 | 0 | { |
1110 | 0 | return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity, |
1111 | 0 | NULL, 0, |
1112 | 0 | NULL, preferencesPtr); |
1113 | 0 | } |
1114 | | |
1115 | | size_t LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx, |
1116 | | void* dstBuffer, size_t dstCapacity, |
1117 | | const void* dict, size_t dictSize, |
1118 | | const LZ4F_preferences_t* preferencesPtr) |
1119 | 0 | { |
1120 | 0 | return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity, |
1121 | 0 | dict, dictSize, |
1122 | 0 | NULL, preferencesPtr); |
1123 | 0 | } |
1124 | | |
1125 | | size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx, |
1126 | | void* dstBuffer, size_t dstCapacity, |
1127 | | const LZ4F_CDict* cdict, |
1128 | | const LZ4F_preferences_t* preferencesPtr) |
1129 | 0 | { |
1130 | 0 | return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity, |
1131 | 0 | NULL, 0, |
1132 | 0 | cdict, preferencesPtr); |
1133 | 0 | } |
1134 | | |
1135 | | |
1136 | | /* LZ4F_compressBound() : |
1137 | | * @return minimum capacity of dstBuffer for a given srcSize to handle worst case scenario. |
1138 | | * LZ4F_preferences_t structure is optional : if NULL, preferences will be set to cover worst case scenario. |
1139 | | * This function cannot fail. |
1140 | | */ |
1141 | | size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr) |
1142 | 0 | { |
1143 | 0 | size_t bound; |
1144 | 0 | size_t const blockCRCSize = preferencesPtr |
1145 | 0 | ? BFSize * preferencesPtr->frameInfo.blockChecksumFlag |
1146 | 0 | : BFSize; |
1147 | 0 | if (preferencesPtr && !preferencesPtr->autoFlush && LZ4F_mtEligible(preferencesPtr)) { |
1148 | | /* frame cut into jobs : output can lag behind input */ |
1149 | 0 | return LZ4F_mtCompressBound(srcSize, preferencesPtr); |
1150 | 0 | } |
1151 | 0 | if (preferencesPtr && preferencesPtr->autoFlush) { |
1152 | | /* + 1 : output of LZ4F_flush() and LZ4F_compressEnd() remains strictly below LZ4F_compressBound(0), |
1153 | | * since a filled dstBuffer means more output may remain */ |
1154 | 0 | return LZ4F_compressBound_autoFlush(srcSize, preferencesPtr) + (srcSize == 0); |
1155 | 0 | } |
1156 | | /* single-threaded : full blocks only, each one stored uncompressed in worst case. |
1157 | | * Up to (blockSize-1) bytes can already be buffered : srcSize completes at most srcSize/blockSize + 1 blocks. |
1158 | | * The buffered block can also be emitted separately (mode switch), or remain from an incomplete LZ4F_flush() : |
1159 | | * then, srcSize completes at most srcSize/blockSize blocks. |
1160 | | * @srcSize == 0 : LZ4F_flush() and LZ4F_compressEnd() emit the buffered block (< blockSize bytes : output |
1161 | | * remains strictly below the bound, so that a single invocation completes them), then the frame footer. |
1162 | | * The frame footer is always included, so that the bound grows with @srcSize. */ |
1163 | 0 | { size_t const bs = LZ4F_getBlockSize(preferencesPtr ? preferencesPtr->frameInfo.blockSizeID : LZ4F_default); |
1164 | 0 | size_t const blockSize = LZ4F_isError(bs) ? 4 MB : bs; |
1165 | 0 | size_t const contentCRCSize = preferencesPtr |
1166 | 0 | ? BFSize * preferencesPtr->frameInfo.contentChecksumFlag |
1167 | 0 | : BFSize; |
1168 | 0 | size_t const nbBlocks = srcSize / blockSize + 1; |
1169 | 0 | bound = nbBlocks * (blockSize + BHSize + blockCRCSize) + BHSize + contentCRCSize; |
1170 | 0 | } |
1171 | 0 | return bound; |
1172 | 0 | } |
1173 | | |
1174 | | |
1175 | | typedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level, const LZ4F_CDict* cdict); |
1176 | | |
1177 | | |
1178 | | /*! LZ4F_makeBlock(): |
1179 | | * compress a single block, add header and optional checksum. |
1180 | | * The block is stored uncompressed when compression doesn't save space. |
1181 | | * @return : size of the block written into @dst, |
1182 | | * or an error code if it doesn't fit into @dstCapacity. |
1183 | | * Note : success is guaranteed when dstCapacity >= BHSize + srcSize + crcSize |
1184 | | */ |
1185 | | static size_t LZ4F_makeBlock(void* dst, size_t dstCapacity, |
1186 | | const void* src, size_t srcSize, |
1187 | | compressFunc_t compress, void* lz4ctx, int level, |
1188 | | const LZ4F_CDict* cdict, |
1189 | | LZ4F_blockChecksum_t crcFlag) |
1190 | 0 | { |
1191 | 0 | BYTE* const cSizePtr = (BYTE*)dst; |
1192 | 0 | size_t const overhead = BHSize + (size_t)crcFlag * BFSize; |
1193 | 0 | int cCapacity = (srcSize > 1) ? (int)srcSize - 1 : 1; |
1194 | 0 | U32 cSize; |
1195 | 0 | assert(compress != NULL); |
1196 | 0 | assert(srcSize > 0); |
1197 | 0 | RETURN_ERROR_IF(dstCapacity <= overhead, dstCapacity_tooSmall); |
1198 | 0 | if (dstCapacity - overhead < (size_t)cCapacity) |
1199 | 0 | cCapacity = (int)(dstCapacity - overhead); |
1200 | 0 | cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+BHSize), |
1201 | 0 | (int)srcSize, cCapacity, |
1202 | 0 | level, cdict); |
1203 | |
|
1204 | 0 | if (cSize == 0 || cSize >= srcSize) { |
1205 | 0 | RETURN_ERROR_IF(dstCapacity - overhead < srcSize, dstCapacity_tooSmall); |
1206 | 0 | cSize = (U32)srcSize; |
1207 | 0 | LZ4F_writeLE32(cSizePtr, cSize | LZ4F_BLOCKUNCOMPRESSED_FLAG); |
1208 | 0 | LZ4_memcpy(cSizePtr+BHSize, src, srcSize); |
1209 | 0 | } else { |
1210 | 0 | LZ4F_writeLE32(cSizePtr, cSize); |
1211 | 0 | } |
1212 | 0 | if (crcFlag) { |
1213 | 0 | U32 const crc32 = XXH32(cSizePtr+BHSize, cSize, 0); /* checksum of compressed data */ |
1214 | 0 | LZ4F_writeLE32(cSizePtr+BHSize+cSize, crc32); |
1215 | 0 | } |
1216 | 0 | return BHSize + cSize + ((U32)crcFlag)*BFSize; |
1217 | 0 | } |
1218 | | |
1219 | | /*! LZ4F_compressBlocks_internal(): |
1220 | | * compress @src as a sequence of blocks of @blockSize bytes (the last one can be smaller), |
1221 | | * each with its header and optional checksum, but without frame header, endMark nor content checksum. |
1222 | | * @lz4ctx must be prepared for @compress : |
1223 | | * linked blocks continue the stream, so they need a state initialized at frame start (or with a prefix). |
1224 | | * @return : nb of bytes written into @dst, |
1225 | | * or an error code if it doesn't fit into @dstCapacity. |
1226 | | * Note : success is guaranteed when dstCapacity >= srcSize + nbBlocks * (BHSize + crcFlag * BFSize) |
1227 | | */ |
1228 | | static size_t LZ4F_compressBlocks_internal(void* dst, size_t dstCapacity, |
1229 | | const void* src, size_t srcSize, size_t blockSize, |
1230 | | compressFunc_t compress, void* lz4ctx, int level, |
1231 | | const LZ4F_CDict* cdict, |
1232 | | LZ4F_blockChecksum_t crcFlag) |
1233 | 0 | { |
1234 | 0 | const BYTE* ip = (const BYTE*)src; |
1235 | 0 | const BYTE* const iend = srcSize ? ip + srcSize : ip; |
1236 | 0 | BYTE* const ostart = (BYTE*)dst; |
1237 | 0 | BYTE* op = ostart; |
1238 | 0 | BYTE* const oend = dstCapacity ? ostart + dstCapacity : ostart; |
1239 | |
|
1240 | 0 | while (ip < iend) { |
1241 | 0 | size_t const bSize = MIN(blockSize, (size_t)(iend - ip)); |
1242 | 0 | size_t const cSize = LZ4F_makeBlock(op, (size_t)(oend - op), |
1243 | 0 | ip, bSize, |
1244 | 0 | compress, lz4ctx, level, |
1245 | 0 | cdict, crcFlag); |
1246 | 0 | FORWARD_IF_ERROR(cSize); |
1247 | 0 | ip += bSize; |
1248 | 0 | op += cSize; |
1249 | 0 | } |
1250 | 0 | return (size_t)(op - ostart); |
1251 | 0 | } |
1252 | | |
1253 | | |
1254 | | /* Negative compression levels select LZ4 "fast" mode, with acceleration = -level + 1. |
1255 | | * Acceleration is capped at LZ4_ACCELERATION_MAX before this computation, |
1256 | | * which would overflow for INT_MIN and INT_MIN+1. */ |
1257 | | static int LZ4F_levelToAcceleration(int level) |
1258 | 0 | { |
1259 | 0 | if (level >= 0) return 1; |
1260 | 0 | if (level < 1 - LZ4_ACCELERATION_MAX) return LZ4_ACCELERATION_MAX; |
1261 | 0 | return -level + 1; |
1262 | 0 | } |
1263 | | |
1264 | | static int LZ4F_compressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) |
1265 | 0 | { |
1266 | 0 | int const acceleration = LZ4F_levelToAcceleration(level); |
1267 | 0 | DEBUGLOG(5, "LZ4F_compressBlock (srcSize=%i)", srcSize); |
1268 | 0 | LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent); |
1269 | 0 | if (cdict) { |
1270 | 0 | return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration); |
1271 | 0 | } else { |
1272 | 0 | return LZ4_compress_fast_extState_fastReset(ctx, src, dst, srcSize, dstCapacity, acceleration); |
1273 | 0 | } |
1274 | 0 | } |
1275 | | |
1276 | | static int LZ4F_compressBlock_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) |
1277 | 0 | { |
1278 | 0 | int const acceleration = LZ4F_levelToAcceleration(level); |
1279 | 0 | (void)cdict; /* init once at beginning of frame */ |
1280 | 0 | DEBUGLOG(5, "LZ4F_compressBlock_continue (srcSize=%i)", srcSize); |
1281 | 0 | return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration); |
1282 | 0 | } |
1283 | | |
1284 | | static int LZ4F_compressBlockHC(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) |
1285 | 0 | { |
1286 | 0 | LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent); |
1287 | 0 | if (cdict) { |
1288 | 0 | return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity); |
1289 | 0 | } |
1290 | 0 | return LZ4_compress_HC_extStateHC_fastReset(ctx, src, dst, srcSize, dstCapacity, level); |
1291 | 0 | } |
1292 | | |
1293 | | static int LZ4F_compressBlockHC_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) |
1294 | 0 | { |
1295 | 0 | (void)level; (void)cdict; /* init once at beginning of frame */ |
1296 | 0 | return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity); |
1297 | 0 | } |
1298 | | |
1299 | | static int LZ4F_doNotCompressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) |
1300 | 0 | { |
1301 | 0 | (void)ctx; (void)src; (void)dst; (void)srcSize; (void)dstCapacity; (void)level; (void)cdict; |
1302 | 0 | return 0; |
1303 | 0 | } |
1304 | | |
1305 | | static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_BlockCompressMode_e compressMode) |
1306 | 0 | { |
1307 | 0 | if (compressMode == LZ4B_UNCOMPRESSED) |
1308 | 0 | return LZ4F_doNotCompressBlock; |
1309 | 0 | if (level < LZ4HC_CLEVEL_MIN) { |
1310 | 0 | if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock; |
1311 | 0 | return LZ4F_compressBlock_continue; |
1312 | 0 | } |
1313 | 0 | if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlockHC; |
1314 | 0 | return LZ4F_compressBlockHC_continue; |
1315 | 0 | } |
1316 | | |
1317 | | /* Save or shorten history (up to 64KB) into @tmpBuff */ |
1318 | | static void LZ4F_localSaveDict(LZ4F_cctx_t* cctxPtr) |
1319 | 0 | { |
1320 | 0 | int const dictSize = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? |
1321 | 0 | LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB) : |
1322 | 0 | LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB); |
1323 | 0 | cctxPtr->tmpIn = cctxPtr->tmpBuff + dictSize; |
1324 | 0 | } |
1325 | | |
1326 | | typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus; |
1327 | | |
1328 | | static const LZ4F_compressOptions_t k_cOptionsNull = { 0, 0, 0, 0 }; |
1329 | | |
1330 | | /*-*************************************************** |
1331 | | * Output not fitting into dstBuffer yet (LZ4F_flush(), LZ4F_compressEnd()) |
1332 | | *****************************************************/ |
1333 | | |
1334 | | /* stageBuff holds one block, stored uncompressed in worst case. |
1335 | | * @return : 0, or an error code (allocation_failed) */ |
1336 | | static size_t LZ4F_reserveStage(LZ4F_cctx_t* cctx) |
1337 | 0 | { |
1338 | 0 | size_t const needed = cctx->maxBlockSize + BHSize + BFSize; |
1339 | 0 | if (cctx->stageCapacity >= needed) return 0; |
1340 | 0 | LZ4F_free(cctx->stageBuff, cctx->cmem); |
1341 | 0 | cctx->stageCapacity = 0; |
1342 | 0 | cctx->stageBuff = (BYTE*)LZ4F_malloc(needed, cctx->cmem); |
1343 | 0 | RETURN_ERROR_IF(cctx->stageBuff == NULL, allocation_failed); |
1344 | 0 | cctx->stageCapacity = needed; |
1345 | 0 | return 0; |
1346 | 0 | } |
1347 | | |
1348 | | /* copies pending output into @dst + @pos, as much as fits. |
1349 | | * @return : nb of bytes copied */ |
1350 | | static size_t LZ4F_copyPending(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity, size_t pos) |
1351 | 0 | { |
1352 | 0 | size_t const n = MIN(cctx->pendingSize, dstCapacity - pos); |
1353 | 0 | assert(pos <= dstCapacity); |
1354 | 0 | if (n) { |
1355 | 0 | LZ4_memcpy(dst + pos, cctx->pending, n); |
1356 | 0 | cctx->pending += n; |
1357 | 0 | } |
1358 | 0 | cctx->pendingSize -= n; |
1359 | 0 | return n; |
1360 | 0 | } |
1361 | | |
1362 | | /* compression operations first emit output left pending by an incomplete LZ4F_flush(), |
1363 | | * entirely, since they must succeed : the flush ends there. |
1364 | | * @return : nb of bytes written into @dst, or an error code (callers invalidate the frame) */ |
1365 | | static size_t LZ4F_emitPendingWhole(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity) |
1366 | 0 | { |
1367 | 0 | cctx->flushStage = 0; |
1368 | 0 | RETURN_ERROR_IF(cctx->pendingSize > dstCapacity, dstCapacity_tooSmall); |
1369 | 0 | return LZ4F_copyPending(cctx, dst, dstCapacity, 0); |
1370 | 0 | } |
1371 | | |
1372 | | /*! LZ4F_flushBlock() : |
1373 | | * compresses input buffered within cctx (single-threaded mode), if any, into @dst. |
1374 | | * @return : nb of bytes written into @dst, or an error code (the frame is then invalidated) */ |
1375 | | static size_t LZ4F_flushBlock(LZ4F_cctx_t* cctxPtr, void* dstBuffer, size_t dstCapacity) |
1376 | 0 | { |
1377 | 0 | compressFunc_t compress; |
1378 | 0 | size_t cSize; |
1379 | |
|
1380 | 0 | DEBUGLOG(5, "LZ4F_flushBlock: %zu buffered bytes (saved dict size = %i) (dstCapacity=%u)", |
1381 | 0 | cctxPtr->tmpInSize, (int)(cctxPtr->tmpIn - cctxPtr->tmpBuff), (unsigned)dstCapacity); |
1382 | 0 | if (cctxPtr->tmpInSize == 0) return 0; /* nothing to flush */ |
1383 | | |
1384 | | /* select compression function */ |
1385 | 0 | compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompressMode); |
1386 | | |
1387 | | /* compress tmp buffer */ |
1388 | 0 | cSize = LZ4F_makeBlock(dstBuffer, dstCapacity, |
1389 | 0 | cctxPtr->tmpIn, cctxPtr->tmpInSize, |
1390 | 0 | compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, |
1391 | 0 | cctxPtr->cdict, |
1392 | 0 | cctxPtr->prefs.frameInfo.blockChecksumFlag); |
1393 | 0 | FORWARD_IF_ERROR_INVALIDATE(cSize, cctxPtr); |
1394 | 0 | assert(((void)"flush overflows dstBuffer!", cSize <= dstCapacity)); |
1395 | |
|
1396 | 0 | if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) |
1397 | 0 | cctxPtr->tmpIn += cctxPtr->tmpInSize; |
1398 | 0 | cctxPtr->tmpInSize = 0; |
1399 | | |
1400 | | /* keep tmpIn within limits */ |
1401 | 0 | if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity)) { |
1402 | 0 | assert(cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked); |
1403 | 0 | LZ4F_localSaveDict(cctxPtr); |
1404 | 0 | } |
1405 | |
|
1406 | 0 | return cSize; |
1407 | 0 | } |
1408 | | |
1409 | | /* flush point, single-threaded mode : the buffered block is compressed into @dst when it fits in any case, |
1410 | | * otherwise into stageBuff, as pending output. Same output : compression capacity is the same. |
1411 | | * @return : nb of bytes written into @dst, or an error code (the frame is then invalidated) */ |
1412 | | static size_t LZ4F_flushBlockPartial(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity) |
1413 | 0 | { |
1414 | 0 | size_t const worstCase = cctx->tmpInSize + BHSize + (size_t)cctx->prefs.frameInfo.blockChecksumFlag * BFSize; |
1415 | 0 | size_t cSize; |
1416 | 0 | if ((cctx->tmpInSize == 0) || (dstCapacity >= worstCase)) |
1417 | 0 | return LZ4F_flushBlock(cctx, dst, dstCapacity); |
1418 | 0 | FORWARD_IF_ERROR_INVALIDATE(LZ4F_reserveStage(cctx), cctx); |
1419 | 0 | cSize = LZ4F_flushBlock(cctx, cctx->stageBuff, cctx->stageCapacity); |
1420 | 0 | FORWARD_IF_ERROR(cSize); /* already invalidated */ |
1421 | 0 | cctx->pending = cctx->stageBuff; |
1422 | 0 | cctx->pendingSize = cSize; |
1423 | 0 | return 0; |
1424 | 0 | } |
1425 | | |
1426 | | |
1427 | | /*-*************************************************** |
1428 | | * Multi-threaded compression |
1429 | | *****************************************************/ |
1430 | | /* When prefs.nbWorkers >= 1, input is cut into jobs (see LZ4F_mtJobSize()). |
1431 | | * Jobs are compressed by a pool of worker threads, kept within cctx, |
1432 | | * and their outputs are emitted in order by the calling thread. |
1433 | | * Output only depends on content and flush points : |
1434 | | * never on nb of workers, scheduling, input slicing, nor stableSrc. |
1435 | | * nbWorkers is the nb of worker threads compressing jobs : the calling thread fills and emits them. |
1436 | | * With a content checksum, one more thread hashes jobs, in order (see LZ4F_mt_hashJob()). |
1437 | | * At a flush point (LZ4F_flush(), LZ4F_compressEnd(), autoFlush), it waits for all jobs : when no other job is running, |
1438 | | * it compresses the flushed job itself. So at most nbWorkers threads compress at any time. |
1439 | | * Without multi-threading support (LZ4F_MULTITHREAD), the calling thread processes jobs alone, producing the same output. |
1440 | | * If no worker thread can be created, frame compression fails (allocation_failed) ; |
1441 | | * with fewer threads than requested (ex: system limits), it proceeds with them. */ |
1442 | | |
1443 | | /*! LZ4F_compressJob() : |
1444 | | * compress one job, as a sequence of blocks (stored uncompressed when @mode == LZ4B_UNCOMPRESSED). |
1445 | | * With linked blocks, each job restarts the stream, using as dictionary |
1446 | | * the @prefixSize bytes of history right before @src, |
1447 | | * or @cdict for the first job of the frame (@prefixSize == 0). |
1448 | | * Output doesn't depend on @lz4ctx history. |
1449 | | * @return : nb of bytes written into @dst, or an error code */ |
1450 | | static size_t LZ4F_compressJob(void* lz4ctx, const LZ4F_preferences_t* prefs, |
1451 | | const LZ4F_CDict* cdict, size_t blockSize, |
1452 | | void* dst, size_t dstCapacity, |
1453 | | const BYTE* src, size_t srcSize, size_t prefixSize, |
1454 | | LZ4F_BlockCompressMode_e mode) |
1455 | 0 | { |
1456 | 0 | int const level = prefs->compressionLevel; |
1457 | 0 | LZ4F_blockMode_t const blockMode = prefs->frameInfo.blockMode; |
1458 | |
|
1459 | 0 | if (mode == LZ4B_UNCOMPRESSED) { /* LZ4F_compressOptions_t.uncompressed */ |
1460 | 0 | return LZ4F_compressBlocks_internal(dst, dstCapacity, src, srcSize, blockSize, |
1461 | 0 | LZ4F_doNotCompressBlock, NULL, 0, NULL, |
1462 | 0 | prefs->frameInfo.blockChecksumFlag); |
1463 | 0 | } |
1464 | | |
1465 | 0 | assert(prefixSize <= LZ4F_MT_PREFIX_SIZE); |
1466 | 0 | if (prefixSize) { |
1467 | 0 | LZ4F_startStream(lz4ctx, prefs, NULL, src - prefixSize, prefixSize); |
1468 | 0 | } else { |
1469 | 0 | LZ4F_startStream(lz4ctx, prefs, cdict, NULL, 0); |
1470 | 0 | } |
1471 | |
|
1472 | 0 | return LZ4F_compressBlocks_internal(dst, dstCapacity, |
1473 | 0 | src, srcSize, blockSize, |
1474 | 0 | LZ4F_selectCompression(blockMode, level, LZ4B_COMPRESSED), |
1475 | 0 | lz4ctx, level, cdict, |
1476 | 0 | prefs->frameInfo.blockChecksumFlag); |
1477 | 0 | } |
1478 | | |
1479 | | typedef void (*LZ4F_job_f)(void* arg, unsigned workerID); |
1480 | | typedef struct LZ4F_pool_s LZ4F_pool_t; |
1481 | | |
1482 | | #if LZ4F_MULTITHREAD |
1483 | | |
1484 | | #if defined(_WIN32) |
1485 | | # ifndef WIN32_LEAN_AND_MEAN |
1486 | | # define WIN32_LEAN_AND_MEAN |
1487 | | # endif |
1488 | | /* condition variables require Windows Vista+ ; _WIN32_WINNT may already be defined lower, |
1489 | | * ex: by <_mingw.h> (included by standard headers) on older mingw-w64 (0x502) */ |
1490 | | # if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0600) |
1491 | | # if defined(_WINDOWS_) /* <windows.h> already included (ex: amalgamated sources), without them */ |
1492 | | # error "LZ4F_MULTITHREAD requires Windows Vista API : define _WIN32_WINNT >= 0x0600 before including <windows.h>, or disable LZ4F_MULTITHREAD" |
1493 | | # endif |
1494 | | # undef _WIN32_WINNT |
1495 | | # define _WIN32_WINNT 0x0600 |
1496 | | # endif |
1497 | | # include <windows.h> |
1498 | | typedef HANDLE LZ4F_thread_t; |
1499 | | typedef CRITICAL_SECTION LZ4F_mutex_t; |
1500 | | typedef CONDITION_VARIABLE LZ4F_cond_t; |
1501 | | # define LZ4F_mutex_init(m) (InitializeCriticalSection(m), 0) |
1502 | | # define LZ4F_mutex_destroy(m) DeleteCriticalSection(m) |
1503 | | # define LZ4F_mutex_lock(m) EnterCriticalSection(m) |
1504 | | # define LZ4F_mutex_unlock(m) LeaveCriticalSection(m) |
1505 | | # define LZ4F_cond_init(c) (InitializeConditionVariable(c), 0) |
1506 | | # define LZ4F_cond_destroy(c) ((void)(c)) |
1507 | | # define LZ4F_cond_wait(c, m) SleepConditionVariableCS((c), (m), INFINITE) |
1508 | | # define LZ4F_cond_signal(c) WakeConditionVariable(c) |
1509 | | # define LZ4F_cond_broadcast(c) WakeAllConditionVariable(c) |
1510 | | #else |
1511 | | # include <pthread.h> |
1512 | | # include <signal.h> |
1513 | | typedef pthread_t LZ4F_thread_t; |
1514 | | typedef pthread_mutex_t LZ4F_mutex_t; |
1515 | | typedef pthread_cond_t LZ4F_cond_t; |
1516 | | # define LZ4F_mutex_init(m) pthread_mutex_init((m), NULL) |
1517 | | # define LZ4F_mutex_destroy(m) pthread_mutex_destroy(m) |
1518 | | # define LZ4F_mutex_lock(m) pthread_mutex_lock(m) |
1519 | | # define LZ4F_mutex_unlock(m) pthread_mutex_unlock(m) |
1520 | | # define LZ4F_cond_init(c) pthread_cond_init((c), NULL) |
1521 | | # define LZ4F_cond_destroy(c) pthread_cond_destroy(c) |
1522 | | # define LZ4F_cond_wait(c, m) pthread_cond_wait((c), (m)) |
1523 | | # define LZ4F_cond_signal(c) pthread_cond_signal(c) |
1524 | | # define LZ4F_cond_broadcast(c) pthread_cond_broadcast(c) |
1525 | | /* worker threads must not receive process-directed signals intended for the application, |
1526 | | * but synchronous signals (faults) remain deliverable : when blocked, a fault kills the process, |
1527 | | * bypassing the application's handlers (ex: SIGBUS from a memory-mapped input truncated during compression) */ |
1528 | | # if defined(SIG_SETMASK) && (!defined(_POSIX_C_SOURCE) || (_POSIX_C_SOURCE >= 199506L)) |
1529 | | # define LZ4F_MT_BLOCK_SIGNALS 1 |
1530 | | # else |
1531 | | # define LZ4F_MT_BLOCK_SIGNALS 0 |
1532 | | # endif |
1533 | | #endif |
1534 | | |
1535 | | /* some compression functions employ large stack buffers when not in HEAPMODE, |
1536 | | * while default thread stacks can be small (ex: 128 KB on musl) */ |
1537 | | #define LZ4F_MT_STACKSIZE_MIN (1 MB) |
1538 | | |
1539 | | /* Persistent pool of worker threads, started on demand (see LZ4F_pool_submit()), up to maxThreads. |
1540 | | * Queued jobs are run by worker threads (workerID 1 to nbThreads) : |
1541 | | * the calling thread only submits jobs and waits for them (without pool, it runs jobs itself : workerID 0). |
1542 | | * Allocations happen in the calling thread, since @cmem might not be thread-safe : |
1543 | | * HC states are extended (LZ4_STREAMHC_EXTSIZE), so lz4hc allocates nothing within worker threads. |
1544 | | * Note : like any thread, workers don't survive fork() : a forked child must not employ this pool. */ |
1545 | | typedef struct { LZ4F_job_f fn; void* arg; } LZ4F_poolJob_t; |
1546 | | typedef struct { LZ4F_pool_t* pool; unsigned workerID; } LZ4F_poolWorker_t; |
1547 | | |
1548 | | struct LZ4F_pool_s { |
1549 | | LZ4F_mutex_t lock; |
1550 | | LZ4F_cond_t jobQueued; /* to worker threads */ |
1551 | | LZ4F_cond_t jobDone; /* to the calling thread */ |
1552 | | LZ4F_poolJob_t* queue; /* circular */ |
1553 | | unsigned queueCapacity; |
1554 | | unsigned queueHead; |
1555 | | unsigned queueSize; |
1556 | | int shutdown; |
1557 | | int cancel; /* jobs of an abandoned frame : not started yet, they end without running */ |
1558 | | unsigned nbDone; /* incremented at each job completion */ |
1559 | | unsigned nbBusy; /* worker threads running a job */ |
1560 | | LZ4F_thread_t* threads; |
1561 | | LZ4F_poolWorker_t* workers; |
1562 | | unsigned nbThreads; /* started on demand, up to maxThreads */ |
1563 | | unsigned maxThreads; |
1564 | | }; |
1565 | | |
1566 | | /* requires lock */ |
1567 | | static LZ4F_poolJob_t LZ4F_pool_pop(LZ4F_pool_t* pool) |
1568 | | { |
1569 | | LZ4F_poolJob_t const job = pool->queue[pool->queueHead]; |
1570 | | assert(pool->queueSize > 0); |
1571 | | pool->queueHead = (pool->queueHead + 1) % pool->queueCapacity; |
1572 | | pool->queueSize--; |
1573 | | return job; |
1574 | | } |
1575 | | |
1576 | | static void LZ4F_pool_work(LZ4F_poolWorker_t* worker) |
1577 | | { |
1578 | | LZ4F_pool_t* const pool = worker->pool; |
1579 | | int busy = 0; |
1580 | | for (;;) { |
1581 | | LZ4F_poolJob_t job; |
1582 | | LZ4F_mutex_lock(&pool->lock); |
1583 | | if (busy) pool->nbBusy--; |
1584 | | while ((pool->queueSize == 0) && !pool->shutdown) |
1585 | | LZ4F_cond_wait(&pool->jobQueued, &pool->lock); |
1586 | | if (pool->queueSize == 0) { /* shutdown */ |
1587 | | LZ4F_mutex_unlock(&pool->lock); |
1588 | | return; |
1589 | | } |
1590 | | job = LZ4F_pool_pop(pool); |
1591 | | pool->nbBusy++; |
1592 | | busy = 1; |
1593 | | LZ4F_mutex_unlock(&pool->lock); |
1594 | | job.fn(job.arg, worker->workerID); |
1595 | | } |
1596 | | } |
1597 | | |
1598 | | #if defined(_WIN32) |
1599 | | static DWORD WINAPI LZ4F_pool_thread(LPVOID arg) |
1600 | | { |
1601 | | LZ4F_pool_work((LZ4F_poolWorker_t*)arg); |
1602 | | return 0; |
1603 | | } |
1604 | | #else |
1605 | | static void* LZ4F_pool_thread(void* arg) |
1606 | | { |
1607 | | LZ4F_pool_work((LZ4F_poolWorker_t*)arg); |
1608 | | return NULL; |
1609 | | } |
1610 | | #endif |
1611 | | |
1612 | | /* starts threads, up to @nbThreads in total |
1613 | | * @return : nb of threads of @pool (fewer than @nbThreads when a creation fails) */ |
1614 | | static unsigned LZ4F_pool_startThreads(LZ4F_pool_t* pool, unsigned nbThreads) |
1615 | | { |
1616 | | unsigned n; |
1617 | | #if defined(_WIN32) |
1618 | | assert(nbThreads <= pool->maxThreads); |
1619 | | for (n = pool->nbThreads; n < nbThreads; n++) { |
1620 | | /* stack size : reserved, and committed on demand (otherwise, CreateThread() commits it upfront) */ |
1621 | | pool->threads[n] = CreateThread(NULL, LZ4F_MT_STACKSIZE_MIN, LZ4F_pool_thread, &pool->workers[n], |
1622 | | STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); |
1623 | | if (pool->threads[n] == NULL) break; |
1624 | | } |
1625 | | #else |
1626 | | pthread_attr_t attr; |
1627 | | int const attrOK = !pthread_attr_init(&attr); |
1628 | | # if LZ4F_MT_BLOCK_SIGNALS |
1629 | | sigset_t allSignals, previousMask; |
1630 | | sigfillset(&allSignals); |
1631 | | sigdelset(&allSignals, SIGBUS); |
1632 | | sigdelset(&allSignals, SIGSEGV); |
1633 | | sigdelset(&allSignals, SIGFPE); |
1634 | | sigdelset(&allSignals, SIGILL); |
1635 | | pthread_sigmask(SIG_SETMASK, &allSignals, &previousMask); /* new threads inherit this mask */ |
1636 | | # endif |
1637 | | if (attrOK) { |
1638 | | size_t stackSize; |
1639 | | if (!pthread_attr_getstacksize(&attr, &stackSize) && (stackSize < LZ4F_MT_STACKSIZE_MIN)) |
1640 | | (void)pthread_attr_setstacksize(&attr, LZ4F_MT_STACKSIZE_MIN); |
1641 | | } |
1642 | | assert(nbThreads <= pool->maxThreads); |
1643 | | for (n = pool->nbThreads; n < nbThreads; n++) { |
1644 | | if (pthread_create(&pool->threads[n], attrOK ? &attr : NULL, LZ4F_pool_thread, &pool->workers[n])) break; |
1645 | | } |
1646 | | # if LZ4F_MT_BLOCK_SIGNALS |
1647 | | pthread_sigmask(SIG_SETMASK, &previousMask, NULL); |
1648 | | # endif |
1649 | | if (attrOK) pthread_attr_destroy(&attr); |
1650 | | #endif |
1651 | | pool->nbThreads = n; |
1652 | | return n; |
1653 | | } |
1654 | | |
1655 | | static void LZ4F_pool_freeMem(LZ4F_pool_t* pool, LZ4F_CustomMem cmem) |
1656 | | { |
1657 | | LZ4F_free(pool->queue, cmem); |
1658 | | LZ4F_free(pool->threads, cmem); |
1659 | | LZ4F_free(pool->workers, cmem); |
1660 | | LZ4F_free(pool, cmem); |
1661 | | } |
1662 | | |
1663 | | static void LZ4F_pool_free(LZ4F_pool_t* pool, LZ4F_CustomMem cmem) |
1664 | | { |
1665 | | unsigned n; |
1666 | | if (pool == NULL) return; |
1667 | | LZ4F_mutex_lock(&pool->lock); |
1668 | | pool->shutdown = 1; |
1669 | | LZ4F_cond_broadcast(&pool->jobQueued); |
1670 | | LZ4F_mutex_unlock(&pool->lock); |
1671 | | for (n = 0; n < pool->nbThreads; n++) { |
1672 | | #if defined(_WIN32) |
1673 | | WaitForSingleObject(pool->threads[n], INFINITE); /* never ends under the loader lock (see lz4frame.h) */ |
1674 | | CloseHandle(pool->threads[n]); |
1675 | | #else |
1676 | | pthread_join(pool->threads[n], NULL); |
1677 | | #endif |
1678 | | } |
1679 | | LZ4F_cond_destroy(&pool->jobDone); |
1680 | | LZ4F_cond_destroy(&pool->jobQueued); |
1681 | | LZ4F_mutex_destroy(&pool->lock); |
1682 | | LZ4F_pool_freeMem(pool, cmem); |
1683 | | } |
1684 | | |
1685 | | /*! LZ4F_pool_create() : |
1686 | | * threads are started on demand (see LZ4F_pool_submit()), up to @maxThreads. |
1687 | | * @return : a pool with one thread started, or NULL */ |
1688 | | static LZ4F_pool_t* LZ4F_pool_create(unsigned maxThreads, unsigned queueCapacity, LZ4F_CustomMem cmem) |
1689 | | { |
1690 | | LZ4F_pool_t* const pool = (LZ4F_pool_t*)LZ4F_calloc(sizeof(*pool), cmem); |
1691 | | if (pool == NULL) return NULL; |
1692 | | pool->queue = (LZ4F_poolJob_t*)LZ4F_malloc(queueCapacity * sizeof(*pool->queue), cmem); |
1693 | | pool->threads = (LZ4F_thread_t*)LZ4F_malloc(maxThreads * sizeof(*pool->threads), cmem); |
1694 | | pool->workers = (LZ4F_poolWorker_t*)LZ4F_malloc(maxThreads * sizeof(*pool->workers), cmem); |
1695 | | if (pool->queue == NULL || pool->threads == NULL || pool->workers == NULL) { |
1696 | | LZ4F_pool_freeMem(pool, cmem); |
1697 | | return NULL; |
1698 | | } |
1699 | | if (LZ4F_mutex_init(&pool->lock)) { |
1700 | | LZ4F_pool_freeMem(pool, cmem); |
1701 | | return NULL; |
1702 | | } |
1703 | | if (LZ4F_cond_init(&pool->jobQueued)) { |
1704 | | LZ4F_mutex_destroy(&pool->lock); |
1705 | | LZ4F_pool_freeMem(pool, cmem); |
1706 | | return NULL; |
1707 | | } |
1708 | | if (LZ4F_cond_init(&pool->jobDone)) { |
1709 | | LZ4F_cond_destroy(&pool->jobQueued); |
1710 | | LZ4F_mutex_destroy(&pool->lock); |
1711 | | LZ4F_pool_freeMem(pool, cmem); |
1712 | | return NULL; |
1713 | | } |
1714 | | pool->queueCapacity = queueCapacity; |
1715 | | pool->maxThreads = maxThreads; |
1716 | | { unsigned n; |
1717 | | for (n = 0; n < maxThreads; n++) { |
1718 | | pool->workers[n].pool = pool; |
1719 | | pool->workers[n].workerID = n+1; |
1720 | | } } |
1721 | | if (LZ4F_pool_startThreads(pool, 1) == 0) { |
1722 | | LZ4F_pool_free(pool, cmem); |
1723 | | return NULL; |
1724 | | } |
1725 | | return pool; |
1726 | | } |
1727 | | |
1728 | | /* A frame cut into jobs has a pool : its creation failure fails the frame (see LZ4F_mt_begin()). |
1729 | | * Only LZ4F_pool_free() and LZ4F_pool_setCancel() accept a NULL pool, left by such a failure (see LZ4F_mt_free()). */ |
1730 | | |
1731 | | static unsigned LZ4F_pool_nbThreads(const LZ4F_pool_t* pool) |
1732 | | { |
1733 | | assert(pool != NULL); |
1734 | | return pool->nbThreads; |
1735 | | } |
1736 | | |
1737 | | /* memory allocated with the custom allocator (thread stacks excluded) */ |
1738 | | static size_t LZ4F_pool_sizeof(const LZ4F_pool_t* pool) |
1739 | | { |
1740 | | assert(pool != NULL); |
1741 | | return sizeof(*pool) + pool->queueCapacity * sizeof(*pool->queue) |
1742 | | + pool->maxThreads * (sizeof(*pool->threads) + sizeof(*pool->workers)); |
1743 | | } |
1744 | | |
1745 | | /* @return : 1 when queued jobs outnumber idle threads, and more threads can be started (see LZ4F_pool_startThreads()) */ |
1746 | | static int LZ4F_pool_submit(LZ4F_pool_t* pool, LZ4F_job_f fn, void* arg) |
1747 | | { |
1748 | | int moreThreads; |
1749 | | assert(pool != NULL); |
1750 | | LZ4F_mutex_lock(&pool->lock); |
1751 | | assert(pool->queueSize < pool->queueCapacity); |
1752 | | { LZ4F_poolJob_t* const job = pool->queue + (pool->queueHead + pool->queueSize) % pool->queueCapacity; |
1753 | | job->fn = fn; |
1754 | | job->arg = arg; |
1755 | | } |
1756 | | pool->queueSize++; |
1757 | | moreThreads = (pool->queueSize > pool->nbThreads - pool->nbBusy) && (pool->nbThreads < pool->maxThreads); |
1758 | | LZ4F_cond_signal(&pool->jobQueued); |
1759 | | LZ4F_mutex_unlock(&pool->lock); |
1760 | | return moreThreads; |
1761 | | } |
1762 | | |
1763 | | /* one task of a job completed : the job is done when *pending reaches 0 */ |
1764 | | static void LZ4F_pool_taskDone(LZ4F_pool_t* pool, int* pending) |
1765 | | { |
1766 | | assert(pool != NULL); |
1767 | | LZ4F_mutex_lock(&pool->lock); |
1768 | | assert(*pending > 0); |
1769 | | if (--*pending == 0) { |
1770 | | pool->nbDone++; |
1771 | | LZ4F_cond_broadcast(&pool->jobDone); |
1772 | | } |
1773 | | LZ4F_mutex_unlock(&pool->lock); |
1774 | | } |
1775 | | |
1776 | | static void LZ4F_pool_setCancel(LZ4F_pool_t* pool, int cancel) |
1777 | | { |
1778 | | if (pool == NULL) return; |
1779 | | LZ4F_mutex_lock(&pool->lock); |
1780 | | pool->cancel = cancel; |
1781 | | LZ4F_mutex_unlock(&pool->lock); |
1782 | | } |
1783 | | |
1784 | | static int LZ4F_pool_isCancelled(LZ4F_pool_t* pool) |
1785 | | { |
1786 | | int cancel; |
1787 | | assert(pool != NULL); |
1788 | | LZ4F_mutex_lock(&pool->lock); |
1789 | | cancel = pool->cancel; |
1790 | | LZ4F_mutex_unlock(&pool->lock); |
1791 | | return cancel; |
1792 | | } |
1793 | | |
1794 | | static int LZ4F_pool_isDone(LZ4F_pool_t* pool, const int* pending) |
1795 | | { |
1796 | | int done; |
1797 | | assert(pool != NULL); |
1798 | | LZ4F_mutex_lock(&pool->lock); |
1799 | | done = (*pending == 0); |
1800 | | LZ4F_mutex_unlock(&pool->lock); |
1801 | | return done; |
1802 | | } |
1803 | | |
1804 | | /* waits for all tasks of a job (*pending == 0) */ |
1805 | | static void LZ4F_pool_waitDone(LZ4F_pool_t* pool, const int* pending) |
1806 | | { |
1807 | | assert(pool != NULL); |
1808 | | LZ4F_mutex_lock(&pool->lock); |
1809 | | while (*pending) LZ4F_cond_wait(&pool->jobDone, &pool->lock); |
1810 | | LZ4F_mutex_unlock(&pool->lock); |
1811 | | } |
1812 | | |
1813 | | static unsigned LZ4F_pool_nbDone(LZ4F_pool_t* pool) |
1814 | | { |
1815 | | unsigned nbDone; |
1816 | | assert(pool != NULL); |
1817 | | LZ4F_mutex_lock(&pool->lock); |
1818 | | nbDone = pool->nbDone; |
1819 | | LZ4F_mutex_unlock(&pool->lock); |
1820 | | return nbDone; |
1821 | | } |
1822 | | |
1823 | | /* waits for any job completion after @nbDone was observed */ |
1824 | | static void LZ4F_pool_waitAny(LZ4F_pool_t* pool, unsigned nbDone) |
1825 | | { |
1826 | | assert(pool != NULL); |
1827 | | LZ4F_mutex_lock(&pool->lock); |
1828 | | while (pool->nbDone == nbDone) LZ4F_cond_wait(&pool->jobDone, &pool->lock); |
1829 | | LZ4F_mutex_unlock(&pool->lock); |
1830 | | } |
1831 | | |
1832 | | #else /* !LZ4F_MULTITHREAD : no pool is ever created, jobs run within the calling thread */ |
1833 | | |
1834 | 0 | static unsigned LZ4F_pool_nbThreads(const LZ4F_pool_t* pool) { (void)pool; return 0; } |
1835 | 0 | static size_t LZ4F_pool_sizeof(const LZ4F_pool_t* pool) { (void)pool; return 0; } |
1836 | 0 | static void LZ4F_pool_free(LZ4F_pool_t* pool, LZ4F_CustomMem cmem) { (void)pool; (void)cmem; } |
1837 | 0 | static int LZ4F_pool_submit(LZ4F_pool_t* pool, LZ4F_job_f fn, void* arg) { (void)pool; fn(arg, 0); return 0; } |
1838 | 0 | static unsigned LZ4F_pool_startThreads(LZ4F_pool_t* pool, unsigned nbThreads) { (void)pool; (void)nbThreads; return 0; } |
1839 | 0 | static void LZ4F_pool_taskDone(LZ4F_pool_t* pool, int* pending) { (void)pool; assert(*pending > 0); (*pending)--; } |
1840 | 0 | static void LZ4F_pool_setCancel(LZ4F_pool_t* pool, int cancel) { (void)pool; (void)cancel; } |
1841 | 0 | static int LZ4F_pool_isCancelled(LZ4F_pool_t* pool) { (void)pool; return 0; } |
1842 | 0 | static int LZ4F_pool_isDone(LZ4F_pool_t* pool, const int* pending) { (void)pool; return *pending == 0; } |
1843 | 0 | static void LZ4F_pool_waitDone(LZ4F_pool_t* pool, const int* pending) { (void)pool; (void)pending; assert(*pending == 0); } |
1844 | 0 | static unsigned LZ4F_pool_nbDone(LZ4F_pool_t* pool) { (void)pool; return 0; } |
1845 | 0 | static void LZ4F_pool_waitAny(LZ4F_pool_t* pool, unsigned nbDone) { (void)pool; (void)nbDone; assert(0); } |
1846 | | |
1847 | | #endif /* LZ4F_MULTITHREAD */ |
1848 | | |
1849 | | typedef struct { |
1850 | | LZ4F_mtCtx_t* mt; |
1851 | | const BYTE* src; /* job content, right after its prefixSize bytes of history */ |
1852 | | size_t srcSize; |
1853 | | size_t prefixSize; |
1854 | | BYTE* inBuff; /* input buffer (LZ4F_MT_PREFIX_SIZE + jobSize), when content is copied : NULL when read in place */ |
1855 | | BYTE* outBuff; /* compressed blocks */ |
1856 | | LZ4F_BlockCompressMode_e mode; /* LZ4B_UNCOMPRESSED : uncompressed input (LZ4F_compressOptions_t.uncompressed) */ |
1857 | | size_t cSize; /* result : compressed size, or error code */ |
1858 | | int pending; /* tasks not completed yet : compression, and hashing (content checksum) ; 0 : result available (protected by pool's lock) */ |
1859 | | } LZ4F_mtJob_t; |
1860 | | |
1861 | | struct LZ4F_mtCtx_s { |
1862 | | LZ4F_CustomMem cmem; |
1863 | | LZ4F_pool_t* pool; /* NULL without multi-threading support (jobs run within the calling thread), or after a failed creation */ |
1864 | | LZ4F_pool_t* hPool; /* hashing thread (content checksum), created on first need : jobs hashed in order ; NULL : hashed by the calling thread */ |
1865 | | unsigned poolRequested; /* nbWorkers requested when pool was created : threads are started on demand, up to it */ |
1866 | | void** states; /* one LZ4 state per worker (allocated when it starts) ; states[0] : cctx's own state, without pool */ |
1867 | | unsigned nbStates; /* capacity of states[] */ |
1868 | | LZ4F_CtxType_e statesType; |
1869 | | LZ4F_mtJob_t* jobs; /* ring buffer of job slots, for the maximum nb of threads : outBuff allocated on first use */ |
1870 | | unsigned nbJobSlots; |
1871 | | size_t inCapacity; /* of each input buffer */ |
1872 | | size_t outCapacity; /* of each outBuff */ |
1873 | | /* input buffers are only needed until their job is compressed : they are shared by job slots */ |
1874 | | BYTE** inBuffs; /* all allocated input buffers */ |
1875 | | BYTE** inFree; /* free input buffers (stack) */ |
1876 | | unsigned nbInBuffs; |
1877 | | unsigned nbInFree; |
1878 | | unsigned maxInBuffs; /* capacity of inBuffs[] and inFree[] : one per thread, plus the one being filled */ |
1879 | | unsigned oldest; /* oldest submitted job, not emitted yet */ |
1880 | | size_t emitted; /* part of the oldest job already emitted, see LZ4F_mt_emitPartial() */ |
1881 | | unsigned nbSubmitted; |
1882 | | int filling; /* the slot following submitted jobs is being filled */ |
1883 | | BYTE* history; /* last bytes of content, up to LZ4F_MT_PREFIX_SIZE (linked blocks) */ |
1884 | | size_t historySize; |
1885 | | const BYTE* stableEnd; /* end of previous input, when stable (LZ4F_srcStableUntilFlush) */ |
1886 | | size_t stableRun; /* stable input contiguously preceding stableEnd, up to LZ4F_MT_PREFIX_SIZE */ |
1887 | | /* current frame */ |
1888 | | const LZ4F_preferences_t* prefs; |
1889 | | const LZ4F_CDict* cdict; |
1890 | | size_t blockSize; |
1891 | | size_t jobSize; |
1892 | | XXH32_state_t* xxh; /* content checksum, or NULL : jobs are hashed in order, see LZ4F_mt_hashJob() */ |
1893 | | }; |
1894 | | |
1895 | | static void LZ4F_mt_runJob(void* arg, unsigned workerID) |
1896 | 0 | { |
1897 | 0 | LZ4F_mtJob_t* const job = (LZ4F_mtJob_t*)arg; |
1898 | 0 | LZ4F_mtCtx_t* const mt = job->mt; |
1899 | 0 | assert(mt->states[workerID] != NULL); |
1900 | 0 | if (LZ4F_pool_isCancelled(mt->pool)) { |
1901 | 0 | job->cSize = 0; /* abandoned frame : result discarded */ |
1902 | 0 | } else { |
1903 | 0 | job->cSize = LZ4F_compressJob(mt->states[workerID], mt->prefs, mt->cdict, mt->blockSize, |
1904 | 0 | job->outBuff, mt->outCapacity, |
1905 | 0 | job->src, job->srcSize, job->prefixSize, job->mode); |
1906 | 0 | } |
1907 | 0 | LZ4F_pool_taskDone(mt->pool, &job->pending); |
1908 | 0 | } |
1909 | | |
1910 | | /* content checksum : by the hashing thread, which runs jobs in order (or by the calling thread, without it) */ |
1911 | | static void LZ4F_mt_hashJob(void* arg, unsigned workerID) |
1912 | 0 | { |
1913 | 0 | LZ4F_mtJob_t* const job = (LZ4F_mtJob_t*)arg; |
1914 | 0 | LZ4F_mtCtx_t* const mt = job->mt; |
1915 | 0 | (void)workerID; |
1916 | 0 | if (!LZ4F_pool_isCancelled(mt->pool)) /* abandoned frame : checksum discarded */ |
1917 | 0 | (void)XXH32_update(mt->xxh, job->src, job->srcSize); |
1918 | 0 | LZ4F_pool_taskDone(mt->pool, &job->pending); |
1919 | 0 | } |
1920 | | |
1921 | | /* jobs in flight : up to LZ4F_MT_NBSLOTS() of current nb of threads (within ring buffer of job slots) */ |
1922 | | static unsigned LZ4F_mt_nbUsableSlots(const LZ4F_mtCtx_t* mt) |
1923 | 0 | { |
1924 | 0 | unsigned const nbThreads = LZ4F_pool_nbThreads(mt->pool); |
1925 | 0 | return nbThreads ? (unsigned)LZ4F_MT_NBSLOTS(nbThreads) : 1; |
1926 | 0 | } |
1927 | | |
1928 | | /* allocates the LZ4 state of worker @workerID, unless already done |
1929 | | * @return : 1 when the state is ready, 0 if allocation failed */ |
1930 | | static int LZ4F_mt_allocState(LZ4F_mtCtx_t* mt, unsigned workerID, int level) |
1931 | 0 | { |
1932 | 0 | if (mt->states[workerID] == NULL) { |
1933 | 0 | void* const state = LZ4F_malloc(LZ4F_sizeofLZ4State(mt->statesType), mt->cmem); |
1934 | 0 | if (state == NULL) return 0; |
1935 | 0 | LZ4F_initLZ4State(state, mt->statesType, level); |
1936 | 0 | mt->states[workerID] = state; |
1937 | 0 | } |
1938 | 0 | return 1; |
1939 | 0 | } |
1940 | | |
1941 | | /* starts one more worker thread, with its LZ4 state (allocated by the calling thread) : |
1942 | | * on failure (allocation, thread creation), compression proceeds with current threads */ |
1943 | | static void LZ4F_mt_addWorker(LZ4F_mtCtx_t* mt) |
1944 | 0 | { |
1945 | 0 | unsigned const workerID = LZ4F_pool_nbThreads(mt->pool) + 1; |
1946 | 0 | assert(workerID < mt->nbStates); |
1947 | 0 | if (LZ4F_mt_allocState(mt, workerID, mt->prefs->compressionLevel)) |
1948 | 0 | (void)LZ4F_pool_startThreads(mt->pool, workerID); |
1949 | 0 | } |
1950 | | |
1951 | | /* @n-th submitted job, from the oldest one : @n == nbSubmitted is the slot following them (see LZ4F_mt_fillingSlot()) */ |
1952 | | static LZ4F_mtJob_t* LZ4F_mt_job(LZ4F_mtCtx_t* mt, unsigned n) |
1953 | 0 | { |
1954 | 0 | return mt->jobs + (mt->oldest + n) % mt->nbJobSlots; |
1955 | 0 | } |
1956 | | |
1957 | | static LZ4F_mtJob_t* LZ4F_mt_fillingSlot(LZ4F_mtCtx_t* mt) |
1958 | 0 | { |
1959 | 0 | return LZ4F_mt_job(mt, mt->nbSubmitted); |
1960 | 0 | } |
1961 | | |
1962 | | /* keeps the last LZ4F_MT_PREFIX_SIZE bytes of content */ |
1963 | | static void LZ4F_mt_addHistory(LZ4F_mtCtx_t* mt, const BYTE* content, size_t size) |
1964 | 0 | { |
1965 | 0 | if (size >= LZ4F_MT_PREFIX_SIZE) { |
1966 | 0 | LZ4_memcpy(mt->history, content + size - LZ4F_MT_PREFIX_SIZE, LZ4F_MT_PREFIX_SIZE); |
1967 | 0 | mt->historySize = LZ4F_MT_PREFIX_SIZE; |
1968 | 0 | } else { |
1969 | 0 | size_t const kept = MIN(mt->historySize, LZ4F_MT_PREFIX_SIZE - size); |
1970 | 0 | LZ4_memmove(mt->history, mt->history + mt->historySize - kept, kept); |
1971 | 0 | LZ4_memcpy(mt->history + kept, content, size); |
1972 | 0 | mt->historySize = kept + size; |
1973 | 0 | } |
1974 | 0 | } |
1975 | | |
1976 | | /* submits the job being filled : to worker threads, |
1977 | | * or, @inCallingThread, runs it right away with the cctx's own state (states[0], unused by workers) */ |
1978 | | static void LZ4F_mt_submit_internal(LZ4F_mtCtx_t* mt, int inCallingThread) |
1979 | 0 | { |
1980 | 0 | LZ4F_mtJob_t* const job = LZ4F_mt_fillingSlot(mt); |
1981 | 0 | assert(mt->filling); |
1982 | 0 | assert(job->srcSize > 0); |
1983 | 0 | job->pending = 1 + (mt->xxh != NULL); /* compression, and hashing */ |
1984 | 0 | mt->filling = 0; |
1985 | 0 | mt->nbSubmitted++; |
1986 | 0 | if (inCallingThread) |
1987 | 0 | LZ4F_mt_runJob(job, 0); |
1988 | 0 | else if (LZ4F_pool_submit(mt->pool, LZ4F_mt_runJob, job)) |
1989 | 0 | LZ4F_mt_addWorker(mt); /* more jobs than idle threads */ |
1990 | 0 | if (mt->xxh != NULL) { |
1991 | 0 | if (mt->hPool != NULL) |
1992 | 0 | (void)LZ4F_pool_submit(mt->hPool, LZ4F_mt_hashJob, job); |
1993 | 0 | else |
1994 | 0 | LZ4F_mt_hashJob(job, 0); |
1995 | 0 | } |
1996 | 0 | if (mt->prefs->frameInfo.blockMode == LZ4F_blockLinked) |
1997 | 0 | LZ4F_mt_addHistory(mt, job->src, job->srcSize); /* job content is only read while job runs */ |
1998 | 0 | } |
1999 | | |
2000 | 0 | static void LZ4F_mt_submit(LZ4F_mtCtx_t* mt) { LZ4F_mt_submit_internal(mt, 0); } |
2001 | | |
2002 | | /* the calling thread is about to wait for all jobs : when no other job is running, it compresses the last one itself, |
2003 | | * which saves the synchronization with a worker (same output : jobs don't depend on their state) */ |
2004 | 0 | static void LZ4F_mt_submitLast(LZ4F_mtCtx_t* mt) { LZ4F_mt_submit_internal(mt, mt->nbSubmitted == 0); } |
2005 | | |
2006 | | /* input buffer of a completed job returns to the free stack */ |
2007 | | static void LZ4F_mt_releaseInBuff(LZ4F_mtCtx_t* mt, LZ4F_mtJob_t* job) |
2008 | 0 | { |
2009 | 0 | if (job->inBuff == NULL) return; |
2010 | 0 | assert(mt->nbInFree < mt->nbInBuffs); |
2011 | 0 | mt->inFree[mt->nbInFree++] = job->inBuff; |
2012 | 0 | job->inBuff = NULL; |
2013 | 0 | } |
2014 | | |
2015 | | /* the oldest job, completed, is emitted or discarded : its slot is free */ |
2016 | | static void LZ4F_mt_retireOldest(LZ4F_mtCtx_t* mt) |
2017 | 0 | { |
2018 | 0 | LZ4F_mt_releaseInBuff(mt, mt->jobs + mt->oldest); |
2019 | 0 | mt->oldest = (mt->oldest + 1) % mt->nbJobSlots; |
2020 | 0 | mt->nbSubmitted--; |
2021 | 0 | mt->emitted = 0; |
2022 | 0 | } |
2023 | | |
2024 | | /*! LZ4F_mt_acquireInBuff() : |
2025 | | * When all input buffers are employed, one is reclaimed from a submitted job, |
2026 | | * the first one to complete (job durations vary). |
2027 | | * @return : an input buffer, or NULL if allocation failed */ |
2028 | | static BYTE* LZ4F_mt_acquireInBuff(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem) |
2029 | 0 | { |
2030 | 0 | if (mt->nbInFree) return mt->inFree[--mt->nbInFree]; |
2031 | 0 | if (mt->nbInBuffs < LZ4F_pool_nbThreads(mt->pool) + LZ4F_MT_EXTRA_INBUFFS) { |
2032 | 0 | BYTE* const buff = (BYTE*)LZ4F_malloc(mt->inCapacity, cmem); |
2033 | 0 | assert(mt->nbInBuffs < mt->maxInBuffs); |
2034 | 0 | if (buff != NULL) mt->inBuffs[mt->nbInBuffs++] = buff; |
2035 | 0 | return buff; |
2036 | 0 | } |
2037 | 0 | for (;;) { |
2038 | 0 | unsigned const nbDone = LZ4F_pool_nbDone(mt->pool); |
2039 | 0 | unsigned n; |
2040 | 0 | for (n = 0; n < mt->nbSubmitted; n++) { |
2041 | 0 | LZ4F_mtJob_t* const job = LZ4F_mt_job(mt, n); |
2042 | 0 | if ((job->inBuff != NULL) && LZ4F_pool_isDone(mt->pool, &job->pending)) { |
2043 | 0 | BYTE* const buff = job->inBuff; |
2044 | 0 | job->inBuff = NULL; |
2045 | 0 | return buff; |
2046 | 0 | } } |
2047 | | /* buffers are held by submitted jobs, still running : wait for one of them */ |
2048 | 0 | LZ4F_pool_waitAny(mt->pool, nbDone); |
2049 | 0 | } |
2050 | 0 | } |
2051 | | |
2052 | | /* emits oldest submitted job into @dst + @pos, waiting for it if needed. |
2053 | | * On error, the job remains submitted : callers invalidate the frame, discarding its jobs (FORWARD_IF_ERROR_INVALIDATE) */ |
2054 | | static size_t LZ4F_mt_emitOldest(LZ4F_mtCtx_t* mt, BYTE* dst, size_t dstCapacity, size_t pos) |
2055 | 0 | { |
2056 | 0 | LZ4F_mtJob_t* const job = mt->jobs + mt->oldest; |
2057 | 0 | size_t toEmit; |
2058 | 0 | assert(mt->nbSubmitted > 0); |
2059 | 0 | assert(pos <= dstCapacity); |
2060 | 0 | LZ4F_pool_waitDone(mt->pool, &job->pending); |
2061 | 0 | FORWARD_IF_ERROR(job->cSize); |
2062 | 0 | toEmit = job->cSize - mt->emitted; /* part already emitted by an incomplete LZ4F_flush() */ |
2063 | 0 | RETURN_ERROR_IF(toEmit > dstCapacity - pos, dstCapacity_tooSmall); |
2064 | 0 | LZ4_memcpy(dst + pos, job->outBuff + mt->emitted, toEmit); |
2065 | 0 | LZ4F_mt_retireOldest(mt); |
2066 | 0 | return toEmit; |
2067 | 0 | } |
2068 | | |
2069 | | /* emits submitted jobs in order : all of them (@all), or only the already completed ones fitting into @dst |
2070 | | * (their emission isn't required yet : the others are emitted later). |
2071 | | * On error, callers invalidate the frame (FORWARD_IF_ERROR_INVALIDATE) */ |
2072 | | static size_t LZ4F_mt_emit(LZ4F_mtCtx_t* mt, BYTE* dst, size_t dstCapacity, size_t pos, int all) |
2073 | 0 | { |
2074 | 0 | size_t written = 0; |
2075 | 0 | while (mt->nbSubmitted > 0) { |
2076 | 0 | const LZ4F_mtJob_t* const job = mt->jobs + mt->oldest; |
2077 | 0 | if (!all) { |
2078 | 0 | if (!LZ4F_pool_isDone(mt->pool, &job->pending)) break; |
2079 | 0 | if (job->cSize - mt->emitted > dstCapacity - (pos + written)) break; /* also defers an error code */ |
2080 | 0 | } |
2081 | 0 | { size_t const r = LZ4F_mt_emitOldest(mt, dst, dstCapacity, pos + written); |
2082 | 0 | FORWARD_IF_ERROR(r); |
2083 | 0 | written += r; |
2084 | 0 | } } |
2085 | 0 | return written; |
2086 | 0 | } |
2087 | | |
2088 | | /* discards submitted jobs : those not started yet end without running, others are waited for */ |
2089 | | static void LZ4F_mt_abort(LZ4F_mtCtx_t* mt) |
2090 | 0 | { |
2091 | 0 | LZ4F_pool_setCancel(mt->pool, 1); |
2092 | 0 | while (mt->nbSubmitted > 0) { |
2093 | 0 | LZ4F_pool_waitDone(mt->pool, &mt->jobs[mt->oldest].pending); |
2094 | 0 | LZ4F_mt_retireOldest(mt); |
2095 | 0 | } |
2096 | 0 | LZ4F_pool_setCancel(mt->pool, 0); |
2097 | 0 | if (mt->filling) LZ4F_mt_releaseInBuff(mt, LZ4F_mt_fillingSlot(mt)); |
2098 | 0 | mt->filling = 0; |
2099 | 0 | mt->emitted = 0; |
2100 | 0 | mt->stableEnd = NULL; |
2101 | 0 | } |
2102 | | |
2103 | | static void LZ4F_mt_freeStates(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem) |
2104 | 0 | { |
2105 | 0 | unsigned n; |
2106 | 0 | for (n = 1; n < mt->nbStates; n++) LZ4F_free(mt->states[n], cmem); /* states[0] belongs to cctx ; NULL : not allocated */ |
2107 | 0 | LZ4F_free(mt->states, cmem); |
2108 | 0 | mt->states = NULL; |
2109 | 0 | mt->nbStates = 0; |
2110 | 0 | } |
2111 | | |
2112 | | static void LZ4F_mt_freeInBuffs(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem) |
2113 | 0 | { |
2114 | 0 | unsigned n; |
2115 | 0 | assert(mt->nbInFree == mt->nbInBuffs); /* no job in flight */ |
2116 | 0 | for (n = 0; n < mt->nbInBuffs; n++) LZ4F_free(mt->inBuffs[n], cmem); |
2117 | 0 | LZ4F_free(mt->inBuffs, cmem); |
2118 | 0 | LZ4F_free(mt->inFree, cmem); |
2119 | 0 | mt->inBuffs = mt->inFree = NULL; |
2120 | 0 | mt->nbInBuffs = mt->nbInFree = mt->maxInBuffs = 0; |
2121 | 0 | } |
2122 | | |
2123 | | static void LZ4F_mt_freeJobs(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem) |
2124 | 0 | { |
2125 | 0 | unsigned n; |
2126 | 0 | for (n = 0; n < mt->nbJobSlots; n++) { |
2127 | 0 | assert(mt->jobs[n].inBuff == NULL); |
2128 | 0 | LZ4F_free(mt->jobs[n].outBuff, cmem); |
2129 | 0 | } |
2130 | 0 | LZ4F_free(mt->jobs, cmem); |
2131 | 0 | mt->jobs = NULL; |
2132 | 0 | mt->nbJobSlots = 0; |
2133 | 0 | } |
2134 | | |
2135 | | static void LZ4F_mt_free(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem) |
2136 | 0 | { |
2137 | 0 | if (mt == NULL) return; |
2138 | 0 | LZ4F_mt_abort(mt); |
2139 | 0 | LZ4F_pool_free(mt->pool, cmem); |
2140 | 0 | LZ4F_pool_free(mt->hPool, cmem); |
2141 | 0 | LZ4F_mt_freeStates(mt, cmem); |
2142 | 0 | LZ4F_mt_freeJobs(mt, cmem); |
2143 | 0 | LZ4F_mt_freeInBuffs(mt, cmem); |
2144 | 0 | LZ4F_free(mt->history, cmem); |
2145 | 0 | LZ4F_free(mt, cmem); |
2146 | 0 | } |
2147 | | |
2148 | | static size_t LZ4F_mt_sizeof(const LZ4F_mtCtx_t* mt) |
2149 | 0 | { |
2150 | 0 | size_t size; |
2151 | 0 | unsigned n; |
2152 | 0 | if (mt == NULL) return 0; |
2153 | 0 | size = sizeof(*mt) + LZ4F_MT_PREFIX_SIZE |
2154 | 0 | + mt->nbStates * sizeof(void*) |
2155 | 0 | + mt->nbJobSlots * sizeof(LZ4F_mtJob_t) |
2156 | 0 | + mt->maxInBuffs * 2 * sizeof(BYTE*) + mt->nbInBuffs * mt->inCapacity |
2157 | 0 | + (mt->pool ? LZ4F_pool_sizeof(mt->pool) : 0) |
2158 | 0 | + (mt->hPool ? LZ4F_pool_sizeof(mt->hPool) : 0); |
2159 | 0 | for (n = 1; n < mt->nbStates; n++) if (mt->states[n] != NULL) size += LZ4F_sizeofLZ4State(mt->statesType); |
2160 | 0 | for (n = 0; n < mt->nbJobSlots; n++) if (mt->jobs[n].outBuff != NULL) size += mt->outCapacity; |
2161 | 0 | return size; |
2162 | 0 | } |
2163 | | |
2164 | | /*! LZ4F_mt_begin() : |
2165 | | * prepares multi-threading resources for a new frame, cut into jobs. |
2166 | | * Resources are kept within cctx, and reused by next frames. |
2167 | | * Requires a cctx prepared by LZ4F_compressBegin_internal(), with no job in flight. |
2168 | | * @return : 0, or an error code */ |
2169 | | static size_t LZ4F_mt_begin(LZ4F_cctx_t* cctx) |
2170 | 0 | { |
2171 | 0 | LZ4F_CustomMem const cmem = cctx->cmem; |
2172 | 0 | unsigned const nbWorkers = MIN(cctx->prefs.nbWorkers, LZ4F_NBWORKERS_MAX); |
2173 | 0 | LZ4F_CtxType_e const ctxType = (LZ4F_CtxType_e)cctx->lz4CtxType; |
2174 | 0 | size_t const blockSize = cctx->maxBlockSize; |
2175 | 0 | size_t const jobSize = LZ4F_mtJobSize(blockSize); |
2176 | 0 | size_t const inCapacity = LZ4F_MT_PREFIX_SIZE + jobSize; |
2177 | 0 | size_t const outCapacity = LZ4F_blocksBound(jobSize, blockSize, LZ4F_blockChecksumEnabled); |
2178 | 0 | int const checksum = (cctx->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled); |
2179 | 0 | LZ4F_mtCtx_t* mt = cctx->mt; |
2180 | 0 | unsigned nbThreads, maxThreads, nbJobSlots; |
2181 | |
|
2182 | 0 | assert(nbWorkers >= 1); |
2183 | 0 | (void)nbWorkers; /* only employed by multi-threading support */ |
2184 | 0 | if (mt == NULL) { |
2185 | 0 | mt = (LZ4F_mtCtx_t*)LZ4F_calloc(sizeof(*mt), cmem); |
2186 | 0 | RETURN_ERROR_IF(mt == NULL, allocation_failed); |
2187 | 0 | mt->history = (BYTE*)LZ4F_malloc(LZ4F_MT_PREFIX_SIZE, cmem); |
2188 | 0 | if (mt->history == NULL) { |
2189 | 0 | LZ4F_free(mt, cmem); |
2190 | 0 | RETURN_ERROR(allocation_failed); |
2191 | 0 | } |
2192 | 0 | mt->cmem = cmem; |
2193 | 0 | cctx->mt = mt; |
2194 | 0 | } |
2195 | 0 | assert(mt->nbSubmitted == 0 && !mt->filling); |
2196 | | |
2197 | | /* worker threads */ |
2198 | | #if LZ4F_MULTITHREAD |
2199 | | /* an incomplete pool (fewer threads than requested) is kept ; |
2200 | | * without any worker thread, frame compression fails, and next frames try again */ |
2201 | | if ((mt->pool == NULL) || (mt->poolRequested != nbWorkers)) { |
2202 | | LZ4F_pool_free(mt->pool, cmem); |
2203 | | mt->pool = LZ4F_pool_create(nbWorkers, (unsigned)LZ4F_MT_NBSLOTS(nbWorkers), cmem); /* queue : all job slots */ |
2204 | | mt->poolRequested = nbWorkers; |
2205 | | LZ4F_pool_free(mt->hPool, cmem); /* its queue holds all job slots too */ |
2206 | | mt->hPool = NULL; |
2207 | | RETURN_ERROR_IF(mt->pool == NULL, allocation_failed); |
2208 | | } |
2209 | | /* content checksum : hashing thread, kept for next frames ; on creation failure, the calling thread hashes jobs */ |
2210 | | if (checksum && (mt->hPool == NULL)) |
2211 | | mt->hPool = LZ4F_pool_create(1, (unsigned)LZ4F_MT_NBSLOTS(nbWorkers), cmem); |
2212 | | #endif |
2213 | | /* resources are sized for the maximum nb of threads, but only allocated when needed : |
2214 | | * threads with their LZ4 state, job slots' outputs and input buffers */ |
2215 | 0 | nbThreads = LZ4F_pool_nbThreads(mt->pool); /* already started */ |
2216 | 0 | maxThreads = mt->pool ? mt->poolRequested : 0; |
2217 | 0 | nbJobSlots = maxThreads ? (unsigned)LZ4F_MT_NBSLOTS(maxThreads) : 1; |
2218 | | |
2219 | | /* one LZ4 state per worker */ |
2220 | 0 | if ((mt->nbStates != maxThreads + 1) || (mt->statesType != ctxType)) { |
2221 | 0 | LZ4F_mt_freeStates(mt, cmem); |
2222 | 0 | mt->states = (void**)LZ4F_calloc((maxThreads + 1) * sizeof(void*), cmem); |
2223 | 0 | RETURN_ERROR_IF(mt->states == NULL, allocation_failed); |
2224 | 0 | mt->nbStates = maxThreads + 1; |
2225 | 0 | mt->statesType = ctxType; |
2226 | 0 | } |
2227 | 0 | { unsigned n; |
2228 | 0 | for (n = 1; n <= nbThreads; n++) /* threads already started (previous frames) */ |
2229 | 0 | RETURN_ERROR_IF(!LZ4F_mt_allocState(mt, n, cctx->prefs.compressionLevel), allocation_failed); |
2230 | 0 | } |
2231 | 0 | mt->states[0] = cctx->lz4CtxPtr; |
2232 | | |
2233 | | /* job slots (outputs allocated on first use) */ |
2234 | 0 | if (mt->nbJobSlots != nbJobSlots) { |
2235 | 0 | LZ4F_mt_freeJobs(mt, cmem); |
2236 | 0 | mt->jobs = (LZ4F_mtJob_t*)LZ4F_calloc(nbJobSlots * sizeof(LZ4F_mtJob_t), cmem); |
2237 | 0 | RETURN_ERROR_IF(mt->jobs == NULL, allocation_failed); |
2238 | 0 | mt->nbJobSlots = nbJobSlots; |
2239 | 0 | } |
2240 | 0 | if (mt->outCapacity < outCapacity) { |
2241 | 0 | unsigned n; |
2242 | 0 | for (n = 0; n < mt->nbJobSlots; n++) { |
2243 | 0 | LZ4F_free(mt->jobs[n].outBuff, cmem); |
2244 | 0 | mt->jobs[n].outBuff = NULL; |
2245 | 0 | } |
2246 | 0 | mt->outCapacity = outCapacity; |
2247 | 0 | } |
2248 | | |
2249 | | /* input buffers : one per thread, plus the one being filled (allocated on first need) */ |
2250 | 0 | if ((mt->maxInBuffs != maxThreads + LZ4F_MT_EXTRA_INBUFFS) || (mt->inCapacity < inCapacity)) { |
2251 | 0 | LZ4F_mt_freeInBuffs(mt, cmem); |
2252 | 0 | mt->inBuffs = (BYTE**)LZ4F_malloc((maxThreads + LZ4F_MT_EXTRA_INBUFFS) * sizeof(BYTE*), cmem); |
2253 | 0 | mt->inFree = (BYTE**)LZ4F_malloc((maxThreads + LZ4F_MT_EXTRA_INBUFFS) * sizeof(BYTE*), cmem); |
2254 | 0 | if ((mt->inBuffs == NULL) || (mt->inFree == NULL)) { |
2255 | 0 | LZ4F_mt_freeInBuffs(mt, cmem); |
2256 | 0 | RETURN_ERROR(allocation_failed); |
2257 | 0 | } |
2258 | 0 | mt->maxInBuffs = maxThreads + LZ4F_MT_EXTRA_INBUFFS; |
2259 | 0 | mt->inCapacity = inCapacity; |
2260 | 0 | } |
2261 | | |
2262 | | /* current frame */ |
2263 | 0 | { unsigned n; |
2264 | 0 | for (n = 0; n < nbJobSlots; n++) mt->jobs[n].mt = mt; |
2265 | 0 | } |
2266 | 0 | mt->prefs = &cctx->prefs; |
2267 | 0 | mt->cdict = cctx->cdict; |
2268 | 0 | mt->blockSize = blockSize; |
2269 | 0 | mt->jobSize = jobSize; |
2270 | 0 | mt->xxh = checksum ? &cctx->xxh : NULL; |
2271 | 0 | mt->oldest = 0; |
2272 | 0 | mt->emitted = 0; |
2273 | 0 | mt->nbSubmitted = 0; |
2274 | 0 | mt->filling = 0; |
2275 | 0 | mt->historySize = 0; |
2276 | 0 | mt->stableEnd = NULL; |
2277 | 0 | mt->stableRun = 0; |
2278 | 0 | cctx->mtActive = 1; |
2279 | 0 | return 0; |
2280 | 0 | } |
2281 | | |
2282 | | /*! LZ4F_mt_flushPoint() : |
2283 | | * LZ4F_flush() and LZ4F_compressEnd(), multi-threaded mode : the job being filled is submitted (see LZ4F_mt_submitLast()), |
2284 | | * and all jobs are waited for : input is no longer read, and their output is emitted by LZ4F_mt_emitPartial(). */ |
2285 | | static void LZ4F_mt_flushPoint(LZ4F_mtCtx_t* mt) |
2286 | 0 | { |
2287 | 0 | unsigned n; |
2288 | 0 | if (mt->filling) LZ4F_mt_submitLast(mt); |
2289 | 0 | for (n = 0; n < mt->nbSubmitted; n++) |
2290 | 0 | LZ4F_pool_waitDone(mt->pool, &LZ4F_mt_job(mt, n)->pending); |
2291 | 0 | } |
2292 | | |
2293 | | /*! LZ4F_mt_emitPartial() : |
2294 | | * emits completed jobs in order into @dst + @pos, as much as fits : the oldest one can be emitted partially. |
2295 | | * Requires all submitted jobs completed, see LZ4F_mt_flushPoint(). |
2296 | | * @return : nb of bytes written, or an error code */ |
2297 | | static size_t LZ4F_mt_emitPartial(LZ4F_mtCtx_t* mt, BYTE* dst, size_t dstCapacity, size_t pos) |
2298 | 0 | { |
2299 | 0 | size_t const start = pos; |
2300 | 0 | while (mt->nbSubmitted > 0) { |
2301 | 0 | LZ4F_mtJob_t* const job = mt->jobs + mt->oldest; |
2302 | 0 | size_t n; |
2303 | 0 | assert(LZ4F_pool_isDone(mt->pool, &job->pending)); |
2304 | 0 | FORWARD_IF_ERROR(job->cSize); |
2305 | 0 | n = MIN(job->cSize - mt->emitted, dstCapacity - pos); |
2306 | 0 | if (n) LZ4_memcpy(dst + pos, job->outBuff + mt->emitted, n); |
2307 | 0 | pos += n; |
2308 | 0 | mt->emitted += n; |
2309 | 0 | if (mt->emitted < job->cSize) break; /* dst is full */ |
2310 | 0 | LZ4F_mt_retireOldest(mt); |
2311 | 0 | } |
2312 | 0 | return pos - start; |
2313 | 0 | } |
2314 | | |
2315 | | /*! LZ4F_mt_update() : |
2316 | | * LZ4F_compressUpdate(), multi-threaded mode (@mode : compressed or uncompressed input ; @cOptPtr : not NULL). |
2317 | | * Input is copied into jobs, submitted once full. |
2318 | | * Job content is read in place instead, when it remains available until the job completes : |
2319 | | * with stableSrc == LZ4F_srcStableUntilFlush, or with autoFlush, since all jobs complete within the invocation. |
2320 | | * LZ4F_srcStable (historical value 1) only guarantees the last 64 KB : content is copied. |
2321 | | * Uncompressed segments are jobs too : a mode switch submits the job being filled, |
2322 | | * so that blocks are cut as in single-threaded mode (the buffered block is flushed on a mode switch). |
2323 | | * Completed jobs are emitted in order, as long as they fit. With autoFlush, all input is compressed and emitted. |
2324 | | * Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, prefs) : |
2325 | | * without autoFlush, output is only required to start a job while all slots are busy (oldest job). */ |
2326 | | static size_t LZ4F_mt_update(LZ4F_cctx_t* cctx, |
2327 | | void* dstBuffer, size_t dstCapacity, |
2328 | | const void* srcBuffer, size_t srcSize, |
2329 | | const LZ4F_compressOptions_t* cOptPtr, |
2330 | | LZ4F_BlockCompressMode_e mode) |
2331 | 0 | { |
2332 | 0 | LZ4F_mtCtx_t* const mt = cctx->mt; |
2333 | 0 | const BYTE* const istart = (const BYTE*)srcBuffer; |
2334 | 0 | const BYTE* ip = istart; |
2335 | 0 | const BYTE* const iend = srcSize ? istart + srcSize : istart; |
2336 | 0 | BYTE* const dst = (BYTE*)dstBuffer; |
2337 | 0 | size_t pos = 0; |
2338 | 0 | int const linked = (cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked); |
2339 | 0 | int const stableUntilFlush = (cOptPtr->stableSrc == LZ4F_srcStableUntilFlush); |
2340 | 0 | int const inPlace = cctx->prefs.autoFlush || stableUntilFlush; |
2341 | | /* stable input remains available : when contiguous with previous input, history can be read in place */ |
2342 | 0 | size_t const prevRun = (stableUntilFlush && srcSize && (istart == mt->stableEnd)) ? mt->stableRun : 0; |
2343 | |
|
2344 | 0 | DEBUGLOG(4, "LZ4F_mt_update (srcSize=%u, mode=%u)", (unsigned)srcSize, (unsigned)mode); |
2345 | 0 | RETURN_ERROR_IF(cctx->cStage != 1, compressionState_uninitialized); |
2346 | 0 | assert(cctx->pendingSize == 0); /* multi-threaded mode : pending output is within jobs */ |
2347 | 0 | cctx->flushStage = 0; /* an incomplete LZ4F_flush() ends here : remaining jobs are emitted as usual */ |
2348 | 0 | if (mt->filling && (LZ4F_mt_fillingSlot(mt)->mode != mode)) |
2349 | 0 | LZ4F_mt_submit(mt); /* mode switch */ |
2350 | |
|
2351 | 0 | while (ip < iend) { |
2352 | 0 | LZ4F_mtJob_t* const job = LZ4F_mt_fillingSlot(mt); |
2353 | 0 | if (!mt->filling) { |
2354 | | /* new job */ |
2355 | 0 | size_t const remaining = (size_t)(iend - ip); |
2356 | 0 | size_t const prefixSize = linked ? mt->historySize : 0; |
2357 | 0 | if (mt->nbSubmitted >= LZ4F_mt_nbUsableSlots(mt)) { |
2358 | | /* all slots busy : emit oldest job, to free a slot */ |
2359 | 0 | size_t const r = LZ4F_mt_emitOldest(mt, dst, dstCapacity, pos); |
2360 | 0 | FORWARD_IF_ERROR_INVALIDATE(r, cctx); |
2361 | 0 | pos += r; |
2362 | 0 | assert(job == LZ4F_mt_fillingSlot(mt)); |
2363 | 0 | } |
2364 | 0 | if (job->outBuff == NULL) { /* first use of this slot */ |
2365 | 0 | job->outBuff = (BYTE*)LZ4F_malloc(mt->outCapacity, cctx->cmem); |
2366 | 0 | if (job->outBuff == NULL) { |
2367 | 0 | LZ4F_invalidateFrame(cctx); |
2368 | 0 | RETURN_ERROR(allocation_failed); |
2369 | 0 | } |
2370 | 0 | } |
2371 | 0 | mt->filling = 1; |
2372 | 0 | job->mode = mode; |
2373 | 0 | job->prefixSize = prefixSize; |
2374 | 0 | if ( inPlace |
2375 | 0 | && ((remaining >= mt->jobSize) || cctx->prefs.autoFlush) |
2376 | 0 | && (prevRun + (size_t)(ip - istart) >= prefixSize) ) { |
2377 | | /* read in place : whole job is within @srcBuffer, and its history right before */ |
2378 | 0 | size_t const jobSize = MIN(remaining, mt->jobSize); |
2379 | 0 | job->src = ip; |
2380 | 0 | job->srcSize = jobSize; |
2381 | 0 | if (cctx->prefs.autoFlush && (jobSize == remaining)) |
2382 | 0 | LZ4F_mt_submitLast(mt); /* all jobs are waited for before returning */ |
2383 | 0 | else |
2384 | 0 | LZ4F_mt_submit(mt); |
2385 | 0 | ip += jobSize; |
2386 | 0 | continue; |
2387 | 0 | } |
2388 | | /* copy : history first, right before content */ |
2389 | 0 | assert(job->inBuff == NULL); |
2390 | 0 | job->inBuff = LZ4F_mt_acquireInBuff(mt, cctx->cmem); |
2391 | 0 | if (job->inBuff == NULL) { |
2392 | 0 | mt->filling = 0; |
2393 | 0 | LZ4F_invalidateFrame(cctx); |
2394 | 0 | RETURN_ERROR(allocation_failed); |
2395 | 0 | } |
2396 | 0 | job->src = job->inBuff + LZ4F_MT_PREFIX_SIZE; |
2397 | 0 | job->srcSize = 0; |
2398 | 0 | LZ4_memcpy(job->inBuff + LZ4F_MT_PREFIX_SIZE - prefixSize, mt->history + mt->historySize - prefixSize, prefixSize); |
2399 | 0 | } |
2400 | 0 | { size_t const toCopy = MIN(mt->jobSize - job->srcSize, (size_t)(iend - ip)); |
2401 | 0 | assert(job->src == job->inBuff + LZ4F_MT_PREFIX_SIZE); |
2402 | 0 | LZ4_memcpy(job->inBuff + LZ4F_MT_PREFIX_SIZE + job->srcSize, ip, toCopy); |
2403 | 0 | job->srcSize += toCopy; |
2404 | 0 | if (job->srcSize == mt->jobSize) LZ4F_mt_submit(mt); |
2405 | 0 | ip += toCopy; |
2406 | 0 | } |
2407 | 0 | } |
2408 | 0 | cctx->totalInSize += srcSize; |
2409 | 0 | if (srcSize) { |
2410 | 0 | mt->stableEnd = stableUntilFlush ? iend : NULL; |
2411 | 0 | mt->stableRun = MIN(prevRun + srcSize, LZ4F_MT_PREFIX_SIZE); |
2412 | 0 | } |
2413 | | |
2414 | | /* autoFlush : the last job is submitted too (see LZ4F_mt_submitLast()), and all jobs are emitted */ |
2415 | 0 | if (cctx->prefs.autoFlush && mt->filling) LZ4F_mt_submitLast(mt); |
2416 | 0 | { size_t const r = LZ4F_mt_emit(mt, dst, dstCapacity, pos, cctx->prefs.autoFlush != 0); |
2417 | 0 | FORWARD_IF_ERROR_INVALIDATE(r, cctx); |
2418 | 0 | return pos + r; |
2419 | 0 | } |
2420 | 0 | } |
2421 | | |
2422 | | |
2423 | | /*! LZ4F_st_update() : |
2424 | | * LZ4F_compressUpdate(), single-threaded mode (@blockCompression : compressed or uncompressed input ; |
2425 | | * @compressOptionsPtr : not NULL). |
2426 | | * Input first completes the block buffered within cctx, then full blocks are compressed directly from @srcBuffer |
2427 | | * (all remaining input with autoFlush), and the remainder is buffered. |
2428 | | * A change of @blockCompression first flushes the buffered block. */ |
2429 | | static size_t LZ4F_st_update(LZ4F_cctx* cctxPtr, |
2430 | | void* dstBuffer, size_t dstCapacity, |
2431 | | const void* srcBuffer, size_t srcSize, |
2432 | | const LZ4F_compressOptions_t* compressOptionsPtr, |
2433 | | LZ4F_BlockCompressMode_e blockCompression) |
2434 | 0 | { |
2435 | 0 | size_t const blockSize = cctxPtr->maxBlockSize; |
2436 | 0 | const BYTE* srcPtr = (const BYTE*)srcBuffer; |
2437 | 0 | const BYTE* const srcEnd = srcSize ? (assert(srcPtr!=NULL), srcPtr + srcSize) : srcPtr; |
2438 | 0 | BYTE* const dstStart = (BYTE*)dstBuffer; |
2439 | 0 | BYTE* const dstEnd = dstStart + dstCapacity; |
2440 | 0 | BYTE* dstPtr = dstStart; |
2441 | 0 | LZ4F_lastBlockStatus lastBlockCompressed = notDone; |
2442 | 0 | compressFunc_t const compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, blockCompression); |
2443 | 0 | size_t bytesWritten; |
2444 | 0 | DEBUGLOG(4, "LZ4F_compressUpdate (srcSize=%zu)", srcSize); |
2445 | |
|
2446 | 0 | RETURN_ERROR_IF(cctxPtr->cStage != 1, compressionState_uninitialized); /* state must be initialized and waiting for next block */ |
2447 | | |
2448 | | /* output left pending by an incomplete LZ4F_flush() */ |
2449 | 0 | bytesWritten = LZ4F_emitPendingWhole(cctxPtr, dstPtr, dstCapacity); |
2450 | 0 | FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr); |
2451 | 0 | dstPtr += bytesWritten; |
2452 | | |
2453 | | /* flush currently written block, to continue with new block compression */ |
2454 | 0 | if (cctxPtr->blockCompressMode != blockCompression) { |
2455 | 0 | bytesWritten = LZ4F_flushBlock(cctxPtr, dstPtr, (size_t)(dstEnd - dstPtr)); |
2456 | 0 | FORWARD_IF_ERROR(bytesWritten); /* note : a failed flush invalidates the frame */ |
2457 | 0 | dstPtr += bytesWritten; |
2458 | 0 | cctxPtr->blockCompressMode = blockCompression; |
2459 | 0 | if ((blockCompression == LZ4B_UNCOMPRESSED) && (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked)) { |
2460 | | /* linked blocks : the decoder's history will contain uncompressed data, unknown to the LZ4 state : |
2461 | | * history is dropped, blocks compressed next don't reference anything before them */ |
2462 | 0 | LZ4F_startStream(cctxPtr->lz4CtxPtr, &cctxPtr->prefs, NULL, NULL, 0); |
2463 | 0 | } |
2464 | 0 | } |
2465 | | |
2466 | | /* complete tmp buffer */ |
2467 | 0 | if (cctxPtr->tmpInSize > 0) { /* some data already within tmp buffer */ |
2468 | 0 | size_t const sizeToCopy = blockSize - cctxPtr->tmpInSize; |
2469 | 0 | assert(blockSize > cctxPtr->tmpInSize); |
2470 | 0 | if (sizeToCopy > srcSize) { |
2471 | | /* add src to tmpIn buffer */ |
2472 | 0 | LZ4_memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize); |
2473 | 0 | srcPtr = srcEnd; |
2474 | 0 | cctxPtr->tmpInSize += srcSize; |
2475 | | /* still needs some CRC */ |
2476 | 0 | } else { |
2477 | | /* complete tmpIn block and then compress it */ |
2478 | 0 | lastBlockCompressed = fromTmpBuffer; |
2479 | 0 | LZ4_memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy); |
2480 | 0 | srcPtr += sizeToCopy; |
2481 | |
|
2482 | 0 | bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr), |
2483 | 0 | cctxPtr->tmpIn, blockSize, |
2484 | 0 | compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, |
2485 | 0 | cctxPtr->cdict, |
2486 | 0 | cctxPtr->prefs.frameInfo.blockChecksumFlag); |
2487 | 0 | FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr); |
2488 | 0 | dstPtr += bytesWritten; |
2489 | 0 | if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += blockSize; |
2490 | 0 | cctxPtr->tmpInSize = 0; |
2491 | 0 | } } |
2492 | | |
2493 | | /* compress full blocks; with autoFlush, remaining input (< blockSize) is compressed too */ |
2494 | 0 | { size_t const remaining = (size_t)(srcEnd - srcPtr); |
2495 | 0 | size_t const toCompress = cctxPtr->prefs.autoFlush ? remaining : remaining - (remaining % blockSize); |
2496 | | /* autoFlush, linked blocks, unstable input smaller than the history window (64 KB) : |
2497 | | * compressed from @srcBuffer, it would become the only history of next blocks. |
2498 | | * It's compressed from tmpBuff instead, right after the history, which remains whole. */ |
2499 | 0 | int const viaTmp = cctxPtr->prefs.autoFlush |
2500 | 0 | && (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) |
2501 | 0 | && !compressOptionsPtr->stableSrc |
2502 | 0 | && (blockCompression == LZ4B_COMPRESSED) |
2503 | 0 | && (toCompress > 0) && (toCompress < 64 KB); |
2504 | 0 | if (viaTmp) { |
2505 | 0 | if (cctxPtr->tmpIn + toCompress > cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity) |
2506 | 0 | LZ4F_localSaveDict(cctxPtr); /* tmpBuff >= 128 KB : room after the history */ |
2507 | 0 | LZ4_memcpy(cctxPtr->tmpIn, srcPtr, toCompress); |
2508 | 0 | lastBlockCompressed = fromTmpBuffer; |
2509 | 0 | bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr), |
2510 | 0 | cctxPtr->tmpIn, toCompress, |
2511 | 0 | compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, |
2512 | 0 | cctxPtr->cdict, |
2513 | 0 | cctxPtr->prefs.frameInfo.blockChecksumFlag); |
2514 | 0 | FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr); |
2515 | 0 | dstPtr += bytesWritten; |
2516 | 0 | srcPtr += toCompress; |
2517 | 0 | cctxPtr->tmpIn += toCompress; |
2518 | 0 | } else if (toCompress) { |
2519 | 0 | lastBlockCompressed = fromSrcBuffer; |
2520 | 0 | bytesWritten = LZ4F_compressBlocks_internal(dstPtr, (size_t)(dstEnd - dstPtr), |
2521 | 0 | srcPtr, toCompress, blockSize, |
2522 | 0 | compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, |
2523 | 0 | cctxPtr->cdict, |
2524 | 0 | cctxPtr->prefs.frameInfo.blockChecksumFlag); |
2525 | 0 | FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr); |
2526 | 0 | dstPtr += bytesWritten; |
2527 | 0 | srcPtr += toCompress; |
2528 | 0 | } } |
2529 | | |
2530 | | /* preserve dictionary within @tmpBuff whenever necessary */ |
2531 | 0 | if ((cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) && (lastBlockCompressed==fromSrcBuffer)) { |
2532 | | /* note : after uncompressed blocks, the LZ4 state is empty (history dropped), so is the saved dictionary */ |
2533 | 0 | if (compressOptionsPtr->stableSrc) { |
2534 | 0 | cctxPtr->tmpIn = cctxPtr->tmpBuff; /* src is stable : dictionary remains in src across invocations */ |
2535 | 0 | } else { |
2536 | 0 | LZ4F_localSaveDict(cctxPtr); |
2537 | 0 | } |
2538 | 0 | } |
2539 | | |
2540 | | /* keep tmpIn within limits */ |
2541 | 0 | if (!(cctxPtr->prefs.autoFlush) /* no autoflush : there may be some data left within internal buffer */ |
2542 | 0 | && (cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity) ) /* not enough room to store next block */ |
2543 | 0 | { |
2544 | | /* only preserve 64KB within internal buffer. Ensures there is enough room for next block. |
2545 | | * note: this situation necessarily implies lastBlockCompressed==fromTmpBuffer */ |
2546 | 0 | LZ4F_localSaveDict(cctxPtr); |
2547 | 0 | assert((cctxPtr->tmpIn + blockSize) <= (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity)); |
2548 | 0 | } |
2549 | | |
2550 | | /* some input data left, necessarily < blockSize */ |
2551 | 0 | if (srcPtr < srcEnd) { |
2552 | | /* fill tmp buffer */ |
2553 | 0 | size_t const sizeToCopy = (size_t)(srcEnd - srcPtr); |
2554 | 0 | LZ4_memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy); |
2555 | 0 | cctxPtr->tmpInSize = sizeToCopy; |
2556 | 0 | } |
2557 | |
|
2558 | 0 | if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) |
2559 | 0 | (void)XXH32_update(&(cctxPtr->xxh), srcBuffer, srcSize); |
2560 | |
|
2561 | 0 | cctxPtr->totalInSize += srcSize; |
2562 | 0 | return (size_t)(dstPtr - dstStart); |
2563 | 0 | } |
2564 | | |
2565 | | /*! LZ4F_compressUpdate() : |
2566 | | * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary. |
2567 | | * When successful, the function always entirely consumes @srcBuffer. |
2568 | | * src data is either buffered or compressed into @dstBuffer. |
2569 | | * With @compressOptionsPtr->uncompressed == 1, src data is stored as uncompressed blocks instead. |
2570 | | * With linked blocks, blocks compressed next don't reference data preceding them (single-threaded mode), |
2571 | | * or reference the uncompressed data (multi-threaded mode, see LZ4F_compressJob()). |
2572 | | * A switch between compressed and uncompressed input first flushes buffered data. |
2573 | | * Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, preferencesPtr). |
2574 | | * Otherwise, the operation fails with dstCapacity_tooSmall if its output doesn't fit. |
2575 | | * @compressOptionsPtr is optional : provide NULL to mean "default". |
2576 | | * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered. |
2577 | | * or an error code if it fails (which can be tested using LZ4F_isError()) |
2578 | | * After an error, the frame is invalidated, and must be restarted with LZ4F_compressBegin(). |
2579 | | */ |
2580 | | size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr, |
2581 | | void* dstBuffer, size_t dstCapacity, |
2582 | | const void* srcBuffer, size_t srcSize, |
2583 | | const LZ4F_compressOptions_t* compressOptionsPtr) |
2584 | 0 | { |
2585 | 0 | LZ4F_BlockCompressMode_e mode; |
2586 | 0 | if (compressOptionsPtr == NULL) compressOptionsPtr = &k_cOptionsNull; |
2587 | 0 | mode = (compressOptionsPtr->uncompressed == 1) ? LZ4B_UNCOMPRESSED : LZ4B_COMPRESSED; |
2588 | 0 | if (cctxPtr->mtActive) |
2589 | 0 | return LZ4F_mt_update(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, compressOptionsPtr, mode); |
2590 | 0 | return LZ4F_st_update(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, compressOptionsPtr, mode); |
2591 | 0 | } |
2592 | | |
2593 | | /*! LZ4F_uncompressedUpdate() : deprecated |
2594 | | * LZ4F_compressUpdate() with option uncompressed. |
2595 | | */ |
2596 | | size_t LZ4F_uncompressedUpdate(LZ4F_cctx* cctxPtr, |
2597 | | void* dstBuffer, size_t dstCapacity, |
2598 | | const void* srcBuffer, size_t srcSize, |
2599 | | const LZ4F_compressOptions_t* compressOptionsPtr) |
2600 | 0 | { |
2601 | 0 | LZ4F_compressOptions_t cOpts = k_cOptionsNull; |
2602 | 0 | if (compressOptionsPtr != NULL) cOpts = *compressOptionsPtr; |
2603 | 0 | cOpts.uncompressed = 1; |
2604 | 0 | return LZ4F_compressUpdate(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, &cOpts); |
2605 | 0 | } |
2606 | | |
2607 | | |
2608 | | /* emits pending output into @dst + @pos, as much as fits : block or footer (pending), then jobs (multi-threaded mode). |
2609 | | * @return : new position, or an error code (the frame is then invalidated) */ |
2610 | | static size_t LZ4F_emitPending(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity, size_t pos) |
2611 | 0 | { |
2612 | 0 | pos += LZ4F_copyPending(cctx, dst, dstCapacity, pos); |
2613 | 0 | if (cctx->mtActive && (cctx->pendingSize == 0)) { |
2614 | 0 | size_t const r = LZ4F_mt_emitPartial(cctx->mt, dst, dstCapacity, pos); |
2615 | 0 | FORWARD_IF_ERROR_INVALIDATE(r, cctx); |
2616 | 0 | pos += r; |
2617 | 0 | } |
2618 | 0 | return pos; |
2619 | 0 | } |
2620 | | |
2621 | | static int LZ4F_outputPending(const LZ4F_cctx_t* cctx) |
2622 | 0 | { |
2623 | 0 | return (cctx->pendingSize > 0) || (cctx->mtActive && (cctx->mt->nbSubmitted > 0)); |
2624 | 0 | } |
2625 | | |
2626 | | /* @return : 1 if LZ4F_flush() has output to produce */ |
2627 | | static int LZ4F_somethingToFlush(const LZ4F_cctx_t* cctx) |
2628 | 0 | { |
2629 | 0 | if (LZ4F_outputPending(cctx)) return 1; |
2630 | 0 | if (cctx->mtActive) return cctx->mt->filling; |
2631 | 0 | return cctx->tmpInSize > 0; |
2632 | 0 | } |
2633 | | |
2634 | | /* flush point : input retained within cctx is compressed, and no longer read. |
2635 | | * @return : nb of bytes written into @dst, or an error code (the frame is then invalidated) */ |
2636 | | static size_t LZ4F_flushPoint(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity) |
2637 | 0 | { |
2638 | 0 | size_t r = 0; |
2639 | 0 | if (cctx->mtActive) { |
2640 | 0 | LZ4F_mt_flushPoint(cctx->mt); |
2641 | 0 | } else { |
2642 | 0 | r = LZ4F_flushBlockPartial(cctx, dst, dstCapacity); |
2643 | 0 | } |
2644 | 0 | if (!LZ4F_isError(r)) cctx->flushStage = 1; |
2645 | 0 | return r; |
2646 | 0 | } |
2647 | | |
2648 | | /*! LZ4F_flush() : |
2649 | | * When compressed data must be sent immediately, without waiting for a block to be filled, |
2650 | | * invoke LZ4F_flush(), which will immediately compress any remaining data stored within LZ4F_cctx. |
2651 | | * The invocation fills @dstBuffer, or completes the flush : |
2652 | | * as long as it returns @dstCapacity, output may remain : invoke LZ4F_flush() again. |
2653 | | * The first invocation sets the flush point : input retained within cctx is compressed (all jobs completed). |
2654 | | * The result of the function is the number of bytes written into dstBuffer. |
2655 | | * It can be zero, this means there was no data left within LZ4F_cctx. |
2656 | | * The function outputs an error code if it fails (can be tested using LZ4F_isError()) |
2657 | | * A single invocation completes the flush when dstCapacity >= LZ4F_compressBound(0, preferencesPtr). |
2658 | | * dstCapacity == 0 is rejected (dstCapacity_tooSmall) when there is something to flush, without modifying the frame. |
2659 | | * LZ4F_compressOptions_t* is optional : NULL is a valid argument. |
2660 | | */ |
2661 | | size_t LZ4F_flush(LZ4F_cctx* cctxPtr, |
2662 | | void* dstBuffer, size_t dstCapacity, |
2663 | | const LZ4F_compressOptions_t* compressOptionsPtr) |
2664 | 0 | { |
2665 | 0 | BYTE* const dst = (BYTE*)dstBuffer; |
2666 | 0 | size_t pos = 0; |
2667 | 0 | DEBUGLOG(5, "LZ4F_flush (dstCapacity=%u)", (unsigned)dstCapacity); |
2668 | 0 | (void)compressOptionsPtr; /* not useful (yet) */ |
2669 | 0 | RETURN_ERROR_IF(cctxPtr->cStage != 1, compressionState_uninitialized); |
2670 | 0 | if (dstCapacity == 0) { |
2671 | | /* no progress possible : rejected, the frame continues */ |
2672 | 0 | RETURN_ERROR_IF(LZ4F_somethingToFlush(cctxPtr), dstCapacity_tooSmall); |
2673 | 0 | cctxPtr->flushStage = 0; |
2674 | 0 | return 0; |
2675 | 0 | } |
2676 | 0 | if (cctxPtr->flushStage == 0) { |
2677 | 0 | pos = LZ4F_flushPoint(cctxPtr, dst, dstCapacity); |
2678 | 0 | FORWARD_IF_ERROR(pos); /* already invalidated */ |
2679 | 0 | } |
2680 | 0 | pos = LZ4F_emitPending(cctxPtr, dst, dstCapacity, pos); |
2681 | 0 | FORWARD_IF_ERROR(pos); /* already invalidated */ |
2682 | 0 | if (pos < dstCapacity) cctxPtr->flushStage = 0; /* completed */ |
2683 | 0 | return pos; |
2684 | 0 | } |
2685 | | |
2686 | | |
2687 | | /*! LZ4F_compressEnd() : |
2688 | | * When you want to properly finish the compressed frame, just call LZ4F_compressEnd(). |
2689 | | * It will flush whatever data remained within compressionContext (like LZ4_flush()) |
2690 | | * but also properly finalize the frame, with an endMark and an (optional) checksum. |
2691 | | * The invocation fills @dstBuffer, or completes the frame : |
2692 | | * as long as it returns @dstCapacity, output may remain : invoke LZ4F_compressEnd() again. |
2693 | | * LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. |
2694 | | * @return: the number of bytes written into dstBuffer (the last invocation writes the endMark, unless already written) |
2695 | | * or an error code if it fails (can be tested using LZ4F_isError()) |
2696 | | * Once completed, the context can be used again to compress a new frame, starting with LZ4F_compressBegin(). |
2697 | | */ |
2698 | | size_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr, |
2699 | | void* dstBuffer, size_t dstCapacity, |
2700 | | const LZ4F_compressOptions_t* compressOptionsPtr) |
2701 | 0 | { |
2702 | 0 | BYTE* const dst = (BYTE*)dstBuffer; |
2703 | 0 | size_t pos = 0; |
2704 | 0 | DEBUGLOG(5,"LZ4F_compressEnd: dstCapacity=%u", (unsigned)dstCapacity); |
2705 | 0 | (void)compressOptionsPtr; /* not useful (yet) */ |
2706 | 0 | RETURN_ERROR_IF((cctxPtr->cStage != 1) && (cctxPtr->cStage != 2), compressionState_uninitialized); |
2707 | 0 | RETURN_ERROR_IF(dstCapacity == 0, dstCapacity_tooSmall); /* no progress possible : rejected, the frame continues */ |
2708 | | |
2709 | 0 | if (cctxPtr->cStage == 1) { |
2710 | | /* end of frame : no more input */ |
2711 | 0 | if (cctxPtr->prefs.frameInfo.contentSize && (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize)) { |
2712 | 0 | LZ4F_invalidateFrame(cctxPtr); |
2713 | 0 | RETURN_ERROR(frameSize_wrong); |
2714 | 0 | } |
2715 | 0 | cctxPtr->cStage = 2; |
2716 | 0 | if (cctxPtr->flushStage == 0) { |
2717 | 0 | pos = LZ4F_flushPoint(cctxPtr, dst, dstCapacity); |
2718 | 0 | FORWARD_IF_ERROR(pos); /* already invalidated */ |
2719 | 0 | } } |
2720 | | |
2721 | 0 | if (cctxPtr->flushStage == 1) { |
2722 | 0 | pos = LZ4F_emitPending(cctxPtr, dst, dstCapacity, pos); |
2723 | 0 | FORWARD_IF_ERROR(pos); /* already invalidated */ |
2724 | 0 | if (LZ4F_outputPending(cctxPtr)) return pos; /* dstBuffer is full */ |
2725 | | /* footer : endMark, then optional content checksum */ |
2726 | 0 | LZ4F_writeLE32(cctxPtr->footer, 0); |
2727 | 0 | cctxPtr->pendingSize = 4; |
2728 | 0 | if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) { |
2729 | 0 | U32 const xxh = XXH32_digest(&(cctxPtr->xxh)); |
2730 | 0 | DEBUGLOG(5,"Writing 32-bit content checksum (0x%0X)", xxh); |
2731 | 0 | LZ4F_writeLE32(cctxPtr->footer + 4, xxh); |
2732 | 0 | cctxPtr->pendingSize = 8; |
2733 | 0 | } |
2734 | 0 | cctxPtr->pending = cctxPtr->footer; |
2735 | 0 | cctxPtr->flushStage = 2; |
2736 | 0 | } |
2737 | | |
2738 | 0 | if (cctxPtr->flushStage == 2) { |
2739 | 0 | pos += LZ4F_copyPending(cctxPtr, dst, dstCapacity, pos); |
2740 | 0 | if (cctxPtr->pendingSize) return pos; /* dstBuffer is full */ |
2741 | 0 | cctxPtr->flushStage = 3; |
2742 | 0 | } |
2743 | | |
2744 | 0 | assert(cctxPtr->flushStage == 3); |
2745 | 0 | if (pos < dstCapacity) { |
2746 | | /* completed : the context is available for a new frame */ |
2747 | 0 | cctxPtr->cStage = 0; |
2748 | 0 | cctxPtr->flushStage = 0; |
2749 | 0 | } /* otherwise, completed, but dstBuffer is full : next invocation returns 0 */ |
2750 | 0 | return pos; |
2751 | 0 | } |
2752 | | |
2753 | | |
2754 | | /*-*************************************************** |
2755 | | * Frame Decompression |
2756 | | *****************************************************/ |
2757 | | |
2758 | | typedef enum { |
2759 | | dstage_getFrameHeader=0, dstage_storeFrameHeader, |
2760 | | dstage_init, |
2761 | | dstage_getBlockHeader, |
2762 | | dstage_copyDirect, dstage_getBlockChecksum, |
2763 | | dstage_getCBlock, |
2764 | | dstage_flushOut, |
2765 | | dstage_getSuffix, |
2766 | | dstage_getSFrameSize, |
2767 | | dstage_skipSkippable |
2768 | | } dStage_t; |
2769 | | |
2770 | | struct LZ4F_dctx_s { |
2771 | | LZ4F_CustomMem cmem; |
2772 | | LZ4F_frameInfo_t frameInfo; |
2773 | | U32 version; |
2774 | | dStage_t dStage; |
2775 | | U64 frameRemainingSize; |
2776 | | size_t maxBlockSize; |
2777 | | size_t tmpOutBufferCapacity; |
2778 | | BYTE* tmpIn; |
2779 | | size_t tmpInCapacity; |
2780 | | size_t tmpInSize; |
2781 | | size_t tmpInTarget; |
2782 | | unsigned progressive; /* see LZ4F_setProgressiveDecoding() */ |
2783 | | unsigned progressiveFrame; /* progressive decoding of the current frame : set at its start (tmpOutBuffer sized for it) */ |
2784 | | size_t tmpInDecoded; /* first block, incomplete : bytes of tmpIn already decoded (see LZ4F_decodeProgressive()) */ |
2785 | | size_t blockDecoded; /* first block, incomplete : its decoded size so far */ |
2786 | | const BYTE* blockDict; /* dictionary before the first block : restored after it (independent blocks) */ |
2787 | | size_t blockDictSize; |
2788 | | unsigned blockNb; /* blocks of the frame started so far, up to 2 */ |
2789 | | BYTE* tmpOutBuffer; |
2790 | | const BYTE* dict; |
2791 | | size_t dictSize; |
2792 | | BYTE* tmpOut; |
2793 | | size_t tmpOutSize; |
2794 | | size_t tmpOutStart; |
2795 | | XXH32_state_t xxh; |
2796 | | XXH32_state_t blockChecksum; |
2797 | | int skipBlockChecksum; |
2798 | | int skipContentChecksum; |
2799 | | unsigned frameEnded; /* a frame just ended : frameInfo still describes it (see LZ4F_getFrameInfo()) */ |
2800 | | BYTE header[LZ4F_HEADER_SIZE_MAX]; |
2801 | | }; /* typedef'd to LZ4F_dctx in lz4frame.h */ |
2802 | | |
2803 | | |
2804 | | LZ4F_dctx* LZ4F_createDecompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version) |
2805 | 0 | { |
2806 | 0 | LZ4F_dctx* const dctx = (LZ4F_dctx*)LZ4F_calloc(sizeof(LZ4F_dctx), customMem); |
2807 | 0 | if (dctx == NULL) return NULL; |
2808 | | |
2809 | 0 | dctx->cmem = customMem; |
2810 | 0 | dctx->version = version; |
2811 | 0 | return dctx; |
2812 | 0 | } |
2813 | | |
2814 | | /*! LZ4F_createDecompressionContext() : |
2815 | | * Create a decompressionContext object, which will track all decompression operations. |
2816 | | * Provides a pointer to a fully allocated and initialized LZ4F_decompressionContext object. |
2817 | | * Object can later be released using LZ4F_freeDecompressionContext(). |
2818 | | * @return : if != 0, there was an error during context creation. |
2819 | | */ |
2820 | | LZ4F_errorCode_t |
2821 | | LZ4F_createDecompressionContext(LZ4F_dctx** LZ4F_decompressionContextPtr, unsigned versionNumber) |
2822 | 0 | { |
2823 | 0 | assert(LZ4F_decompressionContextPtr != NULL); /* violation of narrow contract */ |
2824 | 0 | RETURN_ERROR_IF(LZ4F_decompressionContextPtr == NULL, parameter_null); /* in case it nonetheless happen in production */ |
2825 | | |
2826 | 0 | *LZ4F_decompressionContextPtr = LZ4F_createDecompressionContext_advanced(LZ4F_defaultCMem, versionNumber); |
2827 | 0 | if (*LZ4F_decompressionContextPtr == NULL) { /* failed allocation */ |
2828 | 0 | RETURN_ERROR(allocation_failed); |
2829 | 0 | } |
2830 | 0 | return LZ4F_OK_NoError; |
2831 | 0 | } |
2832 | | |
2833 | | LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx) |
2834 | 0 | { |
2835 | 0 | LZ4F_errorCode_t result = LZ4F_OK_NoError; |
2836 | 0 | if (dctx != NULL) { /* can accept NULL input, like free() */ |
2837 | 0 | result = (LZ4F_errorCode_t)dctx->dStage; |
2838 | 0 | LZ4F_free(dctx->tmpIn, dctx->cmem); |
2839 | 0 | LZ4F_free(dctx->tmpOutBuffer, dctx->cmem); |
2840 | 0 | LZ4F_free(dctx, dctx->cmem); |
2841 | 0 | } |
2842 | 0 | return result; |
2843 | 0 | } |
2844 | | |
2845 | 0 | size_t LZ4F_dctx_size(const LZ4F_dctx* dctx) { |
2846 | 0 | if (dctx == NULL) { |
2847 | 0 | return 0; |
2848 | 0 | } |
2849 | 0 | return sizeof(*dctx) + dctx->tmpInCapacity + dctx->tmpOutBufferCapacity; |
2850 | 0 | } |
2851 | | |
2852 | | |
2853 | | /*==--- Streaming Decompression operations ---==*/ |
2854 | | void LZ4F_setProgressiveDecoding(LZ4F_dctx* dctx, unsigned enable) |
2855 | 0 | { |
2856 | 0 | dctx->progressive = (enable != 0); |
2857 | 0 | } |
2858 | | |
2859 | | void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx) |
2860 | 0 | { |
2861 | 0 | DEBUGLOG(5, "LZ4F_resetDecompressionContext"); |
2862 | 0 | dctx->dStage = dstage_getFrameHeader; |
2863 | 0 | dctx->dict = NULL; |
2864 | 0 | dctx->dictSize = 0; |
2865 | 0 | dctx->skipBlockChecksum = 0; |
2866 | 0 | dctx->skipContentChecksum = 0; |
2867 | 0 | dctx->frameRemainingSize = 0; |
2868 | 0 | dctx->frameEnded = 0; |
2869 | 0 | } |
2870 | | |
2871 | | /* LZ4F_endFrame() : |
2872 | | * prepares dctx for a new frame, keeping the parameters of the frame that just ended (see LZ4F_getFrameInfo()) */ |
2873 | | static void LZ4F_endFrame(LZ4F_dctx* dctx) |
2874 | 0 | { |
2875 | 0 | LZ4F_resetDecompressionContext(dctx); |
2876 | 0 | dctx->frameEnded = 1; |
2877 | 0 | } |
2878 | | |
2879 | | |
2880 | | /*! LZ4F_decodeHeader() : |
2881 | | * input : `src` points at the **beginning of the frame**, srcSize >= minFHSize |
2882 | | * output : set internal values of dctx, such as |
2883 | | * dctx->frameInfo and dctx->dStage. |
2884 | | * @return : nb Bytes read from src (necessarily <= srcSize) |
2885 | | * or an error code (testable with LZ4F_isError()) |
2886 | | */ |
2887 | | static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize) |
2888 | 0 | { |
2889 | 0 | unsigned blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictIDFlag, blockSizeID; |
2890 | 0 | size_t frameHeaderSize; |
2891 | 0 | const BYTE* srcPtr = (const BYTE*)src; |
2892 | |
|
2893 | 0 | DEBUGLOG(5, "LZ4F_decodeHeader"); |
2894 | 0 | assert(srcSize >= minFHSize); /* minimal frame header size */ |
2895 | 0 | MEM_INIT(&(dctx->frameInfo), 0, sizeof(dctx->frameInfo)); |
2896 | 0 | dctx->frameEnded = 0; |
2897 | | |
2898 | | /* special case : skippable frames */ |
2899 | 0 | if ((LZ4F_readLE32(srcPtr) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) { |
2900 | 0 | dctx->frameInfo.frameType = LZ4F_skippableFrame; |
2901 | 0 | dctx->dStage = dstage_getSFrameSize; |
2902 | 0 | if (src == (void*)(dctx->header)) { |
2903 | | /* the beginning of the frame size field is already gathered in header+4 */ |
2904 | 0 | assert(srcSize <= 8); |
2905 | 0 | dctx->tmpInSize = srcSize - 4; |
2906 | 0 | return srcSize; |
2907 | 0 | } else { |
2908 | 0 | dctx->tmpInSize = 0; |
2909 | 0 | return 4; |
2910 | 0 | } } |
2911 | | |
2912 | | /* control magic number */ |
2913 | | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
2914 | | if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) { |
2915 | | DEBUGLOG(4, "frame header error : unknown magic number"); |
2916 | | RETURN_ERROR(frameType_unknown); |
2917 | | } |
2918 | | #endif |
2919 | 0 | dctx->frameInfo.frameType = LZ4F_frame; |
2920 | | |
2921 | | /* Flags */ |
2922 | 0 | { U32 const FLG = srcPtr[4]; |
2923 | 0 | U32 const version = (FLG>>6) & _2BITS; |
2924 | 0 | blockChecksumFlag = (FLG>>4) & _1BIT; |
2925 | 0 | blockMode = (FLG>>5) & _1BIT; |
2926 | 0 | contentSizeFlag = (FLG>>3) & _1BIT; |
2927 | 0 | contentChecksumFlag = (FLG>>2) & _1BIT; |
2928 | 0 | dictIDFlag = FLG & _1BIT; |
2929 | | /* validate */ |
2930 | 0 | if (((FLG>>1)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bit */ |
2931 | 0 | if (version != 1) RETURN_ERROR(headerVersion_wrong); /* Version Number, only supported value */ |
2932 | 0 | } |
2933 | 0 | DEBUGLOG(6, "contentSizeFlag: %u", contentSizeFlag); |
2934 | | |
2935 | | /* Frame Header Size */ |
2936 | 0 | frameHeaderSize = minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0); |
2937 | |
|
2938 | 0 | if (srcSize < frameHeaderSize) { |
2939 | | /* only the minimal header is gathered into dctx->header : gather the rest */ |
2940 | 0 | assert(srcPtr == dctx->header); |
2941 | 0 | assert(dctx->dStage == dstage_storeFrameHeader); |
2942 | 0 | assert(dctx->tmpInSize == srcSize); |
2943 | 0 | dctx->tmpInTarget = frameHeaderSize; |
2944 | 0 | return srcSize; |
2945 | 0 | } |
2946 | | |
2947 | 0 | { U32 const BD = srcPtr[5]; |
2948 | 0 | blockSizeID = (BD>>4) & _3BITS; |
2949 | | /* validate */ |
2950 | 0 | if (((BD>>7)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bit */ |
2951 | 0 | if (blockSizeID < 4) RETURN_ERROR(maxBlockSize_invalid); /* 4-7 only supported values for the time being */ |
2952 | 0 | if (((BD>>0)&_4BITS) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bits */ |
2953 | 0 | } |
2954 | | |
2955 | | /* check header */ |
2956 | 0 | assert(frameHeaderSize > 5); |
2957 | | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
2958 | | { BYTE const HC = LZ4F_headerChecksum(srcPtr+4, frameHeaderSize-5); |
2959 | | RETURN_ERROR_IF(HC != srcPtr[frameHeaderSize-1], headerChecksum_invalid); |
2960 | | } |
2961 | | #endif |
2962 | | |
2963 | | /* save */ |
2964 | 0 | dctx->frameInfo.blockMode = (LZ4F_blockMode_t)blockMode; |
2965 | 0 | dctx->frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)blockChecksumFlag; |
2966 | 0 | dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag; |
2967 | 0 | dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID; |
2968 | 0 | dctx->maxBlockSize = LZ4F_getBlockSize((LZ4F_blockSizeID_t)blockSizeID); |
2969 | 0 | if (contentSizeFlag) { |
2970 | 0 | dctx->frameRemainingSize = dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6); |
2971 | 0 | } |
2972 | 0 | if (dictIDFlag) |
2973 | 0 | dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5); |
2974 | |
|
2975 | 0 | dctx->dStage = dstage_init; |
2976 | |
|
2977 | 0 | return frameHeaderSize; |
2978 | 0 | } |
2979 | | |
2980 | | |
2981 | | /*! LZ4F_headerSize() : |
2982 | | * @return : size of frame header |
2983 | | * or an error code, which can be tested using LZ4F_isError() |
2984 | | */ |
2985 | | size_t LZ4F_headerSize(const void* src, size_t srcSize) |
2986 | 0 | { |
2987 | 0 | RETURN_ERROR_IF(src == NULL, srcPtr_wrong); |
2988 | | |
2989 | | /* minimal srcSize to determine header size */ |
2990 | 0 | if (srcSize < LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH) |
2991 | 0 | RETURN_ERROR(frameHeader_incomplete); |
2992 | | |
2993 | | /* special case : skippable frames */ |
2994 | 0 | if ((LZ4F_readLE32(src) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) |
2995 | 0 | return 8; |
2996 | | |
2997 | | /* control magic number */ |
2998 | | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
2999 | | if (LZ4F_readLE32(src) != LZ4F_MAGICNUMBER) |
3000 | | RETURN_ERROR(frameType_unknown); |
3001 | | #endif |
3002 | | |
3003 | | /* Frame Header Size */ |
3004 | 0 | { BYTE const FLG = ((const BYTE*)src)[4]; |
3005 | 0 | U32 const contentSizeFlag = (FLG>>3) & _1BIT; |
3006 | 0 | U32 const dictIDFlag = FLG & _1BIT; |
3007 | 0 | return minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0); |
3008 | 0 | } |
3009 | 0 | } |
3010 | | |
3011 | | /*! LZ4F_getFrameInfo() : |
3012 | | * This function extracts frame parameters (max blockSize, frame checksum, etc.). |
3013 | | * Usage is optional. Objective is to provide relevant information for allocation purposes. |
3014 | | * This function works in 2 situations : |
3015 | | * - At the beginning of a new frame, in which case it will decode this information from `srcBuffer`, and start the decoding process. |
3016 | | * Amount of input data provided must be large enough to successfully decode the frame header. |
3017 | | * A header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. It's possible to provide more input data than this minimum. |
3018 | | * - After decoding has been started. In which case, no input is read, frame parameters are extracted from dctx. |
3019 | | * - After the end of a frame, with no input (*srcSizePtr == 0) : parameters of this frame are extracted from dctx, and the function returns 0. |
3020 | | * The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value). |
3021 | | * Decompression must resume from (srcBuffer + *srcSizePtr). |
3022 | | * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call, |
3023 | | * or an error code which can be tested using LZ4F_isError() |
3024 | | * note 1 : in case of error, dctx is not modified. Decoding operations can resume from where they stopped. |
3025 | | * note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure. |
3026 | | */ |
3027 | | LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_dctx* dctx, |
3028 | | LZ4F_frameInfo_t* frameInfoPtr, |
3029 | | const void* srcBuffer, size_t* srcSizePtr) |
3030 | 0 | { |
3031 | 0 | assert(dctx != NULL); |
3032 | 0 | RETURN_ERROR_IF(frameInfoPtr == NULL, parameter_null); |
3033 | 0 | RETURN_ERROR_IF(srcSizePtr == NULL, parameter_null); |
3034 | | |
3035 | 0 | LZ4F_STATIC_ASSERT(dstage_getFrameHeader < dstage_storeFrameHeader); |
3036 | 0 | if (dctx->dStage > dstage_storeFrameHeader) { |
3037 | | /* frameInfo already decoded */ |
3038 | 0 | size_t o=0, i=0; |
3039 | 0 | *srcSizePtr = 0; |
3040 | 0 | *frameInfoPtr = dctx->frameInfo; |
3041 | | /* returns : recommended nb of bytes for LZ4F_decompress() */ |
3042 | 0 | return LZ4F_decompress(dctx, NULL, &o, NULL, &i, NULL); |
3043 | 0 | } else { |
3044 | 0 | if (dctx->dStage == dstage_storeFrameHeader) { |
3045 | | /* frame decoding already started, in the middle of header => automatic fail */ |
3046 | 0 | *srcSizePtr = 0; |
3047 | 0 | RETURN_ERROR(frameDecoding_alreadyStarted); |
3048 | 0 | } else if (dctx->frameEnded && (*srcSizePtr == 0)) { |
3049 | | /* no input, after the end of a frame : parameters of this frame */ |
3050 | 0 | *frameInfoPtr = dctx->frameInfo; |
3051 | 0 | return 0; |
3052 | 0 | } else { |
3053 | 0 | size_t const hSize = LZ4F_headerSize(srcBuffer, *srcSizePtr); |
3054 | 0 | if (LZ4F_isError(hSize)) { *srcSizePtr=0; return hSize; } |
3055 | 0 | if (*srcSizePtr < hSize) { |
3056 | 0 | *srcSizePtr=0; |
3057 | 0 | RETURN_ERROR(frameHeader_incomplete); |
3058 | 0 | } |
3059 | | |
3060 | 0 | { size_t decodeResult = LZ4F_decodeHeader(dctx, srcBuffer, hSize); |
3061 | 0 | if (LZ4F_isError(decodeResult)) { |
3062 | 0 | *srcSizePtr = 0; |
3063 | 0 | } else { |
3064 | 0 | *srcSizePtr = decodeResult; |
3065 | 0 | decodeResult = BHSize; /* block header size */ |
3066 | 0 | } |
3067 | 0 | *frameInfoPtr = dctx->frameInfo; |
3068 | 0 | return decodeResult; |
3069 | 0 | } } } |
3070 | 0 | } |
3071 | | |
3072 | | |
3073 | | /* LZ4F_moveDictBeforeTmpOut() : |
3074 | | * The block decoded in tmpOut is being flushed, while the history preceding it is elsewhere. |
3075 | | * Copy the end of this history in front of tmpOut (up to 64 KB with the block), so that the dictionary |
3076 | | * becomes contiguous within tmpOutBuffer, ending with the flushed part of tmpOut. |
3077 | | * @flushSize : bytes being flushed, not yet counted in tmpOutStart |
3078 | | */ |
3079 | | static void LZ4F_moveDictBeforeTmpOut(LZ4F_dctx* dctx, size_t flushSize) |
3080 | 0 | { |
3081 | 0 | size_t const preserveSize = (size_t)(dctx->tmpOut - dctx->tmpOutBuffer); |
3082 | 0 | size_t copySize = 64 KB - dctx->tmpOutSize; |
3083 | 0 | const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart; |
3084 | 0 | if (dctx->tmpOutSize > 64 KB) copySize = 0; |
3085 | 0 | if (copySize > preserveSize) copySize = preserveSize; |
3086 | 0 | assert(dctx->tmpOutBuffer != NULL); |
3087 | |
|
3088 | 0 | LZ4_memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize); |
3089 | |
|
3090 | 0 | dctx->dict = dctx->tmpOutBuffer; |
3091 | 0 | dctx->dictSize = preserveSize + dctx->tmpOutStart + flushSize; |
3092 | 0 | } |
3093 | | |
3094 | | /* LZ4F_updateDict() : |
3095 | | * A linked block references the previous 64 KB of output. |
3096 | | * After each output [dstPtr, dstPtr+dstSize) (a block, or a part of it), |
3097 | | * records where this history is, for the next block : |
3098 | | * [dict, dict+dictSize) is contiguous, and ends with dstPtr+dstSize. |
3099 | | * It stays within dstBuffer (from @dstBufferStart) when possible, otherwise it's copied into tmpOutBuffer. |
3100 | | * Condition : @dstPtr != NULL |
3101 | | */ |
3102 | | static void LZ4F_updateDict(LZ4F_dctx* dctx, |
3103 | | const BYTE* dstPtr, size_t dstSize, const BYTE* dstBufferStart, |
3104 | | unsigned withinTmp) |
3105 | 0 | { |
3106 | 0 | assert(dctx != NULL); |
3107 | 0 | assert(dstPtr != NULL); |
3108 | 0 | if (dctx->dictSize==0) dctx->dict = (const BYTE*)dstPtr; /* will lead to prefix mode */ |
3109 | 0 | assert(dctx->dict != NULL); |
3110 | | |
3111 | | /* prefix mode : the output follows the history within the same buffer. |
3112 | | * A history filling tmpOutBuffer can only be followed by another allocation : not a continuation. */ |
3113 | 0 | if ( (dctx->dict + dctx->dictSize == dstPtr) |
3114 | 0 | && !((dctx->dict == dctx->tmpOutBuffer) && (dctx->dictSize >= dctx->tmpOutBufferCapacity)) ) { |
3115 | 0 | dctx->dictSize += dstSize; |
3116 | 0 | return; |
3117 | 0 | } |
3118 | | |
3119 | 0 | assert(dstPtr >= dstBufferStart); |
3120 | 0 | if ((size_t)(dstPtr - dstBufferStart) + dstSize >= 64 KB) { /* history in dstBuffer becomes large enough to become dictionary */ |
3121 | 0 | dctx->dict = (const BYTE*)dstBufferStart; |
3122 | 0 | dctx->dictSize = (size_t)(dstPtr - dstBufferStart) + dstSize; |
3123 | 0 | return; |
3124 | 0 | } |
3125 | | |
3126 | 0 | assert(dstSize < 64 KB); /* if dstSize >= 64 KB, dictionary would be set into dstBuffer directly */ |
3127 | | |
3128 | | /* dstBuffer does not contain whole useful history (64 KB), so it must be saved within tmpOutBuffer */ |
3129 | 0 | assert(dctx->tmpOutBuffer != NULL); |
3130 | |
|
3131 | 0 | if (withinTmp && (dctx->dict == dctx->tmpOutBuffer)) { /* continue history within tmpOutBuffer */ |
3132 | | /* withinTmp expectation : content of [dstPtr,dstSize] is same as [dict+dictSize,dstSize], so we just extend it */ |
3133 | 0 | assert(dctx->dict + dctx->dictSize == dctx->tmpOut + dctx->tmpOutStart); |
3134 | 0 | dctx->dictSize += dstSize; |
3135 | 0 | return; |
3136 | 0 | } |
3137 | | |
3138 | 0 | if (withinTmp) { /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */ |
3139 | 0 | LZ4F_moveDictBeforeTmpOut(dctx, dstSize); |
3140 | 0 | return; |
3141 | 0 | } |
3142 | | |
3143 | 0 | if (dctx->dict == dctx->tmpOutBuffer) { /* copy dst into tmp to complete dict */ |
3144 | 0 | if (dctx->dictSize + dstSize > dctx->tmpOutBufferCapacity) { /* tmp buffer not large enough */ |
3145 | 0 | size_t const preserveSize = 64 KB - dstSize; |
3146 | 0 | LZ4_memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize); |
3147 | 0 | dctx->dictSize = preserveSize; |
3148 | 0 | } |
3149 | 0 | LZ4_memcpy(dctx->tmpOutBuffer + dctx->dictSize, dstPtr, dstSize); |
3150 | 0 | dctx->dictSize += dstSize; |
3151 | 0 | return; |
3152 | 0 | } |
3153 | | |
3154 | | /* join dict & dest into tmp */ |
3155 | 0 | { size_t preserveSize = 64 KB - dstSize; |
3156 | 0 | if (preserveSize > dctx->dictSize) preserveSize = dctx->dictSize; |
3157 | 0 | LZ4_memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize); |
3158 | 0 | LZ4_memcpy(dctx->tmpOutBuffer + preserveSize, dstPtr, dstSize); |
3159 | 0 | dctx->dict = dctx->tmpOutBuffer; |
3160 | 0 | dctx->dictSize = preserveSize + dstSize; |
3161 | 0 | } |
3162 | 0 | } |
3163 | | |
3164 | | |
3165 | | /* LZ4F_endMarkFollows() : |
3166 | | * the frame's endMark is within input, right after the block just output (after @skip bytes : its block checksum, if not consumed yet) : |
3167 | | * no block follows, so the history of linked blocks is no longer needed (saving it can cost as much as decoding a small block). |
3168 | | * Only valid once the block is entirely output : the same invocation then reads the endMark, which ends the frame. */ |
3169 | | static int LZ4F_endMarkFollows(const BYTE* srcPtr, const BYTE* srcEnd, size_t skip) |
3170 | 0 | { |
3171 | 0 | return ((size_t)(srcEnd - srcPtr) >= skip + BHSize) && (LZ4F_readLE32(srcPtr + skip) == 0); |
3172 | 0 | } |
3173 | | |
3174 | | /* LZ4F_decodeBlock() : |
3175 | | * Decode compressed block @src (block checksum excluded) into @dst (capacity >= @dstCapacity), |
3176 | | * using current dictionary, and update content checksum and remaining frame size. |
3177 | | * @seqSizePtr != NULL : the block is incomplete (@srcSize bytes received so far) : |
3178 | | * decode its complete sequences, *seqSizePtr = their size (see LZ4_decompress_incomplete()). |
3179 | | * @return : decoded size, or an error code (testable with LZ4F_isError()) |
3180 | | */ |
3181 | | /* LZ4F_decodeDetached() : |
3182 | | * History detached from @dst (not just before it) : beyond the block's first 64 KB, no match can reach it. |
3183 | | * So the first LZ4F_DETACHED_PART bytes are decoded with it (LZ4_decompress_incomplete() stops before the first |
3184 | | * sequence which doesn't fit), then the rest with them as a prefix, which is faster. Rarely, the sequence after |
3185 | | * the stop reaches the history (a long match crossing the limit) : the block is decoded again, as on any error. |
3186 | | * Not in place (input within @dst) : the first decoding would overwrite it. |
3187 | | * @return : decoded size, or < 0 (error) */ |
3188 | 0 | #define LZ4F_DETACHED_PART (64 KB + 512) |
3189 | | static int LZ4F_decodeDetached(const char* src, int srcSize, char* dst, int dstCapacity, const char* dict, int dictSize) |
3190 | 0 | { |
3191 | 0 | if ( (dstCapacity > LZ4F_DETACHED_PART) && (dictSize > 0) && (dict + dictSize != dst) |
3192 | 0 | && (((size_t)(src + srcSize) <= (size_t)dst) || ((size_t)src >= (size_t)(dst + dstCapacity))) ) { |
3193 | 0 | int partSrcSize = srcSize; |
3194 | 0 | int const partSize = LZ4_decompress_incomplete(src, dst, &partSrcSize, LZ4F_DETACHED_PART, dict, dictSize); |
3195 | 0 | if (partSize >= 0) { |
3196 | 0 | int const r = LZ4_decompress_safe_usingDict(src + partSrcSize, dst + partSize, |
3197 | 0 | srcSize - partSrcSize, dstCapacity - partSize, dst, partSize); |
3198 | 0 | if (r >= 0) return partSize + r; |
3199 | 0 | } } |
3200 | 0 | return LZ4_decompress_safe_usingDict(src, dst, srcSize, dstCapacity, dict, dictSize); |
3201 | 0 | } |
3202 | | |
3203 | | static size_t LZ4F_decodeBlock(LZ4F_dctx* dctx, const BYTE* src, size_t srcSize, |
3204 | | BYTE* dst, size_t dstCapacity, size_t* seqSizePtr) |
3205 | 0 | { |
3206 | 0 | const char* dict = (const char*)dctx->dict; |
3207 | 0 | size_t dictSize = dctx->dictSize; |
3208 | 0 | int decodedSize; |
3209 | 0 | assert(dst != NULL); |
3210 | 0 | if (dict && dictSize > 1 GB) { |
3211 | | /* the dictSize param is an int, avoid truncation / sign issues */ |
3212 | 0 | dict += dictSize - 64 KB; |
3213 | 0 | dictSize = 64 KB; |
3214 | 0 | } |
3215 | 0 | if (seqSizePtr) { |
3216 | 0 | int seqSize = (int)srcSize; |
3217 | 0 | decodedSize = LZ4_decompress_incomplete( |
3218 | 0 | (const char*)src, (char*)dst, |
3219 | 0 | &seqSize, (int)dstCapacity, |
3220 | 0 | dict, (int)dictSize); |
3221 | 0 | *seqSizePtr = (size_t)seqSize; |
3222 | 0 | } else { |
3223 | 0 | decodedSize = LZ4F_decodeDetached( |
3224 | 0 | (const char*)src, (int)srcSize, |
3225 | 0 | (char*)dst, (int)dstCapacity, |
3226 | 0 | dict, (int)dictSize); |
3227 | 0 | } |
3228 | 0 | RETURN_ERROR_IF(decodedSize < 0, decompressionFailed); |
3229 | 0 | RETURN_ERROR_IF(dctx->frameInfo.contentSize && (U64)decodedSize > dctx->frameRemainingSize, frameSize_wrong); |
3230 | 0 | if (dctx->frameInfo.contentChecksumFlag && !dctx->skipContentChecksum) |
3231 | 0 | XXH32_update(&(dctx->xxh), dst, (size_t)decodedSize); |
3232 | 0 | if (dctx->frameInfo.contentSize) |
3233 | 0 | dctx->frameRemainingSize -= (size_t)decodedSize; |
3234 | 0 | return (size_t)decodedSize; |
3235 | 0 | } |
3236 | | |
3237 | | /* LZ4F_decodeProgressive() : |
3238 | | * The frame's first block is incomplete (dctx->tmpInSize bytes gathered so far into tmpIn) : |
3239 | | * decode its complete sequences into @dst, up to @dstCapacity bytes, without waiting for the rest. |
3240 | | * The rest is decoded once the block is complete, with this output as history. |
3241 | | * @return : decoded size, or an error code */ |
3242 | | static size_t LZ4F_decodeProgressive(LZ4F_dctx* dctx, BYTE* dst, size_t dstCapacity, const BYTE* dstStart) |
3243 | 0 | { |
3244 | 0 | size_t seqSize; |
3245 | 0 | size_t const decodedSize = LZ4F_decodeBlock(dctx, |
3246 | 0 | dctx->tmpIn + dctx->tmpInDecoded, dctx->tmpInSize - dctx->tmpInDecoded, |
3247 | 0 | dst, MIN(dstCapacity, dctx->maxBlockSize - dctx->blockDecoded), &seqSize); |
3248 | 0 | if (LZ4F_isError(decodedSize) || (decodedSize == 0)) return decodedSize; |
3249 | 0 | if (dctx->blockDecoded == 0) { |
3250 | 0 | dctx->blockDict = dctx->dict; |
3251 | 0 | dctx->blockDictSize = dctx->dictSize; |
3252 | 0 | } |
3253 | | /* history : the block's dictionary, then its output (independent blocks : not the previous blocks) */ |
3254 | 0 | LZ4F_updateDict(dctx, dst, decodedSize, |
3255 | 0 | (dctx->frameInfo.blockMode == LZ4F_blockLinked) ? dstStart : dst, 0); |
3256 | 0 | dctx->tmpInDecoded += seqSize; |
3257 | 0 | dctx->blockDecoded += decodedSize; |
3258 | 0 | return decodedSize; |
3259 | 0 | } |
3260 | | |
3261 | | /* LZ4F_endBlock() : |
3262 | | * after a compressed block : the beginning of a block decoded progressively is no longer history (independent blocks) */ |
3263 | | static void LZ4F_endBlock(LZ4F_dctx* dctx) |
3264 | 0 | { |
3265 | 0 | if (dctx->blockDecoded && (dctx->frameInfo.blockMode == LZ4F_blockIndependent)) { |
3266 | 0 | dctx->dict = dctx->blockDict; |
3267 | 0 | dctx->dictSize = dctx->blockDictSize; |
3268 | 0 | } |
3269 | 0 | dctx->tmpInDecoded = 0; |
3270 | 0 | dctx->blockDecoded = 0; |
3271 | 0 | } |
3272 | | |
3273 | | |
3274 | | /* LZ4F_gatherInput() : |
3275 | | * Provides @wanted contiguous input bytes : directly from src if they are all available and none is buffered yet, |
3276 | | * otherwise accumulated into @buffer, over as many calls as needed (dctx->tmpInSize bytes buffered so far). |
3277 | | * @return : pointer to the @wanted bytes (*srcPtrPtr is moved past consumed input), |
3278 | | * or NULL if input is exhausted before (all of it is then buffered). |
3279 | | */ |
3280 | | static const BYTE* |
3281 | | LZ4F_gatherInput(LZ4F_dctx* dctx, BYTE* buffer, size_t wanted, |
3282 | | const BYTE** srcPtrPtr, const BYTE* srcEnd) |
3283 | 0 | { |
3284 | 0 | const BYTE* const srcPtr = *srcPtrPtr; |
3285 | 0 | size_t const available = (size_t)(srcEnd - srcPtr); |
3286 | 0 | if ((dctx->tmpInSize == 0) && (available >= wanted)) { |
3287 | 0 | *srcPtrPtr = srcPtr + wanted; |
3288 | 0 | return srcPtr; |
3289 | 0 | } |
3290 | 0 | { size_t const sizeToCopy = MIN(wanted - dctx->tmpInSize, available); |
3291 | 0 | LZ4_memcpy(buffer + dctx->tmpInSize, srcPtr, sizeToCopy); |
3292 | 0 | dctx->tmpInSize += sizeToCopy; |
3293 | 0 | *srcPtrPtr = srcPtr + sizeToCopy; |
3294 | 0 | } |
3295 | 0 | if (dctx->tmpInSize < wanted) return NULL; |
3296 | 0 | dctx->tmpInSize = 0; /* ready for next gathering */ |
3297 | 0 | return buffer; |
3298 | 0 | } |
3299 | | |
3300 | | |
3301 | | /*! LZ4F_decompress() : |
3302 | | * Call this function repetitively to regenerate compressed data in srcBuffer. |
3303 | | * The function will attempt to decode up to *srcSizePtr bytes from srcBuffer |
3304 | | * into dstBuffer of capacity *dstSizePtr. |
3305 | | * |
3306 | | * The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value). |
3307 | | * |
3308 | | * The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value). |
3309 | | * If number of bytes read is < number of bytes provided, then decompression operation is not complete. |
3310 | | * Remaining data will have to be presented again in a subsequent invocation. |
3311 | | * |
3312 | | * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress. |
3313 | | * Schematically, it's the size of the current (or remaining) compressed block + header of next block. |
3314 | | * Respecting the hint provides a small boost to performance, since it allows less buffer shuffling. |
3315 | | * Note that this is just a hint, and it's always possible to any srcSize value. |
3316 | | * When a frame is fully decoded, @return will be 0. |
3317 | | * If decompression failed, @return is an error code which can be tested using LZ4F_isError(). |
3318 | | */ |
3319 | | size_t LZ4F_decompress(LZ4F_dctx* dctx, |
3320 | | void* dstBuffer, size_t* dstSizePtr, |
3321 | | const void* srcBuffer, size_t* srcSizePtr, |
3322 | | const LZ4F_decompressOptions_t* decompressOptionsPtr) |
3323 | 0 | { |
3324 | 0 | static const BYTE emptySrc = 0; /* NULL srcBuffer (no input, used by LZ4F_getFrameInfo()) points here instead : |
3325 | | * NULL+0 and LZ4_memcpy(dst, NULL, 0) are UB */ |
3326 | 0 | LZ4F_decompressOptions_t optionsNull; |
3327 | 0 | const BYTE* const srcStart = srcBuffer ? (const BYTE*)srcBuffer : &emptySrc; |
3328 | 0 | const BYTE* const srcEnd = srcBuffer ? srcStart + *srcSizePtr : srcStart; |
3329 | 0 | const BYTE* srcPtr = srcStart; |
3330 | 0 | BYTE* const dstStart = (BYTE*)dstBuffer; |
3331 | 0 | BYTE* const dstEnd = dstStart ? dstStart + *dstSizePtr : NULL; |
3332 | 0 | BYTE* dstPtr = dstStart; |
3333 | 0 | const BYTE* selectedIn = NULL; |
3334 | 0 | unsigned doAnotherStage = 1; |
3335 | 0 | size_t nextSrcSizeHint = 1; |
3336 | | |
3337 | |
|
3338 | 0 | DEBUGLOG(5, "LZ4F_decompress: src[%p](%u) => dst[%p](%u)", |
3339 | 0 | srcBuffer, (unsigned)*srcSizePtr, dstBuffer, (unsigned)*dstSizePtr); |
3340 | 0 | if (dstBuffer == NULL) assert(*dstSizePtr == 0); |
3341 | 0 | if (srcBuffer == NULL) assert(*srcSizePtr == 0); |
3342 | 0 | MEM_INIT(&optionsNull, 0, sizeof(optionsNull)); |
3343 | 0 | if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull; |
3344 | 0 | *srcSizePtr = 0; |
3345 | 0 | *dstSizePtr = 0; |
3346 | 0 | assert(dctx != NULL); |
3347 | 0 | switch (decompressOptionsPtr->skipChecksums) { /* once set, disable for the remainder of the frame */ |
3348 | 0 | case LZ4F_verifyChecksums: break; |
3349 | 0 | case LZ4F_skipAllChecksums: dctx->skipBlockChecksum = 1; dctx->skipContentChecksum = 1; break; |
3350 | 0 | case LZ4F_skipContentChecksum: dctx->skipContentChecksum = 1; break; |
3351 | 0 | case LZ4F_skipBlockChecksums: dctx->skipBlockChecksum = 1; break; |
3352 | 0 | default: RETURN_ERROR(parameter_invalid); |
3353 | 0 | } |
3354 | | |
3355 | | /* behaves as a state machine */ |
3356 | | |
3357 | 0 | while (doAnotherStage) { |
3358 | |
|
3359 | 0 | switch(dctx->dStage) |
3360 | 0 | { |
3361 | | |
3362 | 0 | case dstage_getFrameHeader: |
3363 | 0 | DEBUGLOG(6, "dstage_getFrameHeader"); |
3364 | 0 | if ((size_t)(srcEnd-srcPtr) >= maxFHSize) { /* enough to decode - shortcut */ |
3365 | 0 | size_t const hSize = LZ4F_decodeHeader(dctx, srcPtr, (size_t)(srcEnd-srcPtr)); /* will update dStage appropriately */ |
3366 | 0 | if (LZ4F_isError(hSize)) { nextSrcSizeHint = hSize; goto _output; } |
3367 | 0 | srcPtr += hSize; |
3368 | 0 | break; |
3369 | 0 | } |
3370 | 0 | dctx->tmpInSize = 0; |
3371 | 0 | if (srcEnd-srcPtr == 0) return minFHSize; /* 0-size input */ |
3372 | 0 | dctx->tmpInTarget = minFHSize; /* minimum size to decode header */ |
3373 | 0 | dctx->dStage = dstage_storeFrameHeader; |
3374 | | /* fall-through */ |
3375 | |
|
3376 | 0 | case dstage_storeFrameHeader: |
3377 | 0 | DEBUGLOG(6, "dstage_storeFrameHeader"); |
3378 | 0 | { size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr)); |
3379 | 0 | LZ4_memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); |
3380 | 0 | dctx->tmpInSize += sizeToCopy; |
3381 | 0 | srcPtr += sizeToCopy; |
3382 | 0 | } |
3383 | 0 | if (dctx->tmpInSize < dctx->tmpInTarget) { |
3384 | 0 | nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize; /* rest of header + nextBlockHeader */ |
3385 | 0 | doAnotherStage = 0; /* not enough src data, ask for some more */ |
3386 | 0 | break; |
3387 | 0 | } |
3388 | 0 | { size_t const hSize = LZ4F_decodeHeader(dctx, dctx->header, dctx->tmpInTarget); /* will update dStage appropriately */ |
3389 | 0 | if (LZ4F_isError(hSize)) { nextSrcSizeHint = hSize; goto _output; } |
3390 | 0 | } |
3391 | 0 | break; |
3392 | | |
3393 | 0 | case dstage_init: |
3394 | 0 | DEBUGLOG(6, "dstage_init"); |
3395 | 0 | if (dctx->frameInfo.contentChecksumFlag) (void)XXH32_reset(&(dctx->xxh), 0); |
3396 | | /* internal buffers allocation */ |
3397 | 0 | { size_t const tmpInNeeded = dctx->maxBlockSize + BFSize /* block checksum */; |
3398 | 0 | size_t const tmpOutNeeded = dctx->maxBlockSize /* + history : linked blocks, or first block decoded progressively */ |
3399 | 0 | + (((dctx->frameInfo.blockMode==LZ4F_blockLinked) || dctx->progressive) ? 128 KB : 0); |
3400 | 0 | if ( (tmpInNeeded > dctx->tmpInCapacity) |
3401 | 0 | || (tmpOutNeeded > dctx->tmpOutBufferCapacity) ) { /* tmp buffers too small */ |
3402 | | /* capacities remain 0 until allocation succeeds, |
3403 | | * so that allocation will be re-attempted on next entry */ |
3404 | 0 | LZ4F_free(dctx->tmpIn, dctx->cmem); |
3405 | 0 | dctx->tmpInCapacity = 0; |
3406 | 0 | dctx->tmpIn = (BYTE*)LZ4F_malloc(tmpInNeeded, dctx->cmem); |
3407 | 0 | if (dctx->tmpIn == NULL) { |
3408 | 0 | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_allocation_failed); |
3409 | 0 | goto _output; |
3410 | 0 | } |
3411 | 0 | dctx->tmpInCapacity = tmpInNeeded; |
3412 | 0 | LZ4F_free(dctx->tmpOutBuffer, dctx->cmem); |
3413 | 0 | dctx->tmpOutBufferCapacity = 0; |
3414 | 0 | dctx->tmpOutBuffer= (BYTE*)LZ4F_malloc(tmpOutNeeded, dctx->cmem); |
3415 | 0 | if (dctx->tmpOutBuffer== NULL) { |
3416 | 0 | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_allocation_failed); |
3417 | 0 | goto _output; |
3418 | 0 | } |
3419 | 0 | dctx->tmpOutBufferCapacity = tmpOutNeeded; |
3420 | 0 | } } |
3421 | 0 | dctx->tmpInSize = 0; |
3422 | 0 | dctx->tmpInTarget = 0; |
3423 | 0 | dctx->progressiveFrame = dctx->progressive; |
3424 | 0 | dctx->tmpInDecoded = 0; |
3425 | 0 | dctx->blockDecoded = 0; |
3426 | 0 | dctx->blockNb = 0; |
3427 | 0 | dctx->tmpOut = dctx->tmpOutBuffer; |
3428 | 0 | dctx->tmpOutStart = 0; |
3429 | 0 | dctx->tmpOutSize = 0; |
3430 | |
|
3431 | 0 | dctx->dStage = dstage_getBlockHeader; |
3432 | | /* fall-through */ |
3433 | |
|
3434 | 0 | case dstage_getBlockHeader: |
3435 | 0 | selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, BHSize, &srcPtr, srcEnd); |
3436 | 0 | if (selectedIn == NULL) { /* not enough input for cBlockSize */ |
3437 | 0 | nextSrcSizeHint = BHSize - dctx->tmpInSize; |
3438 | 0 | doAnotherStage = 0; |
3439 | 0 | break; |
3440 | 0 | } |
3441 | | |
3442 | | /* decode block header */ |
3443 | 0 | { U32 const blockHeader = LZ4F_readLE32(selectedIn); |
3444 | 0 | size_t const nextCBlockSize = blockHeader & 0x7FFFFFFFU; |
3445 | 0 | size_t const crcSize = dctx->frameInfo.blockChecksumFlag * BFSize; |
3446 | 0 | if (blockHeader==0) { /* frameEnd signal, no more block */ |
3447 | 0 | DEBUGLOG(5, "end of frame"); |
3448 | 0 | dctx->dStage = dstage_getSuffix; |
3449 | 0 | break; |
3450 | 0 | } |
3451 | 0 | if (dctx->blockNb < 2) dctx->blockNb++; |
3452 | 0 | if (nextCBlockSize > dctx->maxBlockSize) { |
3453 | 0 | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_maxBlockSize_invalid); |
3454 | 0 | goto _output; |
3455 | 0 | } |
3456 | 0 | if (blockHeader & LZ4F_BLOCKUNCOMPRESSED_FLAG) { |
3457 | | /* next block is uncompressed */ |
3458 | 0 | if (dctx->frameInfo.contentSize && nextCBlockSize > dctx->frameRemainingSize) { |
3459 | 0 | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_frameSize_wrong); |
3460 | 0 | goto _output; |
3461 | 0 | } |
3462 | 0 | dctx->tmpInTarget = nextCBlockSize; |
3463 | 0 | DEBUGLOG(5, "next block is uncompressed (size %u)", (U32)nextCBlockSize); |
3464 | 0 | if (dctx->frameInfo.blockChecksumFlag) { |
3465 | 0 | (void)XXH32_reset(&dctx->blockChecksum, 0); |
3466 | 0 | } |
3467 | 0 | dctx->dStage = dstage_copyDirect; |
3468 | 0 | break; |
3469 | 0 | } |
3470 | | /* next block is a compressed block */ |
3471 | 0 | dctx->tmpInTarget = nextCBlockSize + crcSize; |
3472 | 0 | assert(dctx->tmpInDecoded == 0 && dctx->blockDecoded == 0); /* see LZ4F_endBlock() */ |
3473 | 0 | dctx->dStage = dstage_getCBlock; |
3474 | 0 | if (dstPtr==dstEnd || srcPtr==srcEnd) { |
3475 | 0 | nextSrcSizeHint = BHSize + nextCBlockSize + crcSize; |
3476 | 0 | doAnotherStage = 0; |
3477 | 0 | } |
3478 | 0 | break; |
3479 | 0 | } |
3480 | | |
3481 | 0 | case dstage_copyDirect: /* uncompressed block */ |
3482 | 0 | DEBUGLOG(6, "dstage_copyDirect"); |
3483 | 0 | { size_t sizeToCopy; |
3484 | 0 | if (dstPtr == NULL) { |
3485 | 0 | sizeToCopy = 0; |
3486 | 0 | } else { |
3487 | 0 | size_t const minBuffSize = MIN((size_t)(srcEnd-srcPtr), (size_t)(dstEnd-dstPtr)); |
3488 | 0 | sizeToCopy = MIN(dctx->tmpInTarget, minBuffSize); |
3489 | 0 | LZ4_memcpy(dstPtr, srcPtr, sizeToCopy); |
3490 | 0 | if (dctx->frameInfo.blockChecksumFlag && !dctx->skipBlockChecksum) |
3491 | 0 | (void)XXH32_update(&dctx->blockChecksum, srcPtr, sizeToCopy); |
3492 | 0 | if (dctx->frameInfo.contentChecksumFlag && !dctx->skipContentChecksum) |
3493 | 0 | (void)XXH32_update(&dctx->xxh, srcPtr, sizeToCopy); |
3494 | 0 | if (dctx->frameInfo.contentSize) |
3495 | 0 | dctx->frameRemainingSize -= sizeToCopy; |
3496 | | |
3497 | | /* history management (linked blocks only), unless the frame ends with this block */ |
3498 | 0 | if ( (dctx->frameInfo.blockMode == LZ4F_blockLinked) |
3499 | 0 | && !( (sizeToCopy == dctx->tmpInTarget) |
3500 | 0 | && LZ4F_endMarkFollows(srcPtr + sizeToCopy, srcEnd, dctx->frameInfo.blockChecksumFlag * BFSize) ) ) { |
3501 | 0 | LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0); |
3502 | 0 | } |
3503 | 0 | srcPtr += sizeToCopy; |
3504 | 0 | dstPtr += sizeToCopy; |
3505 | 0 | } |
3506 | 0 | if (sizeToCopy == dctx->tmpInTarget) { /* all done */ |
3507 | 0 | if (dctx->frameInfo.blockChecksumFlag) |
3508 | 0 | dctx->dStage = dstage_getBlockChecksum; |
3509 | 0 | else |
3510 | 0 | dctx->dStage = dstage_getBlockHeader; /* new block */ |
3511 | 0 | break; |
3512 | 0 | } |
3513 | 0 | dctx->tmpInTarget -= sizeToCopy; /* need to copy more */ |
3514 | 0 | } |
3515 | 0 | nextSrcSizeHint = dctx->tmpInTarget |
3516 | 0 | + (dctx->frameInfo.blockChecksumFlag ? BFSize : 0) |
3517 | 0 | + BHSize /* next header size */; |
3518 | 0 | doAnotherStage = 0; |
3519 | 0 | break; |
3520 | | |
3521 | | /* check block checksum for recently transferred uncompressed block */ |
3522 | 0 | case dstage_getBlockChecksum: |
3523 | 0 | DEBUGLOG(6, "dstage_getBlockChecksum"); |
3524 | 0 | selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, BFSize, &srcPtr, srcEnd); |
3525 | 0 | if (selectedIn == NULL) { /* all input consumed */ |
3526 | 0 | nextSrcSizeHint = (BFSize - dctx->tmpInSize) + BHSize /* next header size */; |
3527 | 0 | doAnotherStage = 0; |
3528 | 0 | break; |
3529 | 0 | } |
3530 | 0 | if (!dctx->skipBlockChecksum) { |
3531 | 0 | U32 const readCRC = LZ4F_readLE32(selectedIn); |
3532 | 0 | U32 const calcCRC = XXH32_digest(&dctx->blockChecksum); |
3533 | | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
3534 | | DEBUGLOG(6, "compare block checksum"); |
3535 | | if (readCRC != calcCRC) { |
3536 | | DEBUGLOG(4, "incorrect block checksum: %08X != %08X", |
3537 | | readCRC, calcCRC); |
3538 | | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_blockChecksum_invalid); |
3539 | | goto _output; |
3540 | | } |
3541 | | #else |
3542 | 0 | (void)readCRC; |
3543 | 0 | (void)calcCRC; |
3544 | 0 | #endif |
3545 | 0 | } |
3546 | 0 | dctx->dStage = dstage_getBlockHeader; /* new block */ |
3547 | 0 | break; |
3548 | | |
3549 | 0 | case dstage_getCBlock: |
3550 | 0 | DEBUGLOG(6, "dstage_getCBlock"); |
3551 | 0 | selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, dctx->tmpInTarget, &srcPtr, srcEnd); |
3552 | 0 | if (selectedIn == NULL) { /* need more input */ |
3553 | | /* first block of the frame : output what can be decoded already (see LZ4F_setProgressiveDecoding()), |
3554 | | * unless a block checksum must be verified first */ |
3555 | 0 | if ( dctx->progressiveFrame && (dctx->blockNb == 1) |
3556 | 0 | && !dctx->frameInfo.blockChecksumFlag && (dstPtr != NULL) ) { |
3557 | 0 | size_t const decodedSize = LZ4F_decodeProgressive(dctx, dstPtr, (size_t)(dstEnd - dstPtr), dstStart); |
3558 | 0 | if (LZ4F_isError(decodedSize)) { nextSrcSizeHint = decodedSize; goto _output; } |
3559 | 0 | dstPtr += decodedSize; |
3560 | 0 | } |
3561 | 0 | nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) /* block checksum included */ |
3562 | 0 | + BHSize /* next header size */; |
3563 | 0 | doAnotherStage = 0; |
3564 | 0 | break; |
3565 | 0 | } |
3566 | | |
3567 | | /* At this stage, input is large enough to decode a block */ |
3568 | | /* (or the rest of a block decoded progressively : dctx->tmpInDecoded bytes already decoded, never with block checksum) */ |
3569 | 0 | assert((dctx->tmpInDecoded == 0) || (selectedIn == dctx->tmpIn)); |
3570 | 0 | assert((dctx->tmpInDecoded == 0) || !dctx->frameInfo.blockChecksumFlag); |
3571 | | |
3572 | | /* First, decode and control block checksum if it exists */ |
3573 | 0 | if (dctx->frameInfo.blockChecksumFlag) { |
3574 | 0 | assert(dctx->tmpInTarget >= 4); |
3575 | 0 | dctx->tmpInTarget -= 4; |
3576 | 0 | if (!dctx->skipBlockChecksum) { |
3577 | 0 | U32 const readBlockCrc = LZ4F_readLE32(selectedIn + dctx->tmpInTarget); |
3578 | 0 | U32 const calcBlockCrc = XXH32(selectedIn, dctx->tmpInTarget, 0); |
3579 | | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
3580 | | if (readBlockCrc != calcBlockCrc) { |
3581 | | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_blockChecksum_invalid); |
3582 | | goto _output; |
3583 | | } |
3584 | | #else |
3585 | 0 | (void)readBlockCrc; |
3586 | 0 | (void)calcBlockCrc; |
3587 | 0 | #endif |
3588 | 0 | } } |
3589 | | |
3590 | | /* decode directly into destination buffer if there is enough room */ |
3591 | 0 | if ( ((size_t)(dstEnd-dstPtr) >= dctx->maxBlockSize - dctx->blockDecoded) |
3592 | | /* unless the dictionary is stored in tmpOut: |
3593 | | * in which case it's faster to decode within tmpOut |
3594 | | * to benefit from prefix speedup (but the rest of a block decoded progressively would be copied) */ |
3595 | 0 | && ( dctx->blockDecoded |
3596 | 0 | || !(dctx->dict!= NULL && (const BYTE*)dctx->dict + dctx->dictSize == dctx->tmpOut) ) ) |
3597 | 0 | { size_t const decodedSize = LZ4F_decodeBlock(dctx, |
3598 | 0 | selectedIn + dctx->tmpInDecoded, dctx->tmpInTarget - dctx->tmpInDecoded, |
3599 | 0 | dstPtr, dctx->maxBlockSize - dctx->blockDecoded, NULL); |
3600 | 0 | if (LZ4F_isError(decodedSize)) { nextSrcSizeHint = decodedSize; goto _output; } |
3601 | | |
3602 | | /* dictionary management, unless the frame ends with this block */ |
3603 | 0 | if ( (dctx->frameInfo.blockMode==LZ4F_blockLinked) |
3604 | 0 | && !LZ4F_endMarkFollows(srcPtr, srcEnd, 0) ) { |
3605 | 0 | LZ4F_updateDict(dctx, dstPtr, decodedSize, dstStart, 0); |
3606 | 0 | } |
3607 | |
|
3608 | 0 | dstPtr += decodedSize; |
3609 | 0 | LZ4F_endBlock(dctx); |
3610 | 0 | dctx->dStage = dstage_getBlockHeader; /* end of block, let's get another one */ |
3611 | 0 | break; |
3612 | 0 | } |
3613 | | |
3614 | | /* not enough place into dst : decode into tmpOut */ |
3615 | | |
3616 | | /* manage dictionary : history of linked blocks, or beginning of a block decoded progressively */ |
3617 | 0 | if ((dctx->frameInfo.blockMode == LZ4F_blockLinked) || dctx->blockDecoded) { |
3618 | 0 | if (dctx->dict == dctx->tmpOutBuffer) { |
3619 | | /* truncate dictionary to 64 KB if too big */ |
3620 | 0 | if (dctx->dictSize > 128 KB) { |
3621 | 0 | LZ4_memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - 64 KB, 64 KB); |
3622 | 0 | dctx->dictSize = 64 KB; |
3623 | 0 | } |
3624 | 0 | dctx->tmpOut = dctx->tmpOutBuffer + dctx->dictSize; |
3625 | 0 | } else { /* dict not within tmpOut */ |
3626 | 0 | size_t const reservedDictSpace = MIN(dctx->dictSize, 64 KB); |
3627 | 0 | dctx->tmpOut = dctx->tmpOutBuffer + reservedDictSpace; |
3628 | 0 | } } |
3629 | | |
3630 | | /* Decode block into tmpOut */ |
3631 | 0 | { size_t const decodedSize = LZ4F_decodeBlock(dctx, |
3632 | 0 | selectedIn + dctx->tmpInDecoded, dctx->tmpInTarget - dctx->tmpInDecoded, |
3633 | 0 | dctx->tmpOut, dctx->maxBlockSize - dctx->blockDecoded, NULL); |
3634 | 0 | if (LZ4F_isError(decodedSize)) { nextSrcSizeHint = decodedSize; goto _output; } |
3635 | 0 | LZ4F_endBlock(dctx); |
3636 | 0 | dctx->tmpOutSize = decodedSize; |
3637 | 0 | dctx->tmpOutStart = 0; |
3638 | 0 | dctx->dStage = dstage_flushOut; |
3639 | 0 | } |
3640 | | /* fall-through */ |
3641 | | |
3642 | 0 | case dstage_flushOut: /* flush decoded data from tmpOut to dstBuffer */ |
3643 | 0 | DEBUGLOG(6, "dstage_flushOut"); |
3644 | 0 | if (dstPtr != NULL) { |
3645 | 0 | size_t const sizeToCopy = MIN(dctx->tmpOutSize - dctx->tmpOutStart, (size_t)(dstEnd-dstPtr)); |
3646 | 0 | LZ4_memcpy(dstPtr, dctx->tmpOut + dctx->tmpOutStart, sizeToCopy); |
3647 | | |
3648 | | /* dictionary management, unless the frame ends with this block */ |
3649 | 0 | if ( (dctx->frameInfo.blockMode == LZ4F_blockLinked) |
3650 | 0 | && !( (dctx->tmpOutStart + sizeToCopy == dctx->tmpOutSize) |
3651 | 0 | && LZ4F_endMarkFollows(srcPtr, srcEnd, 0) ) ) |
3652 | 0 | LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 1 /*withinTmp*/); |
3653 | |
|
3654 | 0 | dctx->tmpOutStart += sizeToCopy; |
3655 | 0 | dstPtr += sizeToCopy; |
3656 | 0 | } |
3657 | 0 | if (dctx->tmpOutStart == dctx->tmpOutSize) { /* all flushed */ |
3658 | 0 | dctx->dStage = dstage_getBlockHeader; /* get next block */ |
3659 | 0 | break; |
3660 | 0 | } |
3661 | | /* could not flush everything : stop there, just request a block header */ |
3662 | 0 | doAnotherStage = 0; |
3663 | 0 | nextSrcSizeHint = BHSize; |
3664 | 0 | break; |
3665 | | |
3666 | 0 | case dstage_getSuffix: |
3667 | 0 | if (dctx->frameRemainingSize) { /* incorrect frame size decoded */ |
3668 | 0 | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_frameSize_wrong); |
3669 | 0 | goto _output; |
3670 | 0 | } |
3671 | 0 | if (!dctx->frameInfo.contentChecksumFlag) { /* no checksum, frame is completed */ |
3672 | 0 | nextSrcSizeHint = 0; |
3673 | 0 | LZ4F_endFrame(dctx); |
3674 | 0 | doAnotherStage = 0; |
3675 | 0 | break; |
3676 | 0 | } |
3677 | 0 | selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, 4, &srcPtr, srcEnd); |
3678 | 0 | if (selectedIn == NULL) { /* not enough input to read complete suffix */ |
3679 | 0 | nextSrcSizeHint = 4 - dctx->tmpInSize; |
3680 | 0 | doAnotherStage = 0; |
3681 | 0 | break; |
3682 | 0 | } |
3683 | 0 | if (!dctx->skipContentChecksum) { |
3684 | 0 | U32 const readCRC = LZ4F_readLE32(selectedIn); |
3685 | 0 | U32 const resultCRC = XXH32_digest(&(dctx->xxh)); |
3686 | 0 | DEBUGLOG(4, "frame checksum: stored 0x%0X vs 0x%0X processed", readCRC, resultCRC); |
3687 | | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
3688 | | if (readCRC != resultCRC) { |
3689 | | nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_contentChecksum_invalid); |
3690 | | goto _output; |
3691 | | } |
3692 | | #else |
3693 | 0 | (void)readCRC; |
3694 | 0 | (void)resultCRC; |
3695 | 0 | #endif |
3696 | 0 | } |
3697 | 0 | nextSrcSizeHint = 0; |
3698 | 0 | LZ4F_endFrame(dctx); |
3699 | 0 | doAnotherStage = 0; |
3700 | 0 | break; |
3701 | | |
3702 | 0 | case dstage_getSFrameSize: |
3703 | 0 | selectedIn = LZ4F_gatherInput(dctx, dctx->header + 4, 4, &srcPtr, srcEnd); |
3704 | 0 | if (selectedIn == NULL) { /* not enough input to read the skippable frame size */ |
3705 | 0 | nextSrcSizeHint = 4 - dctx->tmpInSize; |
3706 | 0 | doAnotherStage = 0; |
3707 | 0 | break; |
3708 | 0 | } |
3709 | 0 | { size_t const SFrameSize = LZ4F_readLE32(selectedIn); |
3710 | 0 | dctx->frameInfo.contentSize = SFrameSize; |
3711 | 0 | dctx->tmpInTarget = SFrameSize; |
3712 | 0 | dctx->dStage = dstage_skipSkippable; |
3713 | 0 | break; |
3714 | 0 | } |
3715 | | |
3716 | 0 | case dstage_skipSkippable: |
3717 | 0 | { size_t const skipSize = MIN(dctx->tmpInTarget, (size_t)(srcEnd-srcPtr)); |
3718 | 0 | srcPtr += skipSize; |
3719 | 0 | dctx->tmpInTarget -= skipSize; |
3720 | 0 | doAnotherStage = 0; |
3721 | 0 | nextSrcSizeHint = dctx->tmpInTarget; |
3722 | 0 | if (nextSrcSizeHint) break; /* still more to skip */ |
3723 | | /* frame fully skipped : prepare context for a new frame */ |
3724 | 0 | LZ4F_endFrame(dctx); |
3725 | 0 | break; |
3726 | 0 | } |
3727 | 0 | } /* switch (dctx->dStage) */ |
3728 | 0 | } /* while (doAnotherStage) */ |
3729 | | |
3730 | | /* preserve history within tmpOut whenever necessary */ |
3731 | 0 | LZ4F_STATIC_ASSERT((unsigned)dstage_init == 2); |
3732 | 0 | if ( ( (dctx->frameInfo.blockMode==LZ4F_blockLinked) /* next block will use up to 64KB from previous ones */ |
3733 | 0 | || (dctx->blockDecoded && (dctx->dStage == dstage_getCBlock)) ) /* rest of the block decoded progressively too */ |
3734 | 0 | && (dctx->dict != dctx->tmpOutBuffer) /* dictionary is not already within tmp */ |
3735 | 0 | && (dctx->dict != NULL) /* dictionary exists */ |
3736 | 0 | && (!decompressOptionsPtr->stableDst) /* cannot rely on dst data to remain there for next call */ |
3737 | 0 | && ((unsigned)(dctx->dStage)-2 < (unsigned)(dstage_getSuffix)-2) ) /* valid stages : [init ... getSuffix[ */ |
3738 | 0 | { |
3739 | 0 | if (dctx->dStage == dstage_flushOut) { |
3740 | 0 | LZ4F_moveDictBeforeTmpOut(dctx, 0); |
3741 | 0 | } else { |
3742 | 0 | const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize; |
3743 | 0 | size_t const newDictSize = MIN(dctx->dictSize, 64 KB); |
3744 | |
|
3745 | 0 | LZ4_memcpy(dctx->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize); |
3746 | |
|
3747 | 0 | dctx->dict = dctx->tmpOutBuffer; |
3748 | 0 | dctx->dictSize = newDictSize; |
3749 | 0 | dctx->tmpOut = dctx->tmpOutBuffer + newDictSize; |
3750 | 0 | } |
3751 | 0 | } |
3752 | |
|
3753 | 0 | _output: /* also on error : report progress, but do not preserve history for reuse */ |
3754 | 0 | *srcSizePtr = (size_t)(srcPtr - srcStart); |
3755 | 0 | *dstSizePtr = dstStart ? (size_t)(dstPtr - dstStart) : 0; |
3756 | 0 | return nextSrcSizeHint; |
3757 | 0 | } |
3758 | | |
3759 | | /*! LZ4F_decompress_usingDict() : |
3760 | | * Same as LZ4F_decompress(), using a predefined dictionary. |
3761 | | * Dictionary is used "in place", without any preprocessing. |
3762 | | * It must remain accessible throughout the entire frame decoding. |
3763 | | */ |
3764 | | size_t LZ4F_decompress_usingDict(LZ4F_dctx* dctx, |
3765 | | void* dstBuffer, size_t* dstSizePtr, |
3766 | | const void* srcBuffer, size_t* srcSizePtr, |
3767 | | const void* dict, size_t dictSize, |
3768 | | const LZ4F_decompressOptions_t* decompressOptionsPtr) |
3769 | 0 | { |
3770 | 0 | if (dctx->dStage <= dstage_init) { |
3771 | 0 | dctx->dict = (const BYTE*)dict; |
3772 | 0 | dctx->dictSize = dictSize; |
3773 | 0 | } |
3774 | 0 | return LZ4F_decompress(dctx, dstBuffer, dstSizePtr, |
3775 | 0 | srcBuffer, srcSizePtr, |
3776 | 0 | decompressOptionsPtr); |
3777 | 0 | } |
3778 | | |
3779 | | /*! LZ4F_resumeFrame() : |
3780 | | * see lz4frame.h (static section) */ |
3781 | | size_t LZ4F_resumeFrame(LZ4F_dctx* dctx, const LZ4F_frameInfo_t* frameInfo, |
3782 | | unsigned long long decodedPos, |
3783 | | const void* dict, size_t dictSize) |
3784 | 0 | { |
3785 | 0 | assert(dctx != NULL); |
3786 | 0 | RETURN_ERROR_IF(frameInfo == NULL, parameter_null); |
3787 | 0 | RETURN_ERROR_IF(dict == NULL && dictSize > 0, parameter_null); |
3788 | 0 | RETURN_ERROR_IF(frameInfo->frameType != LZ4F_frame, frameType_unknown); |
3789 | 0 | RETURN_ERROR_IF(frameInfo->blockSizeID < LZ4F_max64KB || frameInfo->blockSizeID > LZ4F_max4MB, maxBlockSize_invalid); |
3790 | 0 | RETURN_ERROR_IF((unsigned)frameInfo->blockMode > 1, blockMode_invalid); |
3791 | 0 | RETURN_ERROR_IF((unsigned)frameInfo->blockChecksumFlag > 1, parameter_invalid); |
3792 | 0 | RETURN_ERROR_IF((unsigned)frameInfo->contentChecksumFlag > 1, parameter_invalid); |
3793 | 0 | RETURN_ERROR_IF(frameInfo->contentSize && decodedPos > frameInfo->contentSize, frameSize_wrong); |
3794 | | |
3795 | 0 | LZ4F_resetDecompressionContext(dctx); |
3796 | 0 | dctx->frameInfo = *frameInfo; |
3797 | 0 | dctx->maxBlockSize = LZ4F_getBlockSize(frameInfo->blockSizeID); |
3798 | 0 | if (frameInfo->contentSize) |
3799 | 0 | dctx->frameRemainingSize = frameInfo->contentSize - decodedPos; |
3800 | 0 | dctx->dict = (const BYTE*)dict; |
3801 | 0 | dctx->dictSize = dictSize; |
3802 | 0 | dctx->skipContentChecksum = 1; /* content checksum covers the whole frame : can't be verified */ |
3803 | 0 | dctx->dStage = dstage_init; |
3804 | 0 | return 0; |
3805 | 0 | } |