zstd_decompress.c 78 KB

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