Brandon Maier | 4b9b25d | 2023-01-12 10:27:45 -0600 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (c) Yann Collet, Facebook, Inc. |
| 3 | * All rights reserved. |
| 4 | * |
| 5 | * This source code is licensed under both the BSD-style license (found in the |
| 6 | * LICENSE file in the root directory of this source tree) and the GPLv2 (found |
| 7 | * in the COPYING file in the root directory of this source tree). |
| 8 | * You may select, at your option, one of the above-listed licenses. |
| 9 | */ |
| 10 | |
| 11 | |
| 12 | /* *************************************************************** |
| 13 | * Tuning parameters |
| 14 | *****************************************************************/ |
| 15 | /*! |
| 16 | * HEAPMODE : |
| 17 | * Select how default decompression function ZSTD_decompress() allocates its context, |
| 18 | * on stack (0), or into heap (1, default; requires malloc()). |
| 19 | * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected. |
| 20 | */ |
| 21 | #ifndef ZSTD_HEAPMODE |
| 22 | # define ZSTD_HEAPMODE 1 |
| 23 | #endif |
| 24 | |
| 25 | /*! |
| 26 | * LEGACY_SUPPORT : |
| 27 | * if set to 1+, ZSTD_decompress() can decode older formats (v0.1+) |
| 28 | */ |
| 29 | |
| 30 | /*! |
| 31 | * MAXWINDOWSIZE_DEFAULT : |
| 32 | * maximum window size accepted by DStream __by default__. |
| 33 | * Frames requiring more memory will be rejected. |
| 34 | * It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize(). |
| 35 | */ |
| 36 | #ifndef ZSTD_MAXWINDOWSIZE_DEFAULT |
| 37 | # define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1) |
| 38 | #endif |
| 39 | |
| 40 | /*! |
| 41 | * NO_FORWARD_PROGRESS_MAX : |
| 42 | * maximum allowed nb of calls to ZSTD_decompressStream() |
| 43 | * without any forward progress |
| 44 | * (defined as: no byte read from input, and no byte flushed to output) |
| 45 | * before triggering an error. |
| 46 | */ |
| 47 | #ifndef ZSTD_NO_FORWARD_PROGRESS_MAX |
| 48 | # define ZSTD_NO_FORWARD_PROGRESS_MAX 16 |
| 49 | #endif |
| 50 | |
| 51 | |
| 52 | /*-******************************************************* |
| 53 | * Dependencies |
| 54 | *********************************************************/ |
| 55 | #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */ |
| 56 | #include "../common/mem.h" /* low level memory routines */ |
| 57 | #define FSE_STATIC_LINKING_ONLY |
| 58 | #include "../common/fse.h" |
| 59 | #define HUF_STATIC_LINKING_ONLY |
| 60 | #include "../common/huf.h" |
| 61 | #include <linux/xxhash.h> /* xxh64_reset, xxh64_update, xxh64_digest, XXH64 */ |
| 62 | #include "../common/zstd_internal.h" /* blockProperties_t */ |
| 63 | #include "zstd_decompress_internal.h" /* ZSTD_DCtx */ |
| 64 | #include "zstd_ddict.h" /* ZSTD_DDictDictContent */ |
| 65 | #include "zstd_decompress_block.h" /* ZSTD_decompressBlock_internal */ |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | /* *********************************** |
| 71 | * Multiple DDicts Hashset internals * |
| 72 | *************************************/ |
| 73 | |
| 74 | #define DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT 4 |
| 75 | #define DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT 3 /* These two constants represent SIZE_MULT/COUNT_MULT load factor without using a float. |
| 76 | * Currently, that means a 0.75 load factor. |
| 77 | * So, if count * COUNT_MULT / size * SIZE_MULT != 0, then we've exceeded |
| 78 | * the load factor of the ddict hash set. |
| 79 | */ |
| 80 | |
| 81 | #define DDICT_HASHSET_TABLE_BASE_SIZE 64 |
| 82 | #define DDICT_HASHSET_RESIZE_FACTOR 2 |
| 83 | |
| 84 | /* Hash function to determine starting position of dict insertion within the table |
| 85 | * Returns an index between [0, hashSet->ddictPtrTableSize] |
| 86 | */ |
| 87 | static size_t ZSTD_DDictHashSet_getIndex(const ZSTD_DDictHashSet* hashSet, U32 dictID) { |
| 88 | const U64 hash = xxh64(&dictID, sizeof(U32), 0); |
| 89 | /* DDict ptr table size is a multiple of 2, use size - 1 as mask to get index within [0, hashSet->ddictPtrTableSize) */ |
| 90 | return hash & (hashSet->ddictPtrTableSize - 1); |
| 91 | } |
| 92 | |
| 93 | /* Adds DDict to a hashset without resizing it. |
| 94 | * If inserting a DDict with a dictID that already exists in the set, replaces the one in the set. |
| 95 | * Returns 0 if successful, or a zstd error code if something went wrong. |
| 96 | */ |
| 97 | static size_t ZSTD_DDictHashSet_emplaceDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict) { |
| 98 | const U32 dictID = ZSTD_getDictID_fromDDict(ddict); |
| 99 | size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID); |
| 100 | const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1; |
| 101 | RETURN_ERROR_IF(hashSet->ddictPtrCount == hashSet->ddictPtrTableSize, GENERIC, "Hash set is full!"); |
| 102 | DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx); |
| 103 | while (hashSet->ddictPtrTable[idx] != NULL) { |
| 104 | /* Replace existing ddict if inserting ddict with same dictID */ |
| 105 | if (ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]) == dictID) { |
| 106 | DEBUGLOG(4, "DictID already exists, replacing rather than adding"); |
| 107 | hashSet->ddictPtrTable[idx] = ddict; |
| 108 | return 0; |
| 109 | } |
| 110 | idx &= idxRangeMask; |
| 111 | idx++; |
| 112 | } |
| 113 | DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx); |
| 114 | hashSet->ddictPtrTable[idx] = ddict; |
| 115 | hashSet->ddictPtrCount++; |
| 116 | return 0; |
| 117 | } |
| 118 | |
| 119 | /* Expands hash table by factor of DDICT_HASHSET_RESIZE_FACTOR and |
| 120 | * rehashes all values, allocates new table, frees old table. |
| 121 | * Returns 0 on success, otherwise a zstd error code. |
| 122 | */ |
| 123 | static size_t ZSTD_DDictHashSet_expand(ZSTD_DDictHashSet* hashSet, ZSTD_customMem customMem) { |
| 124 | size_t newTableSize = hashSet->ddictPtrTableSize * DDICT_HASHSET_RESIZE_FACTOR; |
| 125 | const ZSTD_DDict** newTable = (const ZSTD_DDict**)ZSTD_customCalloc(sizeof(ZSTD_DDict*) * newTableSize, customMem); |
| 126 | const ZSTD_DDict** oldTable = hashSet->ddictPtrTable; |
| 127 | size_t oldTableSize = hashSet->ddictPtrTableSize; |
| 128 | size_t i; |
| 129 | |
| 130 | DEBUGLOG(4, "Expanding DDict hash table! Old size: %zu new size: %zu", oldTableSize, newTableSize); |
| 131 | RETURN_ERROR_IF(!newTable, memory_allocation, "Expanded hashset allocation failed!"); |
| 132 | hashSet->ddictPtrTable = newTable; |
| 133 | hashSet->ddictPtrTableSize = newTableSize; |
| 134 | hashSet->ddictPtrCount = 0; |
| 135 | for (i = 0; i < oldTableSize; ++i) { |
| 136 | if (oldTable[i] != NULL) { |
| 137 | FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, oldTable[i]), ""); |
| 138 | } |
| 139 | } |
| 140 | ZSTD_customFree((void*)oldTable, customMem); |
| 141 | DEBUGLOG(4, "Finished re-hash"); |
| 142 | return 0; |
| 143 | } |
| 144 | |
| 145 | /* Fetches a DDict with the given dictID |
| 146 | * Returns the ZSTD_DDict* with the requested dictID. If it doesn't exist, then returns NULL. |
| 147 | */ |
| 148 | static const ZSTD_DDict* ZSTD_DDictHashSet_getDDict(ZSTD_DDictHashSet* hashSet, U32 dictID) { |
| 149 | size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID); |
| 150 | const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1; |
| 151 | DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx); |
| 152 | for (;;) { |
| 153 | size_t currDictID = ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]); |
| 154 | if (currDictID == dictID || currDictID == 0) { |
| 155 | /* currDictID == 0 implies a NULL ddict entry */ |
| 156 | break; |
| 157 | } else { |
| 158 | idx &= idxRangeMask; /* Goes to start of table when we reach the end */ |
| 159 | idx++; |
| 160 | } |
| 161 | } |
| 162 | DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx); |
| 163 | return hashSet->ddictPtrTable[idx]; |
| 164 | } |
| 165 | |
| 166 | /* Allocates space for and returns a ddict hash set |
| 167 | * The hash set's ZSTD_DDict* table has all values automatically set to NULL to begin with. |
| 168 | * Returns NULL if allocation failed. |
| 169 | */ |
| 170 | static ZSTD_DDictHashSet* ZSTD_createDDictHashSet(ZSTD_customMem customMem) { |
| 171 | ZSTD_DDictHashSet* ret = (ZSTD_DDictHashSet*)ZSTD_customMalloc(sizeof(ZSTD_DDictHashSet), customMem); |
| 172 | DEBUGLOG(4, "Allocating new hash set"); |
| 173 | if (!ret) |
| 174 | return NULL; |
| 175 | ret->ddictPtrTable = (const ZSTD_DDict**)ZSTD_customCalloc(DDICT_HASHSET_TABLE_BASE_SIZE * sizeof(ZSTD_DDict*), customMem); |
| 176 | if (!ret->ddictPtrTable) { |
| 177 | ZSTD_customFree(ret, customMem); |
| 178 | return NULL; |
| 179 | } |
| 180 | ret->ddictPtrTableSize = DDICT_HASHSET_TABLE_BASE_SIZE; |
| 181 | ret->ddictPtrCount = 0; |
| 182 | return ret; |
| 183 | } |
| 184 | |
| 185 | /* Frees the table of ZSTD_DDict* within a hashset, then frees the hashset itself. |
| 186 | * Note: The ZSTD_DDict* within the table are NOT freed. |
| 187 | */ |
| 188 | static void ZSTD_freeDDictHashSet(ZSTD_DDictHashSet* hashSet, ZSTD_customMem customMem) { |
| 189 | DEBUGLOG(4, "Freeing ddict hash set"); |
| 190 | if (hashSet && hashSet->ddictPtrTable) { |
| 191 | ZSTD_customFree((void*)hashSet->ddictPtrTable, customMem); |
| 192 | } |
| 193 | if (hashSet) { |
| 194 | ZSTD_customFree(hashSet, customMem); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /* Public function: Adds a DDict into the ZSTD_DDictHashSet, possibly triggering a resize of the hash set. |
| 199 | * Returns 0 on success, or a ZSTD error. |
| 200 | */ |
| 201 | static size_t ZSTD_DDictHashSet_addDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict, ZSTD_customMem customMem) { |
| 202 | DEBUGLOG(4, "Adding dict ID: %u to hashset with - Count: %zu Tablesize: %zu", ZSTD_getDictID_fromDDict(ddict), hashSet->ddictPtrCount, hashSet->ddictPtrTableSize); |
| 203 | if (hashSet->ddictPtrCount * DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT / hashSet->ddictPtrTableSize * DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT != 0) { |
| 204 | FORWARD_IF_ERROR(ZSTD_DDictHashSet_expand(hashSet, customMem), ""); |
| 205 | } |
| 206 | FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, ddict), ""); |
| 207 | return 0; |
| 208 | } |
| 209 | |
| 210 | /*-************************************************************* |
| 211 | * Context management |
| 212 | ***************************************************************/ |
| 213 | size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx) |
| 214 | { |
| 215 | if (dctx==NULL) return 0; /* support sizeof NULL */ |
| 216 | return sizeof(*dctx) |
| 217 | + ZSTD_sizeof_DDict(dctx->ddictLocal) |
| 218 | + dctx->inBuffSize + dctx->outBuffSize; |
| 219 | } |
| 220 | |
| 221 | size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); } |
| 222 | |
| 223 | |
| 224 | static size_t ZSTD_startingInputLength(ZSTD_format_e format) |
| 225 | { |
| 226 | size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format); |
| 227 | /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */ |
| 228 | assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) ); |
| 229 | return startingInputLength; |
| 230 | } |
| 231 | |
| 232 | static void ZSTD_DCtx_resetParameters(ZSTD_DCtx* dctx) |
| 233 | { |
| 234 | assert(dctx->streamStage == zdss_init); |
| 235 | dctx->format = ZSTD_f_zstd1; |
| 236 | dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT; |
| 237 | dctx->outBufferMode = ZSTD_bm_buffered; |
| 238 | dctx->forceIgnoreChecksum = ZSTD_d_validateChecksum; |
| 239 | dctx->refMultipleDDicts = ZSTD_rmd_refSingleDDict; |
| 240 | } |
| 241 | |
| 242 | static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) |
| 243 | { |
| 244 | dctx->staticSize = 0; |
| 245 | dctx->ddict = NULL; |
| 246 | dctx->ddictLocal = NULL; |
| 247 | dctx->dictEnd = NULL; |
| 248 | dctx->ddictIsCold = 0; |
| 249 | dctx->dictUses = ZSTD_dont_use; |
| 250 | dctx->inBuff = NULL; |
| 251 | dctx->inBuffSize = 0; |
| 252 | dctx->outBuffSize = 0; |
| 253 | dctx->streamStage = zdss_init; |
| 254 | dctx->noForwardProgress = 0; |
| 255 | dctx->oversizedDuration = 0; |
| 256 | #if DYNAMIC_BMI2 |
| 257 | dctx->bmi2 = ZSTD_cpuSupportsBmi2(); |
| 258 | #endif |
| 259 | dctx->ddictSet = NULL; |
| 260 | ZSTD_DCtx_resetParameters(dctx); |
| 261 | #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
| 262 | dctx->dictContentEndForFuzzing = NULL; |
| 263 | #endif |
| 264 | } |
| 265 | |
| 266 | ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize) |
| 267 | { |
| 268 | ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace; |
| 269 | |
| 270 | if ((size_t)workspace & 7) return NULL; /* 8-aligned */ |
| 271 | if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */ |
| 272 | |
| 273 | ZSTD_initDCtx_internal(dctx); |
| 274 | dctx->staticSize = workspaceSize; |
| 275 | dctx->inBuff = (char*)(dctx+1); |
| 276 | return dctx; |
| 277 | } |
| 278 | |
| 279 | static ZSTD_DCtx* ZSTD_createDCtx_internal(ZSTD_customMem customMem) { |
| 280 | if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL; |
| 281 | |
| 282 | { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_customMalloc(sizeof(*dctx), customMem); |
| 283 | if (!dctx) return NULL; |
| 284 | dctx->customMem = customMem; |
| 285 | ZSTD_initDCtx_internal(dctx); |
| 286 | return dctx; |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem) |
| 291 | { |
| 292 | return ZSTD_createDCtx_internal(customMem); |
| 293 | } |
| 294 | |
| 295 | ZSTD_DCtx* ZSTD_createDCtx(void) |
| 296 | { |
| 297 | DEBUGLOG(3, "ZSTD_createDCtx"); |
| 298 | return ZSTD_createDCtx_internal(ZSTD_defaultCMem); |
| 299 | } |
| 300 | |
| 301 | static void ZSTD_clearDict(ZSTD_DCtx* dctx) |
| 302 | { |
| 303 | ZSTD_freeDDict(dctx->ddictLocal); |
| 304 | dctx->ddictLocal = NULL; |
| 305 | dctx->ddict = NULL; |
| 306 | dctx->dictUses = ZSTD_dont_use; |
| 307 | } |
| 308 | |
| 309 | size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx) |
| 310 | { |
| 311 | if (dctx==NULL) return 0; /* support free on NULL */ |
| 312 | RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx"); |
| 313 | { ZSTD_customMem const cMem = dctx->customMem; |
| 314 | ZSTD_clearDict(dctx); |
| 315 | ZSTD_customFree(dctx->inBuff, cMem); |
| 316 | dctx->inBuff = NULL; |
| 317 | if (dctx->ddictSet) { |
| 318 | ZSTD_freeDDictHashSet(dctx->ddictSet, cMem); |
| 319 | dctx->ddictSet = NULL; |
| 320 | } |
| 321 | ZSTD_customFree(dctx, cMem); |
| 322 | return 0; |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | /* no longer useful */ |
| 327 | void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx) |
| 328 | { |
| 329 | size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx); |
| 330 | ZSTD_memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */ |
| 331 | } |
| 332 | |
| 333 | /* Given a dctx with a digested frame params, re-selects the correct ZSTD_DDict based on |
| 334 | * the requested dict ID from the frame. If there exists a reference to the correct ZSTD_DDict, then |
| 335 | * accordingly sets the ddict to be used to decompress the frame. |
| 336 | * |
| 337 | * If no DDict is found, then no action is taken, and the ZSTD_DCtx::ddict remains as-is. |
| 338 | * |
| 339 | * ZSTD_d_refMultipleDDicts must be enabled for this function to be called. |
| 340 | */ |
| 341 | static void ZSTD_DCtx_selectFrameDDict(ZSTD_DCtx* dctx) { |
| 342 | assert(dctx->refMultipleDDicts && dctx->ddictSet); |
| 343 | DEBUGLOG(4, "Adjusting DDict based on requested dict ID from frame"); |
| 344 | if (dctx->ddict) { |
| 345 | const ZSTD_DDict* frameDDict = ZSTD_DDictHashSet_getDDict(dctx->ddictSet, dctx->fParams.dictID); |
| 346 | if (frameDDict) { |
| 347 | DEBUGLOG(4, "DDict found!"); |
| 348 | ZSTD_clearDict(dctx); |
| 349 | dctx->dictID = dctx->fParams.dictID; |
| 350 | dctx->ddict = frameDDict; |
| 351 | dctx->dictUses = ZSTD_use_indefinitely; |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | |
| 357 | /*-************************************************************* |
| 358 | * Frame header decoding |
| 359 | ***************************************************************/ |
| 360 | |
| 361 | /*! ZSTD_isFrame() : |
| 362 | * Tells if the content of `buffer` starts with a valid Frame Identifier. |
| 363 | * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. |
| 364 | * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. |
| 365 | * Note 3 : Skippable Frame Identifiers are considered valid. */ |
| 366 | unsigned ZSTD_isFrame(const void* buffer, size_t size) |
| 367 | { |
| 368 | if (size < ZSTD_FRAMEIDSIZE) return 0; |
| 369 | { U32 const magic = MEM_readLE32(buffer); |
| 370 | if (magic == ZSTD_MAGICNUMBER) return 1; |
| 371 | if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1; |
| 372 | } |
| 373 | return 0; |
| 374 | } |
| 375 | |
| 376 | /*! ZSTD_isSkippableFrame() : |
| 377 | * Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame. |
| 378 | * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. |
| 379 | */ |
| 380 | unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size) |
| 381 | { |
| 382 | if (size < ZSTD_FRAMEIDSIZE) return 0; |
| 383 | { U32 const magic = MEM_readLE32(buffer); |
| 384 | if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1; |
| 385 | } |
| 386 | return 0; |
| 387 | } |
| 388 | |
| 389 | /* ZSTD_frameHeaderSize_internal() : |
| 390 | * srcSize must be large enough to reach header size fields. |
| 391 | * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless. |
| 392 | * @return : size of the Frame Header |
| 393 | * or an error code, which can be tested with ZSTD_isError() */ |
| 394 | static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format) |
| 395 | { |
| 396 | size_t const minInputSize = ZSTD_startingInputLength(format); |
| 397 | RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, ""); |
| 398 | |
| 399 | { BYTE const fhd = ((const BYTE*)src)[minInputSize-1]; |
| 400 | U32 const dictID= fhd & 3; |
| 401 | U32 const singleSegment = (fhd >> 5) & 1; |
| 402 | U32 const fcsId = fhd >> 6; |
| 403 | return minInputSize + !singleSegment |
| 404 | + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId] |
| 405 | + (singleSegment && !fcsId); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | /* ZSTD_frameHeaderSize() : |
| 410 | * srcSize must be >= ZSTD_frameHeaderSize_prefix. |
| 411 | * @return : size of the Frame Header, |
| 412 | * or an error code (if srcSize is too small) */ |
| 413 | size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize) |
| 414 | { |
| 415 | return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1); |
| 416 | } |
| 417 | |
| 418 | |
| 419 | /* ZSTD_getFrameHeader_advanced() : |
| 420 | * decode Frame Header, or require larger `srcSize`. |
| 421 | * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless |
| 422 | * @return : 0, `zfhPtr` is correctly filled, |
| 423 | * >0, `srcSize` is too small, value is wanted `srcSize` amount, |
| 424 | * or an error code, which can be tested using ZSTD_isError() */ |
| 425 | size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format) |
| 426 | { |
| 427 | const BYTE* ip = (const BYTE*)src; |
| 428 | size_t const minInputSize = ZSTD_startingInputLength(format); |
| 429 | |
| 430 | ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr)); /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */ |
| 431 | if (srcSize < minInputSize) return minInputSize; |
| 432 | RETURN_ERROR_IF(src==NULL, GENERIC, "invalid parameter"); |
| 433 | |
| 434 | if ( (format != ZSTD_f_zstd1_magicless) |
| 435 | && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) { |
| 436 | if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { |
| 437 | /* skippable frame */ |
| 438 | if (srcSize < ZSTD_SKIPPABLEHEADERSIZE) |
| 439 | return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */ |
| 440 | ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr)); |
| 441 | zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE); |
| 442 | zfhPtr->frameType = ZSTD_skippableFrame; |
| 443 | return 0; |
| 444 | } |
| 445 | RETURN_ERROR(prefix_unknown, ""); |
| 446 | } |
| 447 | |
| 448 | /* ensure there is enough `srcSize` to fully read/decode frame header */ |
| 449 | { size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format); |
| 450 | if (srcSize < fhsize) return fhsize; |
| 451 | zfhPtr->headerSize = (U32)fhsize; |
| 452 | } |
| 453 | |
| 454 | { BYTE const fhdByte = ip[minInputSize-1]; |
| 455 | size_t pos = minInputSize; |
| 456 | U32 const dictIDSizeCode = fhdByte&3; |
| 457 | U32 const checksumFlag = (fhdByte>>2)&1; |
| 458 | U32 const singleSegment = (fhdByte>>5)&1; |
| 459 | U32 const fcsID = fhdByte>>6; |
| 460 | U64 windowSize = 0; |
| 461 | U32 dictID = 0; |
| 462 | U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN; |
| 463 | RETURN_ERROR_IF((fhdByte & 0x08) != 0, frameParameter_unsupported, |
| 464 | "reserved bits, must be zero"); |
| 465 | |
| 466 | if (!singleSegment) { |
| 467 | BYTE const wlByte = ip[pos++]; |
| 468 | U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN; |
| 469 | RETURN_ERROR_IF(windowLog > ZSTD_WINDOWLOG_MAX, frameParameter_windowTooLarge, ""); |
| 470 | windowSize = (1ULL << windowLog); |
| 471 | windowSize += (windowSize >> 3) * (wlByte&7); |
| 472 | } |
| 473 | switch(dictIDSizeCode) |
| 474 | { |
| 475 | default: |
| 476 | assert(0); /* impossible */ |
| 477 | ZSTD_FALLTHROUGH; |
| 478 | case 0 : break; |
| 479 | case 1 : dictID = ip[pos]; pos++; break; |
| 480 | case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break; |
| 481 | case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break; |
| 482 | } |
| 483 | switch(fcsID) |
| 484 | { |
| 485 | default: |
| 486 | assert(0); /* impossible */ |
| 487 | ZSTD_FALLTHROUGH; |
| 488 | case 0 : if (singleSegment) frameContentSize = ip[pos]; break; |
| 489 | case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break; |
| 490 | case 2 : frameContentSize = MEM_readLE32(ip+pos); break; |
| 491 | case 3 : frameContentSize = MEM_readLE64(ip+pos); break; |
| 492 | } |
| 493 | if (singleSegment) windowSize = frameContentSize; |
| 494 | |
| 495 | zfhPtr->frameType = ZSTD_frame; |
| 496 | zfhPtr->frameContentSize = frameContentSize; |
| 497 | zfhPtr->windowSize = windowSize; |
| 498 | zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); |
| 499 | zfhPtr->dictID = dictID; |
| 500 | zfhPtr->checksumFlag = checksumFlag; |
| 501 | } |
| 502 | return 0; |
| 503 | } |
| 504 | |
| 505 | /* ZSTD_getFrameHeader() : |
| 506 | * decode Frame Header, or require larger `srcSize`. |
| 507 | * note : this function does not consume input, it only reads it. |
| 508 | * @return : 0, `zfhPtr` is correctly filled, |
| 509 | * >0, `srcSize` is too small, value is wanted `srcSize` amount, |
| 510 | * or an error code, which can be tested using ZSTD_isError() */ |
| 511 | size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize) |
| 512 | { |
| 513 | return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1); |
| 514 | } |
| 515 | |
| 516 | /* ZSTD_getFrameContentSize() : |
| 517 | * compatible with legacy mode |
| 518 | * @return : decompressed size of the single frame pointed to be `src` if known, otherwise |
| 519 | * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined |
| 520 | * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */ |
| 521 | unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize) |
| 522 | { |
| 523 | { ZSTD_frameHeader zfh; |
| 524 | if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0) |
| 525 | return ZSTD_CONTENTSIZE_ERROR; |
| 526 | if (zfh.frameType == ZSTD_skippableFrame) { |
| 527 | return 0; |
| 528 | } else { |
| 529 | return zfh.frameContentSize; |
| 530 | } } |
| 531 | } |
| 532 | |
| 533 | static size_t readSkippableFrameSize(void const* src, size_t srcSize) |
| 534 | { |
| 535 | size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE; |
| 536 | U32 sizeU32; |
| 537 | |
| 538 | RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, ""); |
| 539 | |
| 540 | sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE); |
| 541 | RETURN_ERROR_IF((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32, |
| 542 | frameParameter_unsupported, ""); |
| 543 | { |
| 544 | size_t const skippableSize = skippableHeaderSize + sizeU32; |
| 545 | RETURN_ERROR_IF(skippableSize > srcSize, srcSize_wrong, ""); |
| 546 | return skippableSize; |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | /*! ZSTD_readSkippableFrame() : |
| 551 | * Retrieves a zstd skippable frame containing data given by src, and writes it to dst buffer. |
| 552 | * |
| 553 | * The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, |
| 554 | * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested |
| 555 | * in the magicVariant. |
| 556 | * |
| 557 | * Returns an error if destination buffer is not large enough, or if the frame is not skippable. |
| 558 | * |
| 559 | * @return : number of bytes written or a ZSTD error. |
| 560 | */ |
| 561 | ZSTDLIB_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, unsigned* magicVariant, |
| 562 | const void* src, size_t srcSize) |
| 563 | { |
| 564 | U32 const magicNumber = MEM_readLE32(src); |
| 565 | size_t skippableFrameSize = readSkippableFrameSize(src, srcSize); |
| 566 | size_t skippableContentSize = skippableFrameSize - ZSTD_SKIPPABLEHEADERSIZE; |
| 567 | |
| 568 | /* check input validity */ |
| 569 | RETURN_ERROR_IF(!ZSTD_isSkippableFrame(src, srcSize), frameParameter_unsupported, ""); |
| 570 | RETURN_ERROR_IF(skippableFrameSize < ZSTD_SKIPPABLEHEADERSIZE || skippableFrameSize > srcSize, srcSize_wrong, ""); |
| 571 | RETURN_ERROR_IF(skippableContentSize > dstCapacity, dstSize_tooSmall, ""); |
| 572 | |
| 573 | /* deliver payload */ |
| 574 | if (skippableContentSize > 0 && dst != NULL) |
| 575 | ZSTD_memcpy(dst, (const BYTE *)src + ZSTD_SKIPPABLEHEADERSIZE, skippableContentSize); |
| 576 | if (magicVariant != NULL) |
| 577 | *magicVariant = magicNumber - ZSTD_MAGIC_SKIPPABLE_START; |
| 578 | return skippableContentSize; |
| 579 | } |
| 580 | |
| 581 | /* ZSTD_findDecompressedSize() : |
| 582 | * compatible with legacy mode |
| 583 | * `srcSize` must be the exact length of some number of ZSTD compressed and/or |
| 584 | * skippable frames |
| 585 | * @return : decompressed size of the frames contained */ |
| 586 | unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize) |
| 587 | { |
| 588 | unsigned long long totalDstSize = 0; |
| 589 | |
| 590 | while (srcSize >= ZSTD_startingInputLength(ZSTD_f_zstd1)) { |
| 591 | U32 const magicNumber = MEM_readLE32(src); |
| 592 | |
| 593 | if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { |
| 594 | size_t const skippableSize = readSkippableFrameSize(src, srcSize); |
| 595 | if (ZSTD_isError(skippableSize)) { |
| 596 | return ZSTD_CONTENTSIZE_ERROR; |
| 597 | } |
| 598 | assert(skippableSize <= srcSize); |
| 599 | |
| 600 | src = (const BYTE *)src + skippableSize; |
| 601 | srcSize -= skippableSize; |
| 602 | continue; |
| 603 | } |
| 604 | |
| 605 | { unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); |
| 606 | if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret; |
| 607 | |
| 608 | /* check for overflow */ |
| 609 | if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR; |
| 610 | totalDstSize += ret; |
| 611 | } |
| 612 | { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize); |
| 613 | if (ZSTD_isError(frameSrcSize)) { |
| 614 | return ZSTD_CONTENTSIZE_ERROR; |
| 615 | } |
| 616 | |
| 617 | src = (const BYTE *)src + frameSrcSize; |
| 618 | srcSize -= frameSrcSize; |
| 619 | } |
| 620 | } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ |
| 621 | |
| 622 | if (srcSize) return ZSTD_CONTENTSIZE_ERROR; |
| 623 | |
| 624 | return totalDstSize; |
| 625 | } |
| 626 | |
| 627 | /* ZSTD_getDecompressedSize() : |
| 628 | * compatible with legacy mode |
| 629 | * @return : decompressed size if known, 0 otherwise |
| 630 | note : 0 can mean any of the following : |
| 631 | - frame content is empty |
| 632 | - decompressed size field is not present in frame header |
| 633 | - frame header unknown / not supported |
| 634 | - frame header not complete (`srcSize` too small) */ |
| 635 | unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize) |
| 636 | { |
| 637 | unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); |
| 638 | ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN); |
| 639 | return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret; |
| 640 | } |
| 641 | |
| 642 | |
| 643 | /* ZSTD_decodeFrameHeader() : |
| 644 | * `headerSize` must be the size provided by ZSTD_frameHeaderSize(). |
| 645 | * If multiple DDict references are enabled, also will choose the correct DDict to use. |
| 646 | * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */ |
| 647 | static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize) |
| 648 | { |
| 649 | size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format); |
| 650 | if (ZSTD_isError(result)) return result; /* invalid header */ |
| 651 | RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small"); |
| 652 | |
| 653 | /* Reference DDict requested by frame if dctx references multiple ddicts */ |
| 654 | if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts && dctx->ddictSet) { |
| 655 | ZSTD_DCtx_selectFrameDDict(dctx); |
| 656 | } |
| 657 | |
| 658 | #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
| 659 | /* Skip the dictID check in fuzzing mode, because it makes the search |
| 660 | * harder. |
| 661 | */ |
| 662 | RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID), |
| 663 | dictionary_wrong, ""); |
| 664 | #endif |
| 665 | dctx->validateChecksum = (dctx->fParams.checksumFlag && !dctx->forceIgnoreChecksum) ? 1 : 0; |
| 666 | if (dctx->validateChecksum) xxh64_reset(&dctx->xxhState, 0); |
| 667 | dctx->processedCSize += headerSize; |
| 668 | return 0; |
| 669 | } |
| 670 | |
| 671 | static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret) |
| 672 | { |
| 673 | ZSTD_frameSizeInfo frameSizeInfo; |
| 674 | frameSizeInfo.compressedSize = ret; |
| 675 | frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; |
| 676 | return frameSizeInfo; |
| 677 | } |
| 678 | |
| 679 | static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize) |
| 680 | { |
| 681 | ZSTD_frameSizeInfo frameSizeInfo; |
| 682 | ZSTD_memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo)); |
| 683 | |
| 684 | |
| 685 | if ((srcSize >= ZSTD_SKIPPABLEHEADERSIZE) |
| 686 | && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { |
| 687 | frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize); |
| 688 | assert(ZSTD_isError(frameSizeInfo.compressedSize) || |
| 689 | frameSizeInfo.compressedSize <= srcSize); |
| 690 | return frameSizeInfo; |
| 691 | } else { |
| 692 | const BYTE* ip = (const BYTE*)src; |
| 693 | const BYTE* const ipstart = ip; |
| 694 | size_t remainingSize = srcSize; |
| 695 | size_t nbBlocks = 0; |
| 696 | ZSTD_frameHeader zfh; |
| 697 | |
| 698 | /* Extract Frame Header */ |
| 699 | { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize); |
| 700 | if (ZSTD_isError(ret)) |
| 701 | return ZSTD_errorFrameSizeInfo(ret); |
| 702 | if (ret > 0) |
| 703 | return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); |
| 704 | } |
| 705 | |
| 706 | ip += zfh.headerSize; |
| 707 | remainingSize -= zfh.headerSize; |
| 708 | |
| 709 | /* Iterate over each block */ |
| 710 | while (1) { |
| 711 | blockProperties_t blockProperties; |
| 712 | size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties); |
| 713 | if (ZSTD_isError(cBlockSize)) |
| 714 | return ZSTD_errorFrameSizeInfo(cBlockSize); |
| 715 | |
| 716 | if (ZSTD_blockHeaderSize + cBlockSize > remainingSize) |
| 717 | return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); |
| 718 | |
| 719 | ip += ZSTD_blockHeaderSize + cBlockSize; |
| 720 | remainingSize -= ZSTD_blockHeaderSize + cBlockSize; |
| 721 | nbBlocks++; |
| 722 | |
| 723 | if (blockProperties.lastBlock) break; |
| 724 | } |
| 725 | |
| 726 | /* Final frame content checksum */ |
| 727 | if (zfh.checksumFlag) { |
| 728 | if (remainingSize < 4) |
| 729 | return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); |
| 730 | ip += 4; |
| 731 | } |
| 732 | |
| 733 | frameSizeInfo.compressedSize = (size_t)(ip - ipstart); |
| 734 | frameSizeInfo.decompressedBound = (zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) |
| 735 | ? zfh.frameContentSize |
| 736 | : nbBlocks * zfh.blockSizeMax; |
| 737 | return frameSizeInfo; |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | /* ZSTD_findFrameCompressedSize() : |
| 742 | * compatible with legacy mode |
| 743 | * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame |
| 744 | * `srcSize` must be at least as large as the frame contained |
| 745 | * @return : the compressed size of the frame starting at `src` */ |
| 746 | size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize) |
| 747 | { |
| 748 | ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); |
| 749 | return frameSizeInfo.compressedSize; |
| 750 | } |
| 751 | |
| 752 | /* ZSTD_decompressBound() : |
| 753 | * compatible with legacy mode |
| 754 | * `src` must point to the start of a ZSTD frame or a skippeable frame |
| 755 | * `srcSize` must be at least as large as the frame contained |
| 756 | * @return : the maximum decompressed size of the compressed source |
| 757 | */ |
| 758 | unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize) |
| 759 | { |
| 760 | unsigned long long bound = 0; |
| 761 | /* Iterate over each frame */ |
| 762 | while (srcSize > 0) { |
| 763 | ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); |
| 764 | size_t const compressedSize = frameSizeInfo.compressedSize; |
| 765 | unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; |
| 766 | if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) |
| 767 | return ZSTD_CONTENTSIZE_ERROR; |
| 768 | assert(srcSize >= compressedSize); |
| 769 | src = (const BYTE*)src + compressedSize; |
| 770 | srcSize -= compressedSize; |
| 771 | bound += decompressedBound; |
| 772 | } |
| 773 | return bound; |
| 774 | } |
| 775 | |
| 776 | |
| 777 | /*-************************************************************* |
| 778 | * Frame decoding |
| 779 | ***************************************************************/ |
| 780 | |
| 781 | /* ZSTD_insertBlock() : |
| 782 | * insert `src` block into `dctx` history. Useful to track uncompressed blocks. */ |
| 783 | size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize) |
| 784 | { |
| 785 | DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize); |
| 786 | ZSTD_checkContinuity(dctx, blockStart, blockSize); |
| 787 | dctx->previousDstEnd = (const char*)blockStart + blockSize; |
| 788 | return blockSize; |
| 789 | } |
| 790 | |
| 791 | |
| 792 | static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity, |
| 793 | const void* src, size_t srcSize) |
| 794 | { |
| 795 | DEBUGLOG(5, "ZSTD_copyRawBlock"); |
| 796 | RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, ""); |
| 797 | if (dst == NULL) { |
| 798 | if (srcSize == 0) return 0; |
| 799 | RETURN_ERROR(dstBuffer_null, ""); |
| 800 | } |
| 801 | ZSTD_memcpy(dst, src, srcSize); |
| 802 | return srcSize; |
| 803 | } |
| 804 | |
| 805 | static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity, |
| 806 | BYTE b, |
| 807 | size_t regenSize) |
| 808 | { |
| 809 | RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, ""); |
| 810 | if (dst == NULL) { |
| 811 | if (regenSize == 0) return 0; |
| 812 | RETURN_ERROR(dstBuffer_null, ""); |
| 813 | } |
| 814 | ZSTD_memset(dst, b, regenSize); |
| 815 | return regenSize; |
| 816 | } |
| 817 | |
| 818 | static void ZSTD_DCtx_trace_end(ZSTD_DCtx const* dctx, U64 uncompressedSize, U64 compressedSize, unsigned streaming) |
| 819 | { |
| 820 | (void)dctx; |
| 821 | (void)uncompressedSize; |
| 822 | (void)compressedSize; |
| 823 | (void)streaming; |
| 824 | } |
| 825 | |
| 826 | |
| 827 | /*! ZSTD_decompressFrame() : |
| 828 | * @dctx must be properly initialized |
| 829 | * will update *srcPtr and *srcSizePtr, |
| 830 | * to make *srcPtr progress by one frame. */ |
| 831 | static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, |
| 832 | void* dst, size_t dstCapacity, |
| 833 | const void** srcPtr, size_t *srcSizePtr) |
| 834 | { |
| 835 | const BYTE* const istart = (const BYTE*)(*srcPtr); |
| 836 | const BYTE* ip = istart; |
| 837 | BYTE* const ostart = (BYTE*)dst; |
| 838 | BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart; |
| 839 | BYTE* op = ostart; |
| 840 | size_t remainingSrcSize = *srcSizePtr; |
| 841 | |
| 842 | DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr); |
| 843 | |
| 844 | /* check */ |
| 845 | RETURN_ERROR_IF( |
| 846 | remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize, |
| 847 | srcSize_wrong, ""); |
| 848 | |
| 849 | /* Frame Header */ |
| 850 | { size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal( |
| 851 | ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format); |
| 852 | if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize; |
| 853 | RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize, |
| 854 | srcSize_wrong, ""); |
| 855 | FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , ""); |
| 856 | ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize; |
| 857 | } |
| 858 | |
| 859 | /* Loop on each block */ |
| 860 | while (1) { |
| 861 | size_t decodedSize; |
| 862 | blockProperties_t blockProperties; |
| 863 | size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties); |
| 864 | if (ZSTD_isError(cBlockSize)) return cBlockSize; |
| 865 | |
| 866 | ip += ZSTD_blockHeaderSize; |
| 867 | remainingSrcSize -= ZSTD_blockHeaderSize; |
| 868 | RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, ""); |
| 869 | |
| 870 | switch(blockProperties.blockType) |
| 871 | { |
| 872 | case bt_compressed: |
| 873 | decodedSize = ZSTD_decompressBlock_internal(dctx, op, (size_t)(oend-op), ip, cBlockSize, /* frame */ 1, not_streaming); |
| 874 | break; |
| 875 | case bt_raw : |
| 876 | decodedSize = ZSTD_copyRawBlock(op, (size_t)(oend-op), ip, cBlockSize); |
| 877 | break; |
| 878 | case bt_rle : |
| 879 | decodedSize = ZSTD_setRleBlock(op, (size_t)(oend-op), *ip, blockProperties.origSize); |
| 880 | break; |
| 881 | case bt_reserved : |
| 882 | default: |
| 883 | RETURN_ERROR(corruption_detected, "invalid block type"); |
| 884 | } |
| 885 | |
| 886 | if (ZSTD_isError(decodedSize)) return decodedSize; |
| 887 | if (dctx->validateChecksum) |
| 888 | xxh64_update(&dctx->xxhState, op, decodedSize); |
| 889 | if (decodedSize != 0) |
| 890 | op += decodedSize; |
| 891 | assert(ip != NULL); |
| 892 | ip += cBlockSize; |
| 893 | remainingSrcSize -= cBlockSize; |
| 894 | if (blockProperties.lastBlock) break; |
| 895 | } |
| 896 | |
| 897 | if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) { |
| 898 | RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize, |
| 899 | corruption_detected, ""); |
| 900 | } |
| 901 | if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */ |
| 902 | RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, ""); |
| 903 | if (!dctx->forceIgnoreChecksum) { |
| 904 | U32 const checkCalc = (U32)xxh64_digest(&dctx->xxhState); |
| 905 | U32 checkRead; |
| 906 | checkRead = MEM_readLE32(ip); |
| 907 | RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, ""); |
| 908 | } |
| 909 | ip += 4; |
| 910 | remainingSrcSize -= 4; |
| 911 | } |
| 912 | ZSTD_DCtx_trace_end(dctx, (U64)(op-ostart), (U64)(ip-istart), /* streaming */ 0); |
| 913 | /* Allow caller to get size read */ |
| 914 | *srcPtr = ip; |
| 915 | *srcSizePtr = remainingSrcSize; |
| 916 | return (size_t)(op-ostart); |
| 917 | } |
| 918 | |
| 919 | static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, |
| 920 | void* dst, size_t dstCapacity, |
| 921 | const void* src, size_t srcSize, |
| 922 | const void* dict, size_t dictSize, |
| 923 | const ZSTD_DDict* ddict) |
| 924 | { |
| 925 | void* const dststart = dst; |
| 926 | int moreThan1Frame = 0; |
| 927 | |
| 928 | DEBUGLOG(5, "ZSTD_decompressMultiFrame"); |
| 929 | assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */ |
| 930 | |
| 931 | if (ddict) { |
| 932 | dict = ZSTD_DDict_dictContent(ddict); |
| 933 | dictSize = ZSTD_DDict_dictSize(ddict); |
| 934 | } |
| 935 | |
| 936 | while (srcSize >= ZSTD_startingInputLength(dctx->format)) { |
| 937 | |
| 938 | |
| 939 | { U32 const magicNumber = MEM_readLE32(src); |
| 940 | DEBUGLOG(4, "reading magic number %08X (expecting %08X)", |
| 941 | (unsigned)magicNumber, ZSTD_MAGICNUMBER); |
| 942 | if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { |
| 943 | size_t const skippableSize = readSkippableFrameSize(src, srcSize); |
| 944 | FORWARD_IF_ERROR(skippableSize, "readSkippableFrameSize failed"); |
| 945 | assert(skippableSize <= srcSize); |
| 946 | |
| 947 | src = (const BYTE *)src + skippableSize; |
| 948 | srcSize -= skippableSize; |
| 949 | continue; |
| 950 | } } |
| 951 | |
| 952 | if (ddict) { |
| 953 | /* we were called from ZSTD_decompress_usingDDict */ |
| 954 | FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), ""); |
| 955 | } else { |
| 956 | /* this will initialize correctly with no dict if dict == NULL, so |
| 957 | * use this in all cases but ddict */ |
| 958 | FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), ""); |
| 959 | } |
| 960 | ZSTD_checkContinuity(dctx, dst, dstCapacity); |
| 961 | |
| 962 | { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity, |
| 963 | &src, &srcSize); |
| 964 | RETURN_ERROR_IF( |
| 965 | (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown) |
| 966 | && (moreThan1Frame==1), |
| 967 | srcSize_wrong, |
| 968 | "At least one frame successfully completed, " |
| 969 | "but following bytes are garbage: " |
| 970 | "it's more likely to be a srcSize error, " |
| 971 | "specifying more input bytes than size of frame(s). " |
| 972 | "Note: one could be unlucky, it might be a corruption error instead, " |
| 973 | "happening right at the place where we expect zstd magic bytes. " |
| 974 | "But this is _much_ less likely than a srcSize field error."); |
| 975 | if (ZSTD_isError(res)) return res; |
| 976 | assert(res <= dstCapacity); |
| 977 | if (res != 0) |
| 978 | dst = (BYTE*)dst + res; |
| 979 | dstCapacity -= res; |
| 980 | } |
| 981 | moreThan1Frame = 1; |
| 982 | } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ |
| 983 | |
| 984 | RETURN_ERROR_IF(srcSize, srcSize_wrong, "input not entirely consumed"); |
| 985 | |
| 986 | return (size_t)((BYTE*)dst - (BYTE*)dststart); |
| 987 | } |
| 988 | |
| 989 | size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, |
| 990 | void* dst, size_t dstCapacity, |
| 991 | const void* src, size_t srcSize, |
| 992 | const void* dict, size_t dictSize) |
| 993 | { |
| 994 | return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL); |
| 995 | } |
| 996 | |
| 997 | |
| 998 | static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx) |
| 999 | { |
| 1000 | switch (dctx->dictUses) { |
| 1001 | default: |
| 1002 | assert(0 /* Impossible */); |
| 1003 | ZSTD_FALLTHROUGH; |
| 1004 | case ZSTD_dont_use: |
| 1005 | ZSTD_clearDict(dctx); |
| 1006 | return NULL; |
| 1007 | case ZSTD_use_indefinitely: |
| 1008 | return dctx->ddict; |
| 1009 | case ZSTD_use_once: |
| 1010 | dctx->dictUses = ZSTD_dont_use; |
| 1011 | return dctx->ddict; |
| 1012 | } |
| 1013 | } |
| 1014 | |
| 1015 | size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) |
| 1016 | { |
| 1017 | return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx)); |
| 1018 | } |
| 1019 | |
| 1020 | |
| 1021 | size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize) |
| 1022 | { |
| 1023 | #if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1) |
| 1024 | size_t regenSize; |
| 1025 | ZSTD_DCtx* const dctx = ZSTD_createDCtx_internal(ZSTD_defaultCMem); |
| 1026 | RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!"); |
| 1027 | regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize); |
| 1028 | ZSTD_freeDCtx(dctx); |
| 1029 | return regenSize; |
| 1030 | #else /* stack mode */ |
| 1031 | ZSTD_DCtx dctx; |
| 1032 | ZSTD_initDCtx_internal(&dctx); |
| 1033 | return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize); |
| 1034 | #endif |
| 1035 | } |
| 1036 | |
| 1037 | |
| 1038 | /*-************************************** |
| 1039 | * Advanced Streaming Decompression API |
| 1040 | * Bufferless and synchronous |
| 1041 | ****************************************/ |
| 1042 | size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; } |
| 1043 | |
| 1044 | /* |
| 1045 | * Similar to ZSTD_nextSrcSizeToDecompress(), but when a block input can be streamed, |
| 1046 | * we allow taking a partial block as the input. Currently only raw uncompressed blocks can |
| 1047 | * be streamed. |
| 1048 | * |
| 1049 | * For blocks that can be streamed, this allows us to reduce the latency until we produce |
| 1050 | * output, and avoid copying the input. |
| 1051 | * |
| 1052 | * @param inputSize - The total amount of input that the caller currently has. |
| 1053 | */ |
| 1054 | static size_t ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx* dctx, size_t inputSize) { |
| 1055 | if (!(dctx->stage == ZSTDds_decompressBlock || dctx->stage == ZSTDds_decompressLastBlock)) |
| 1056 | return dctx->expected; |
| 1057 | if (dctx->bType != bt_raw) |
| 1058 | return dctx->expected; |
| 1059 | return BOUNDED(1, inputSize, dctx->expected); |
| 1060 | } |
| 1061 | |
| 1062 | ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) { |
| 1063 | switch(dctx->stage) |
| 1064 | { |
| 1065 | default: /* should not happen */ |
| 1066 | assert(0); |
| 1067 | ZSTD_FALLTHROUGH; |
| 1068 | case ZSTDds_getFrameHeaderSize: |
| 1069 | ZSTD_FALLTHROUGH; |
| 1070 | case ZSTDds_decodeFrameHeader: |
| 1071 | return ZSTDnit_frameHeader; |
| 1072 | case ZSTDds_decodeBlockHeader: |
| 1073 | return ZSTDnit_blockHeader; |
| 1074 | case ZSTDds_decompressBlock: |
| 1075 | return ZSTDnit_block; |
| 1076 | case ZSTDds_decompressLastBlock: |
| 1077 | return ZSTDnit_lastBlock; |
| 1078 | case ZSTDds_checkChecksum: |
| 1079 | return ZSTDnit_checksum; |
| 1080 | case ZSTDds_decodeSkippableHeader: |
| 1081 | ZSTD_FALLTHROUGH; |
| 1082 | case ZSTDds_skipFrame: |
| 1083 | return ZSTDnit_skippableFrame; |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; } |
| 1088 | |
| 1089 | /* ZSTD_decompressContinue() : |
| 1090 | * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress()) |
| 1091 | * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity) |
| 1092 | * or an error code, which can be tested using ZSTD_isError() */ |
| 1093 | size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) |
| 1094 | { |
| 1095 | DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize); |
| 1096 | /* Sanity check */ |
| 1097 | RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed"); |
| 1098 | ZSTD_checkContinuity(dctx, dst, dstCapacity); |
| 1099 | |
| 1100 | dctx->processedCSize += srcSize; |
| 1101 | |
| 1102 | switch (dctx->stage) |
| 1103 | { |
| 1104 | case ZSTDds_getFrameHeaderSize : |
| 1105 | assert(src != NULL); |
| 1106 | if (dctx->format == ZSTD_f_zstd1) { /* allows header */ |
| 1107 | assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */ |
| 1108 | if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ |
| 1109 | ZSTD_memcpy(dctx->headerBuffer, src, srcSize); |
| 1110 | dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */ |
| 1111 | dctx->stage = ZSTDds_decodeSkippableHeader; |
| 1112 | return 0; |
| 1113 | } } |
| 1114 | dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format); |
| 1115 | if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize; |
| 1116 | ZSTD_memcpy(dctx->headerBuffer, src, srcSize); |
| 1117 | dctx->expected = dctx->headerSize - srcSize; |
| 1118 | dctx->stage = ZSTDds_decodeFrameHeader; |
| 1119 | return 0; |
| 1120 | |
| 1121 | case ZSTDds_decodeFrameHeader: |
| 1122 | assert(src != NULL); |
| 1123 | ZSTD_memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize); |
| 1124 | FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), ""); |
| 1125 | dctx->expected = ZSTD_blockHeaderSize; |
| 1126 | dctx->stage = ZSTDds_decodeBlockHeader; |
| 1127 | return 0; |
| 1128 | |
| 1129 | case ZSTDds_decodeBlockHeader: |
| 1130 | { blockProperties_t bp; |
| 1131 | size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp); |
| 1132 | if (ZSTD_isError(cBlockSize)) return cBlockSize; |
| 1133 | RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum"); |
| 1134 | dctx->expected = cBlockSize; |
| 1135 | dctx->bType = bp.blockType; |
| 1136 | dctx->rleSize = bp.origSize; |
| 1137 | if (cBlockSize) { |
| 1138 | dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock; |
| 1139 | return 0; |
| 1140 | } |
| 1141 | /* empty block */ |
| 1142 | if (bp.lastBlock) { |
| 1143 | if (dctx->fParams.checksumFlag) { |
| 1144 | dctx->expected = 4; |
| 1145 | dctx->stage = ZSTDds_checkChecksum; |
| 1146 | } else { |
| 1147 | dctx->expected = 0; /* end of frame */ |
| 1148 | dctx->stage = ZSTDds_getFrameHeaderSize; |
| 1149 | } |
| 1150 | } else { |
| 1151 | dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */ |
| 1152 | dctx->stage = ZSTDds_decodeBlockHeader; |
| 1153 | } |
| 1154 | return 0; |
| 1155 | } |
| 1156 | |
| 1157 | case ZSTDds_decompressLastBlock: |
| 1158 | case ZSTDds_decompressBlock: |
| 1159 | DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock"); |
| 1160 | { size_t rSize; |
| 1161 | switch(dctx->bType) |
| 1162 | { |
| 1163 | case bt_compressed: |
| 1164 | DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed"); |
| 1165 | rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1, is_streaming); |
| 1166 | dctx->expected = 0; /* Streaming not supported */ |
| 1167 | break; |
| 1168 | case bt_raw : |
| 1169 | assert(srcSize <= dctx->expected); |
| 1170 | rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize); |
| 1171 | FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed"); |
| 1172 | assert(rSize == srcSize); |
| 1173 | dctx->expected -= rSize; |
| 1174 | break; |
| 1175 | case bt_rle : |
| 1176 | rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize); |
| 1177 | dctx->expected = 0; /* Streaming not supported */ |
| 1178 | break; |
| 1179 | case bt_reserved : /* should never happen */ |
| 1180 | default: |
| 1181 | RETURN_ERROR(corruption_detected, "invalid block type"); |
| 1182 | } |
| 1183 | FORWARD_IF_ERROR(rSize, ""); |
| 1184 | RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum"); |
| 1185 | DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize); |
| 1186 | dctx->decodedSize += rSize; |
| 1187 | if (dctx->validateChecksum) xxh64_update(&dctx->xxhState, dst, rSize); |
| 1188 | dctx->previousDstEnd = (char*)dst + rSize; |
| 1189 | |
| 1190 | /* Stay on the same stage until we are finished streaming the block. */ |
| 1191 | if (dctx->expected > 0) { |
| 1192 | return rSize; |
| 1193 | } |
| 1194 | |
| 1195 | if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */ |
| 1196 | DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize); |
| 1197 | RETURN_ERROR_IF( |
| 1198 | dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN |
| 1199 | && dctx->decodedSize != dctx->fParams.frameContentSize, |
| 1200 | corruption_detected, ""); |
| 1201 | if (dctx->fParams.checksumFlag) { /* another round for frame checksum */ |
| 1202 | dctx->expected = 4; |
| 1203 | dctx->stage = ZSTDds_checkChecksum; |
| 1204 | } else { |
| 1205 | ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1); |
| 1206 | dctx->expected = 0; /* ends here */ |
| 1207 | dctx->stage = ZSTDds_getFrameHeaderSize; |
| 1208 | } |
| 1209 | } else { |
| 1210 | dctx->stage = ZSTDds_decodeBlockHeader; |
| 1211 | dctx->expected = ZSTD_blockHeaderSize; |
| 1212 | } |
| 1213 | return rSize; |
| 1214 | } |
| 1215 | |
| 1216 | case ZSTDds_checkChecksum: |
| 1217 | assert(srcSize == 4); /* guaranteed by dctx->expected */ |
| 1218 | { |
| 1219 | if (dctx->validateChecksum) { |
| 1220 | U32 const h32 = (U32)xxh64_digest(&dctx->xxhState); |
| 1221 | U32 const check32 = MEM_readLE32(src); |
| 1222 | DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32); |
| 1223 | RETURN_ERROR_IF(check32 != h32, checksum_wrong, ""); |
| 1224 | } |
| 1225 | ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1); |
| 1226 | dctx->expected = 0; |
| 1227 | dctx->stage = ZSTDds_getFrameHeaderSize; |
| 1228 | return 0; |
| 1229 | } |
| 1230 | |
| 1231 | case ZSTDds_decodeSkippableHeader: |
| 1232 | assert(src != NULL); |
| 1233 | assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE); |
| 1234 | ZSTD_memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */ |
| 1235 | dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */ |
| 1236 | dctx->stage = ZSTDds_skipFrame; |
| 1237 | return 0; |
| 1238 | |
| 1239 | case ZSTDds_skipFrame: |
| 1240 | dctx->expected = 0; |
| 1241 | dctx->stage = ZSTDds_getFrameHeaderSize; |
| 1242 | return 0; |
| 1243 | |
| 1244 | default: |
| 1245 | assert(0); /* impossible */ |
| 1246 | RETURN_ERROR(GENERIC, "impossible to reach"); /* some compiler require default to do something */ |
| 1247 | } |
| 1248 | } |
| 1249 | |
| 1250 | |
| 1251 | static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) |
| 1252 | { |
| 1253 | dctx->dictEnd = dctx->previousDstEnd; |
| 1254 | dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); |
| 1255 | dctx->prefixStart = dict; |
| 1256 | dctx->previousDstEnd = (const char*)dict + dictSize; |
| 1257 | #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
| 1258 | dctx->dictContentBeginForFuzzing = dctx->prefixStart; |
| 1259 | dctx->dictContentEndForFuzzing = dctx->previousDstEnd; |
| 1260 | #endif |
| 1261 | return 0; |
| 1262 | } |
| 1263 | |
| 1264 | /*! ZSTD_loadDEntropy() : |
| 1265 | * dict : must point at beginning of a valid zstd dictionary. |
| 1266 | * @return : size of entropy tables read */ |
| 1267 | size_t |
| 1268 | ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, |
| 1269 | const void* const dict, size_t const dictSize) |
| 1270 | { |
| 1271 | const BYTE* dictPtr = (const BYTE*)dict; |
| 1272 | const BYTE* const dictEnd = dictPtr + dictSize; |
| 1273 | |
| 1274 | RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small"); |
| 1275 | assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */ |
| 1276 | dictPtr += 8; /* skip header = magic + dictID */ |
| 1277 | |
| 1278 | ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable)); |
| 1279 | ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable)); |
| 1280 | ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE); |
| 1281 | { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */ |
| 1282 | size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable); |
| 1283 | #ifdef HUF_FORCE_DECOMPRESS_X1 |
| 1284 | /* in minimal huffman, we always use X1 variants */ |
| 1285 | size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable, |
| 1286 | dictPtr, dictEnd - dictPtr, |
| 1287 | workspace, workspaceSize); |
| 1288 | #else |
| 1289 | size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable, |
| 1290 | dictPtr, (size_t)(dictEnd - dictPtr), |
| 1291 | workspace, workspaceSize); |
| 1292 | #endif |
| 1293 | RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, ""); |
| 1294 | dictPtr += hSize; |
| 1295 | } |
| 1296 | |
| 1297 | { short offcodeNCount[MaxOff+1]; |
| 1298 | unsigned offcodeMaxValue = MaxOff, offcodeLog; |
| 1299 | size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr)); |
| 1300 | RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, ""); |
| 1301 | RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, ""); |
| 1302 | RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, ""); |
| 1303 | ZSTD_buildFSETable( entropy->OFTable, |
| 1304 | offcodeNCount, offcodeMaxValue, |
| 1305 | OF_base, OF_bits, |
| 1306 | offcodeLog, |
| 1307 | entropy->workspace, sizeof(entropy->workspace), |
| 1308 | /* bmi2 */0); |
| 1309 | dictPtr += offcodeHeaderSize; |
| 1310 | } |
| 1311 | |
| 1312 | { short matchlengthNCount[MaxML+1]; |
| 1313 | unsigned matchlengthMaxValue = MaxML, matchlengthLog; |
| 1314 | size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr)); |
| 1315 | RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, ""); |
| 1316 | RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, ""); |
| 1317 | RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, ""); |
| 1318 | ZSTD_buildFSETable( entropy->MLTable, |
| 1319 | matchlengthNCount, matchlengthMaxValue, |
| 1320 | ML_base, ML_bits, |
| 1321 | matchlengthLog, |
| 1322 | entropy->workspace, sizeof(entropy->workspace), |
| 1323 | /* bmi2 */ 0); |
| 1324 | dictPtr += matchlengthHeaderSize; |
| 1325 | } |
| 1326 | |
| 1327 | { short litlengthNCount[MaxLL+1]; |
| 1328 | unsigned litlengthMaxValue = MaxLL, litlengthLog; |
| 1329 | size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr)); |
| 1330 | RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, ""); |
| 1331 | RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, ""); |
| 1332 | RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, ""); |
| 1333 | ZSTD_buildFSETable( entropy->LLTable, |
| 1334 | litlengthNCount, litlengthMaxValue, |
| 1335 | LL_base, LL_bits, |
| 1336 | litlengthLog, |
| 1337 | entropy->workspace, sizeof(entropy->workspace), |
| 1338 | /* bmi2 */ 0); |
| 1339 | dictPtr += litlengthHeaderSize; |
| 1340 | } |
| 1341 | |
| 1342 | RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, ""); |
| 1343 | { int i; |
| 1344 | size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12)); |
| 1345 | for (i=0; i<3; i++) { |
| 1346 | U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4; |
| 1347 | RETURN_ERROR_IF(rep==0 || rep > dictContentSize, |
| 1348 | dictionary_corrupted, ""); |
| 1349 | entropy->rep[i] = rep; |
| 1350 | } } |
| 1351 | |
| 1352 | return (size_t)(dictPtr - (const BYTE*)dict); |
| 1353 | } |
| 1354 | |
| 1355 | static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) |
| 1356 | { |
| 1357 | if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize); |
| 1358 | { U32 const magic = MEM_readLE32(dict); |
| 1359 | if (magic != ZSTD_MAGIC_DICTIONARY) { |
| 1360 | return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */ |
| 1361 | } } |
| 1362 | dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); |
| 1363 | |
| 1364 | /* load entropy tables */ |
| 1365 | { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize); |
| 1366 | RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, ""); |
| 1367 | dict = (const char*)dict + eSize; |
| 1368 | dictSize -= eSize; |
| 1369 | } |
| 1370 | dctx->litEntropy = dctx->fseEntropy = 1; |
| 1371 | |
| 1372 | /* reference dictionary content */ |
| 1373 | return ZSTD_refDictContent(dctx, dict, dictSize); |
| 1374 | } |
| 1375 | |
| 1376 | size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) |
| 1377 | { |
| 1378 | assert(dctx != NULL); |
| 1379 | dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */ |
| 1380 | dctx->stage = ZSTDds_getFrameHeaderSize; |
| 1381 | dctx->processedCSize = 0; |
| 1382 | dctx->decodedSize = 0; |
| 1383 | dctx->previousDstEnd = NULL; |
| 1384 | dctx->prefixStart = NULL; |
| 1385 | dctx->virtualStart = NULL; |
| 1386 | dctx->dictEnd = NULL; |
| 1387 | dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */ |
| 1388 | dctx->litEntropy = dctx->fseEntropy = 0; |
| 1389 | dctx->dictID = 0; |
| 1390 | dctx->bType = bt_reserved; |
| 1391 | ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue)); |
| 1392 | ZSTD_memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */ |
| 1393 | dctx->LLTptr = dctx->entropy.LLTable; |
| 1394 | dctx->MLTptr = dctx->entropy.MLTable; |
| 1395 | dctx->OFTptr = dctx->entropy.OFTable; |
| 1396 | dctx->HUFptr = dctx->entropy.hufTable; |
| 1397 | return 0; |
| 1398 | } |
| 1399 | |
| 1400 | size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) |
| 1401 | { |
| 1402 | FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); |
| 1403 | if (dict && dictSize) |
| 1404 | RETURN_ERROR_IF( |
| 1405 | ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)), |
| 1406 | dictionary_corrupted, ""); |
| 1407 | return 0; |
| 1408 | } |
| 1409 | |
| 1410 | |
| 1411 | /* ====== ZSTD_DDict ====== */ |
| 1412 | |
| 1413 | size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) |
| 1414 | { |
| 1415 | DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict"); |
| 1416 | assert(dctx != NULL); |
| 1417 | if (ddict) { |
| 1418 | const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict); |
| 1419 | size_t const dictSize = ZSTD_DDict_dictSize(ddict); |
| 1420 | const void* const dictEnd = dictStart + dictSize; |
| 1421 | dctx->ddictIsCold = (dctx->dictEnd != dictEnd); |
| 1422 | DEBUGLOG(4, "DDict is %s", |
| 1423 | dctx->ddictIsCold ? "~cold~" : "hot!"); |
| 1424 | } |
| 1425 | FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); |
| 1426 | if (ddict) { /* NULL ddict is equivalent to no dictionary */ |
| 1427 | ZSTD_copyDDictParameters(dctx, ddict); |
| 1428 | } |
| 1429 | return 0; |
| 1430 | } |
| 1431 | |
| 1432 | /*! ZSTD_getDictID_fromDict() : |
| 1433 | * Provides the dictID stored within dictionary. |
| 1434 | * if @return == 0, the dictionary is not conformant with Zstandard specification. |
| 1435 | * It can still be loaded, but as a content-only dictionary. */ |
| 1436 | unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize) |
| 1437 | { |
| 1438 | if (dictSize < 8) return 0; |
| 1439 | if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0; |
| 1440 | return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); |
| 1441 | } |
| 1442 | |
| 1443 | /*! ZSTD_getDictID_fromFrame() : |
| 1444 | * Provides the dictID required to decompress frame stored within `src`. |
| 1445 | * If @return == 0, the dictID could not be decoded. |
| 1446 | * This could for one of the following reasons : |
| 1447 | * - The frame does not require a dictionary (most common case). |
| 1448 | * - The frame was built with dictID intentionally removed. |
| 1449 | * Needed dictionary is a hidden information. |
| 1450 | * Note : this use case also happens when using a non-conformant dictionary. |
| 1451 | * - `srcSize` is too small, and as a result, frame header could not be decoded. |
| 1452 | * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`. |
| 1453 | * - This is not a Zstandard frame. |
| 1454 | * When identifying the exact failure cause, it's possible to use |
| 1455 | * ZSTD_getFrameHeader(), which will provide a more precise error code. */ |
| 1456 | unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize) |
| 1457 | { |
| 1458 | ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 }; |
| 1459 | size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize); |
| 1460 | if (ZSTD_isError(hError)) return 0; |
| 1461 | return zfp.dictID; |
| 1462 | } |
| 1463 | |
| 1464 | |
| 1465 | /*! ZSTD_decompress_usingDDict() : |
| 1466 | * Decompression using a pre-digested Dictionary |
| 1467 | * Use dictionary without significant overhead. */ |
| 1468 | size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, |
| 1469 | void* dst, size_t dstCapacity, |
| 1470 | const void* src, size_t srcSize, |
| 1471 | const ZSTD_DDict* ddict) |
| 1472 | { |
| 1473 | /* pass content and size in case legacy frames are encountered */ |
| 1474 | return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, |
| 1475 | NULL, 0, |
| 1476 | ddict); |
| 1477 | } |
| 1478 | |
| 1479 | |
| 1480 | /*===================================== |
| 1481 | * Streaming decompression |
| 1482 | *====================================*/ |
| 1483 | |
| 1484 | ZSTD_DStream* ZSTD_createDStream(void) |
| 1485 | { |
| 1486 | DEBUGLOG(3, "ZSTD_createDStream"); |
| 1487 | return ZSTD_createDCtx_internal(ZSTD_defaultCMem); |
| 1488 | } |
| 1489 | |
| 1490 | ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize) |
| 1491 | { |
| 1492 | return ZSTD_initStaticDCtx(workspace, workspaceSize); |
| 1493 | } |
| 1494 | |
| 1495 | ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem) |
| 1496 | { |
| 1497 | return ZSTD_createDCtx_internal(customMem); |
| 1498 | } |
| 1499 | |
| 1500 | size_t ZSTD_freeDStream(ZSTD_DStream* zds) |
| 1501 | { |
| 1502 | return ZSTD_freeDCtx(zds); |
| 1503 | } |
| 1504 | |
| 1505 | |
| 1506 | /* *** Initialization *** */ |
| 1507 | |
| 1508 | size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; } |
| 1509 | size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; } |
| 1510 | |
| 1511 | size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, |
| 1512 | const void* dict, size_t dictSize, |
| 1513 | ZSTD_dictLoadMethod_e dictLoadMethod, |
| 1514 | ZSTD_dictContentType_e dictContentType) |
| 1515 | { |
| 1516 | RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); |
| 1517 | ZSTD_clearDict(dctx); |
| 1518 | if (dict && dictSize != 0) { |
| 1519 | dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem); |
| 1520 | RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!"); |
| 1521 | dctx->ddict = dctx->ddictLocal; |
| 1522 | dctx->dictUses = ZSTD_use_indefinitely; |
| 1523 | } |
| 1524 | return 0; |
| 1525 | } |
| 1526 | |
| 1527 | size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) |
| 1528 | { |
| 1529 | return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto); |
| 1530 | } |
| 1531 | |
| 1532 | size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) |
| 1533 | { |
| 1534 | return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto); |
| 1535 | } |
| 1536 | |
| 1537 | size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType) |
| 1538 | { |
| 1539 | FORWARD_IF_ERROR(ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType), ""); |
| 1540 | dctx->dictUses = ZSTD_use_once; |
| 1541 | return 0; |
| 1542 | } |
| 1543 | |
| 1544 | size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize) |
| 1545 | { |
| 1546 | return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent); |
| 1547 | } |
| 1548 | |
| 1549 | |
| 1550 | /* ZSTD_initDStream_usingDict() : |
| 1551 | * return : expected size, aka ZSTD_startingInputLength(). |
| 1552 | * this function cannot fail */ |
| 1553 | size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize) |
| 1554 | { |
| 1555 | DEBUGLOG(4, "ZSTD_initDStream_usingDict"); |
| 1556 | FORWARD_IF_ERROR( ZSTD_DCtx_reset(zds, ZSTD_reset_session_only) , ""); |
| 1557 | FORWARD_IF_ERROR( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) , ""); |
| 1558 | return ZSTD_startingInputLength(zds->format); |
| 1559 | } |
| 1560 | |
| 1561 | /* note : this variant can't fail */ |
| 1562 | size_t ZSTD_initDStream(ZSTD_DStream* zds) |
| 1563 | { |
| 1564 | DEBUGLOG(4, "ZSTD_initDStream"); |
| 1565 | return ZSTD_initDStream_usingDDict(zds, NULL); |
| 1566 | } |
| 1567 | |
| 1568 | /* ZSTD_initDStream_usingDDict() : |
| 1569 | * ddict will just be referenced, and must outlive decompression session |
| 1570 | * this function cannot fail */ |
| 1571 | size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict) |
| 1572 | { |
| 1573 | FORWARD_IF_ERROR( ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) , ""); |
| 1574 | FORWARD_IF_ERROR( ZSTD_DCtx_refDDict(dctx, ddict) , ""); |
| 1575 | return ZSTD_startingInputLength(dctx->format); |
| 1576 | } |
| 1577 | |
| 1578 | /* ZSTD_resetDStream() : |
| 1579 | * return : expected size, aka ZSTD_startingInputLength(). |
| 1580 | * this function cannot fail */ |
| 1581 | size_t ZSTD_resetDStream(ZSTD_DStream* dctx) |
| 1582 | { |
| 1583 | FORWARD_IF_ERROR(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only), ""); |
| 1584 | return ZSTD_startingInputLength(dctx->format); |
| 1585 | } |
| 1586 | |
| 1587 | |
| 1588 | size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) |
| 1589 | { |
| 1590 | RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); |
| 1591 | ZSTD_clearDict(dctx); |
| 1592 | if (ddict) { |
| 1593 | dctx->ddict = ddict; |
| 1594 | dctx->dictUses = ZSTD_use_indefinitely; |
| 1595 | if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts) { |
| 1596 | if (dctx->ddictSet == NULL) { |
| 1597 | dctx->ddictSet = ZSTD_createDDictHashSet(dctx->customMem); |
| 1598 | if (!dctx->ddictSet) { |
| 1599 | RETURN_ERROR(memory_allocation, "Failed to allocate memory for hash set!"); |
| 1600 | } |
| 1601 | } |
| 1602 | assert(!dctx->staticSize); /* Impossible: ddictSet cannot have been allocated if static dctx */ |
| 1603 | FORWARD_IF_ERROR(ZSTD_DDictHashSet_addDDict(dctx->ddictSet, ddict, dctx->customMem), ""); |
| 1604 | } |
| 1605 | } |
| 1606 | return 0; |
| 1607 | } |
| 1608 | |
| 1609 | /* ZSTD_DCtx_setMaxWindowSize() : |
| 1610 | * note : no direct equivalence in ZSTD_DCtx_setParameter, |
| 1611 | * since this version sets windowSize, and the other sets windowLog */ |
| 1612 | size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize) |
| 1613 | { |
| 1614 | ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax); |
| 1615 | size_t const min = (size_t)1 << bounds.lowerBound; |
| 1616 | size_t const max = (size_t)1 << bounds.upperBound; |
| 1617 | RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); |
| 1618 | RETURN_ERROR_IF(maxWindowSize < min, parameter_outOfBound, ""); |
| 1619 | RETURN_ERROR_IF(maxWindowSize > max, parameter_outOfBound, ""); |
| 1620 | dctx->maxWindowSize = maxWindowSize; |
| 1621 | return 0; |
| 1622 | } |
| 1623 | |
| 1624 | size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format) |
| 1625 | { |
| 1626 | return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, (int)format); |
| 1627 | } |
| 1628 | |
| 1629 | ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam) |
| 1630 | { |
| 1631 | ZSTD_bounds bounds = { 0, 0, 0 }; |
| 1632 | switch(dParam) { |
| 1633 | case ZSTD_d_windowLogMax: |
| 1634 | bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN; |
| 1635 | bounds.upperBound = ZSTD_WINDOWLOG_MAX; |
| 1636 | return bounds; |
| 1637 | case ZSTD_d_format: |
| 1638 | bounds.lowerBound = (int)ZSTD_f_zstd1; |
| 1639 | bounds.upperBound = (int)ZSTD_f_zstd1_magicless; |
| 1640 | ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless); |
| 1641 | return bounds; |
| 1642 | case ZSTD_d_stableOutBuffer: |
| 1643 | bounds.lowerBound = (int)ZSTD_bm_buffered; |
| 1644 | bounds.upperBound = (int)ZSTD_bm_stable; |
| 1645 | return bounds; |
| 1646 | case ZSTD_d_forceIgnoreChecksum: |
| 1647 | bounds.lowerBound = (int)ZSTD_d_validateChecksum; |
| 1648 | bounds.upperBound = (int)ZSTD_d_ignoreChecksum; |
| 1649 | return bounds; |
| 1650 | case ZSTD_d_refMultipleDDicts: |
| 1651 | bounds.lowerBound = (int)ZSTD_rmd_refSingleDDict; |
| 1652 | bounds.upperBound = (int)ZSTD_rmd_refMultipleDDicts; |
| 1653 | return bounds; |
| 1654 | default:; |
| 1655 | } |
| 1656 | bounds.error = ERROR(parameter_unsupported); |
| 1657 | return bounds; |
| 1658 | } |
| 1659 | |
| 1660 | /* ZSTD_dParam_withinBounds: |
| 1661 | * @return 1 if value is within dParam bounds, |
| 1662 | * 0 otherwise */ |
| 1663 | static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value) |
| 1664 | { |
| 1665 | ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam); |
| 1666 | if (ZSTD_isError(bounds.error)) return 0; |
| 1667 | if (value < bounds.lowerBound) return 0; |
| 1668 | if (value > bounds.upperBound) return 0; |
| 1669 | return 1; |
| 1670 | } |
| 1671 | |
| 1672 | #define CHECK_DBOUNDS(p,v) { \ |
| 1673 | RETURN_ERROR_IF(!ZSTD_dParam_withinBounds(p, v), parameter_outOfBound, ""); \ |
| 1674 | } |
| 1675 | |
| 1676 | size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value) |
| 1677 | { |
| 1678 | switch (param) { |
| 1679 | case ZSTD_d_windowLogMax: |
| 1680 | *value = (int)ZSTD_highbit32((U32)dctx->maxWindowSize); |
| 1681 | return 0; |
| 1682 | case ZSTD_d_format: |
| 1683 | *value = (int)dctx->format; |
| 1684 | return 0; |
| 1685 | case ZSTD_d_stableOutBuffer: |
| 1686 | *value = (int)dctx->outBufferMode; |
| 1687 | return 0; |
| 1688 | case ZSTD_d_forceIgnoreChecksum: |
| 1689 | *value = (int)dctx->forceIgnoreChecksum; |
| 1690 | return 0; |
| 1691 | case ZSTD_d_refMultipleDDicts: |
| 1692 | *value = (int)dctx->refMultipleDDicts; |
| 1693 | return 0; |
| 1694 | default:; |
| 1695 | } |
| 1696 | RETURN_ERROR(parameter_unsupported, ""); |
| 1697 | } |
| 1698 | |
| 1699 | size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value) |
| 1700 | { |
| 1701 | RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); |
| 1702 | switch(dParam) { |
| 1703 | case ZSTD_d_windowLogMax: |
| 1704 | if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT; |
| 1705 | CHECK_DBOUNDS(ZSTD_d_windowLogMax, value); |
| 1706 | dctx->maxWindowSize = ((size_t)1) << value; |
| 1707 | return 0; |
| 1708 | case ZSTD_d_format: |
| 1709 | CHECK_DBOUNDS(ZSTD_d_format, value); |
| 1710 | dctx->format = (ZSTD_format_e)value; |
| 1711 | return 0; |
| 1712 | case ZSTD_d_stableOutBuffer: |
| 1713 | CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value); |
| 1714 | dctx->outBufferMode = (ZSTD_bufferMode_e)value; |
| 1715 | return 0; |
| 1716 | case ZSTD_d_forceIgnoreChecksum: |
| 1717 | CHECK_DBOUNDS(ZSTD_d_forceIgnoreChecksum, value); |
| 1718 | dctx->forceIgnoreChecksum = (ZSTD_forceIgnoreChecksum_e)value; |
| 1719 | return 0; |
| 1720 | case ZSTD_d_refMultipleDDicts: |
| 1721 | CHECK_DBOUNDS(ZSTD_d_refMultipleDDicts, value); |
| 1722 | if (dctx->staticSize != 0) { |
| 1723 | RETURN_ERROR(parameter_unsupported, "Static dctx does not support multiple DDicts!"); |
| 1724 | } |
| 1725 | dctx->refMultipleDDicts = (ZSTD_refMultipleDDicts_e)value; |
| 1726 | return 0; |
| 1727 | default:; |
| 1728 | } |
| 1729 | RETURN_ERROR(parameter_unsupported, ""); |
| 1730 | } |
| 1731 | |
| 1732 | size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset) |
| 1733 | { |
| 1734 | if ( (reset == ZSTD_reset_session_only) |
| 1735 | || (reset == ZSTD_reset_session_and_parameters) ) { |
| 1736 | dctx->streamStage = zdss_init; |
| 1737 | dctx->noForwardProgress = 0; |
| 1738 | } |
| 1739 | if ( (reset == ZSTD_reset_parameters) |
| 1740 | || (reset == ZSTD_reset_session_and_parameters) ) { |
| 1741 | RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); |
| 1742 | ZSTD_clearDict(dctx); |
| 1743 | ZSTD_DCtx_resetParameters(dctx); |
| 1744 | } |
| 1745 | return 0; |
| 1746 | } |
| 1747 | |
| 1748 | |
| 1749 | size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx) |
| 1750 | { |
| 1751 | return ZSTD_sizeof_DCtx(dctx); |
| 1752 | } |
| 1753 | |
| 1754 | size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) |
| 1755 | { |
| 1756 | size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); |
| 1757 | /* space is needed to store the litbuffer after the output of a given block without stomping the extDict of a previous run, as well as to cover both windows against wildcopy*/ |
| 1758 | unsigned long long const neededRBSize = windowSize + blockSize + ZSTD_BLOCKSIZE_MAX + (WILDCOPY_OVERLENGTH * 2); |
| 1759 | unsigned long long const neededSize = MIN(frameContentSize, neededRBSize); |
| 1760 | size_t const minRBSize = (size_t) neededSize; |
| 1761 | RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize, |
| 1762 | frameParameter_windowTooLarge, ""); |
| 1763 | return minRBSize; |
| 1764 | } |
| 1765 | |
| 1766 | size_t ZSTD_estimateDStreamSize(size_t windowSize) |
| 1767 | { |
| 1768 | size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX); |
| 1769 | size_t const inBuffSize = blockSize; /* no block can be larger */ |
| 1770 | size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN); |
| 1771 | return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize; |
| 1772 | } |
| 1773 | |
| 1774 | size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize) |
| 1775 | { |
| 1776 | U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */ |
| 1777 | ZSTD_frameHeader zfh; |
| 1778 | size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize); |
| 1779 | if (ZSTD_isError(err)) return err; |
| 1780 | RETURN_ERROR_IF(err>0, srcSize_wrong, ""); |
| 1781 | RETURN_ERROR_IF(zfh.windowSize > windowSizeMax, |
| 1782 | frameParameter_windowTooLarge, ""); |
| 1783 | return ZSTD_estimateDStreamSize((size_t)zfh.windowSize); |
| 1784 | } |
| 1785 | |
| 1786 | |
| 1787 | /* ***** Decompression ***** */ |
| 1788 | |
| 1789 | static int ZSTD_DCtx_isOverflow(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize) |
| 1790 | { |
| 1791 | return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR; |
| 1792 | } |
| 1793 | |
| 1794 | static void ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize) |
| 1795 | { |
| 1796 | if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize)) |
| 1797 | zds->oversizedDuration++; |
| 1798 | else |
| 1799 | zds->oversizedDuration = 0; |
| 1800 | } |
| 1801 | |
| 1802 | static int ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream* zds) |
| 1803 | { |
| 1804 | return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION; |
| 1805 | } |
| 1806 | |
| 1807 | /* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */ |
| 1808 | static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output) |
| 1809 | { |
| 1810 | ZSTD_outBuffer const expect = zds->expectedOutBuffer; |
| 1811 | /* No requirement when ZSTD_obm_stable is not enabled. */ |
| 1812 | if (zds->outBufferMode != ZSTD_bm_stable) |
| 1813 | return 0; |
| 1814 | /* Any buffer is allowed in zdss_init, this must be the same for every other call until |
| 1815 | * the context is reset. |
| 1816 | */ |
| 1817 | if (zds->streamStage == zdss_init) |
| 1818 | return 0; |
| 1819 | /* The buffer must match our expectation exactly. */ |
| 1820 | if (expect.dst == output->dst && expect.pos == output->pos && expect.size == output->size) |
| 1821 | return 0; |
| 1822 | RETURN_ERROR(dstBuffer_wrong, "ZSTD_d_stableOutBuffer enabled but output differs!"); |
| 1823 | } |
| 1824 | |
| 1825 | /* Calls ZSTD_decompressContinue() with the right parameters for ZSTD_decompressStream() |
| 1826 | * and updates the stage and the output buffer state. This call is extracted so it can be |
| 1827 | * used both when reading directly from the ZSTD_inBuffer, and in buffered input mode. |
| 1828 | * NOTE: You must break after calling this function since the streamStage is modified. |
| 1829 | */ |
| 1830 | static size_t ZSTD_decompressContinueStream( |
| 1831 | ZSTD_DStream* zds, char** op, char* oend, |
| 1832 | void const* src, size_t srcSize) { |
| 1833 | int const isSkipFrame = ZSTD_isSkipFrame(zds); |
| 1834 | if (zds->outBufferMode == ZSTD_bm_buffered) { |
| 1835 | size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart; |
| 1836 | size_t const decodedSize = ZSTD_decompressContinue(zds, |
| 1837 | zds->outBuff + zds->outStart, dstSize, src, srcSize); |
| 1838 | FORWARD_IF_ERROR(decodedSize, ""); |
| 1839 | if (!decodedSize && !isSkipFrame) { |
| 1840 | zds->streamStage = zdss_read; |
| 1841 | } else { |
| 1842 | zds->outEnd = zds->outStart + decodedSize; |
| 1843 | zds->streamStage = zdss_flush; |
| 1844 | } |
| 1845 | } else { |
| 1846 | /* Write directly into the output buffer */ |
| 1847 | size_t const dstSize = isSkipFrame ? 0 : (size_t)(oend - *op); |
| 1848 | size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize); |
| 1849 | FORWARD_IF_ERROR(decodedSize, ""); |
| 1850 | *op += decodedSize; |
| 1851 | /* Flushing is not needed. */ |
| 1852 | zds->streamStage = zdss_read; |
| 1853 | assert(*op <= oend); |
| 1854 | assert(zds->outBufferMode == ZSTD_bm_stable); |
| 1855 | } |
| 1856 | return 0; |
| 1857 | } |
| 1858 | |
| 1859 | size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input) |
| 1860 | { |
| 1861 | const char* const src = (const char*)input->src; |
| 1862 | const char* const istart = input->pos != 0 ? src + input->pos : src; |
| 1863 | const char* const iend = input->size != 0 ? src + input->size : src; |
| 1864 | const char* ip = istart; |
| 1865 | char* const dst = (char*)output->dst; |
| 1866 | char* const ostart = output->pos != 0 ? dst + output->pos : dst; |
| 1867 | char* const oend = output->size != 0 ? dst + output->size : dst; |
| 1868 | char* op = ostart; |
| 1869 | U32 someMoreWork = 1; |
| 1870 | |
| 1871 | DEBUGLOG(5, "ZSTD_decompressStream"); |
| 1872 | RETURN_ERROR_IF( |
| 1873 | input->pos > input->size, |
| 1874 | srcSize_wrong, |
| 1875 | "forbidden. in: pos: %u vs size: %u", |
| 1876 | (U32)input->pos, (U32)input->size); |
| 1877 | RETURN_ERROR_IF( |
| 1878 | output->pos > output->size, |
| 1879 | dstSize_tooSmall, |
| 1880 | "forbidden. out: pos: %u vs size: %u", |
| 1881 | (U32)output->pos, (U32)output->size); |
| 1882 | DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos)); |
| 1883 | FORWARD_IF_ERROR(ZSTD_checkOutBuffer(zds, output), ""); |
| 1884 | |
| 1885 | while (someMoreWork) { |
| 1886 | switch(zds->streamStage) |
| 1887 | { |
| 1888 | case zdss_init : |
| 1889 | DEBUGLOG(5, "stage zdss_init => transparent reset "); |
| 1890 | zds->streamStage = zdss_loadHeader; |
| 1891 | zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0; |
| 1892 | zds->hostageByte = 0; |
| 1893 | zds->expectedOutBuffer = *output; |
| 1894 | ZSTD_FALLTHROUGH; |
| 1895 | |
| 1896 | case zdss_loadHeader : |
| 1897 | DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip)); |
| 1898 | { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format); |
| 1899 | if (zds->refMultipleDDicts && zds->ddictSet) { |
| 1900 | ZSTD_DCtx_selectFrameDDict(zds); |
| 1901 | } |
| 1902 | DEBUGLOG(5, "header size : %u", (U32)hSize); |
| 1903 | if (ZSTD_isError(hSize)) { |
| 1904 | return hSize; /* error */ |
| 1905 | } |
| 1906 | if (hSize != 0) { /* need more input */ |
| 1907 | size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */ |
| 1908 | size_t const remainingInput = (size_t)(iend-ip); |
| 1909 | assert(iend >= ip); |
| 1910 | if (toLoad > remainingInput) { /* not enough input to load full header */ |
| 1911 | if (remainingInput > 0) { |
| 1912 | ZSTD_memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput); |
| 1913 | zds->lhSize += remainingInput; |
| 1914 | } |
| 1915 | input->pos = input->size; |
| 1916 | return (MAX((size_t)ZSTD_FRAMEHEADERSIZE_MIN(zds->format), hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */ |
| 1917 | } |
| 1918 | assert(ip != NULL); |
| 1919 | ZSTD_memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad; |
| 1920 | break; |
| 1921 | } } |
| 1922 | |
| 1923 | /* check for single-pass mode opportunity */ |
| 1924 | if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN |
| 1925 | && zds->fParams.frameType != ZSTD_skippableFrame |
| 1926 | && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) { |
| 1927 | size_t const cSize = ZSTD_findFrameCompressedSize(istart, (size_t)(iend-istart)); |
| 1928 | if (cSize <= (size_t)(iend-istart)) { |
| 1929 | /* shortcut : using single-pass mode */ |
| 1930 | size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, (size_t)(oend-op), istart, cSize, ZSTD_getDDict(zds)); |
| 1931 | if (ZSTD_isError(decompressedSize)) return decompressedSize; |
| 1932 | DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()") |
| 1933 | ip = istart + cSize; |
| 1934 | op += decompressedSize; |
| 1935 | zds->expected = 0; |
| 1936 | zds->streamStage = zdss_init; |
| 1937 | someMoreWork = 0; |
| 1938 | break; |
| 1939 | } } |
| 1940 | |
| 1941 | /* Check output buffer is large enough for ZSTD_odm_stable. */ |
| 1942 | if (zds->outBufferMode == ZSTD_bm_stable |
| 1943 | && zds->fParams.frameType != ZSTD_skippableFrame |
| 1944 | && zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN |
| 1945 | && (U64)(size_t)(oend-op) < zds->fParams.frameContentSize) { |
| 1946 | RETURN_ERROR(dstSize_tooSmall, "ZSTD_obm_stable passed but ZSTD_outBuffer is too small"); |
| 1947 | } |
| 1948 | |
| 1949 | /* Consume header (see ZSTDds_decodeFrameHeader) */ |
| 1950 | DEBUGLOG(4, "Consume header"); |
| 1951 | FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), ""); |
| 1952 | |
| 1953 | if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ |
| 1954 | zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE); |
| 1955 | zds->stage = ZSTDds_skipFrame; |
| 1956 | } else { |
| 1957 | FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), ""); |
| 1958 | zds->expected = ZSTD_blockHeaderSize; |
| 1959 | zds->stage = ZSTDds_decodeBlockHeader; |
| 1960 | } |
| 1961 | |
| 1962 | /* control buffer memory usage */ |
| 1963 | DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)", |
| 1964 | (U32)(zds->fParams.windowSize >>10), |
| 1965 | (U32)(zds->maxWindowSize >> 10) ); |
| 1966 | zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN); |
| 1967 | RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize, |
| 1968 | frameParameter_windowTooLarge, ""); |
| 1969 | |
| 1970 | /* Adapt buffer sizes to frame header instructions */ |
| 1971 | { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */); |
| 1972 | size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_bm_buffered |
| 1973 | ? ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize) |
| 1974 | : 0; |
| 1975 | |
| 1976 | ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize); |
| 1977 | |
| 1978 | { int const tooSmall = (zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize); |
| 1979 | int const tooLarge = ZSTD_DCtx_isOversizedTooLong(zds); |
| 1980 | |
| 1981 | if (tooSmall || tooLarge) { |
| 1982 | size_t const bufferSize = neededInBuffSize + neededOutBuffSize; |
| 1983 | DEBUGLOG(4, "inBuff : from %u to %u", |
| 1984 | (U32)zds->inBuffSize, (U32)neededInBuffSize); |
| 1985 | DEBUGLOG(4, "outBuff : from %u to %u", |
| 1986 | (U32)zds->outBuffSize, (U32)neededOutBuffSize); |
| 1987 | if (zds->staticSize) { /* static DCtx */ |
| 1988 | DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize); |
| 1989 | assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */ |
| 1990 | RETURN_ERROR_IF( |
| 1991 | bufferSize > zds->staticSize - sizeof(ZSTD_DCtx), |
| 1992 | memory_allocation, ""); |
| 1993 | } else { |
| 1994 | ZSTD_customFree(zds->inBuff, zds->customMem); |
| 1995 | zds->inBuffSize = 0; |
| 1996 | zds->outBuffSize = 0; |
| 1997 | zds->inBuff = (char*)ZSTD_customMalloc(bufferSize, zds->customMem); |
| 1998 | RETURN_ERROR_IF(zds->inBuff == NULL, memory_allocation, ""); |
| 1999 | } |
| 2000 | zds->inBuffSize = neededInBuffSize; |
| 2001 | zds->outBuff = zds->inBuff + zds->inBuffSize; |
| 2002 | zds->outBuffSize = neededOutBuffSize; |
| 2003 | } } } |
| 2004 | zds->streamStage = zdss_read; |
| 2005 | ZSTD_FALLTHROUGH; |
| 2006 | |
| 2007 | case zdss_read: |
| 2008 | DEBUGLOG(5, "stage zdss_read"); |
| 2009 | { size_t const neededInSize = ZSTD_nextSrcSizeToDecompressWithInputSize(zds, (size_t)(iend - ip)); |
| 2010 | DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize); |
| 2011 | if (neededInSize==0) { /* end of frame */ |
| 2012 | zds->streamStage = zdss_init; |
| 2013 | someMoreWork = 0; |
| 2014 | break; |
| 2015 | } |
| 2016 | if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */ |
| 2017 | FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, ip, neededInSize), ""); |
| 2018 | ip += neededInSize; |
| 2019 | /* Function modifies the stage so we must break */ |
| 2020 | break; |
| 2021 | } } |
| 2022 | if (ip==iend) { someMoreWork = 0; break; } /* no more input */ |
| 2023 | zds->streamStage = zdss_load; |
| 2024 | ZSTD_FALLTHROUGH; |
| 2025 | |
| 2026 | case zdss_load: |
| 2027 | { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds); |
| 2028 | size_t const toLoad = neededInSize - zds->inPos; |
| 2029 | int const isSkipFrame = ZSTD_isSkipFrame(zds); |
| 2030 | size_t loadedSize; |
| 2031 | /* At this point we shouldn't be decompressing a block that we can stream. */ |
| 2032 | assert(neededInSize == ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip)); |
| 2033 | if (isSkipFrame) { |
| 2034 | loadedSize = MIN(toLoad, (size_t)(iend-ip)); |
| 2035 | } else { |
| 2036 | RETURN_ERROR_IF(toLoad > zds->inBuffSize - zds->inPos, |
| 2037 | corruption_detected, |
| 2038 | "should never happen"); |
| 2039 | loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, (size_t)(iend-ip)); |
| 2040 | } |
| 2041 | ip += loadedSize; |
| 2042 | zds->inPos += loadedSize; |
| 2043 | if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */ |
| 2044 | |
| 2045 | /* decode loaded input */ |
| 2046 | zds->inPos = 0; /* input is consumed */ |
| 2047 | FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, zds->inBuff, neededInSize), ""); |
| 2048 | /* Function modifies the stage so we must break */ |
| 2049 | break; |
| 2050 | } |
| 2051 | case zdss_flush: |
| 2052 | { size_t const toFlushSize = zds->outEnd - zds->outStart; |
| 2053 | size_t const flushedSize = ZSTD_limitCopy(op, (size_t)(oend-op), zds->outBuff + zds->outStart, toFlushSize); |
| 2054 | op += flushedSize; |
| 2055 | zds->outStart += flushedSize; |
| 2056 | if (flushedSize == toFlushSize) { /* flush completed */ |
| 2057 | zds->streamStage = zdss_read; |
| 2058 | if ( (zds->outBuffSize < zds->fParams.frameContentSize) |
| 2059 | && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) { |
| 2060 | DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)", |
| 2061 | (int)(zds->outBuffSize - zds->outStart), |
| 2062 | (U32)zds->fParams.blockSizeMax); |
| 2063 | zds->outStart = zds->outEnd = 0; |
| 2064 | } |
| 2065 | break; |
| 2066 | } } |
| 2067 | /* cannot complete flush */ |
| 2068 | someMoreWork = 0; |
| 2069 | break; |
| 2070 | |
| 2071 | default: |
| 2072 | assert(0); /* impossible */ |
| 2073 | RETURN_ERROR(GENERIC, "impossible to reach"); /* some compiler require default to do something */ |
| 2074 | } } |
| 2075 | |
| 2076 | /* result */ |
| 2077 | input->pos = (size_t)(ip - (const char*)(input->src)); |
| 2078 | output->pos = (size_t)(op - (char*)(output->dst)); |
| 2079 | |
| 2080 | /* Update the expected output buffer for ZSTD_obm_stable. */ |
| 2081 | zds->expectedOutBuffer = *output; |
| 2082 | |
| 2083 | if ((ip==istart) && (op==ostart)) { /* no forward progress */ |
| 2084 | zds->noForwardProgress ++; |
| 2085 | if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) { |
| 2086 | RETURN_ERROR_IF(op==oend, dstSize_tooSmall, ""); |
| 2087 | RETURN_ERROR_IF(ip==iend, srcSize_wrong, ""); |
| 2088 | assert(0); |
| 2089 | } |
| 2090 | } else { |
| 2091 | zds->noForwardProgress = 0; |
| 2092 | } |
| 2093 | { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds); |
| 2094 | if (!nextSrcSizeHint) { /* frame fully decoded */ |
| 2095 | if (zds->outEnd == zds->outStart) { /* output fully flushed */ |
| 2096 | if (zds->hostageByte) { |
| 2097 | if (input->pos >= input->size) { |
| 2098 | /* can't release hostage (not present) */ |
| 2099 | zds->streamStage = zdss_read; |
| 2100 | return 1; |
| 2101 | } |
| 2102 | input->pos++; /* release hostage */ |
| 2103 | } /* zds->hostageByte */ |
| 2104 | return 0; |
| 2105 | } /* zds->outEnd == zds->outStart */ |
| 2106 | if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */ |
| 2107 | input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */ |
| 2108 | zds->hostageByte=1; |
| 2109 | } |
| 2110 | return 1; |
| 2111 | } /* nextSrcSizeHint==0 */ |
| 2112 | nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */ |
| 2113 | assert(zds->inPos <= nextSrcSizeHint); |
| 2114 | nextSrcSizeHint -= zds->inPos; /* part already loaded*/ |
| 2115 | return nextSrcSizeHint; |
| 2116 | } |
| 2117 | } |
| 2118 | |
| 2119 | size_t ZSTD_decompressStream_simpleArgs ( |
| 2120 | ZSTD_DCtx* dctx, |
| 2121 | void* dst, size_t dstCapacity, size_t* dstPos, |
| 2122 | const void* src, size_t srcSize, size_t* srcPos) |
| 2123 | { |
| 2124 | ZSTD_outBuffer output = { dst, dstCapacity, *dstPos }; |
| 2125 | ZSTD_inBuffer input = { src, srcSize, *srcPos }; |
| 2126 | /* ZSTD_compress_generic() will check validity of dstPos and srcPos */ |
| 2127 | size_t const cErr = ZSTD_decompressStream(dctx, &output, &input); |
| 2128 | *dstPos = output.pos; |
| 2129 | *srcPos = input.pos; |
| 2130 | return cErr; |
| 2131 | } |