zstd_decompress.c 89 KB

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