You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_decompress.c 77KB

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