1 /* 2 * Copyright (c) 2016-present, 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 #ifndef ZSTD_LEGACY_SUPPORT 30 # define ZSTD_LEGACY_SUPPORT 0 31 #endif 32 33 /*! 34 * MAXWINDOWSIZE_DEFAULT : 35 * maximum window size accepted by DStream __by default__. 36 * Frames requiring more memory will be rejected. 37 * It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize(). 38 */ 39 #ifndef ZSTD_MAXWINDOWSIZE_DEFAULT 40 # define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1) 41 #endif 42 43 /*! 44 * NO_FORWARD_PROGRESS_MAX : 45 * maximum allowed nb of calls to ZSTD_decompressStream() 46 * without any forward progress 47 * (defined as: no byte read from input, and no byte flushed to output) 48 * before triggering an error. 49 */ 50 #ifndef ZSTD_NO_FORWARD_PROGRESS_MAX 51 # define ZSTD_NO_FORWARD_PROGRESS_MAX 16 52 #endif 53 54 55 /*-******************************************************* 56 * Dependencies 57 *********************************************************/ 58 #include <string.h> /* memcpy, memmove, memset */ 59 #include "cpu.h" /* bmi2 */ 60 #include "mem.h" /* low level memory routines */ 61 #define FSE_STATIC_LINKING_ONLY 62 #include "fse.h" 63 #define HUF_STATIC_LINKING_ONLY 64 #include "huf.h" 65 #include "zstd_internal.h" /* blockProperties_t */ 66 #include "zstd_decompress_internal.h" /* ZSTD_DCtx */ 67 #include "zstd_ddict.h" /* ZSTD_DDictDictContent */ 68 #include "zstd_decompress_block.h" /* ZSTD_decompressBlock_internal */ 69 70 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) 71 # include "zstd_legacy.h" 72 #endif 73 74 75 /*-************************************************************* 76 * Context management 77 ***************************************************************/ 78 size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx) 79 { 80 if (dctx==NULL) return 0; /* support sizeof NULL */ 81 return sizeof(*dctx) 82 + ZSTD_sizeof_DDict(dctx->ddictLocal) 83 + dctx->inBuffSize + dctx->outBuffSize; 84 } 85 86 size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); } 87 88 89 static size_t ZSTD_startingInputLength(ZSTD_format_e format) 90 { 91 size_t const startingInputLength = (format==ZSTD_f_zstd1_magicless) ? 92 ZSTD_FRAMEHEADERSIZE_PREFIX - ZSTD_FRAMEIDSIZE : 93 ZSTD_FRAMEHEADERSIZE_PREFIX; 94 ZSTD_STATIC_ASSERT(ZSTD_FRAMEHEADERSIZE_PREFIX >= ZSTD_FRAMEIDSIZE); 95 /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */ 96 assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) ); 97 return startingInputLength; 98 } 99 100 static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) 101 { 102 dctx->format = ZSTD_f_zstd1; /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */ 103 dctx->staticSize = 0; 104 dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT; 105 dctx->ddict = NULL; 106 dctx->ddictLocal = NULL; 107 dctx->dictEnd = NULL; 108 dctx->ddictIsCold = 0; 109 dctx->inBuff = NULL; 110 dctx->inBuffSize = 0; 111 dctx->outBuffSize = 0; 112 dctx->streamStage = zdss_init; 113 dctx->legacyContext = NULL; 114 dctx->previousLegacyVersion = 0; 115 dctx->noForwardProgress = 0; 116 dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); 117 } 118 119 ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize) 120 { 121 ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace; 122 123 if ((size_t)workspace & 7) return NULL; /* 8-aligned */ 124 if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */ 125 126 ZSTD_initDCtx_internal(dctx); 127 dctx->staticSize = workspaceSize; 128 dctx->inBuff = (char*)(dctx+1); 129 return dctx; 130 } 131 132 ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem) 133 { 134 if (!customMem.customAlloc ^ !customMem.customFree) return NULL; 135 136 { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem); 137 if (!dctx) return NULL; 138 dctx->customMem = customMem; 139 ZSTD_initDCtx_internal(dctx); 140 return dctx; 141 } 142 } 143 144 ZSTD_DCtx* ZSTD_createDCtx(void) 145 { 146 DEBUGLOG(3, "ZSTD_createDCtx"); 147 return ZSTD_createDCtx_advanced(ZSTD_defaultCMem); 148 } 149 150 size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx) 151 { 152 if (dctx==NULL) return 0; /* support free on NULL */ 153 if (dctx->staticSize) return ERROR(memory_allocation); /* not compatible with static DCtx */ 154 { ZSTD_customMem const cMem = dctx->customMem; 155 ZSTD_freeDDict(dctx->ddictLocal); 156 dctx->ddictLocal = NULL; 157 ZSTD_free(dctx->inBuff, cMem); 158 dctx->inBuff = NULL; 159 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) 160 if (dctx->legacyContext) 161 ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion); 162 #endif 163 ZSTD_free(dctx, cMem); 164 return 0; 165 } 166 } 167 168 /* no longer useful */ 169 void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx) 170 { 171 size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx); 172 memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */ 173 } 174 175 176 /*-************************************************************* 177 * Frame header decoding 178 ***************************************************************/ 179 180 /*! ZSTD_isFrame() : 181 * Tells if the content of `buffer` starts with a valid Frame Identifier. 182 * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. 183 * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. 184 * Note 3 : Skippable Frame Identifiers are considered valid. */ 185 unsigned ZSTD_isFrame(const void* buffer, size_t size) 186 { 187 if (size < ZSTD_FRAMEIDSIZE) return 0; 188 { U32 const magic = MEM_readLE32(buffer); 189 if (magic == ZSTD_MAGICNUMBER) return 1; 190 if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1; 191 } 192 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) 193 if (ZSTD_isLegacy(buffer, size)) return 1; 194 #endif 195 return 0; 196 } 197 198 /** ZSTD_frameHeaderSize_internal() : 199 * srcSize must be large enough to reach header size fields. 200 * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless. 201 * @return : size of the Frame Header 202 * or an error code, which can be tested with ZSTD_isError() */ 203 static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format) 204 { 205 size_t const minInputSize = ZSTD_startingInputLength(format); 206 if (srcSize < minInputSize) return ERROR(srcSize_wrong); 207 208 { BYTE const fhd = ((const BYTE*)src)[minInputSize-1]; 209 U32 const dictID= fhd & 3; 210 U32 const singleSegment = (fhd >> 5) & 1; 211 U32 const fcsId = fhd >> 6; 212 return minInputSize + !singleSegment 213 + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId] 214 + (singleSegment && !fcsId); 215 } 216 } 217 218 /** ZSTD_frameHeaderSize() : 219 * srcSize must be >= ZSTD_frameHeaderSize_prefix. 220 * @return : size of the Frame Header, 221 * or an error code (if srcSize is too small) */ 222 size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize) 223 { 224 return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1); 225 } 226 227 228 /** ZSTD_getFrameHeader_advanced() : 229 * decode Frame Header, or require larger `srcSize`. 230 * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless 231 * @return : 0, `zfhPtr` is correctly filled, 232 * >0, `srcSize` is too small, value is wanted `srcSize` amount, 233 * or an error code, which can be tested using ZSTD_isError() */ 234 size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format) 235 { 236 const BYTE* ip = (const BYTE*)src; 237 size_t const minInputSize = ZSTD_startingInputLength(format); 238 239 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 */ 240 if (srcSize < minInputSize) return minInputSize; 241 if (src==NULL) return ERROR(GENERIC); /* invalid parameter */ 242 243 if ( (format != ZSTD_f_zstd1_magicless) 244 && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) { 245 if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { 246 /* skippable frame */ 247 if (srcSize < ZSTD_SKIPPABLEHEADERSIZE) 248 return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */ 249 memset(zfhPtr, 0, sizeof(*zfhPtr)); 250 zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE); 251 zfhPtr->frameType = ZSTD_skippableFrame; 252 return 0; 253 } 254 return ERROR(prefix_unknown); 255 } 256 257 /* ensure there is enough `srcSize` to fully read/decode frame header */ 258 { size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format); 259 if (srcSize < fhsize) return fhsize; 260 zfhPtr->headerSize = (U32)fhsize; 261 } 262 263 { BYTE const fhdByte = ip[minInputSize-1]; 264 size_t pos = minInputSize; 265 U32 const dictIDSizeCode = fhdByte&3; 266 U32 const checksumFlag = (fhdByte>>2)&1; 267 U32 const singleSegment = (fhdByte>>5)&1; 268 U32 const fcsID = fhdByte>>6; 269 U64 windowSize = 0; 270 U32 dictID = 0; 271 U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN; 272 if ((fhdByte & 0x08) != 0) 273 return ERROR(frameParameter_unsupported); /* reserved bits, must be zero */ 274 275 if (!singleSegment) { 276 BYTE const wlByte = ip[pos++]; 277 U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN; 278 if (windowLog > ZSTD_WINDOWLOG_MAX) 279 return ERROR(frameParameter_windowTooLarge); 280 windowSize = (1ULL << windowLog); 281 windowSize += (windowSize >> 3) * (wlByte&7); 282 } 283 switch(dictIDSizeCode) 284 { 285 default: assert(0); /* impossible */ 286 case 0 : break; 287 case 1 : dictID = ip[pos]; pos++; break; 288 case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break; 289 case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break; 290 } 291 switch(fcsID) 292 { 293 default: assert(0); /* impossible */ 294 case 0 : if (singleSegment) frameContentSize = ip[pos]; break; 295 case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break; 296 case 2 : frameContentSize = MEM_readLE32(ip+pos); break; 297 case 3 : frameContentSize = MEM_readLE64(ip+pos); break; 298 } 299 if (singleSegment) windowSize = frameContentSize; 300 301 zfhPtr->frameType = ZSTD_frame; 302 zfhPtr->frameContentSize = frameContentSize; 303 zfhPtr->windowSize = windowSize; 304 zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); 305 zfhPtr->dictID = dictID; 306 zfhPtr->checksumFlag = checksumFlag; 307 } 308 return 0; 309 } 310 311 /** ZSTD_getFrameHeader() : 312 * decode Frame Header, or require larger `srcSize`. 313 * note : this function does not consume input, it only reads it. 314 * @return : 0, `zfhPtr` is correctly filled, 315 * >0, `srcSize` is too small, value is wanted `srcSize` amount, 316 * or an error code, which can be tested using ZSTD_isError() */ 317 size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize) 318 { 319 return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1); 320 } 321 322 323 /** ZSTD_getFrameContentSize() : 324 * compatible with legacy mode 325 * @return : decompressed size of the single frame pointed to be `src` if known, otherwise 326 * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined 327 * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */ 328 unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize) 329 { 330 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) 331 if (ZSTD_isLegacy(src, srcSize)) { 332 unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize); 333 return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret; 334 } 335 #endif 336 { ZSTD_frameHeader zfh; 337 if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0) 338 return ZSTD_CONTENTSIZE_ERROR; 339 if (zfh.frameType == ZSTD_skippableFrame) { 340 return 0; 341 } else { 342 return zfh.frameContentSize; 343 } } 344 } 345 346 static size_t readSkippableFrameSize(void const* src, size_t srcSize) 347 { 348 size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE; 349 U32 sizeU32; 350 351 if (srcSize < ZSTD_SKIPPABLEHEADERSIZE) 352 return ERROR(srcSize_wrong); 353 354 sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE); 355 if ((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32) 356 return ERROR(frameParameter_unsupported); 357 358 return skippableHeaderSize + sizeU32; 359 } 360 361 /** ZSTD_findDecompressedSize() : 362 * compatible with legacy mode 363 * `srcSize` must be the exact length of some number of ZSTD compressed and/or 364 * skippable frames 365 * @return : decompressed size of the frames contained */ 366 unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize) 367 { 368 unsigned long long totalDstSize = 0; 369 370 while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) { 371 U32 const magicNumber = MEM_readLE32(src); 372 373 if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { 374 size_t const skippableSize = readSkippableFrameSize(src, srcSize); 375 if (ZSTD_isError(skippableSize)) 376 return skippableSize; 377 if (srcSize < skippableSize) { 378 return ZSTD_CONTENTSIZE_ERROR; 379 } 380 381 src = (const BYTE *)src + skippableSize; 382 srcSize -= skippableSize; 383 continue; 384 } 385 386 { unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); 387 if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret; 388 389 /* check for overflow */ 390 if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR; 391 totalDstSize += ret; 392 } 393 { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize); 394 if (ZSTD_isError(frameSrcSize)) { 395 return ZSTD_CONTENTSIZE_ERROR; 396 } 397 398 src = (const BYTE *)src + frameSrcSize; 399 srcSize -= frameSrcSize; 400 } 401 } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ 402 403 if (srcSize) return ZSTD_CONTENTSIZE_ERROR; 404 405 return totalDstSize; 406 } 407 408 /** ZSTD_getDecompressedSize() : 409 * compatible with legacy mode 410 * @return : decompressed size if known, 0 otherwise 411 note : 0 can mean any of the following : 412 - frame content is empty 413 - decompressed size field is not present in frame header 414 - frame header unknown / not supported 415 - frame header not complete (`srcSize` too small) */ 416 unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize) 417 { 418 unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); 419 ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN); 420 return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret; 421 } 422 423 424 /** ZSTD_decodeFrameHeader() : 425 * `headerSize` must be the size provided by ZSTD_frameHeaderSize(). 426 * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */ 427 static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize) 428 { 429 size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format); 430 if (ZSTD_isError(result)) return result; /* invalid header */ 431 if (result>0) return ERROR(srcSize_wrong); /* headerSize too small */ 432 if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID)) 433 return ERROR(dictionary_wrong); 434 if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0); 435 return 0; 436 } 437 438 439 /** ZSTD_findFrameCompressedSize() : 440 * compatible with legacy mode 441 * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame 442 * `srcSize` must be at least as large as the frame contained 443 * @return : the compressed size of the frame starting at `src` */ 444 size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize) 445 { 446 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) 447 if (ZSTD_isLegacy(src, srcSize)) 448 return ZSTD_findFrameCompressedSizeLegacy(src, srcSize); 449 #endif 450 if ( (srcSize >= ZSTD_SKIPPABLEHEADERSIZE) 451 && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START ) { 452 return readSkippableFrameSize(src, srcSize); 453 } else { 454 const BYTE* ip = (const BYTE*)src; 455 const BYTE* const ipstart = ip; 456 size_t remainingSize = srcSize; 457 ZSTD_frameHeader zfh; 458 459 /* Extract Frame Header */ 460 { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize); 461 if (ZSTD_isError(ret)) return ret; 462 if (ret > 0) return ERROR(srcSize_wrong); 463 } 464 465 ip += zfh.headerSize; 466 remainingSize -= zfh.headerSize; 467 468 /* Loop on each block */ 469 while (1) { 470 blockProperties_t blockProperties; 471 size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties); 472 if (ZSTD_isError(cBlockSize)) return cBlockSize; 473 474 if (ZSTD_blockHeaderSize + cBlockSize > remainingSize) 475 return ERROR(srcSize_wrong); 476 477 ip += ZSTD_blockHeaderSize + cBlockSize; 478 remainingSize -= ZSTD_blockHeaderSize + cBlockSize; 479 480 if (blockProperties.lastBlock) break; 481 } 482 483 if (zfh.checksumFlag) { /* Final frame content checksum */ 484 if (remainingSize < 4) return ERROR(srcSize_wrong); 485 ip += 4; 486 } 487 488 return ip - ipstart; 489 } 490 } 491 492 493 494 /*-************************************************************* 495 * Frame decoding 496 ***************************************************************/ 497 498 499 void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst) 500 { 501 if (dst != dctx->previousDstEnd) { /* not contiguous */ 502 dctx->dictEnd = dctx->previousDstEnd; 503 dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); 504 dctx->prefixStart = dst; 505 dctx->previousDstEnd = dst; 506 } 507 } 508 509 /** ZSTD_insertBlock() : 510 insert `src` block into `dctx` history. Useful to track uncompressed blocks. */ 511 size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize) 512 { 513 ZSTD_checkContinuity(dctx, blockStart); 514 dctx->previousDstEnd = (const char*)blockStart + blockSize; 515 return blockSize; 516 } 517 518 519 static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity, 520 const void* src, size_t srcSize) 521 { 522 DEBUGLOG(5, "ZSTD_copyRawBlock"); 523 if (dst == NULL) { 524 if (srcSize == 0) return 0; 525 return ERROR(dstBuffer_null); 526 } 527 if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall); 528 memcpy(dst, src, srcSize); 529 return srcSize; 530 } 531 532 static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity, 533 BYTE b, 534 size_t regenSize) 535 { 536 if (dst == NULL) { 537 if (regenSize == 0) return 0; 538 return ERROR(dstBuffer_null); 539 } 540 if (regenSize > dstCapacity) return ERROR(dstSize_tooSmall); 541 memset(dst, b, regenSize); 542 return regenSize; 543 } 544 545 546 /*! ZSTD_decompressFrame() : 547 * @dctx must be properly initialized 548 * will update *srcPtr and *srcSizePtr, 549 * to make *srcPtr progress by one frame. */ 550 static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, 551 void* dst, size_t dstCapacity, 552 const void** srcPtr, size_t *srcSizePtr) 553 { 554 const BYTE* ip = (const BYTE*)(*srcPtr); 555 BYTE* const ostart = (BYTE* const)dst; 556 BYTE* const oend = ostart + dstCapacity; 557 BYTE* op = ostart; 558 size_t remainingSrcSize = *srcSizePtr; 559 560 DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr); 561 562 /* check */ 563 if (remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN+ZSTD_blockHeaderSize) 564 return ERROR(srcSize_wrong); 565 566 /* Frame Header */ 567 { size_t const frameHeaderSize = ZSTD_frameHeaderSize(ip, ZSTD_FRAMEHEADERSIZE_PREFIX); 568 if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize; 569 if (remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize) 570 return ERROR(srcSize_wrong); 571 CHECK_F( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) ); 572 ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize; 573 } 574 575 /* Loop on each block */ 576 while (1) { 577 size_t decodedSize; 578 blockProperties_t blockProperties; 579 size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties); 580 if (ZSTD_isError(cBlockSize)) return cBlockSize; 581 582 ip += ZSTD_blockHeaderSize; 583 remainingSrcSize -= ZSTD_blockHeaderSize; 584 if (cBlockSize > remainingSrcSize) return ERROR(srcSize_wrong); 585 586 switch(blockProperties.blockType) 587 { 588 case bt_compressed: 589 decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1); 590 break; 591 case bt_raw : 592 decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize); 593 break; 594 case bt_rle : 595 decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize); 596 break; 597 case bt_reserved : 598 default: 599 return ERROR(corruption_detected); 600 } 601 602 if (ZSTD_isError(decodedSize)) return decodedSize; 603 if (dctx->fParams.checksumFlag) 604 XXH64_update(&dctx->xxhState, op, decodedSize); 605 op += decodedSize; 606 ip += cBlockSize; 607 remainingSrcSize -= cBlockSize; 608 if (blockProperties.lastBlock) break; 609 } 610 611 if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) { 612 if ((U64)(op-ostart) != dctx->fParams.frameContentSize) { 613 return ERROR(corruption_detected); 614 } } 615 if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */ 616 U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState); 617 U32 checkRead; 618 if (remainingSrcSize<4) return ERROR(checksum_wrong); 619 checkRead = MEM_readLE32(ip); 620 if (checkRead != checkCalc) return ERROR(checksum_wrong); 621 ip += 4; 622 remainingSrcSize -= 4; 623 } 624 625 /* Allow caller to get size read */ 626 *srcPtr = ip; 627 *srcSizePtr = remainingSrcSize; 628 return op-ostart; 629 } 630 631 static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, 632 void* dst, size_t dstCapacity, 633 const void* src, size_t srcSize, 634 const void* dict, size_t dictSize, 635 const ZSTD_DDict* ddict) 636 { 637 void* const dststart = dst; 638 int moreThan1Frame = 0; 639 640 DEBUGLOG(5, "ZSTD_decompressMultiFrame"); 641 assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */ 642 643 if (ddict) { 644 dict = ZSTD_DDict_dictContent(ddict); 645 dictSize = ZSTD_DDict_dictSize(ddict); 646 } 647 648 while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) { 649 650 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) 651 if (ZSTD_isLegacy(src, srcSize)) { 652 size_t decodedSize; 653 size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize); 654 if (ZSTD_isError(frameSize)) return frameSize; 655 /* legacy support is not compatible with static dctx */ 656 if (dctx->staticSize) return ERROR(memory_allocation); 657 658 decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize); 659 if (ZSTD_isError(decodedSize)) return decodedSize; 660 661 assert(decodedSize <=- dstCapacity); 662 dst = (BYTE*)dst + decodedSize; 663 dstCapacity -= decodedSize; 664 665 src = (const BYTE*)src + frameSize; 666 srcSize -= frameSize; 667 668 continue; 669 } 670 #endif 671 672 { U32 const magicNumber = MEM_readLE32(src); 673 DEBUGLOG(4, "reading magic number %08X (expecting %08X)", 674 (unsigned)magicNumber, ZSTD_MAGICNUMBER); 675 if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { 676 size_t const skippableSize = readSkippableFrameSize(src, srcSize); 677 if (ZSTD_isError(skippableSize)) 678 return skippableSize; 679 if (srcSize < skippableSize) return ERROR(srcSize_wrong); 680 681 src = (const BYTE *)src + skippableSize; 682 srcSize -= skippableSize; 683 continue; 684 } } 685 686 if (ddict) { 687 /* we were called from ZSTD_decompress_usingDDict */ 688 CHECK_F(ZSTD_decompressBegin_usingDDict(dctx, ddict)); 689 } else { 690 /* this will initialize correctly with no dict if dict == NULL, so 691 * use this in all cases but ddict */ 692 CHECK_F(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize)); 693 } 694 ZSTD_checkContinuity(dctx, dst); 695 696 { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity, 697 &src, &srcSize); 698 if ( (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown) 699 && (moreThan1Frame==1) ) { 700 /* at least one frame successfully completed, 701 * but following bytes are garbage : 702 * it's more likely to be a srcSize error, 703 * specifying more bytes than compressed size of frame(s). 704 * This error message replaces ERROR(prefix_unknown), 705 * which would be confusing, as the first header is actually correct. 706 * Note that one could be unlucky, it might be a corruption error instead, 707 * happening right at the place where we expect zstd magic bytes. 708 * But this is _much_ less likely than a srcSize field error. */ 709 return ERROR(srcSize_wrong); 710 } 711 if (ZSTD_isError(res)) return res; 712 assert(res <= dstCapacity); 713 dst = (BYTE*)dst + res; 714 dstCapacity -= res; 715 } 716 moreThan1Frame = 1; 717 } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ 718 719 if (srcSize) return ERROR(srcSize_wrong); /* input not entirely consumed */ 720 721 return (BYTE*)dst - (BYTE*)dststart; 722 } 723 724 size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, 725 void* dst, size_t dstCapacity, 726 const void* src, size_t srcSize, 727 const void* dict, size_t dictSize) 728 { 729 return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL); 730 } 731 732 733 size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) 734 { 735 return ZSTD_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0); 736 } 737 738 739 size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize) 740 { 741 #if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1) 742 size_t regenSize; 743 ZSTD_DCtx* const dctx = ZSTD_createDCtx(); 744 if (dctx==NULL) return ERROR(memory_allocation); 745 regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize); 746 ZSTD_freeDCtx(dctx); 747 return regenSize; 748 #else /* stack mode */ 749 ZSTD_DCtx dctx; 750 ZSTD_initDCtx_internal(&dctx); 751 return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize); 752 #endif 753 } 754 755 756 /*-************************************** 757 * Advanced Streaming Decompression API 758 * Bufferless and synchronous 759 ****************************************/ 760 size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; } 761 762 ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) { 763 switch(dctx->stage) 764 { 765 default: /* should not happen */ 766 assert(0); 767 case ZSTDds_getFrameHeaderSize: 768 case ZSTDds_decodeFrameHeader: 769 return ZSTDnit_frameHeader; 770 case ZSTDds_decodeBlockHeader: 771 return ZSTDnit_blockHeader; 772 case ZSTDds_decompressBlock: 773 return ZSTDnit_block; 774 case ZSTDds_decompressLastBlock: 775 return ZSTDnit_lastBlock; 776 case ZSTDds_checkChecksum: 777 return ZSTDnit_checksum; 778 case ZSTDds_decodeSkippableHeader: 779 case ZSTDds_skipFrame: 780 return ZSTDnit_skippableFrame; 781 } 782 } 783 784 static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; } 785 786 /** ZSTD_decompressContinue() : 787 * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress()) 788 * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity) 789 * or an error code, which can be tested using ZSTD_isError() */ 790 size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) 791 { 792 DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize); 793 /* Sanity check */ 794 if (srcSize != dctx->expected) 795 return ERROR(srcSize_wrong); /* not allowed */ 796 if (dstCapacity) ZSTD_checkContinuity(dctx, dst); 797 798 switch (dctx->stage) 799 { 800 case ZSTDds_getFrameHeaderSize : 801 assert(src != NULL); 802 if (dctx->format == ZSTD_f_zstd1) { /* allows header */ 803 assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */ 804 if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ 805 memcpy(dctx->headerBuffer, src, srcSize); 806 dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */ 807 dctx->stage = ZSTDds_decodeSkippableHeader; 808 return 0; 809 } } 810 dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format); 811 if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize; 812 memcpy(dctx->headerBuffer, src, srcSize); 813 dctx->expected = dctx->headerSize - srcSize; 814 dctx->stage = ZSTDds_decodeFrameHeader; 815 return 0; 816 817 case ZSTDds_decodeFrameHeader: 818 assert(src != NULL); 819 memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize); 820 CHECK_F(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize)); 821 dctx->expected = ZSTD_blockHeaderSize; 822 dctx->stage = ZSTDds_decodeBlockHeader; 823 return 0; 824 825 case ZSTDds_decodeBlockHeader: 826 { blockProperties_t bp; 827 size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp); 828 if (ZSTD_isError(cBlockSize)) return cBlockSize; 829 dctx->expected = cBlockSize; 830 dctx->bType = bp.blockType; 831 dctx->rleSize = bp.origSize; 832 if (cBlockSize) { 833 dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock; 834 return 0; 835 } 836 /* empty block */ 837 if (bp.lastBlock) { 838 if (dctx->fParams.checksumFlag) { 839 dctx->expected = 4; 840 dctx->stage = ZSTDds_checkChecksum; 841 } else { 842 dctx->expected = 0; /* end of frame */ 843 dctx->stage = ZSTDds_getFrameHeaderSize; 844 } 845 } else { 846 dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */ 847 dctx->stage = ZSTDds_decodeBlockHeader; 848 } 849 return 0; 850 } 851 852 case ZSTDds_decompressLastBlock: 853 case ZSTDds_decompressBlock: 854 DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock"); 855 { size_t rSize; 856 switch(dctx->bType) 857 { 858 case bt_compressed: 859 DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed"); 860 rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1); 861 break; 862 case bt_raw : 863 rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize); 864 break; 865 case bt_rle : 866 rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize); 867 break; 868 case bt_reserved : /* should never happen */ 869 default: 870 return ERROR(corruption_detected); 871 } 872 if (ZSTD_isError(rSize)) return rSize; 873 DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize); 874 dctx->decodedSize += rSize; 875 if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize); 876 877 if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */ 878 DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize); 879 if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) { 880 if (dctx->decodedSize != dctx->fParams.frameContentSize) { 881 return ERROR(corruption_detected); 882 } } 883 if (dctx->fParams.checksumFlag) { /* another round for frame checksum */ 884 dctx->expected = 4; 885 dctx->stage = ZSTDds_checkChecksum; 886 } else { 887 dctx->expected = 0; /* ends here */ 888 dctx->stage = ZSTDds_getFrameHeaderSize; 889 } 890 } else { 891 dctx->stage = ZSTDds_decodeBlockHeader; 892 dctx->expected = ZSTD_blockHeaderSize; 893 dctx->previousDstEnd = (char*)dst + rSize; 894 } 895 return rSize; 896 } 897 898 case ZSTDds_checkChecksum: 899 assert(srcSize == 4); /* guaranteed by dctx->expected */ 900 { U32 const h32 = (U32)XXH64_digest(&dctx->xxhState); 901 U32 const check32 = MEM_readLE32(src); 902 DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32); 903 if (check32 != h32) return ERROR(checksum_wrong); 904 dctx->expected = 0; 905 dctx->stage = ZSTDds_getFrameHeaderSize; 906 return 0; 907 } 908 909 case ZSTDds_decodeSkippableHeader: 910 assert(src != NULL); 911 assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE); 912 memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */ 913 dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */ 914 dctx->stage = ZSTDds_skipFrame; 915 return 0; 916 917 case ZSTDds_skipFrame: 918 dctx->expected = 0; 919 dctx->stage = ZSTDds_getFrameHeaderSize; 920 return 0; 921 922 default: 923 assert(0); /* impossible */ 924 return ERROR(GENERIC); /* some compiler require default to do something */ 925 } 926 } 927 928 929 static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) 930 { 931 dctx->dictEnd = dctx->previousDstEnd; 932 dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); 933 dctx->prefixStart = dict; 934 dctx->previousDstEnd = (const char*)dict + dictSize; 935 return 0; 936 } 937 938 /*! ZSTD_loadDEntropy() : 939 * dict : must point at beginning of a valid zstd dictionary. 940 * @return : size of entropy tables read */ 941 size_t 942 ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, 943 const void* const dict, size_t const dictSize) 944 { 945 const BYTE* dictPtr = (const BYTE*)dict; 946 const BYTE* const dictEnd = dictPtr + dictSize; 947 948 if (dictSize <= 8) return ERROR(dictionary_corrupted); 949 assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */ 950 dictPtr += 8; /* skip header = magic + dictID */ 951 952 ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable)); 953 ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable)); 954 ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE); 955 { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */ 956 size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable); 957 #ifdef HUF_FORCE_DECOMPRESS_X1 958 /* in minimal huffman, we always use X1 variants */ 959 size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable, 960 dictPtr, dictEnd - dictPtr, 961 workspace, workspaceSize); 962 #else 963 size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable, 964 dictPtr, dictEnd - dictPtr, 965 workspace, workspaceSize); 966 #endif 967 if (HUF_isError(hSize)) return ERROR(dictionary_corrupted); 968 dictPtr += hSize; 969 } 970 971 { short offcodeNCount[MaxOff+1]; 972 unsigned offcodeMaxValue = MaxOff, offcodeLog; 973 size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr); 974 if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted); 975 if (offcodeMaxValue > MaxOff) return ERROR(dictionary_corrupted); 976 if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted); 977 ZSTD_buildFSETable( entropy->OFTable, 978 offcodeNCount, offcodeMaxValue, 979 OF_base, OF_bits, 980 offcodeLog); 981 dictPtr += offcodeHeaderSize; 982 } 983 984 { short matchlengthNCount[MaxML+1]; 985 unsigned matchlengthMaxValue = MaxML, matchlengthLog; 986 size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr); 987 if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted); 988 if (matchlengthMaxValue > MaxML) return ERROR(dictionary_corrupted); 989 if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted); 990 ZSTD_buildFSETable( entropy->MLTable, 991 matchlengthNCount, matchlengthMaxValue, 992 ML_base, ML_bits, 993 matchlengthLog); 994 dictPtr += matchlengthHeaderSize; 995 } 996 997 { short litlengthNCount[MaxLL+1]; 998 unsigned litlengthMaxValue = MaxLL, litlengthLog; 999 size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr); 1000 if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted); 1001 if (litlengthMaxValue > MaxLL) return ERROR(dictionary_corrupted); 1002 if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted); 1003 ZSTD_buildFSETable( entropy->LLTable, 1004 litlengthNCount, litlengthMaxValue, 1005 LL_base, LL_bits, 1006 litlengthLog); 1007 dictPtr += litlengthHeaderSize; 1008 } 1009 1010 if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted); 1011 { int i; 1012 size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12)); 1013 for (i=0; i<3; i++) { 1014 U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4; 1015 if (rep==0 || rep >= dictContentSize) return ERROR(dictionary_corrupted); 1016 entropy->rep[i] = rep; 1017 } } 1018 1019 return dictPtr - (const BYTE*)dict; 1020 } 1021 1022 static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) 1023 { 1024 if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize); 1025 { U32 const magic = MEM_readLE32(dict); 1026 if (magic != ZSTD_MAGIC_DICTIONARY) { 1027 return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */ 1028 } } 1029 dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); 1030 1031 /* load entropy tables */ 1032 { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize); 1033 if (ZSTD_isError(eSize)) return ERROR(dictionary_corrupted); 1034 dict = (const char*)dict + eSize; 1035 dictSize -= eSize; 1036 } 1037 dctx->litEntropy = dctx->fseEntropy = 1; 1038 1039 /* reference dictionary content */ 1040 return ZSTD_refDictContent(dctx, dict, dictSize); 1041 } 1042 1043 size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) 1044 { 1045 assert(dctx != NULL); 1046 dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */ 1047 dctx->stage = ZSTDds_getFrameHeaderSize; 1048 dctx->decodedSize = 0; 1049 dctx->previousDstEnd = NULL; 1050 dctx->prefixStart = NULL; 1051 dctx->virtualStart = NULL; 1052 dctx->dictEnd = NULL; 1053 dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */ 1054 dctx->litEntropy = dctx->fseEntropy = 0; 1055 dctx->dictID = 0; 1056 ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue)); 1057 memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */ 1058 dctx->LLTptr = dctx->entropy.LLTable; 1059 dctx->MLTptr = dctx->entropy.MLTable; 1060 dctx->OFTptr = dctx->entropy.OFTable; 1061 dctx->HUFptr = dctx->entropy.hufTable; 1062 return 0; 1063 } 1064 1065 size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) 1066 { 1067 CHECK_F( ZSTD_decompressBegin(dctx) ); 1068 if (dict && dictSize) 1069 CHECK_E(ZSTD_decompress_insertDictionary(dctx, dict, dictSize), dictionary_corrupted); 1070 return 0; 1071 } 1072 1073 1074 /* ====== ZSTD_DDict ====== */ 1075 1076 size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) 1077 { 1078 DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict"); 1079 assert(dctx != NULL); 1080 if (ddict) { 1081 const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict); 1082 size_t const dictSize = ZSTD_DDict_dictSize(ddict); 1083 const void* const dictEnd = dictStart + dictSize; 1084 dctx->ddictIsCold = (dctx->dictEnd != dictEnd); 1085 DEBUGLOG(4, "DDict is %s", 1086 dctx->ddictIsCold ? "~cold~" : "hot!"); 1087 } 1088 CHECK_F( ZSTD_decompressBegin(dctx) ); 1089 if (ddict) { /* NULL ddict is equivalent to no dictionary */ 1090 ZSTD_copyDDictParameters(dctx, ddict); 1091 } 1092 return 0; 1093 } 1094 1095 /*! ZSTD_getDictID_fromDict() : 1096 * Provides the dictID stored within dictionary. 1097 * if @return == 0, the dictionary is not conformant with Zstandard specification. 1098 * It can still be loaded, but as a content-only dictionary. */ 1099 unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize) 1100 { 1101 if (dictSize < 8) return 0; 1102 if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0; 1103 return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); 1104 } 1105 1106 /*! ZSTD_getDictID_fromFrame() : 1107 * Provides the dictID required to decompresse frame stored within `src`. 1108 * If @return == 0, the dictID could not be decoded. 1109 * This could for one of the following reasons : 1110 * - The frame does not require a dictionary (most common case). 1111 * - The frame was built with dictID intentionally removed. 1112 * Needed dictionary is a hidden information. 1113 * Note : this use case also happens when using a non-conformant dictionary. 1114 * - `srcSize` is too small, and as a result, frame header could not be decoded. 1115 * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`. 1116 * - This is not a Zstandard frame. 1117 * When identifying the exact failure cause, it's possible to use 1118 * ZSTD_getFrameHeader(), which will provide a more precise error code. */ 1119 unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize) 1120 { 1121 ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 }; 1122 size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize); 1123 if (ZSTD_isError(hError)) return 0; 1124 return zfp.dictID; 1125 } 1126 1127 1128 /*! ZSTD_decompress_usingDDict() : 1129 * Decompression using a pre-digested Dictionary 1130 * Use dictionary without significant overhead. */ 1131 size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, 1132 void* dst, size_t dstCapacity, 1133 const void* src, size_t srcSize, 1134 const ZSTD_DDict* ddict) 1135 { 1136 /* pass content and size in case legacy frames are encountered */ 1137 return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, 1138 NULL, 0, 1139 ddict); 1140 } 1141 1142 1143 /*===================================== 1144 * Streaming decompression 1145 *====================================*/ 1146 1147 ZSTD_DStream* ZSTD_createDStream(void) 1148 { 1149 DEBUGLOG(3, "ZSTD_createDStream"); 1150 return ZSTD_createDStream_advanced(ZSTD_defaultCMem); 1151 } 1152 1153 ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize) 1154 { 1155 return ZSTD_initStaticDCtx(workspace, workspaceSize); 1156 } 1157 1158 ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem) 1159 { 1160 return ZSTD_createDCtx_advanced(customMem); 1161 } 1162 1163 size_t ZSTD_freeDStream(ZSTD_DStream* zds) 1164 { 1165 return ZSTD_freeDCtx(zds); 1166 } 1167 1168 1169 /* *** Initialization *** */ 1170 1171 size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; } 1172 size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; } 1173 1174 size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, 1175 const void* dict, size_t dictSize, 1176 ZSTD_dictLoadMethod_e dictLoadMethod, 1177 ZSTD_dictContentType_e dictContentType) 1178 { 1179 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong); 1180 ZSTD_freeDDict(dctx->ddictLocal); 1181 if (dict && dictSize >= 8) { 1182 dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem); 1183 if (dctx->ddictLocal == NULL) return ERROR(memory_allocation); 1184 } else { 1185 dctx->ddictLocal = NULL; 1186 } 1187 dctx->ddict = dctx->ddictLocal; 1188 return 0; 1189 } 1190 1191 size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) 1192 { 1193 return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto); 1194 } 1195 1196 size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) 1197 { 1198 return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto); 1199 } 1200 1201 size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType) 1202 { 1203 return ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType); 1204 } 1205 1206 size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize) 1207 { 1208 return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent); 1209 } 1210 1211 1212 /* ZSTD_initDStream_usingDict() : 1213 * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX. 1214 * this function cannot fail */ 1215 size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize) 1216 { 1217 DEBUGLOG(4, "ZSTD_initDStream_usingDict"); 1218 zds->streamStage = zdss_init; 1219 zds->noForwardProgress = 0; 1220 CHECK_F( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) ); 1221 return ZSTD_FRAMEHEADERSIZE_PREFIX; 1222 } 1223 1224 /* note : this variant can't fail */ 1225 size_t ZSTD_initDStream(ZSTD_DStream* zds) 1226 { 1227 DEBUGLOG(4, "ZSTD_initDStream"); 1228 return ZSTD_initDStream_usingDict(zds, NULL, 0); 1229 } 1230 1231 /* ZSTD_initDStream_usingDDict() : 1232 * ddict will just be referenced, and must outlive decompression session 1233 * this function cannot fail */ 1234 size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict) 1235 { 1236 size_t const initResult = ZSTD_initDStream(dctx); 1237 dctx->ddict = ddict; 1238 return initResult; 1239 } 1240 1241 /* ZSTD_resetDStream() : 1242 * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX. 1243 * this function cannot fail */ 1244 size_t ZSTD_resetDStream(ZSTD_DStream* dctx) 1245 { 1246 DEBUGLOG(4, "ZSTD_resetDStream"); 1247 dctx->streamStage = zdss_loadHeader; 1248 dctx->lhSize = dctx->inPos = dctx->outStart = dctx->outEnd = 0; 1249 dctx->legacyVersion = 0; 1250 dctx->hostageByte = 0; 1251 return ZSTD_FRAMEHEADERSIZE_PREFIX; 1252 } 1253 1254 1255 size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) 1256 { 1257 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong); 1258 dctx->ddict = ddict; 1259 return 0; 1260 } 1261 1262 /* ZSTD_DCtx_setMaxWindowSize() : 1263 * note : no direct equivalence in ZSTD_DCtx_setParameter, 1264 * since this version sets windowSize, and the other sets windowLog */ 1265 size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize) 1266 { 1267 ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax); 1268 size_t const min = (size_t)1 << bounds.lowerBound; 1269 size_t const max = (size_t)1 << bounds.upperBound; 1270 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong); 1271 if (maxWindowSize < min) return ERROR(parameter_outOfBound); 1272 if (maxWindowSize > max) return ERROR(parameter_outOfBound); 1273 dctx->maxWindowSize = maxWindowSize; 1274 return 0; 1275 } 1276 1277 size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format) 1278 { 1279 return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format); 1280 } 1281 1282 ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam) 1283 { 1284 ZSTD_bounds bounds = { 0, 0, 0 }; 1285 switch(dParam) { 1286 case ZSTD_d_windowLogMax: 1287 bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN; 1288 bounds.upperBound = ZSTD_WINDOWLOG_MAX; 1289 return bounds; 1290 case ZSTD_d_format: 1291 bounds.lowerBound = (int)ZSTD_f_zstd1; 1292 bounds.upperBound = (int)ZSTD_f_zstd1_magicless; 1293 ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless); 1294 return bounds; 1295 default:; 1296 } 1297 bounds.error = ERROR(parameter_unsupported); 1298 return bounds; 1299 } 1300 1301 /* ZSTD_dParam_withinBounds: 1302 * @return 1 if value is within dParam bounds, 1303 * 0 otherwise */ 1304 static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value) 1305 { 1306 ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam); 1307 if (ZSTD_isError(bounds.error)) return 0; 1308 if (value < bounds.lowerBound) return 0; 1309 if (value > bounds.upperBound) return 0; 1310 return 1; 1311 } 1312 1313 #define CHECK_DBOUNDS(p,v) { \ 1314 if (!ZSTD_dParam_withinBounds(p, v)) \ 1315 return ERROR(parameter_outOfBound); \ 1316 } 1317 1318 size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value) 1319 { 1320 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong); 1321 switch(dParam) { 1322 case ZSTD_d_windowLogMax: 1323 CHECK_DBOUNDS(ZSTD_d_windowLogMax, value); 1324 dctx->maxWindowSize = ((size_t)1) << value; 1325 return 0; 1326 case ZSTD_d_format: 1327 CHECK_DBOUNDS(ZSTD_d_format, value); 1328 dctx->format = (ZSTD_format_e)value; 1329 return 0; 1330 default:; 1331 } 1332 return ERROR(parameter_unsupported); 1333 } 1334 1335 size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset) 1336 { 1337 if ( (reset == ZSTD_reset_session_only) 1338 || (reset == ZSTD_reset_session_and_parameters) ) { 1339 (void)ZSTD_initDStream(dctx); 1340 } 1341 if ( (reset == ZSTD_reset_parameters) 1342 || (reset == ZSTD_reset_session_and_parameters) ) { 1343 if (dctx->streamStage != zdss_init) 1344 return ERROR(stage_wrong); 1345 dctx->format = ZSTD_f_zstd1; 1346 dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT; 1347 } 1348 return 0; 1349 } 1350 1351 1352 size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx) 1353 { 1354 return ZSTD_sizeof_DCtx(dctx); 1355 } 1356 1357 size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) 1358 { 1359 size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); 1360 unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2); 1361 unsigned long long const neededSize = MIN(frameContentSize, neededRBSize); 1362 size_t const minRBSize = (size_t) neededSize; 1363 if ((unsigned long long)minRBSize != neededSize) return ERROR(frameParameter_windowTooLarge); 1364 return minRBSize; 1365 } 1366 1367 size_t ZSTD_estimateDStreamSize(size_t windowSize) 1368 { 1369 size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX); 1370 size_t const inBuffSize = blockSize; /* no block can be larger */ 1371 size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN); 1372 return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize; 1373 } 1374 1375 size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize) 1376 { 1377 U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */ 1378 ZSTD_frameHeader zfh; 1379 size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize); 1380 if (ZSTD_isError(err)) return err; 1381 if (err>0) return ERROR(srcSize_wrong); 1382 if (zfh.windowSize > windowSizeMax) 1383 return ERROR(frameParameter_windowTooLarge); 1384 return ZSTD_estimateDStreamSize((size_t)zfh.windowSize); 1385 } 1386 1387 1388 /* ***** Decompression ***** */ 1389 1390 MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize) 1391 { 1392 size_t const length = MIN(dstCapacity, srcSize); 1393 memcpy(dst, src, length); 1394 return length; 1395 } 1396 1397 1398 size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input) 1399 { 1400 const char* const istart = (const char*)(input->src) + input->pos; 1401 const char* const iend = (const char*)(input->src) + input->size; 1402 const char* ip = istart; 1403 char* const ostart = (char*)(output->dst) + output->pos; 1404 char* const oend = (char*)(output->dst) + output->size; 1405 char* op = ostart; 1406 U32 someMoreWork = 1; 1407 1408 DEBUGLOG(5, "ZSTD_decompressStream"); 1409 if (input->pos > input->size) { /* forbidden */ 1410 DEBUGLOG(5, "in: pos: %u vs size: %u", 1411 (U32)input->pos, (U32)input->size); 1412 return ERROR(srcSize_wrong); 1413 } 1414 if (output->pos > output->size) { /* forbidden */ 1415 DEBUGLOG(5, "out: pos: %u vs size: %u", 1416 (U32)output->pos, (U32)output->size); 1417 return ERROR(dstSize_tooSmall); 1418 } 1419 DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos)); 1420 1421 while (someMoreWork) { 1422 switch(zds->streamStage) 1423 { 1424 case zdss_init : 1425 DEBUGLOG(5, "stage zdss_init => transparent reset "); 1426 ZSTD_resetDStream(zds); /* transparent reset on starting decoding a new frame */ 1427 /* fall-through */ 1428 1429 case zdss_loadHeader : 1430 DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip)); 1431 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) 1432 if (zds->legacyVersion) { 1433 /* legacy support is incompatible with static dctx */ 1434 if (zds->staticSize) return ERROR(memory_allocation); 1435 { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input); 1436 if (hint==0) zds->streamStage = zdss_init; 1437 return hint; 1438 } } 1439 #endif 1440 { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format); 1441 DEBUGLOG(5, "header size : %u", (U32)hSize); 1442 if (ZSTD_isError(hSize)) { 1443 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) 1444 U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart); 1445 if (legacyVersion) { 1446 const void* const dict = zds->ddict ? ZSTD_DDict_dictContent(zds->ddict) : NULL; 1447 size_t const dictSize = zds->ddict ? ZSTD_DDict_dictSize(zds->ddict) : 0; 1448 DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion); 1449 /* legacy support is incompatible with static dctx */ 1450 if (zds->staticSize) return ERROR(memory_allocation); 1451 CHECK_F(ZSTD_initLegacyStream(&zds->legacyContext, 1452 zds->previousLegacyVersion, legacyVersion, 1453 dict, dictSize)); 1454 zds->legacyVersion = zds->previousLegacyVersion = legacyVersion; 1455 { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input); 1456 if (hint==0) zds->streamStage = zdss_init; /* or stay in stage zdss_loadHeader */ 1457 return hint; 1458 } } 1459 #endif 1460 return hSize; /* error */ 1461 } 1462 if (hSize != 0) { /* need more input */ 1463 size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */ 1464 size_t const remainingInput = (size_t)(iend-ip); 1465 assert(iend >= ip); 1466 if (toLoad > remainingInput) { /* not enough input to load full header */ 1467 if (remainingInput > 0) { 1468 memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput); 1469 zds->lhSize += remainingInput; 1470 } 1471 input->pos = input->size; 1472 return (MAX(ZSTD_FRAMEHEADERSIZE_MIN, hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */ 1473 } 1474 assert(ip != NULL); 1475 memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad; 1476 break; 1477 } } 1478 1479 /* check for single-pass mode opportunity */ 1480 if (zds->fParams.frameContentSize && zds->fParams.windowSize /* skippable frame if == 0 */ 1481 && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) { 1482 size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart); 1483 if (cSize <= (size_t)(iend-istart)) { 1484 /* shortcut : using single-pass mode */ 1485 size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, zds->ddict); 1486 if (ZSTD_isError(decompressedSize)) return decompressedSize; 1487 DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()") 1488 ip = istart + cSize; 1489 op += decompressedSize; 1490 zds->expected = 0; 1491 zds->streamStage = zdss_init; 1492 someMoreWork = 0; 1493 break; 1494 } } 1495 1496 /* Consume header (see ZSTDds_decodeFrameHeader) */ 1497 DEBUGLOG(4, "Consume header"); 1498 CHECK_F(ZSTD_decompressBegin_usingDDict(zds, zds->ddict)); 1499 1500 if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ 1501 zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE); 1502 zds->stage = ZSTDds_skipFrame; 1503 } else { 1504 CHECK_F(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize)); 1505 zds->expected = ZSTD_blockHeaderSize; 1506 zds->stage = ZSTDds_decodeBlockHeader; 1507 } 1508 1509 /* control buffer memory usage */ 1510 DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)", 1511 (U32)(zds->fParams.windowSize >>10), 1512 (U32)(zds->maxWindowSize >> 10) ); 1513 zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN); 1514 if (zds->fParams.windowSize > zds->maxWindowSize) return ERROR(frameParameter_windowTooLarge); 1515 1516 /* Adapt buffer sizes to frame header instructions */ 1517 { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */); 1518 size_t const neededOutBuffSize = ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize); 1519 if ((zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize)) { 1520 size_t const bufferSize = neededInBuffSize + neededOutBuffSize; 1521 DEBUGLOG(4, "inBuff : from %u to %u", 1522 (U32)zds->inBuffSize, (U32)neededInBuffSize); 1523 DEBUGLOG(4, "outBuff : from %u to %u", 1524 (U32)zds->outBuffSize, (U32)neededOutBuffSize); 1525 if (zds->staticSize) { /* static DCtx */ 1526 DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize); 1527 assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */ 1528 if (bufferSize > zds->staticSize - sizeof(ZSTD_DCtx)) 1529 return ERROR(memory_allocation); 1530 } else { 1531 ZSTD_free(zds->inBuff, zds->customMem); 1532 zds->inBuffSize = 0; 1533 zds->outBuffSize = 0; 1534 zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem); 1535 if (zds->inBuff == NULL) return ERROR(memory_allocation); 1536 } 1537 zds->inBuffSize = neededInBuffSize; 1538 zds->outBuff = zds->inBuff + zds->inBuffSize; 1539 zds->outBuffSize = neededOutBuffSize; 1540 } } 1541 zds->streamStage = zdss_read; 1542 /* fall-through */ 1543 1544 case zdss_read: 1545 DEBUGLOG(5, "stage zdss_read"); 1546 { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds); 1547 DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize); 1548 if (neededInSize==0) { /* end of frame */ 1549 zds->streamStage = zdss_init; 1550 someMoreWork = 0; 1551 break; 1552 } 1553 if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */ 1554 int const isSkipFrame = ZSTD_isSkipFrame(zds); 1555 size_t const decodedSize = ZSTD_decompressContinue(zds, 1556 zds->outBuff + zds->outStart, (isSkipFrame ? 0 : zds->outBuffSize - zds->outStart), 1557 ip, neededInSize); 1558 if (ZSTD_isError(decodedSize)) return decodedSize; 1559 ip += neededInSize; 1560 if (!decodedSize && !isSkipFrame) break; /* this was just a header */ 1561 zds->outEnd = zds->outStart + decodedSize; 1562 zds->streamStage = zdss_flush; 1563 break; 1564 } } 1565 if (ip==iend) { someMoreWork = 0; break; } /* no more input */ 1566 zds->streamStage = zdss_load; 1567 /* fall-through */ 1568 1569 case zdss_load: 1570 { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds); 1571 size_t const toLoad = neededInSize - zds->inPos; 1572 int const isSkipFrame = ZSTD_isSkipFrame(zds); 1573 size_t loadedSize; 1574 if (isSkipFrame) { 1575 loadedSize = MIN(toLoad, (size_t)(iend-ip)); 1576 } else { 1577 if (toLoad > zds->inBuffSize - zds->inPos) return ERROR(corruption_detected); /* should never happen */ 1578 loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip); 1579 } 1580 ip += loadedSize; 1581 zds->inPos += loadedSize; 1582 if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */ 1583 1584 /* decode loaded input */ 1585 { size_t const decodedSize = ZSTD_decompressContinue(zds, 1586 zds->outBuff + zds->outStart, zds->outBuffSize - zds->outStart, 1587 zds->inBuff, neededInSize); 1588 if (ZSTD_isError(decodedSize)) return decodedSize; 1589 zds->inPos = 0; /* input is consumed */ 1590 if (!decodedSize && !isSkipFrame) { zds->streamStage = zdss_read; break; } /* this was just a header */ 1591 zds->outEnd = zds->outStart + decodedSize; 1592 } } 1593 zds->streamStage = zdss_flush; 1594 /* fall-through */ 1595 1596 case zdss_flush: 1597 { size_t const toFlushSize = zds->outEnd - zds->outStart; 1598 size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize); 1599 op += flushedSize; 1600 zds->outStart += flushedSize; 1601 if (flushedSize == toFlushSize) { /* flush completed */ 1602 zds->streamStage = zdss_read; 1603 if ( (zds->outBuffSize < zds->fParams.frameContentSize) 1604 && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) { 1605 DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)", 1606 (int)(zds->outBuffSize - zds->outStart), 1607 (U32)zds->fParams.blockSizeMax); 1608 zds->outStart = zds->outEnd = 0; 1609 } 1610 break; 1611 } } 1612 /* cannot complete flush */ 1613 someMoreWork = 0; 1614 break; 1615 1616 default: 1617 assert(0); /* impossible */ 1618 return ERROR(GENERIC); /* some compiler require default to do something */ 1619 } } 1620 1621 /* result */ 1622 input->pos = (size_t)(ip - (const char*)(input->src)); 1623 output->pos = (size_t)(op - (char*)(output->dst)); 1624 if ((ip==istart) && (op==ostart)) { /* no forward progress */ 1625 zds->noForwardProgress ++; 1626 if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) { 1627 if (op==oend) return ERROR(dstSize_tooSmall); 1628 if (ip==iend) return ERROR(srcSize_wrong); 1629 assert(0); 1630 } 1631 } else { 1632 zds->noForwardProgress = 0; 1633 } 1634 { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds); 1635 if (!nextSrcSizeHint) { /* frame fully decoded */ 1636 if (zds->outEnd == zds->outStart) { /* output fully flushed */ 1637 if (zds->hostageByte) { 1638 if (input->pos >= input->size) { 1639 /* can't release hostage (not present) */ 1640 zds->streamStage = zdss_read; 1641 return 1; 1642 } 1643 input->pos++; /* release hostage */ 1644 } /* zds->hostageByte */ 1645 return 0; 1646 } /* zds->outEnd == zds->outStart */ 1647 if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */ 1648 input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */ 1649 zds->hostageByte=1; 1650 } 1651 return 1; 1652 } /* nextSrcSizeHint==0 */ 1653 nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */ 1654 assert(zds->inPos <= nextSrcSizeHint); 1655 nextSrcSizeHint -= zds->inPos; /* part already loaded*/ 1656 return nextSrcSizeHint; 1657 } 1658 } 1659 1660 size_t ZSTD_decompressStream_simpleArgs ( 1661 ZSTD_DCtx* dctx, 1662 void* dst, size_t dstCapacity, size_t* dstPos, 1663 const void* src, size_t srcSize, size_t* srcPos) 1664 { 1665 ZSTD_outBuffer output = { dst, dstCapacity, *dstPos }; 1666 ZSTD_inBuffer input = { src, srcSize, *srcPos }; 1667 /* ZSTD_compress_generic() will check validity of dstPos and srcPos */ 1668 size_t const cErr = ZSTD_decompressStream(dctx, &output, &input); 1669 *dstPos = output.pos; 1670 *srcPos = input.pos; 1671 return cErr; 1672 } 1673