zstd_decompress.c 95 KB

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