You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_decompress.c 97KB

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