2
0

zstd_decompress.c 92 KB

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