zstd_decompress.c 100 KB

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