decompress.c 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529
  1. /**
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of https://github.com/facebook/zstd.
  7. * An additional grant of patent rights can be found in the PATENTS file in the
  8. * same directory.
  9. *
  10. * This program is free software; you can redistribute it and/or modify it under
  11. * the terms of the GNU General Public License version 2 as published by the
  12. * Free Software Foundation. This program is dual-licensed; you may select
  13. * either version 2 of the GNU General Public License ("GPL") or BSD license
  14. * ("BSD").
  15. */
  16. /* ***************************************************************
  17. * Tuning parameters
  18. *****************************************************************/
  19. /*!
  20. * MAXWINDOWSIZE_DEFAULT :
  21. * maximum window size accepted by DStream, by default.
  22. * Frames requiring more memory will be rejected.
  23. */
  24. #ifndef ZSTD_MAXWINDOWSIZE_DEFAULT
  25. #define ZSTD_MAXWINDOWSIZE_DEFAULT ((1 << ZSTD_WINDOWLOG_MAX) + 1) /* defined within zstd.h */
  26. #endif
  27. /*-*******************************************************
  28. * Dependencies
  29. *********************************************************/
  30. #include "fse.h"
  31. #include "huf.h"
  32. #include "mem.h" /* low level memory routines */
  33. #include "zstd_internal.h"
  34. #include <linux/kernel.h>
  35. #include <linux/module.h>
  36. #include <linux/string.h> /* memcpy, memmove, memset */
  37. #define ZSTD_PREFETCH(ptr) __builtin_prefetch(ptr, 0, 0)
  38. /*-*************************************
  39. * Macros
  40. ***************************************/
  41. #define ZSTD_isError ERR_isError /* for inlining */
  42. #define FSE_isError ERR_isError
  43. #define HUF_isError ERR_isError
  44. /*_*******************************************************
  45. * Memory operations
  46. **********************************************************/
  47. static void ZSTD_copy4(void *dst, const void *src) { memcpy(dst, src, 4); }
  48. /*-*************************************************************
  49. * Context management
  50. ***************************************************************/
  51. typedef enum {
  52. ZSTDds_getFrameHeaderSize,
  53. ZSTDds_decodeFrameHeader,
  54. ZSTDds_decodeBlockHeader,
  55. ZSTDds_decompressBlock,
  56. ZSTDds_decompressLastBlock,
  57. ZSTDds_checkChecksum,
  58. ZSTDds_decodeSkippableHeader,
  59. ZSTDds_skipFrame
  60. } ZSTD_dStage;
  61. typedef struct {
  62. FSE_DTable LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  63. FSE_DTable OFTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  64. FSE_DTable MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  65. HUF_DTable hufTable[HUF_DTABLE_SIZE(HufLog)]; /* can accommodate HUF_decompress4X */
  66. U64 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32 / 2];
  67. U32 rep[ZSTD_REP_NUM];
  68. } ZSTD_entropyTables_t;
  69. struct ZSTD_DCtx_s {
  70. const FSE_DTable *LLTptr;
  71. const FSE_DTable *MLTptr;
  72. const FSE_DTable *OFTptr;
  73. const HUF_DTable *HUFptr;
  74. ZSTD_entropyTables_t entropy;
  75. const void *previousDstEnd; /* detect continuity */
  76. const void *base; /* start of curr segment */
  77. const void *vBase; /* virtual start of previous segment if it was just before curr one */
  78. const void *dictEnd; /* end of previous segment */
  79. size_t expected;
  80. ZSTD_frameParams fParams;
  81. blockType_e bType; /* used in ZSTD_decompressContinue(), to transfer blockType between header decoding and block decoding stages */
  82. ZSTD_dStage stage;
  83. U32 litEntropy;
  84. U32 fseEntropy;
  85. struct xxh64_state xxhState;
  86. size_t headerSize;
  87. U32 dictID;
  88. const BYTE *litPtr;
  89. ZSTD_customMem customMem;
  90. size_t litSize;
  91. size_t rleSize;
  92. BYTE litBuffer[ZSTD_BLOCKSIZE_ABSOLUTEMAX + WILDCOPY_OVERLENGTH];
  93. BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];
  94. }; /* typedef'd to ZSTD_DCtx within "zstd.h" */
  95. size_t ZSTD_DCtxWorkspaceBound(void) { return ZSTD_ALIGN(sizeof(ZSTD_stack)) + ZSTD_ALIGN(sizeof(ZSTD_DCtx)); }
  96. size_t ZSTD_decompressBegin(ZSTD_DCtx *dctx)
  97. {
  98. dctx->expected = ZSTD_frameHeaderSize_prefix;
  99. dctx->stage = ZSTDds_getFrameHeaderSize;
  100. dctx->previousDstEnd = NULL;
  101. dctx->base = NULL;
  102. dctx->vBase = NULL;
  103. dctx->dictEnd = NULL;
  104. dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
  105. dctx->litEntropy = dctx->fseEntropy = 0;
  106. dctx->dictID = 0;
  107. ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
  108. memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */
  109. dctx->LLTptr = dctx->entropy.LLTable;
  110. dctx->MLTptr = dctx->entropy.MLTable;
  111. dctx->OFTptr = dctx->entropy.OFTable;
  112. dctx->HUFptr = dctx->entropy.hufTable;
  113. return 0;
  114. }
  115. ZSTD_DCtx *ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
  116. {
  117. ZSTD_DCtx *dctx;
  118. if (!customMem.customAlloc || !customMem.customFree)
  119. return NULL;
  120. dctx = (ZSTD_DCtx *)ZSTD_malloc(sizeof(ZSTD_DCtx), customMem);
  121. if (!dctx)
  122. return NULL;
  123. memcpy(&dctx->customMem, &customMem, sizeof(customMem));
  124. ZSTD_decompressBegin(dctx);
  125. return dctx;
  126. }
  127. ZSTD_DCtx *ZSTD_initDCtx(void *workspace, size_t workspaceSize)
  128. {
  129. ZSTD_customMem const stackMem = ZSTD_initStack(workspace, workspaceSize);
  130. return ZSTD_createDCtx_advanced(stackMem);
  131. }
  132. size_t ZSTD_freeDCtx(ZSTD_DCtx *dctx)
  133. {
  134. if (dctx == NULL)
  135. return 0; /* support free on NULL */
  136. ZSTD_free(dctx, dctx->customMem);
  137. return 0; /* reserved as a potential error code in the future */
  138. }
  139. void ZSTD_copyDCtx(ZSTD_DCtx *dstDCtx, const ZSTD_DCtx *srcDCtx)
  140. {
  141. size_t const workSpaceSize = (ZSTD_BLOCKSIZE_ABSOLUTEMAX + WILDCOPY_OVERLENGTH) + ZSTD_frameHeaderSize_max;
  142. memcpy(dstDCtx, srcDCtx, sizeof(ZSTD_DCtx) - workSpaceSize); /* no need to copy workspace */
  143. }
  144. static void ZSTD_refDDict(ZSTD_DCtx *dstDCtx, const ZSTD_DDict *ddict);
  145. /*-*************************************************************
  146. * Decompression section
  147. ***************************************************************/
  148. /*! ZSTD_isFrame() :
  149. * Tells if the content of `buffer` starts with a valid Frame Identifier.
  150. * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
  151. * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
  152. * Note 3 : Skippable Frame Identifiers are considered valid. */
  153. unsigned ZSTD_isFrame(const void *buffer, size_t size)
  154. {
  155. if (size < 4)
  156. return 0;
  157. {
  158. U32 const magic = ZSTD_readLE32(buffer);
  159. if (magic == ZSTD_MAGICNUMBER)
  160. return 1;
  161. if ((magic & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START)
  162. return 1;
  163. }
  164. return 0;
  165. }
  166. /** ZSTD_frameHeaderSize() :
  167. * srcSize must be >= ZSTD_frameHeaderSize_prefix.
  168. * @return : size of the Frame Header */
  169. static size_t ZSTD_frameHeaderSize(const void *src, size_t srcSize)
  170. {
  171. if (srcSize < ZSTD_frameHeaderSize_prefix)
  172. return ERROR(srcSize_wrong);
  173. {
  174. BYTE const fhd = ((const BYTE *)src)[4];
  175. U32 const dictID = fhd & 3;
  176. U32 const singleSegment = (fhd >> 5) & 1;
  177. U32 const fcsId = fhd >> 6;
  178. return ZSTD_frameHeaderSize_prefix + !singleSegment + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId] + (singleSegment && !fcsId);
  179. }
  180. }
  181. /** ZSTD_getFrameParams() :
  182. * decode Frame Header, or require larger `srcSize`.
  183. * @return : 0, `fparamsPtr` is correctly filled,
  184. * >0, `srcSize` is too small, result is expected `srcSize`,
  185. * or an error code, which can be tested using ZSTD_isError() */
  186. size_t ZSTD_getFrameParams(ZSTD_frameParams *fparamsPtr, const void *src, size_t srcSize)
  187. {
  188. const BYTE *ip = (const BYTE *)src;
  189. if (srcSize < ZSTD_frameHeaderSize_prefix)
  190. return ZSTD_frameHeaderSize_prefix;
  191. if (ZSTD_readLE32(src) != ZSTD_MAGICNUMBER) {
  192. if ((ZSTD_readLE32(src) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  193. if (srcSize < ZSTD_skippableHeaderSize)
  194. return ZSTD_skippableHeaderSize; /* magic number + skippable frame length */
  195. memset(fparamsPtr, 0, sizeof(*fparamsPtr));
  196. fparamsPtr->frameContentSize = ZSTD_readLE32((const char *)src + 4);
  197. fparamsPtr->windowSize = 0; /* windowSize==0 means a frame is skippable */
  198. return 0;
  199. }
  200. return ERROR(prefix_unknown);
  201. }
  202. /* ensure there is enough `srcSize` to fully read/decode frame header */
  203. {
  204. size_t const fhsize = ZSTD_frameHeaderSize(src, srcSize);
  205. if (srcSize < fhsize)
  206. return fhsize;
  207. }
  208. {
  209. BYTE const fhdByte = ip[4];
  210. size_t pos = 5;
  211. U32 const dictIDSizeCode = fhdByte & 3;
  212. U32 const checksumFlag = (fhdByte >> 2) & 1;
  213. U32 const singleSegment = (fhdByte >> 5) & 1;
  214. U32 const fcsID = fhdByte >> 6;
  215. U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX;
  216. U32 windowSize = 0;
  217. U32 dictID = 0;
  218. U64 frameContentSize = 0;
  219. if ((fhdByte & 0x08) != 0)
  220. return ERROR(frameParameter_unsupported); /* reserved bits, which must be zero */
  221. if (!singleSegment) {
  222. BYTE const wlByte = ip[pos++];
  223. U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
  224. if (windowLog > ZSTD_WINDOWLOG_MAX)
  225. return ERROR(frameParameter_windowTooLarge); /* avoids issue with 1 << windowLog */
  226. windowSize = (1U << windowLog);
  227. windowSize += (windowSize >> 3) * (wlByte & 7);
  228. }
  229. switch (dictIDSizeCode) {
  230. default: /* impossible */
  231. case 0: break;
  232. case 1:
  233. dictID = ip[pos];
  234. pos++;
  235. break;
  236. case 2:
  237. dictID = ZSTD_readLE16(ip + pos);
  238. pos += 2;
  239. break;
  240. case 3:
  241. dictID = ZSTD_readLE32(ip + pos);
  242. pos += 4;
  243. break;
  244. }
  245. switch (fcsID) {
  246. default: /* impossible */
  247. case 0:
  248. if (singleSegment)
  249. frameContentSize = ip[pos];
  250. break;
  251. case 1: frameContentSize = ZSTD_readLE16(ip + pos) + 256; break;
  252. case 2: frameContentSize = ZSTD_readLE32(ip + pos); break;
  253. case 3: frameContentSize = ZSTD_readLE64(ip + pos); break;
  254. }
  255. if (!windowSize)
  256. windowSize = (U32)frameContentSize;
  257. if (windowSize > windowSizeMax)
  258. return ERROR(frameParameter_windowTooLarge);
  259. fparamsPtr->frameContentSize = frameContentSize;
  260. fparamsPtr->windowSize = windowSize;
  261. fparamsPtr->dictID = dictID;
  262. fparamsPtr->checksumFlag = checksumFlag;
  263. }
  264. return 0;
  265. }
  266. /** ZSTD_getFrameContentSize() :
  267. * compatible with legacy mode
  268. * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
  269. * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
  270. * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
  271. unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
  272. {
  273. {
  274. ZSTD_frameParams fParams;
  275. if (ZSTD_getFrameParams(&fParams, src, srcSize) != 0)
  276. return ZSTD_CONTENTSIZE_ERROR;
  277. if (fParams.windowSize == 0) {
  278. /* Either skippable or empty frame, size == 0 either way */
  279. return 0;
  280. } else if (fParams.frameContentSize != 0) {
  281. return fParams.frameContentSize;
  282. } else {
  283. return ZSTD_CONTENTSIZE_UNKNOWN;
  284. }
  285. }
  286. }
  287. /** ZSTD_findDecompressedSize() :
  288. * compatible with legacy mode
  289. * `srcSize` must be the exact length of some number of ZSTD compressed and/or
  290. * skippable frames
  291. * @return : decompressed size of the frames contained */
  292. unsigned long long ZSTD_findDecompressedSize(const void *src, size_t srcSize)
  293. {
  294. {
  295. unsigned long long totalDstSize = 0;
  296. while (srcSize >= ZSTD_frameHeaderSize_prefix) {
  297. const U32 magicNumber = ZSTD_readLE32(src);
  298. if ((magicNumber & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  299. size_t skippableSize;
  300. if (srcSize < ZSTD_skippableHeaderSize)
  301. return ERROR(srcSize_wrong);
  302. skippableSize = ZSTD_readLE32((const BYTE *)src + 4) + ZSTD_skippableHeaderSize;
  303. if (srcSize < skippableSize) {
  304. return ZSTD_CONTENTSIZE_ERROR;
  305. }
  306. src = (const BYTE *)src + skippableSize;
  307. srcSize -= skippableSize;
  308. continue;
  309. }
  310. {
  311. unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
  312. if (ret >= ZSTD_CONTENTSIZE_ERROR)
  313. return ret;
  314. /* check for overflow */
  315. if (totalDstSize + ret < totalDstSize)
  316. return ZSTD_CONTENTSIZE_ERROR;
  317. totalDstSize += ret;
  318. }
  319. {
  320. size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
  321. if (ZSTD_isError(frameSrcSize)) {
  322. return ZSTD_CONTENTSIZE_ERROR;
  323. }
  324. src = (const BYTE *)src + frameSrcSize;
  325. srcSize -= frameSrcSize;
  326. }
  327. }
  328. if (srcSize) {
  329. return ZSTD_CONTENTSIZE_ERROR;
  330. }
  331. return totalDstSize;
  332. }
  333. }
  334. /** ZSTD_decodeFrameHeader() :
  335. * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
  336. * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
  337. static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx *dctx, const void *src, size_t headerSize)
  338. {
  339. size_t const result = ZSTD_getFrameParams(&(dctx->fParams), src, headerSize);
  340. if (ZSTD_isError(result))
  341. return result; /* invalid header */
  342. if (result > 0)
  343. return ERROR(srcSize_wrong); /* headerSize too small */
  344. if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID))
  345. return ERROR(dictionary_wrong);
  346. if (dctx->fParams.checksumFlag)
  347. xxh64_reset(&dctx->xxhState, 0);
  348. return 0;
  349. }
  350. typedef struct {
  351. blockType_e blockType;
  352. U32 lastBlock;
  353. U32 origSize;
  354. } blockProperties_t;
  355. /*! ZSTD_getcBlockSize() :
  356. * Provides the size of compressed block from block header `src` */
  357. size_t ZSTD_getcBlockSize(const void *src, size_t srcSize, blockProperties_t *bpPtr)
  358. {
  359. if (srcSize < ZSTD_blockHeaderSize)
  360. return ERROR(srcSize_wrong);
  361. {
  362. U32 const cBlockHeader = ZSTD_readLE24(src);
  363. U32 const cSize = cBlockHeader >> 3;
  364. bpPtr->lastBlock = cBlockHeader & 1;
  365. bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
  366. bpPtr->origSize = cSize; /* only useful for RLE */
  367. if (bpPtr->blockType == bt_rle)
  368. return 1;
  369. if (bpPtr->blockType == bt_reserved)
  370. return ERROR(corruption_detected);
  371. return cSize;
  372. }
  373. }
  374. static size_t ZSTD_copyRawBlock(void *dst, size_t dstCapacity, const void *src, size_t srcSize)
  375. {
  376. if (srcSize > dstCapacity)
  377. return ERROR(dstSize_tooSmall);
  378. memcpy(dst, src, srcSize);
  379. return srcSize;
  380. }
  381. static size_t ZSTD_setRleBlock(void *dst, size_t dstCapacity, const void *src, size_t srcSize, size_t regenSize)
  382. {
  383. if (srcSize != 1)
  384. return ERROR(srcSize_wrong);
  385. if (regenSize > dstCapacity)
  386. return ERROR(dstSize_tooSmall);
  387. memset(dst, *(const BYTE *)src, regenSize);
  388. return regenSize;
  389. }
  390. /*! ZSTD_decodeLiteralsBlock() :
  391. @return : nb of bytes read from src (< srcSize ) */
  392. size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx *dctx, const void *src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
  393. {
  394. if (srcSize < MIN_CBLOCK_SIZE)
  395. return ERROR(corruption_detected);
  396. {
  397. const BYTE *const istart = (const BYTE *)src;
  398. symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);
  399. switch (litEncType) {
  400. case set_repeat:
  401. if (dctx->litEntropy == 0)
  402. return ERROR(dictionary_corrupted);
  403. /* fall-through */
  404. case set_compressed:
  405. if (srcSize < 5)
  406. return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3 */
  407. {
  408. size_t lhSize, litSize, litCSize;
  409. U32 singleStream = 0;
  410. U32 const lhlCode = (istart[0] >> 2) & 3;
  411. U32 const lhc = ZSTD_readLE32(istart);
  412. switch (lhlCode) {
  413. case 0:
  414. case 1:
  415. default: /* note : default is impossible, since lhlCode into [0..3] */
  416. /* 2 - 2 - 10 - 10 */
  417. singleStream = !lhlCode;
  418. lhSize = 3;
  419. litSize = (lhc >> 4) & 0x3FF;
  420. litCSize = (lhc >> 14) & 0x3FF;
  421. break;
  422. case 2:
  423. /* 2 - 2 - 14 - 14 */
  424. lhSize = 4;
  425. litSize = (lhc >> 4) & 0x3FFF;
  426. litCSize = lhc >> 18;
  427. break;
  428. case 3:
  429. /* 2 - 2 - 18 - 18 */
  430. lhSize = 5;
  431. litSize = (lhc >> 4) & 0x3FFFF;
  432. litCSize = (lhc >> 22) + (istart[4] << 10);
  433. break;
  434. }
  435. if (litSize > ZSTD_BLOCKSIZE_ABSOLUTEMAX)
  436. return ERROR(corruption_detected);
  437. if (litCSize + lhSize > srcSize)
  438. return ERROR(corruption_detected);
  439. if (HUF_isError(
  440. (litEncType == set_repeat)
  441. ? (singleStream ? HUF_decompress1X_usingDTable(dctx->litBuffer, litSize, istart + lhSize, litCSize, dctx->HUFptr)
  442. : HUF_decompress4X_usingDTable(dctx->litBuffer, litSize, istart + lhSize, litCSize, dctx->HUFptr))
  443. : (singleStream
  444. ? HUF_decompress1X2_DCtx_wksp(dctx->entropy.hufTable, dctx->litBuffer, litSize, istart + lhSize, litCSize,
  445. dctx->entropy.workspace, sizeof(dctx->entropy.workspace))
  446. : HUF_decompress4X_hufOnly_wksp(dctx->entropy.hufTable, dctx->litBuffer, litSize, istart + lhSize, litCSize,
  447. dctx->entropy.workspace, sizeof(dctx->entropy.workspace)))))
  448. return ERROR(corruption_detected);
  449. dctx->litPtr = dctx->litBuffer;
  450. dctx->litSize = litSize;
  451. dctx->litEntropy = 1;
  452. if (litEncType == set_compressed)
  453. dctx->HUFptr = dctx->entropy.hufTable;
  454. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  455. return litCSize + lhSize;
  456. }
  457. case set_basic: {
  458. size_t litSize, lhSize;
  459. U32 const lhlCode = ((istart[0]) >> 2) & 3;
  460. switch (lhlCode) {
  461. case 0:
  462. case 2:
  463. default: /* note : default is impossible, since lhlCode into [0..3] */
  464. lhSize = 1;
  465. litSize = istart[0] >> 3;
  466. break;
  467. case 1:
  468. lhSize = 2;
  469. litSize = ZSTD_readLE16(istart) >> 4;
  470. break;
  471. case 3:
  472. lhSize = 3;
  473. litSize = ZSTD_readLE24(istart) >> 4;
  474. break;
  475. }
  476. if (lhSize + litSize + WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
  477. if (litSize + lhSize > srcSize)
  478. return ERROR(corruption_detected);
  479. memcpy(dctx->litBuffer, istart + lhSize, litSize);
  480. dctx->litPtr = dctx->litBuffer;
  481. dctx->litSize = litSize;
  482. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  483. return lhSize + litSize;
  484. }
  485. /* direct reference into compressed stream */
  486. dctx->litPtr = istart + lhSize;
  487. dctx->litSize = litSize;
  488. return lhSize + litSize;
  489. }
  490. case set_rle: {
  491. U32 const lhlCode = ((istart[0]) >> 2) & 3;
  492. size_t litSize, lhSize;
  493. switch (lhlCode) {
  494. case 0:
  495. case 2:
  496. default: /* note : default is impossible, since lhlCode into [0..3] */
  497. lhSize = 1;
  498. litSize = istart[0] >> 3;
  499. break;
  500. case 1:
  501. lhSize = 2;
  502. litSize = ZSTD_readLE16(istart) >> 4;
  503. break;
  504. case 3:
  505. lhSize = 3;
  506. litSize = ZSTD_readLE24(istart) >> 4;
  507. if (srcSize < 4)
  508. return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4 */
  509. break;
  510. }
  511. if (litSize > ZSTD_BLOCKSIZE_ABSOLUTEMAX)
  512. return ERROR(corruption_detected);
  513. memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
  514. dctx->litPtr = dctx->litBuffer;
  515. dctx->litSize = litSize;
  516. return lhSize + 1;
  517. }
  518. default:
  519. return ERROR(corruption_detected); /* impossible */
  520. }
  521. }
  522. }
  523. typedef union {
  524. FSE_decode_t realData;
  525. U32 alignedBy4;
  526. } FSE_decode_t4;
  527. static const FSE_decode_t4 LL_defaultDTable[(1 << LL_DEFAULTNORMLOG) + 1] = {
  528. {{LL_DEFAULTNORMLOG, 1, 1}}, /* header : tableLog, fastMode, fastMode */
  529. {{0, 0, 4}}, /* 0 : base, symbol, bits */
  530. {{16, 0, 4}},
  531. {{32, 1, 5}},
  532. {{0, 3, 5}},
  533. {{0, 4, 5}},
  534. {{0, 6, 5}},
  535. {{0, 7, 5}},
  536. {{0, 9, 5}},
  537. {{0, 10, 5}},
  538. {{0, 12, 5}},
  539. {{0, 14, 6}},
  540. {{0, 16, 5}},
  541. {{0, 18, 5}},
  542. {{0, 19, 5}},
  543. {{0, 21, 5}},
  544. {{0, 22, 5}},
  545. {{0, 24, 5}},
  546. {{32, 25, 5}},
  547. {{0, 26, 5}},
  548. {{0, 27, 6}},
  549. {{0, 29, 6}},
  550. {{0, 31, 6}},
  551. {{32, 0, 4}},
  552. {{0, 1, 4}},
  553. {{0, 2, 5}},
  554. {{32, 4, 5}},
  555. {{0, 5, 5}},
  556. {{32, 7, 5}},
  557. {{0, 8, 5}},
  558. {{32, 10, 5}},
  559. {{0, 11, 5}},
  560. {{0, 13, 6}},
  561. {{32, 16, 5}},
  562. {{0, 17, 5}},
  563. {{32, 19, 5}},
  564. {{0, 20, 5}},
  565. {{32, 22, 5}},
  566. {{0, 23, 5}},
  567. {{0, 25, 4}},
  568. {{16, 25, 4}},
  569. {{32, 26, 5}},
  570. {{0, 28, 6}},
  571. {{0, 30, 6}},
  572. {{48, 0, 4}},
  573. {{16, 1, 4}},
  574. {{32, 2, 5}},
  575. {{32, 3, 5}},
  576. {{32, 5, 5}},
  577. {{32, 6, 5}},
  578. {{32, 8, 5}},
  579. {{32, 9, 5}},
  580. {{32, 11, 5}},
  581. {{32, 12, 5}},
  582. {{0, 15, 6}},
  583. {{32, 17, 5}},
  584. {{32, 18, 5}},
  585. {{32, 20, 5}},
  586. {{32, 21, 5}},
  587. {{32, 23, 5}},
  588. {{32, 24, 5}},
  589. {{0, 35, 6}},
  590. {{0, 34, 6}},
  591. {{0, 33, 6}},
  592. {{0, 32, 6}},
  593. }; /* LL_defaultDTable */
  594. static const FSE_decode_t4 ML_defaultDTable[(1 << ML_DEFAULTNORMLOG) + 1] = {
  595. {{ML_DEFAULTNORMLOG, 1, 1}}, /* header : tableLog, fastMode, fastMode */
  596. {{0, 0, 6}}, /* 0 : base, symbol, bits */
  597. {{0, 1, 4}},
  598. {{32, 2, 5}},
  599. {{0, 3, 5}},
  600. {{0, 5, 5}},
  601. {{0, 6, 5}},
  602. {{0, 8, 5}},
  603. {{0, 10, 6}},
  604. {{0, 13, 6}},
  605. {{0, 16, 6}},
  606. {{0, 19, 6}},
  607. {{0, 22, 6}},
  608. {{0, 25, 6}},
  609. {{0, 28, 6}},
  610. {{0, 31, 6}},
  611. {{0, 33, 6}},
  612. {{0, 35, 6}},
  613. {{0, 37, 6}},
  614. {{0, 39, 6}},
  615. {{0, 41, 6}},
  616. {{0, 43, 6}},
  617. {{0, 45, 6}},
  618. {{16, 1, 4}},
  619. {{0, 2, 4}},
  620. {{32, 3, 5}},
  621. {{0, 4, 5}},
  622. {{32, 6, 5}},
  623. {{0, 7, 5}},
  624. {{0, 9, 6}},
  625. {{0, 12, 6}},
  626. {{0, 15, 6}},
  627. {{0, 18, 6}},
  628. {{0, 21, 6}},
  629. {{0, 24, 6}},
  630. {{0, 27, 6}},
  631. {{0, 30, 6}},
  632. {{0, 32, 6}},
  633. {{0, 34, 6}},
  634. {{0, 36, 6}},
  635. {{0, 38, 6}},
  636. {{0, 40, 6}},
  637. {{0, 42, 6}},
  638. {{0, 44, 6}},
  639. {{32, 1, 4}},
  640. {{48, 1, 4}},
  641. {{16, 2, 4}},
  642. {{32, 4, 5}},
  643. {{32, 5, 5}},
  644. {{32, 7, 5}},
  645. {{32, 8, 5}},
  646. {{0, 11, 6}},
  647. {{0, 14, 6}},
  648. {{0, 17, 6}},
  649. {{0, 20, 6}},
  650. {{0, 23, 6}},
  651. {{0, 26, 6}},
  652. {{0, 29, 6}},
  653. {{0, 52, 6}},
  654. {{0, 51, 6}},
  655. {{0, 50, 6}},
  656. {{0, 49, 6}},
  657. {{0, 48, 6}},
  658. {{0, 47, 6}},
  659. {{0, 46, 6}},
  660. }; /* ML_defaultDTable */
  661. static const FSE_decode_t4 OF_defaultDTable[(1 << OF_DEFAULTNORMLOG) + 1] = {
  662. {{OF_DEFAULTNORMLOG, 1, 1}}, /* header : tableLog, fastMode, fastMode */
  663. {{0, 0, 5}}, /* 0 : base, symbol, bits */
  664. {{0, 6, 4}},
  665. {{0, 9, 5}},
  666. {{0, 15, 5}},
  667. {{0, 21, 5}},
  668. {{0, 3, 5}},
  669. {{0, 7, 4}},
  670. {{0, 12, 5}},
  671. {{0, 18, 5}},
  672. {{0, 23, 5}},
  673. {{0, 5, 5}},
  674. {{0, 8, 4}},
  675. {{0, 14, 5}},
  676. {{0, 20, 5}},
  677. {{0, 2, 5}},
  678. {{16, 7, 4}},
  679. {{0, 11, 5}},
  680. {{0, 17, 5}},
  681. {{0, 22, 5}},
  682. {{0, 4, 5}},
  683. {{16, 8, 4}},
  684. {{0, 13, 5}},
  685. {{0, 19, 5}},
  686. {{0, 1, 5}},
  687. {{16, 6, 4}},
  688. {{0, 10, 5}},
  689. {{0, 16, 5}},
  690. {{0, 28, 5}},
  691. {{0, 27, 5}},
  692. {{0, 26, 5}},
  693. {{0, 25, 5}},
  694. {{0, 24, 5}},
  695. }; /* OF_defaultDTable */
  696. /*! ZSTD_buildSeqTable() :
  697. @return : nb bytes read from src,
  698. or an error code if it fails, testable with ZSTD_isError()
  699. */
  700. static size_t ZSTD_buildSeqTable(FSE_DTable *DTableSpace, const FSE_DTable **DTablePtr, symbolEncodingType_e type, U32 max, U32 maxLog, const void *src,
  701. size_t srcSize, const FSE_decode_t4 *defaultTable, U32 flagRepeatTable, void *workspace, size_t workspaceSize)
  702. {
  703. const void *const tmpPtr = defaultTable; /* bypass strict aliasing */
  704. switch (type) {
  705. case set_rle:
  706. if (!srcSize)
  707. return ERROR(srcSize_wrong);
  708. if ((*(const BYTE *)src) > max)
  709. return ERROR(corruption_detected);
  710. FSE_buildDTable_rle(DTableSpace, *(const BYTE *)src);
  711. *DTablePtr = DTableSpace;
  712. return 1;
  713. case set_basic: *DTablePtr = (const FSE_DTable *)tmpPtr; return 0;
  714. case set_repeat:
  715. if (!flagRepeatTable)
  716. return ERROR(corruption_detected);
  717. return 0;
  718. default: /* impossible */
  719. case set_compressed: {
  720. U32 tableLog;
  721. S16 *norm = (S16 *)workspace;
  722. size_t const spaceUsed32 = ALIGN(sizeof(S16) * (MaxSeq + 1), sizeof(U32)) >> 2;
  723. if ((spaceUsed32 << 2) > workspaceSize)
  724. return ERROR(GENERIC);
  725. workspace = (U32 *)workspace + spaceUsed32;
  726. workspaceSize -= (spaceUsed32 << 2);
  727. {
  728. size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
  729. if (FSE_isError(headerSize))
  730. return ERROR(corruption_detected);
  731. if (tableLog > maxLog)
  732. return ERROR(corruption_detected);
  733. FSE_buildDTable_wksp(DTableSpace, norm, max, tableLog, workspace, workspaceSize);
  734. *DTablePtr = DTableSpace;
  735. return headerSize;
  736. }
  737. }
  738. }
  739. }
  740. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx *dctx, int *nbSeqPtr, const void *src, size_t srcSize)
  741. {
  742. const BYTE *const istart = (const BYTE *const)src;
  743. const BYTE *const iend = istart + srcSize;
  744. const BYTE *ip = istart;
  745. /* check */
  746. if (srcSize < MIN_SEQUENCES_SIZE)
  747. return ERROR(srcSize_wrong);
  748. /* SeqHead */
  749. {
  750. int nbSeq = *ip++;
  751. if (!nbSeq) {
  752. *nbSeqPtr = 0;
  753. return 1;
  754. }
  755. if (nbSeq > 0x7F) {
  756. if (nbSeq == 0xFF) {
  757. if (ip + 2 > iend)
  758. return ERROR(srcSize_wrong);
  759. nbSeq = ZSTD_readLE16(ip) + LONGNBSEQ, ip += 2;
  760. } else {
  761. if (ip >= iend)
  762. return ERROR(srcSize_wrong);
  763. nbSeq = ((nbSeq - 0x80) << 8) + *ip++;
  764. }
  765. }
  766. *nbSeqPtr = nbSeq;
  767. }
  768. /* FSE table descriptors */
  769. if (ip + 4 > iend)
  770. return ERROR(srcSize_wrong); /* minimum possible size */
  771. {
  772. symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
  773. symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
  774. symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
  775. ip++;
  776. /* Build DTables */
  777. {
  778. size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr, LLtype, MaxLL, LLFSELog, ip, iend - ip,
  779. LL_defaultDTable, dctx->fseEntropy, dctx->entropy.workspace, sizeof(dctx->entropy.workspace));
  780. if (ZSTD_isError(llhSize))
  781. return ERROR(corruption_detected);
  782. ip += llhSize;
  783. }
  784. {
  785. size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr, OFtype, MaxOff, OffFSELog, ip, iend - ip,
  786. OF_defaultDTable, dctx->fseEntropy, dctx->entropy.workspace, sizeof(dctx->entropy.workspace));
  787. if (ZSTD_isError(ofhSize))
  788. return ERROR(corruption_detected);
  789. ip += ofhSize;
  790. }
  791. {
  792. size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr, MLtype, MaxML, MLFSELog, ip, iend - ip,
  793. ML_defaultDTable, dctx->fseEntropy, dctx->entropy.workspace, sizeof(dctx->entropy.workspace));
  794. if (ZSTD_isError(mlhSize))
  795. return ERROR(corruption_detected);
  796. ip += mlhSize;
  797. }
  798. }
  799. return ip - istart;
  800. }
  801. typedef struct {
  802. size_t litLength;
  803. size_t matchLength;
  804. size_t offset;
  805. const BYTE *match;
  806. } seq_t;
  807. typedef struct {
  808. BIT_DStream_t DStream;
  809. FSE_DState_t stateLL;
  810. FSE_DState_t stateOffb;
  811. FSE_DState_t stateML;
  812. size_t prevOffset[ZSTD_REP_NUM];
  813. const BYTE *base;
  814. size_t pos;
  815. uPtrDiff gotoDict;
  816. } seqState_t;
  817. FORCE_NOINLINE
  818. size_t ZSTD_execSequenceLast7(BYTE *op, BYTE *const oend, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const base,
  819. const BYTE *const vBase, const BYTE *const dictEnd)
  820. {
  821. BYTE *const oLitEnd = op + sequence.litLength;
  822. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  823. BYTE *const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  824. BYTE *const oend_w = oend - WILDCOPY_OVERLENGTH;
  825. const BYTE *const iLitEnd = *litPtr + sequence.litLength;
  826. const BYTE *match = oLitEnd - sequence.offset;
  827. /* check */
  828. if (oMatchEnd > oend)
  829. return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  830. if (iLitEnd > litLimit)
  831. return ERROR(corruption_detected); /* over-read beyond lit buffer */
  832. if (oLitEnd <= oend_w)
  833. return ERROR(GENERIC); /* Precondition */
  834. /* copy literals */
  835. if (op < oend_w) {
  836. ZSTD_wildcopy(op, *litPtr, oend_w - op);
  837. *litPtr += oend_w - op;
  838. op = oend_w;
  839. }
  840. while (op < oLitEnd)
  841. *op++ = *(*litPtr)++;
  842. /* copy Match */
  843. if (sequence.offset > (size_t)(oLitEnd - base)) {
  844. /* offset beyond prefix */
  845. if (sequence.offset > (size_t)(oLitEnd - vBase))
  846. return ERROR(corruption_detected);
  847. match = dictEnd - (base - match);
  848. if (match + sequence.matchLength <= dictEnd) {
  849. memmove(oLitEnd, match, sequence.matchLength);
  850. return sequenceLength;
  851. }
  852. /* span extDict & currPrefixSegment */
  853. {
  854. size_t const length1 = dictEnd - match;
  855. memmove(oLitEnd, match, length1);
  856. op = oLitEnd + length1;
  857. sequence.matchLength -= length1;
  858. match = base;
  859. }
  860. }
  861. while (op < oMatchEnd)
  862. *op++ = *match++;
  863. return sequenceLength;
  864. }
  865. static seq_t ZSTD_decodeSequence(seqState_t *seqState)
  866. {
  867. seq_t seq;
  868. U32 const llCode = FSE_peekSymbol(&seqState->stateLL);
  869. U32 const mlCode = FSE_peekSymbol(&seqState->stateML);
  870. U32 const ofCode = FSE_peekSymbol(&seqState->stateOffb); /* <= maxOff, by table construction */
  871. U32 const llBits = LL_bits[llCode];
  872. U32 const mlBits = ML_bits[mlCode];
  873. U32 const ofBits = ofCode;
  874. U32 const totalBits = llBits + mlBits + ofBits;
  875. static const U32 LL_base[MaxLL + 1] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18,
  876. 20, 22, 24, 28, 32, 40, 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, 0x10000};
  877. static const U32 ML_base[MaxML + 1] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  878. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41,
  879. 43, 47, 51, 59, 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803, 0x1003, 0x2003, 0x4003, 0x8003, 0x10003};
  880. static const U32 OF_base[MaxOff + 1] = {0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D, 0xFD, 0x1FD,
  881. 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD, 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD,
  882. 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD, 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD};
  883. /* sequence */
  884. {
  885. size_t offset;
  886. if (!ofCode)
  887. offset = 0;
  888. else {
  889. offset = OF_base[ofCode] + BIT_readBitsFast(&seqState->DStream, ofBits); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  890. if (ZSTD_32bits())
  891. BIT_reloadDStream(&seqState->DStream);
  892. }
  893. if (ofCode <= 1) {
  894. offset += (llCode == 0);
  895. if (offset) {
  896. size_t temp = (offset == 3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  897. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  898. if (offset != 1)
  899. seqState->prevOffset[2] = seqState->prevOffset[1];
  900. seqState->prevOffset[1] = seqState->prevOffset[0];
  901. seqState->prevOffset[0] = offset = temp;
  902. } else {
  903. offset = seqState->prevOffset[0];
  904. }
  905. } else {
  906. seqState->prevOffset[2] = seqState->prevOffset[1];
  907. seqState->prevOffset[1] = seqState->prevOffset[0];
  908. seqState->prevOffset[0] = offset;
  909. }
  910. seq.offset = offset;
  911. }
  912. seq.matchLength = ML_base[mlCode] + ((mlCode > 31) ? BIT_readBitsFast(&seqState->DStream, mlBits) : 0); /* <= 16 bits */
  913. if (ZSTD_32bits() && (mlBits + llBits > 24))
  914. BIT_reloadDStream(&seqState->DStream);
  915. seq.litLength = LL_base[llCode] + ((llCode > 15) ? BIT_readBitsFast(&seqState->DStream, llBits) : 0); /* <= 16 bits */
  916. if (ZSTD_32bits() || (totalBits > 64 - 7 - (LLFSELog + MLFSELog + OffFSELog)))
  917. BIT_reloadDStream(&seqState->DStream);
  918. /* ANS state update */
  919. FSE_updateState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  920. FSE_updateState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  921. if (ZSTD_32bits())
  922. BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  923. FSE_updateState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  924. seq.match = NULL;
  925. return seq;
  926. }
  927. FORCE_INLINE
  928. size_t ZSTD_execSequence(BYTE *op, BYTE *const oend, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const base,
  929. const BYTE *const vBase, const BYTE *const dictEnd)
  930. {
  931. BYTE *const oLitEnd = op + sequence.litLength;
  932. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  933. BYTE *const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  934. BYTE *const oend_w = oend - WILDCOPY_OVERLENGTH;
  935. const BYTE *const iLitEnd = *litPtr + sequence.litLength;
  936. const BYTE *match = oLitEnd - sequence.offset;
  937. /* check */
  938. if (oMatchEnd > oend)
  939. return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  940. if (iLitEnd > litLimit)
  941. return ERROR(corruption_detected); /* over-read beyond lit buffer */
  942. if (oLitEnd > oend_w)
  943. return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, base, vBase, dictEnd);
  944. /* copy Literals */
  945. ZSTD_copy8(op, *litPtr);
  946. if (sequence.litLength > 8)
  947. ZSTD_wildcopy(op + 8, (*litPtr) + 8,
  948. sequence.litLength - 8); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
  949. op = oLitEnd;
  950. *litPtr = iLitEnd; /* update for next sequence */
  951. /* copy Match */
  952. if (sequence.offset > (size_t)(oLitEnd - base)) {
  953. /* offset beyond prefix */
  954. if (sequence.offset > (size_t)(oLitEnd - vBase))
  955. return ERROR(corruption_detected);
  956. match = dictEnd + (match - base);
  957. if (match + sequence.matchLength <= dictEnd) {
  958. memmove(oLitEnd, match, sequence.matchLength);
  959. return sequenceLength;
  960. }
  961. /* span extDict & currPrefixSegment */
  962. {
  963. size_t const length1 = dictEnd - match;
  964. memmove(oLitEnd, match, length1);
  965. op = oLitEnd + length1;
  966. sequence.matchLength -= length1;
  967. match = base;
  968. if (op > oend_w || sequence.matchLength < MINMATCH) {
  969. U32 i;
  970. for (i = 0; i < sequence.matchLength; ++i)
  971. op[i] = match[i];
  972. return sequenceLength;
  973. }
  974. }
  975. }
  976. /* Requirement: op <= oend_w && sequence.matchLength >= MINMATCH */
  977. /* match within prefix */
  978. if (sequence.offset < 8) {
  979. /* close range match, overlap */
  980. static const U32 dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */
  981. static const int dec64table[] = {8, 8, 8, 7, 8, 9, 10, 11}; /* subtracted */
  982. int const sub2 = dec64table[sequence.offset];
  983. op[0] = match[0];
  984. op[1] = match[1];
  985. op[2] = match[2];
  986. op[3] = match[3];
  987. match += dec32table[sequence.offset];
  988. ZSTD_copy4(op + 4, match);
  989. match -= sub2;
  990. } else {
  991. ZSTD_copy8(op, match);
  992. }
  993. op += 8;
  994. match += 8;
  995. if (oMatchEnd > oend - (16 - MINMATCH)) {
  996. if (op < oend_w) {
  997. ZSTD_wildcopy(op, match, oend_w - op);
  998. match += oend_w - op;
  999. op = oend_w;
  1000. }
  1001. while (op < oMatchEnd)
  1002. *op++ = *match++;
  1003. } else {
  1004. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength - 8); /* works even if matchLength < 8 */
  1005. }
  1006. return sequenceLength;
  1007. }
  1008. static size_t ZSTD_decompressSequences(ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize)
  1009. {
  1010. const BYTE *ip = (const BYTE *)seqStart;
  1011. const BYTE *const iend = ip + seqSize;
  1012. BYTE *const ostart = (BYTE * const)dst;
  1013. BYTE *const oend = ostart + maxDstSize;
  1014. BYTE *op = ostart;
  1015. const BYTE *litPtr = dctx->litPtr;
  1016. const BYTE *const litEnd = litPtr + dctx->litSize;
  1017. const BYTE *const base = (const BYTE *)(dctx->base);
  1018. const BYTE *const vBase = (const BYTE *)(dctx->vBase);
  1019. const BYTE *const dictEnd = (const BYTE *)(dctx->dictEnd);
  1020. int nbSeq;
  1021. /* Build Decoding Tables */
  1022. {
  1023. size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, seqSize);
  1024. if (ZSTD_isError(seqHSize))
  1025. return seqHSize;
  1026. ip += seqHSize;
  1027. }
  1028. /* Regen sequences */
  1029. if (nbSeq) {
  1030. seqState_t seqState;
  1031. dctx->fseEntropy = 1;
  1032. {
  1033. U32 i;
  1034. for (i = 0; i < ZSTD_REP_NUM; i++)
  1035. seqState.prevOffset[i] = dctx->entropy.rep[i];
  1036. }
  1037. CHECK_E(BIT_initDStream(&seqState.DStream, ip, iend - ip), corruption_detected);
  1038. FSE_initDState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1039. FSE_initDState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1040. FSE_initDState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1041. for (; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && nbSeq;) {
  1042. nbSeq--;
  1043. {
  1044. seq_t const sequence = ZSTD_decodeSequence(&seqState);
  1045. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, base, vBase, dictEnd);
  1046. if (ZSTD_isError(oneSeqSize))
  1047. return oneSeqSize;
  1048. op += oneSeqSize;
  1049. }
  1050. }
  1051. /* check if reached exact end */
  1052. if (nbSeq)
  1053. return ERROR(corruption_detected);
  1054. /* save reps for next block */
  1055. {
  1056. U32 i;
  1057. for (i = 0; i < ZSTD_REP_NUM; i++)
  1058. dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]);
  1059. }
  1060. }
  1061. /* last literal segment */
  1062. {
  1063. size_t const lastLLSize = litEnd - litPtr;
  1064. if (lastLLSize > (size_t)(oend - op))
  1065. return ERROR(dstSize_tooSmall);
  1066. memcpy(op, litPtr, lastLLSize);
  1067. op += lastLLSize;
  1068. }
  1069. return op - ostart;
  1070. }
  1071. FORCE_INLINE seq_t ZSTD_decodeSequenceLong_generic(seqState_t *seqState, int const longOffsets)
  1072. {
  1073. seq_t seq;
  1074. U32 const llCode = FSE_peekSymbol(&seqState->stateLL);
  1075. U32 const mlCode = FSE_peekSymbol(&seqState->stateML);
  1076. U32 const ofCode = FSE_peekSymbol(&seqState->stateOffb); /* <= maxOff, by table construction */
  1077. U32 const llBits = LL_bits[llCode];
  1078. U32 const mlBits = ML_bits[mlCode];
  1079. U32 const ofBits = ofCode;
  1080. U32 const totalBits = llBits + mlBits + ofBits;
  1081. static const U32 LL_base[MaxLL + 1] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18,
  1082. 20, 22, 24, 28, 32, 40, 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, 0x10000};
  1083. static const U32 ML_base[MaxML + 1] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  1084. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41,
  1085. 43, 47, 51, 59, 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803, 0x1003, 0x2003, 0x4003, 0x8003, 0x10003};
  1086. static const U32 OF_base[MaxOff + 1] = {0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D, 0xFD, 0x1FD,
  1087. 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD, 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD,
  1088. 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD, 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD};
  1089. /* sequence */
  1090. {
  1091. size_t offset;
  1092. if (!ofCode)
  1093. offset = 0;
  1094. else {
  1095. if (longOffsets) {
  1096. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN);
  1097. offset = OF_base[ofCode] + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  1098. if (ZSTD_32bits() || extraBits)
  1099. BIT_reloadDStream(&seqState->DStream);
  1100. if (extraBits)
  1101. offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  1102. } else {
  1103. offset = OF_base[ofCode] + BIT_readBitsFast(&seqState->DStream, ofBits); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  1104. if (ZSTD_32bits())
  1105. BIT_reloadDStream(&seqState->DStream);
  1106. }
  1107. }
  1108. if (ofCode <= 1) {
  1109. offset += (llCode == 0);
  1110. if (offset) {
  1111. size_t temp = (offset == 3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  1112. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  1113. if (offset != 1)
  1114. seqState->prevOffset[2] = seqState->prevOffset[1];
  1115. seqState->prevOffset[1] = seqState->prevOffset[0];
  1116. seqState->prevOffset[0] = offset = temp;
  1117. } else {
  1118. offset = seqState->prevOffset[0];
  1119. }
  1120. } else {
  1121. seqState->prevOffset[2] = seqState->prevOffset[1];
  1122. seqState->prevOffset[1] = seqState->prevOffset[0];
  1123. seqState->prevOffset[0] = offset;
  1124. }
  1125. seq.offset = offset;
  1126. }
  1127. seq.matchLength = ML_base[mlCode] + ((mlCode > 31) ? BIT_readBitsFast(&seqState->DStream, mlBits) : 0); /* <= 16 bits */
  1128. if (ZSTD_32bits() && (mlBits + llBits > 24))
  1129. BIT_reloadDStream(&seqState->DStream);
  1130. seq.litLength = LL_base[llCode] + ((llCode > 15) ? BIT_readBitsFast(&seqState->DStream, llBits) : 0); /* <= 16 bits */
  1131. if (ZSTD_32bits() || (totalBits > 64 - 7 - (LLFSELog + MLFSELog + OffFSELog)))
  1132. BIT_reloadDStream(&seqState->DStream);
  1133. {
  1134. size_t const pos = seqState->pos + seq.litLength;
  1135. seq.match = seqState->base + pos - seq.offset; /* single memory segment */
  1136. if (seq.offset > pos)
  1137. seq.match += seqState->gotoDict; /* separate memory segment */
  1138. seqState->pos = pos + seq.matchLength;
  1139. }
  1140. /* ANS state update */
  1141. FSE_updateState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  1142. FSE_updateState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  1143. if (ZSTD_32bits())
  1144. BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  1145. FSE_updateState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  1146. return seq;
  1147. }
  1148. static seq_t ZSTD_decodeSequenceLong(seqState_t *seqState, unsigned const windowSize)
  1149. {
  1150. if (ZSTD_highbit32(windowSize) > STREAM_ACCUMULATOR_MIN) {
  1151. return ZSTD_decodeSequenceLong_generic(seqState, 1);
  1152. } else {
  1153. return ZSTD_decodeSequenceLong_generic(seqState, 0);
  1154. }
  1155. }
  1156. FORCE_INLINE
  1157. size_t ZSTD_execSequenceLong(BYTE *op, BYTE *const oend, seq_t sequence, const BYTE **litPtr, const BYTE *const litLimit, const BYTE *const base,
  1158. const BYTE *const vBase, const BYTE *const dictEnd)
  1159. {
  1160. BYTE *const oLitEnd = op + sequence.litLength;
  1161. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  1162. BYTE *const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  1163. BYTE *const oend_w = oend - WILDCOPY_OVERLENGTH;
  1164. const BYTE *const iLitEnd = *litPtr + sequence.litLength;
  1165. const BYTE *match = sequence.match;
  1166. /* check */
  1167. if (oMatchEnd > oend)
  1168. return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  1169. if (iLitEnd > litLimit)
  1170. return ERROR(corruption_detected); /* over-read beyond lit buffer */
  1171. if (oLitEnd > oend_w)
  1172. return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, base, vBase, dictEnd);
  1173. /* copy Literals */
  1174. ZSTD_copy8(op, *litPtr);
  1175. if (sequence.litLength > 8)
  1176. ZSTD_wildcopy(op + 8, (*litPtr) + 8,
  1177. sequence.litLength - 8); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
  1178. op = oLitEnd;
  1179. *litPtr = iLitEnd; /* update for next sequence */
  1180. /* copy Match */
  1181. if (sequence.offset > (size_t)(oLitEnd - base)) {
  1182. /* offset beyond prefix */
  1183. if (sequence.offset > (size_t)(oLitEnd - vBase))
  1184. return ERROR(corruption_detected);
  1185. if (match + sequence.matchLength <= dictEnd) {
  1186. memmove(oLitEnd, match, sequence.matchLength);
  1187. return sequenceLength;
  1188. }
  1189. /* span extDict & currPrefixSegment */
  1190. {
  1191. size_t const length1 = dictEnd - match;
  1192. memmove(oLitEnd, match, length1);
  1193. op = oLitEnd + length1;
  1194. sequence.matchLength -= length1;
  1195. match = base;
  1196. if (op > oend_w || sequence.matchLength < MINMATCH) {
  1197. U32 i;
  1198. for (i = 0; i < sequence.matchLength; ++i)
  1199. op[i] = match[i];
  1200. return sequenceLength;
  1201. }
  1202. }
  1203. }
  1204. /* Requirement: op <= oend_w && sequence.matchLength >= MINMATCH */
  1205. /* match within prefix */
  1206. if (sequence.offset < 8) {
  1207. /* close range match, overlap */
  1208. static const U32 dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */
  1209. static const int dec64table[] = {8, 8, 8, 7, 8, 9, 10, 11}; /* subtracted */
  1210. int const sub2 = dec64table[sequence.offset];
  1211. op[0] = match[0];
  1212. op[1] = match[1];
  1213. op[2] = match[2];
  1214. op[3] = match[3];
  1215. match += dec32table[sequence.offset];
  1216. ZSTD_copy4(op + 4, match);
  1217. match -= sub2;
  1218. } else {
  1219. ZSTD_copy8(op, match);
  1220. }
  1221. op += 8;
  1222. match += 8;
  1223. if (oMatchEnd > oend - (16 - MINMATCH)) {
  1224. if (op < oend_w) {
  1225. ZSTD_wildcopy(op, match, oend_w - op);
  1226. match += oend_w - op;
  1227. op = oend_w;
  1228. }
  1229. while (op < oMatchEnd)
  1230. *op++ = *match++;
  1231. } else {
  1232. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength - 8); /* works even if matchLength < 8 */
  1233. }
  1234. return sequenceLength;
  1235. }
  1236. static size_t ZSTD_decompressSequencesLong(ZSTD_DCtx *dctx, void *dst, size_t maxDstSize, const void *seqStart, size_t seqSize)
  1237. {
  1238. const BYTE *ip = (const BYTE *)seqStart;
  1239. const BYTE *const iend = ip + seqSize;
  1240. BYTE *const ostart = (BYTE * const)dst;
  1241. BYTE *const oend = ostart + maxDstSize;
  1242. BYTE *op = ostart;
  1243. const BYTE *litPtr = dctx->litPtr;
  1244. const BYTE *const litEnd = litPtr + dctx->litSize;
  1245. const BYTE *const base = (const BYTE *)(dctx->base);
  1246. const BYTE *const vBase = (const BYTE *)(dctx->vBase);
  1247. const BYTE *const dictEnd = (const BYTE *)(dctx->dictEnd);
  1248. unsigned const windowSize = dctx->fParams.windowSize;
  1249. int nbSeq;
  1250. /* Build Decoding Tables */
  1251. {
  1252. size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, seqSize);
  1253. if (ZSTD_isError(seqHSize))
  1254. return seqHSize;
  1255. ip += seqHSize;
  1256. }
  1257. /* Regen sequences */
  1258. if (nbSeq) {
  1259. #define STORED_SEQS 4
  1260. #define STOSEQ_MASK (STORED_SEQS - 1)
  1261. #define ADVANCED_SEQS 4
  1262. seq_t *sequences = (seq_t *)dctx->entropy.workspace;
  1263. int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
  1264. seqState_t seqState;
  1265. int seqNb;
  1266. ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.workspace) >= sizeof(seq_t) * STORED_SEQS);
  1267. dctx->fseEntropy = 1;
  1268. {
  1269. U32 i;
  1270. for (i = 0; i < ZSTD_REP_NUM; i++)
  1271. seqState.prevOffset[i] = dctx->entropy.rep[i];
  1272. }
  1273. seqState.base = base;
  1274. seqState.pos = (size_t)(op - base);
  1275. seqState.gotoDict = (uPtrDiff)dictEnd - (uPtrDiff)base; /* cast to avoid undefined behaviour */
  1276. CHECK_E(BIT_initDStream(&seqState.DStream, ip, iend - ip), corruption_detected);
  1277. FSE_initDState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1278. FSE_initDState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1279. FSE_initDState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1280. /* prepare in advance */
  1281. for (seqNb = 0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && seqNb < seqAdvance; seqNb++) {
  1282. sequences[seqNb] = ZSTD_decodeSequenceLong(&seqState, windowSize);
  1283. }
  1284. if (seqNb < seqAdvance)
  1285. return ERROR(corruption_detected);
  1286. /* decode and decompress */
  1287. for (; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && seqNb < nbSeq; seqNb++) {
  1288. seq_t const sequence = ZSTD_decodeSequenceLong(&seqState, windowSize);
  1289. size_t const oneSeqSize =
  1290. ZSTD_execSequenceLong(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STOSEQ_MASK], &litPtr, litEnd, base, vBase, dictEnd);
  1291. if (ZSTD_isError(oneSeqSize))
  1292. return oneSeqSize;
  1293. ZSTD_PREFETCH(sequence.match);
  1294. sequences[seqNb & STOSEQ_MASK] = sequence;
  1295. op += oneSeqSize;
  1296. }
  1297. if (seqNb < nbSeq)
  1298. return ERROR(corruption_detected);
  1299. /* finish queue */
  1300. seqNb -= seqAdvance;
  1301. for (; seqNb < nbSeq; seqNb++) {
  1302. size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[seqNb & STOSEQ_MASK], &litPtr, litEnd, base, vBase, dictEnd);
  1303. if (ZSTD_isError(oneSeqSize))
  1304. return oneSeqSize;
  1305. op += oneSeqSize;
  1306. }
  1307. /* save reps for next block */
  1308. {
  1309. U32 i;
  1310. for (i = 0; i < ZSTD_REP_NUM; i++)
  1311. dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]);
  1312. }
  1313. }
  1314. /* last literal segment */
  1315. {
  1316. size_t const lastLLSize = litEnd - litPtr;
  1317. if (lastLLSize > (size_t)(oend - op))
  1318. return ERROR(dstSize_tooSmall);
  1319. memcpy(op, litPtr, lastLLSize);
  1320. op += lastLLSize;
  1321. }
  1322. return op - ostart;
  1323. }
  1324. static size_t ZSTD_decompressBlock_internal(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
  1325. { /* blockType == blockCompressed */
  1326. const BYTE *ip = (const BYTE *)src;
  1327. if (srcSize >= ZSTD_BLOCKSIZE_ABSOLUTEMAX)
  1328. return ERROR(srcSize_wrong);
  1329. /* Decode literals section */
  1330. {
  1331. size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
  1332. if (ZSTD_isError(litCSize))
  1333. return litCSize;
  1334. ip += litCSize;
  1335. srcSize -= litCSize;
  1336. }
  1337. if (sizeof(size_t) > 4) /* do not enable prefetching on 32-bits x86, as it's performance detrimental */
  1338. /* likely because of register pressure */
  1339. /* if that's the correct cause, then 32-bits ARM should be affected differently */
  1340. /* it would be good to test this on ARM real hardware, to see if prefetch version improves speed */
  1341. if (dctx->fParams.windowSize > (1 << 23))
  1342. return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize);
  1343. return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize);
  1344. }
  1345. static void ZSTD_checkContinuity(ZSTD_DCtx *dctx, const void *dst)
  1346. {
  1347. if (dst != dctx->previousDstEnd) { /* not contiguous */
  1348. dctx->dictEnd = dctx->previousDstEnd;
  1349. dctx->vBase = (const char *)dst - ((const char *)(dctx->previousDstEnd) - (const char *)(dctx->base));
  1350. dctx->base = dst;
  1351. dctx->previousDstEnd = dst;
  1352. }
  1353. }
  1354. size_t ZSTD_decompressBlock(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
  1355. {
  1356. size_t dSize;
  1357. ZSTD_checkContinuity(dctx, dst);
  1358. dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize);
  1359. dctx->previousDstEnd = (char *)dst + dSize;
  1360. return dSize;
  1361. }
  1362. /** ZSTD_insertBlock() :
  1363. insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
  1364. size_t ZSTD_insertBlock(ZSTD_DCtx *dctx, const void *blockStart, size_t blockSize)
  1365. {
  1366. ZSTD_checkContinuity(dctx, blockStart);
  1367. dctx->previousDstEnd = (const char *)blockStart + blockSize;
  1368. return blockSize;
  1369. }
  1370. size_t ZSTD_generateNxBytes(void *dst, size_t dstCapacity, BYTE byte, size_t length)
  1371. {
  1372. if (length > dstCapacity)
  1373. return ERROR(dstSize_tooSmall);
  1374. memset(dst, byte, length);
  1375. return length;
  1376. }
  1377. /** ZSTD_findFrameCompressedSize() :
  1378. * compatible with legacy mode
  1379. * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
  1380. * `srcSize` must be at least as large as the frame contained
  1381. * @return : the compressed size of the frame starting at `src` */
  1382. size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
  1383. {
  1384. if (srcSize >= ZSTD_skippableHeaderSize && (ZSTD_readLE32(src) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  1385. return ZSTD_skippableHeaderSize + ZSTD_readLE32((const BYTE *)src + 4);
  1386. } else {
  1387. const BYTE *ip = (const BYTE *)src;
  1388. const BYTE *const ipstart = ip;
  1389. size_t remainingSize = srcSize;
  1390. ZSTD_frameParams fParams;
  1391. size_t const headerSize = ZSTD_frameHeaderSize(ip, remainingSize);
  1392. if (ZSTD_isError(headerSize))
  1393. return headerSize;
  1394. /* Frame Header */
  1395. {
  1396. size_t const ret = ZSTD_getFrameParams(&fParams, ip, remainingSize);
  1397. if (ZSTD_isError(ret))
  1398. return ret;
  1399. if (ret > 0)
  1400. return ERROR(srcSize_wrong);
  1401. }
  1402. ip += headerSize;
  1403. remainingSize -= headerSize;
  1404. /* Loop on each block */
  1405. while (1) {
  1406. blockProperties_t blockProperties;
  1407. size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  1408. if (ZSTD_isError(cBlockSize))
  1409. return cBlockSize;
  1410. if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
  1411. return ERROR(srcSize_wrong);
  1412. ip += ZSTD_blockHeaderSize + cBlockSize;
  1413. remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
  1414. if (blockProperties.lastBlock)
  1415. break;
  1416. }
  1417. if (fParams.checksumFlag) { /* Frame content checksum */
  1418. if (remainingSize < 4)
  1419. return ERROR(srcSize_wrong);
  1420. ip += 4;
  1421. remainingSize -= 4;
  1422. }
  1423. return ip - ipstart;
  1424. }
  1425. }
  1426. /*! ZSTD_decompressFrame() :
  1427. * @dctx must be properly initialized */
  1428. static size_t ZSTD_decompressFrame(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void **srcPtr, size_t *srcSizePtr)
  1429. {
  1430. const BYTE *ip = (const BYTE *)(*srcPtr);
  1431. BYTE *const ostart = (BYTE * const)dst;
  1432. BYTE *const oend = ostart + dstCapacity;
  1433. BYTE *op = ostart;
  1434. size_t remainingSize = *srcSizePtr;
  1435. /* check */
  1436. if (remainingSize < ZSTD_frameHeaderSize_min + ZSTD_blockHeaderSize)
  1437. return ERROR(srcSize_wrong);
  1438. /* Frame Header */
  1439. {
  1440. size_t const frameHeaderSize = ZSTD_frameHeaderSize(ip, ZSTD_frameHeaderSize_prefix);
  1441. if (ZSTD_isError(frameHeaderSize))
  1442. return frameHeaderSize;
  1443. if (remainingSize < frameHeaderSize + ZSTD_blockHeaderSize)
  1444. return ERROR(srcSize_wrong);
  1445. CHECK_F(ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize));
  1446. ip += frameHeaderSize;
  1447. remainingSize -= frameHeaderSize;
  1448. }
  1449. /* Loop on each block */
  1450. while (1) {
  1451. size_t decodedSize;
  1452. blockProperties_t blockProperties;
  1453. size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  1454. if (ZSTD_isError(cBlockSize))
  1455. return cBlockSize;
  1456. ip += ZSTD_blockHeaderSize;
  1457. remainingSize -= ZSTD_blockHeaderSize;
  1458. if (cBlockSize > remainingSize)
  1459. return ERROR(srcSize_wrong);
  1460. switch (blockProperties.blockType) {
  1461. case bt_compressed: decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend - op, ip, cBlockSize); break;
  1462. case bt_raw: decodedSize = ZSTD_copyRawBlock(op, oend - op, ip, cBlockSize); break;
  1463. case bt_rle: decodedSize = ZSTD_generateNxBytes(op, oend - op, *ip, blockProperties.origSize); break;
  1464. case bt_reserved:
  1465. default: return ERROR(corruption_detected);
  1466. }
  1467. if (ZSTD_isError(decodedSize))
  1468. return decodedSize;
  1469. if (dctx->fParams.checksumFlag)
  1470. xxh64_update(&dctx->xxhState, op, decodedSize);
  1471. op += decodedSize;
  1472. ip += cBlockSize;
  1473. remainingSize -= cBlockSize;
  1474. if (blockProperties.lastBlock)
  1475. break;
  1476. }
  1477. if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
  1478. U32 const checkCalc = (U32)xxh64_digest(&dctx->xxhState);
  1479. U32 checkRead;
  1480. if (remainingSize < 4)
  1481. return ERROR(checksum_wrong);
  1482. checkRead = ZSTD_readLE32(ip);
  1483. if (checkRead != checkCalc)
  1484. return ERROR(checksum_wrong);
  1485. ip += 4;
  1486. remainingSize -= 4;
  1487. }
  1488. /* Allow caller to get size read */
  1489. *srcPtr = ip;
  1490. *srcSizePtr = remainingSize;
  1491. return op - ostart;
  1492. }
  1493. static const void *ZSTD_DDictDictContent(const ZSTD_DDict *ddict);
  1494. static size_t ZSTD_DDictDictSize(const ZSTD_DDict *ddict);
  1495. static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize,
  1496. const ZSTD_DDict *ddict)
  1497. {
  1498. void *const dststart = dst;
  1499. if (ddict) {
  1500. if (dict) {
  1501. /* programmer error, these two cases should be mutually exclusive */
  1502. return ERROR(GENERIC);
  1503. }
  1504. dict = ZSTD_DDictDictContent(ddict);
  1505. dictSize = ZSTD_DDictDictSize(ddict);
  1506. }
  1507. while (srcSize >= ZSTD_frameHeaderSize_prefix) {
  1508. U32 magicNumber;
  1509. magicNumber = ZSTD_readLE32(src);
  1510. if (magicNumber != ZSTD_MAGICNUMBER) {
  1511. if ((magicNumber & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  1512. size_t skippableSize;
  1513. if (srcSize < ZSTD_skippableHeaderSize)
  1514. return ERROR(srcSize_wrong);
  1515. skippableSize = ZSTD_readLE32((const BYTE *)src + 4) + ZSTD_skippableHeaderSize;
  1516. if (srcSize < skippableSize) {
  1517. return ERROR(srcSize_wrong);
  1518. }
  1519. src = (const BYTE *)src + skippableSize;
  1520. srcSize -= skippableSize;
  1521. continue;
  1522. } else {
  1523. return ERROR(prefix_unknown);
  1524. }
  1525. }
  1526. if (ddict) {
  1527. /* we were called from ZSTD_decompress_usingDDict */
  1528. ZSTD_refDDict(dctx, ddict);
  1529. } else {
  1530. /* this will initialize correctly with no dict if dict == NULL, so
  1531. * use this in all cases but ddict */
  1532. CHECK_F(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize));
  1533. }
  1534. ZSTD_checkContinuity(dctx, dst);
  1535. {
  1536. const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity, &src, &srcSize);
  1537. if (ZSTD_isError(res))
  1538. return res;
  1539. /* don't need to bounds check this, ZSTD_decompressFrame will have
  1540. * already */
  1541. dst = (BYTE *)dst + res;
  1542. dstCapacity -= res;
  1543. }
  1544. }
  1545. if (srcSize)
  1546. return ERROR(srcSize_wrong); /* input not entirely consumed */
  1547. return (BYTE *)dst - (BYTE *)dststart;
  1548. }
  1549. size_t ZSTD_decompress_usingDict(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize)
  1550. {
  1551. return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
  1552. }
  1553. size_t ZSTD_decompressDCtx(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
  1554. {
  1555. return ZSTD_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
  1556. }
  1557. /*-**************************************
  1558. * Advanced Streaming Decompression API
  1559. * Bufferless and synchronous
  1560. ****************************************/
  1561. size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx *dctx) { return dctx->expected; }
  1562. ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx *dctx)
  1563. {
  1564. switch (dctx->stage) {
  1565. default: /* should not happen */
  1566. case ZSTDds_getFrameHeaderSize:
  1567. case ZSTDds_decodeFrameHeader: return ZSTDnit_frameHeader;
  1568. case ZSTDds_decodeBlockHeader: return ZSTDnit_blockHeader;
  1569. case ZSTDds_decompressBlock: return ZSTDnit_block;
  1570. case ZSTDds_decompressLastBlock: return ZSTDnit_lastBlock;
  1571. case ZSTDds_checkChecksum: return ZSTDnit_checksum;
  1572. case ZSTDds_decodeSkippableHeader:
  1573. case ZSTDds_skipFrame: return ZSTDnit_skippableFrame;
  1574. }
  1575. }
  1576. int ZSTD_isSkipFrame(ZSTD_DCtx *dctx) { return dctx->stage == ZSTDds_skipFrame; } /* for zbuff */
  1577. /** ZSTD_decompressContinue() :
  1578. * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
  1579. * or an error code, which can be tested using ZSTD_isError() */
  1580. size_t ZSTD_decompressContinue(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize)
  1581. {
  1582. /* Sanity check */
  1583. if (srcSize != dctx->expected)
  1584. return ERROR(srcSize_wrong);
  1585. if (dstCapacity)
  1586. ZSTD_checkContinuity(dctx, dst);
  1587. switch (dctx->stage) {
  1588. case ZSTDds_getFrameHeaderSize:
  1589. if (srcSize != ZSTD_frameHeaderSize_prefix)
  1590. return ERROR(srcSize_wrong); /* impossible */
  1591. if ((ZSTD_readLE32(src) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
  1592. memcpy(dctx->headerBuffer, src, ZSTD_frameHeaderSize_prefix);
  1593. dctx->expected = ZSTD_skippableHeaderSize - ZSTD_frameHeaderSize_prefix; /* magic number + skippable frame length */
  1594. dctx->stage = ZSTDds_decodeSkippableHeader;
  1595. return 0;
  1596. }
  1597. dctx->headerSize = ZSTD_frameHeaderSize(src, ZSTD_frameHeaderSize_prefix);
  1598. if (ZSTD_isError(dctx->headerSize))
  1599. return dctx->headerSize;
  1600. memcpy(dctx->headerBuffer, src, ZSTD_frameHeaderSize_prefix);
  1601. if (dctx->headerSize > ZSTD_frameHeaderSize_prefix) {
  1602. dctx->expected = dctx->headerSize - ZSTD_frameHeaderSize_prefix;
  1603. dctx->stage = ZSTDds_decodeFrameHeader;
  1604. return 0;
  1605. }
  1606. dctx->expected = 0; /* not necessary to copy more */
  1607. case ZSTDds_decodeFrameHeader:
  1608. memcpy(dctx->headerBuffer + ZSTD_frameHeaderSize_prefix, src, dctx->expected);
  1609. CHECK_F(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize));
  1610. dctx->expected = ZSTD_blockHeaderSize;
  1611. dctx->stage = ZSTDds_decodeBlockHeader;
  1612. return 0;
  1613. case ZSTDds_decodeBlockHeader: {
  1614. blockProperties_t bp;
  1615. size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  1616. if (ZSTD_isError(cBlockSize))
  1617. return cBlockSize;
  1618. dctx->expected = cBlockSize;
  1619. dctx->bType = bp.blockType;
  1620. dctx->rleSize = bp.origSize;
  1621. if (cBlockSize) {
  1622. dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
  1623. return 0;
  1624. }
  1625. /* empty block */
  1626. if (bp.lastBlock) {
  1627. if (dctx->fParams.checksumFlag) {
  1628. dctx->expected = 4;
  1629. dctx->stage = ZSTDds_checkChecksum;
  1630. } else {
  1631. dctx->expected = 0; /* end of frame */
  1632. dctx->stage = ZSTDds_getFrameHeaderSize;
  1633. }
  1634. } else {
  1635. dctx->expected = 3; /* go directly to next header */
  1636. dctx->stage = ZSTDds_decodeBlockHeader;
  1637. }
  1638. return 0;
  1639. }
  1640. case ZSTDds_decompressLastBlock:
  1641. case ZSTDds_decompressBlock: {
  1642. size_t rSize;
  1643. switch (dctx->bType) {
  1644. case bt_compressed: rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize); break;
  1645. case bt_raw: rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize); break;
  1646. case bt_rle: rSize = ZSTD_setRleBlock(dst, dstCapacity, src, srcSize, dctx->rleSize); break;
  1647. case bt_reserved: /* should never happen */
  1648. default: return ERROR(corruption_detected);
  1649. }
  1650. if (ZSTD_isError(rSize))
  1651. return rSize;
  1652. if (dctx->fParams.checksumFlag)
  1653. xxh64_update(&dctx->xxhState, dst, rSize);
  1654. if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */
  1655. if (dctx->fParams.checksumFlag) { /* another round for frame checksum */
  1656. dctx->expected = 4;
  1657. dctx->stage = ZSTDds_checkChecksum;
  1658. } else {
  1659. dctx->expected = 0; /* ends here */
  1660. dctx->stage = ZSTDds_getFrameHeaderSize;
  1661. }
  1662. } else {
  1663. dctx->stage = ZSTDds_decodeBlockHeader;
  1664. dctx->expected = ZSTD_blockHeaderSize;
  1665. dctx->previousDstEnd = (char *)dst + rSize;
  1666. }
  1667. return rSize;
  1668. }
  1669. case ZSTDds_checkChecksum: {
  1670. U32 const h32 = (U32)xxh64_digest(&dctx->xxhState);
  1671. U32 const check32 = ZSTD_readLE32(src); /* srcSize == 4, guaranteed by dctx->expected */
  1672. if (check32 != h32)
  1673. return ERROR(checksum_wrong);
  1674. dctx->expected = 0;
  1675. dctx->stage = ZSTDds_getFrameHeaderSize;
  1676. return 0;
  1677. }
  1678. case ZSTDds_decodeSkippableHeader: {
  1679. memcpy(dctx->headerBuffer + ZSTD_frameHeaderSize_prefix, src, dctx->expected);
  1680. dctx->expected = ZSTD_readLE32(dctx->headerBuffer + 4);
  1681. dctx->stage = ZSTDds_skipFrame;
  1682. return 0;
  1683. }
  1684. case ZSTDds_skipFrame: {
  1685. dctx->expected = 0;
  1686. dctx->stage = ZSTDds_getFrameHeaderSize;
  1687. return 0;
  1688. }
  1689. default:
  1690. return ERROR(GENERIC); /* impossible */
  1691. }
  1692. }
  1693. static size_t ZSTD_refDictContent(ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
  1694. {
  1695. dctx->dictEnd = dctx->previousDstEnd;
  1696. dctx->vBase = (const char *)dict - ((const char *)(dctx->previousDstEnd) - (const char *)(dctx->base));
  1697. dctx->base = dict;
  1698. dctx->previousDstEnd = (const char *)dict + dictSize;
  1699. return 0;
  1700. }
  1701. /* ZSTD_loadEntropy() :
  1702. * dict : must point at beginning of a valid zstd dictionary
  1703. * @return : size of entropy tables read */
  1704. static size_t ZSTD_loadEntropy(ZSTD_entropyTables_t *entropy, const void *const dict, size_t const dictSize)
  1705. {
  1706. const BYTE *dictPtr = (const BYTE *)dict;
  1707. const BYTE *const dictEnd = dictPtr + dictSize;
  1708. if (dictSize <= 8)
  1709. return ERROR(dictionary_corrupted);
  1710. dictPtr += 8; /* skip header = magic + dictID */
  1711. {
  1712. size_t const hSize = HUF_readDTableX4_wksp(entropy->hufTable, dictPtr, dictEnd - dictPtr, entropy->workspace, sizeof(entropy->workspace));
  1713. if (HUF_isError(hSize))
  1714. return ERROR(dictionary_corrupted);
  1715. dictPtr += hSize;
  1716. }
  1717. {
  1718. short offcodeNCount[MaxOff + 1];
  1719. U32 offcodeMaxValue = MaxOff, offcodeLog;
  1720. size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd - dictPtr);
  1721. if (FSE_isError(offcodeHeaderSize))
  1722. return ERROR(dictionary_corrupted);
  1723. if (offcodeLog > OffFSELog)
  1724. return ERROR(dictionary_corrupted);
  1725. CHECK_E(FSE_buildDTable_wksp(entropy->OFTable, offcodeNCount, offcodeMaxValue, offcodeLog, entropy->workspace, sizeof(entropy->workspace)), dictionary_corrupted);
  1726. dictPtr += offcodeHeaderSize;
  1727. }
  1728. {
  1729. short matchlengthNCount[MaxML + 1];
  1730. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  1731. size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd - dictPtr);
  1732. if (FSE_isError(matchlengthHeaderSize))
  1733. return ERROR(dictionary_corrupted);
  1734. if (matchlengthLog > MLFSELog)
  1735. return ERROR(dictionary_corrupted);
  1736. CHECK_E(FSE_buildDTable_wksp(entropy->MLTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog, entropy->workspace, sizeof(entropy->workspace)), dictionary_corrupted);
  1737. dictPtr += matchlengthHeaderSize;
  1738. }
  1739. {
  1740. short litlengthNCount[MaxLL + 1];
  1741. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  1742. size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd - dictPtr);
  1743. if (FSE_isError(litlengthHeaderSize))
  1744. return ERROR(dictionary_corrupted);
  1745. if (litlengthLog > LLFSELog)
  1746. return ERROR(dictionary_corrupted);
  1747. CHECK_E(FSE_buildDTable_wksp(entropy->LLTable, litlengthNCount, litlengthMaxValue, litlengthLog, entropy->workspace, sizeof(entropy->workspace)), dictionary_corrupted);
  1748. dictPtr += litlengthHeaderSize;
  1749. }
  1750. if (dictPtr + 12 > dictEnd)
  1751. return ERROR(dictionary_corrupted);
  1752. {
  1753. int i;
  1754. size_t const dictContentSize = (size_t)(dictEnd - (dictPtr + 12));
  1755. for (i = 0; i < 3; i++) {
  1756. U32 const rep = ZSTD_readLE32(dictPtr);
  1757. dictPtr += 4;
  1758. if (rep == 0 || rep >= dictContentSize)
  1759. return ERROR(dictionary_corrupted);
  1760. entropy->rep[i] = rep;
  1761. }
  1762. }
  1763. return dictPtr - (const BYTE *)dict;
  1764. }
  1765. static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
  1766. {
  1767. if (dictSize < 8)
  1768. return ZSTD_refDictContent(dctx, dict, dictSize);
  1769. {
  1770. U32 const magic = ZSTD_readLE32(dict);
  1771. if (magic != ZSTD_DICT_MAGIC) {
  1772. return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */
  1773. }
  1774. }
  1775. dctx->dictID = ZSTD_readLE32((const char *)dict + 4);
  1776. /* load entropy tables */
  1777. {
  1778. size_t const eSize = ZSTD_loadEntropy(&dctx->entropy, dict, dictSize);
  1779. if (ZSTD_isError(eSize))
  1780. return ERROR(dictionary_corrupted);
  1781. dict = (const char *)dict + eSize;
  1782. dictSize -= eSize;
  1783. }
  1784. dctx->litEntropy = dctx->fseEntropy = 1;
  1785. /* reference dictionary content */
  1786. return ZSTD_refDictContent(dctx, dict, dictSize);
  1787. }
  1788. size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx *dctx, const void *dict, size_t dictSize)
  1789. {
  1790. CHECK_F(ZSTD_decompressBegin(dctx));
  1791. if (dict && dictSize)
  1792. CHECK_E(ZSTD_decompress_insertDictionary(dctx, dict, dictSize), dictionary_corrupted);
  1793. return 0;
  1794. }
  1795. /* ====== ZSTD_DDict ====== */
  1796. struct ZSTD_DDict_s {
  1797. void *dictBuffer;
  1798. const void *dictContent;
  1799. size_t dictSize;
  1800. ZSTD_entropyTables_t entropy;
  1801. U32 dictID;
  1802. U32 entropyPresent;
  1803. ZSTD_customMem cMem;
  1804. }; /* typedef'd to ZSTD_DDict within "zstd.h" */
  1805. size_t ZSTD_DDictWorkspaceBound(void) { return ZSTD_ALIGN(sizeof(ZSTD_stack)) + ZSTD_ALIGN(sizeof(ZSTD_DDict)); }
  1806. static const void *ZSTD_DDictDictContent(const ZSTD_DDict *ddict) { return ddict->dictContent; }
  1807. static size_t ZSTD_DDictDictSize(const ZSTD_DDict *ddict) { return ddict->dictSize; }
  1808. static void ZSTD_refDDict(ZSTD_DCtx *dstDCtx, const ZSTD_DDict *ddict)
  1809. {
  1810. ZSTD_decompressBegin(dstDCtx); /* init */
  1811. if (ddict) { /* support refDDict on NULL */
  1812. dstDCtx->dictID = ddict->dictID;
  1813. dstDCtx->base = ddict->dictContent;
  1814. dstDCtx->vBase = ddict->dictContent;
  1815. dstDCtx->dictEnd = (const BYTE *)ddict->dictContent + ddict->dictSize;
  1816. dstDCtx->previousDstEnd = dstDCtx->dictEnd;
  1817. if (ddict->entropyPresent) {
  1818. dstDCtx->litEntropy = 1;
  1819. dstDCtx->fseEntropy = 1;
  1820. dstDCtx->LLTptr = ddict->entropy.LLTable;
  1821. dstDCtx->MLTptr = ddict->entropy.MLTable;
  1822. dstDCtx->OFTptr = ddict->entropy.OFTable;
  1823. dstDCtx->HUFptr = ddict->entropy.hufTable;
  1824. dstDCtx->entropy.rep[0] = ddict->entropy.rep[0];
  1825. dstDCtx->entropy.rep[1] = ddict->entropy.rep[1];
  1826. dstDCtx->entropy.rep[2] = ddict->entropy.rep[2];
  1827. } else {
  1828. dstDCtx->litEntropy = 0;
  1829. dstDCtx->fseEntropy = 0;
  1830. }
  1831. }
  1832. }
  1833. static size_t ZSTD_loadEntropy_inDDict(ZSTD_DDict *ddict)
  1834. {
  1835. ddict->dictID = 0;
  1836. ddict->entropyPresent = 0;
  1837. if (ddict->dictSize < 8)
  1838. return 0;
  1839. {
  1840. U32 const magic = ZSTD_readLE32(ddict->dictContent);
  1841. if (magic != ZSTD_DICT_MAGIC)
  1842. return 0; /* pure content mode */
  1843. }
  1844. ddict->dictID = ZSTD_readLE32((const char *)ddict->dictContent + 4);
  1845. /* load entropy tables */
  1846. CHECK_E(ZSTD_loadEntropy(&ddict->entropy, ddict->dictContent, ddict->dictSize), dictionary_corrupted);
  1847. ddict->entropyPresent = 1;
  1848. return 0;
  1849. }
  1850. static ZSTD_DDict *ZSTD_createDDict_advanced(const void *dict, size_t dictSize, unsigned byReference, ZSTD_customMem customMem)
  1851. {
  1852. if (!customMem.customAlloc || !customMem.customFree)
  1853. return NULL;
  1854. {
  1855. ZSTD_DDict *const ddict = (ZSTD_DDict *)ZSTD_malloc(sizeof(ZSTD_DDict), customMem);
  1856. if (!ddict)
  1857. return NULL;
  1858. ddict->cMem = customMem;
  1859. if ((byReference) || (!dict) || (!dictSize)) {
  1860. ddict->dictBuffer = NULL;
  1861. ddict->dictContent = dict;
  1862. } else {
  1863. void *const internalBuffer = ZSTD_malloc(dictSize, customMem);
  1864. if (!internalBuffer) {
  1865. ZSTD_freeDDict(ddict);
  1866. return NULL;
  1867. }
  1868. memcpy(internalBuffer, dict, dictSize);
  1869. ddict->dictBuffer = internalBuffer;
  1870. ddict->dictContent = internalBuffer;
  1871. }
  1872. ddict->dictSize = dictSize;
  1873. ddict->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
  1874. /* parse dictionary content */
  1875. {
  1876. size_t const errorCode = ZSTD_loadEntropy_inDDict(ddict);
  1877. if (ZSTD_isError(errorCode)) {
  1878. ZSTD_freeDDict(ddict);
  1879. return NULL;
  1880. }
  1881. }
  1882. return ddict;
  1883. }
  1884. }
  1885. /*! ZSTD_initDDict() :
  1886. * Create a digested dictionary, to start decompression without startup delay.
  1887. * `dict` content is copied inside DDict.
  1888. * Consequently, `dict` can be released after `ZSTD_DDict` creation */
  1889. ZSTD_DDict *ZSTD_initDDict(const void *dict, size_t dictSize, void *workspace, size_t workspaceSize)
  1890. {
  1891. ZSTD_customMem const stackMem = ZSTD_initStack(workspace, workspaceSize);
  1892. return ZSTD_createDDict_advanced(dict, dictSize, 1, stackMem);
  1893. }
  1894. size_t ZSTD_freeDDict(ZSTD_DDict *ddict)
  1895. {
  1896. if (ddict == NULL)
  1897. return 0; /* support free on NULL */
  1898. {
  1899. ZSTD_customMem const cMem = ddict->cMem;
  1900. ZSTD_free(ddict->dictBuffer, cMem);
  1901. ZSTD_free(ddict, cMem);
  1902. return 0;
  1903. }
  1904. }
  1905. /*! ZSTD_getDictID_fromDict() :
  1906. * Provides the dictID stored within dictionary.
  1907. * if @return == 0, the dictionary is not conformant with Zstandard specification.
  1908. * It can still be loaded, but as a content-only dictionary. */
  1909. unsigned ZSTD_getDictID_fromDict(const void *dict, size_t dictSize)
  1910. {
  1911. if (dictSize < 8)
  1912. return 0;
  1913. if (ZSTD_readLE32(dict) != ZSTD_DICT_MAGIC)
  1914. return 0;
  1915. return ZSTD_readLE32((const char *)dict + 4);
  1916. }
  1917. /*! ZSTD_getDictID_fromDDict() :
  1918. * Provides the dictID of the dictionary loaded into `ddict`.
  1919. * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
  1920. * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
  1921. unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict *ddict)
  1922. {
  1923. if (ddict == NULL)
  1924. return 0;
  1925. return ZSTD_getDictID_fromDict(ddict->dictContent, ddict->dictSize);
  1926. }
  1927. /*! ZSTD_getDictID_fromFrame() :
  1928. * Provides the dictID required to decompressed the frame stored within `src`.
  1929. * If @return == 0, the dictID could not be decoded.
  1930. * This could for one of the following reasons :
  1931. * - The frame does not require a dictionary to be decoded (most common case).
  1932. * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information.
  1933. * Note : this use case also happens when using a non-conformant dictionary.
  1934. * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
  1935. * - This is not a Zstandard frame.
  1936. * When identifying the exact failure cause, it's possible to used ZSTD_getFrameParams(), which will provide a more precise error code. */
  1937. unsigned ZSTD_getDictID_fromFrame(const void *src, size_t srcSize)
  1938. {
  1939. ZSTD_frameParams zfp = {0, 0, 0, 0};
  1940. size_t const hError = ZSTD_getFrameParams(&zfp, src, srcSize);
  1941. if (ZSTD_isError(hError))
  1942. return 0;
  1943. return zfp.dictID;
  1944. }
  1945. /*! ZSTD_decompress_usingDDict() :
  1946. * Decompression using a pre-digested Dictionary
  1947. * Use dictionary without significant overhead. */
  1948. size_t ZSTD_decompress_usingDDict(ZSTD_DCtx *dctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_DDict *ddict)
  1949. {
  1950. /* pass content and size in case legacy frames are encountered */
  1951. return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, NULL, 0, ddict);
  1952. }
  1953. /*=====================================
  1954. * Streaming decompression
  1955. *====================================*/
  1956. typedef enum { zdss_init, zdss_loadHeader, zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage;
  1957. /* *** Resource management *** */
  1958. struct ZSTD_DStream_s {
  1959. ZSTD_DCtx *dctx;
  1960. ZSTD_DDict *ddictLocal;
  1961. const ZSTD_DDict *ddict;
  1962. ZSTD_frameParams fParams;
  1963. ZSTD_dStreamStage stage;
  1964. char *inBuff;
  1965. size_t inBuffSize;
  1966. size_t inPos;
  1967. size_t maxWindowSize;
  1968. char *outBuff;
  1969. size_t outBuffSize;
  1970. size_t outStart;
  1971. size_t outEnd;
  1972. size_t blockSize;
  1973. BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX]; /* tmp buffer to store frame header */
  1974. size_t lhSize;
  1975. ZSTD_customMem customMem;
  1976. void *legacyContext;
  1977. U32 previousLegacyVersion;
  1978. U32 legacyVersion;
  1979. U32 hostageByte;
  1980. }; /* typedef'd to ZSTD_DStream within "zstd.h" */
  1981. size_t ZSTD_DStreamWorkspaceBound(size_t maxWindowSize)
  1982. {
  1983. size_t const blockSize = MIN(maxWindowSize, ZSTD_BLOCKSIZE_ABSOLUTEMAX);
  1984. size_t const inBuffSize = blockSize;
  1985. size_t const outBuffSize = maxWindowSize + blockSize + WILDCOPY_OVERLENGTH * 2;
  1986. return ZSTD_DCtxWorkspaceBound() + ZSTD_ALIGN(sizeof(ZSTD_DStream)) + ZSTD_ALIGN(inBuffSize) + ZSTD_ALIGN(outBuffSize);
  1987. }
  1988. static ZSTD_DStream *ZSTD_createDStream_advanced(ZSTD_customMem customMem)
  1989. {
  1990. ZSTD_DStream *zds;
  1991. if (!customMem.customAlloc || !customMem.customFree)
  1992. return NULL;
  1993. zds = (ZSTD_DStream *)ZSTD_malloc(sizeof(ZSTD_DStream), customMem);
  1994. if (zds == NULL)
  1995. return NULL;
  1996. memset(zds, 0, sizeof(ZSTD_DStream));
  1997. memcpy(&zds->customMem, &customMem, sizeof(ZSTD_customMem));
  1998. zds->dctx = ZSTD_createDCtx_advanced(customMem);
  1999. if (zds->dctx == NULL) {
  2000. ZSTD_freeDStream(zds);
  2001. return NULL;
  2002. }
  2003. zds->stage = zdss_init;
  2004. zds->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
  2005. return zds;
  2006. }
  2007. ZSTD_DStream *ZSTD_initDStream(size_t maxWindowSize, void *workspace, size_t workspaceSize)
  2008. {
  2009. ZSTD_customMem const stackMem = ZSTD_initStack(workspace, workspaceSize);
  2010. ZSTD_DStream *zds = ZSTD_createDStream_advanced(stackMem);
  2011. if (!zds) {
  2012. return NULL;
  2013. }
  2014. zds->maxWindowSize = maxWindowSize;
  2015. zds->stage = zdss_loadHeader;
  2016. zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;
  2017. ZSTD_freeDDict(zds->ddictLocal);
  2018. zds->ddictLocal = NULL;
  2019. zds->ddict = zds->ddictLocal;
  2020. zds->legacyVersion = 0;
  2021. zds->hostageByte = 0;
  2022. {
  2023. size_t const blockSize = MIN(zds->maxWindowSize, ZSTD_BLOCKSIZE_ABSOLUTEMAX);
  2024. size_t const neededOutSize = zds->maxWindowSize + blockSize + WILDCOPY_OVERLENGTH * 2;
  2025. zds->inBuff = (char *)ZSTD_malloc(blockSize, zds->customMem);
  2026. zds->inBuffSize = blockSize;
  2027. zds->outBuff = (char *)ZSTD_malloc(neededOutSize, zds->customMem);
  2028. zds->outBuffSize = neededOutSize;
  2029. if (zds->inBuff == NULL || zds->outBuff == NULL) {
  2030. ZSTD_freeDStream(zds);
  2031. return NULL;
  2032. }
  2033. }
  2034. return zds;
  2035. }
  2036. ZSTD_DStream *ZSTD_initDStream_usingDDict(size_t maxWindowSize, const ZSTD_DDict *ddict, void *workspace, size_t workspaceSize)
  2037. {
  2038. ZSTD_DStream *zds = ZSTD_initDStream(maxWindowSize, workspace, workspaceSize);
  2039. if (zds) {
  2040. zds->ddict = ddict;
  2041. }
  2042. return zds;
  2043. }
  2044. size_t ZSTD_freeDStream(ZSTD_DStream *zds)
  2045. {
  2046. if (zds == NULL)
  2047. return 0; /* support free on null */
  2048. {
  2049. ZSTD_customMem const cMem = zds->customMem;
  2050. ZSTD_freeDCtx(zds->dctx);
  2051. zds->dctx = NULL;
  2052. ZSTD_freeDDict(zds->ddictLocal);
  2053. zds->ddictLocal = NULL;
  2054. ZSTD_free(zds->inBuff, cMem);
  2055. zds->inBuff = NULL;
  2056. ZSTD_free(zds->outBuff, cMem);
  2057. zds->outBuff = NULL;
  2058. ZSTD_free(zds, cMem);
  2059. return 0;
  2060. }
  2061. }
  2062. /* *** Initialization *** */
  2063. size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_ABSOLUTEMAX + ZSTD_blockHeaderSize; }
  2064. size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_ABSOLUTEMAX; }
  2065. size_t ZSTD_resetDStream(ZSTD_DStream *zds)
  2066. {
  2067. zds->stage = zdss_loadHeader;
  2068. zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;
  2069. zds->legacyVersion = 0;
  2070. zds->hostageByte = 0;
  2071. return ZSTD_frameHeaderSize_prefix;
  2072. }
  2073. /* ***** Decompression ***** */
  2074. ZSTD_STATIC size_t ZSTD_limitCopy(void *dst, size_t dstCapacity, const void *src, size_t srcSize)
  2075. {
  2076. size_t const length = MIN(dstCapacity, srcSize);
  2077. memcpy(dst, src, length);
  2078. return length;
  2079. }
  2080. size_t ZSTD_decompressStream(ZSTD_DStream *zds, ZSTD_outBuffer *output, ZSTD_inBuffer *input)
  2081. {
  2082. const char *const istart = (const char *)(input->src) + input->pos;
  2083. const char *const iend = (const char *)(input->src) + input->size;
  2084. const char *ip = istart;
  2085. char *const ostart = (char *)(output->dst) + output->pos;
  2086. char *const oend = (char *)(output->dst) + output->size;
  2087. char *op = ostart;
  2088. U32 someMoreWork = 1;
  2089. while (someMoreWork) {
  2090. switch (zds->stage) {
  2091. case zdss_init:
  2092. ZSTD_resetDStream(zds); /* transparent reset on starting decoding a new frame */
  2093. /* fall-through */
  2094. case zdss_loadHeader: {
  2095. size_t const hSize = ZSTD_getFrameParams(&zds->fParams, zds->headerBuffer, zds->lhSize);
  2096. if (ZSTD_isError(hSize))
  2097. return hSize;
  2098. if (hSize != 0) { /* need more input */
  2099. size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */
  2100. if (toLoad > (size_t)(iend - ip)) { /* not enough input to load full header */
  2101. memcpy(zds->headerBuffer + zds->lhSize, ip, iend - ip);
  2102. zds->lhSize += iend - ip;
  2103. input->pos = input->size;
  2104. return (MAX(ZSTD_frameHeaderSize_min, hSize) - zds->lhSize) +
  2105. ZSTD_blockHeaderSize; /* remaining header bytes + next block header */
  2106. }
  2107. memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad);
  2108. zds->lhSize = hSize;
  2109. ip += toLoad;
  2110. break;
  2111. }
  2112. /* check for single-pass mode opportunity */
  2113. if (zds->fParams.frameContentSize && zds->fParams.windowSize /* skippable frame if == 0 */
  2114. && (U64)(size_t)(oend - op) >= zds->fParams.frameContentSize) {
  2115. size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend - istart);
  2116. if (cSize <= (size_t)(iend - istart)) {
  2117. size_t const decompressedSize = ZSTD_decompress_usingDDict(zds->dctx, op, oend - op, istart, cSize, zds->ddict);
  2118. if (ZSTD_isError(decompressedSize))
  2119. return decompressedSize;
  2120. ip = istart + cSize;
  2121. op += decompressedSize;
  2122. zds->dctx->expected = 0;
  2123. zds->stage = zdss_init;
  2124. someMoreWork = 0;
  2125. break;
  2126. }
  2127. }
  2128. /* Consume header */
  2129. ZSTD_refDDict(zds->dctx, zds->ddict);
  2130. {
  2131. size_t const h1Size = ZSTD_nextSrcSizeToDecompress(zds->dctx); /* == ZSTD_frameHeaderSize_prefix */
  2132. CHECK_F(ZSTD_decompressContinue(zds->dctx, NULL, 0, zds->headerBuffer, h1Size));
  2133. {
  2134. size_t const h2Size = ZSTD_nextSrcSizeToDecompress(zds->dctx);
  2135. CHECK_F(ZSTD_decompressContinue(zds->dctx, NULL, 0, zds->headerBuffer + h1Size, h2Size));
  2136. }
  2137. }
  2138. zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
  2139. if (zds->fParams.windowSize > zds->maxWindowSize)
  2140. return ERROR(frameParameter_windowTooLarge);
  2141. /* Buffers are preallocated, but double check */
  2142. {
  2143. size_t const blockSize = MIN(zds->maxWindowSize, ZSTD_BLOCKSIZE_ABSOLUTEMAX);
  2144. size_t const neededOutSize = zds->maxWindowSize + blockSize + WILDCOPY_OVERLENGTH * 2;
  2145. if (zds->inBuffSize < blockSize) {
  2146. return ERROR(GENERIC);
  2147. }
  2148. if (zds->outBuffSize < neededOutSize) {
  2149. return ERROR(GENERIC);
  2150. }
  2151. zds->blockSize = blockSize;
  2152. }
  2153. zds->stage = zdss_read;
  2154. }
  2155. /* pass-through */
  2156. case zdss_read: {
  2157. size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds->dctx);
  2158. if (neededInSize == 0) { /* end of frame */
  2159. zds->stage = zdss_init;
  2160. someMoreWork = 0;
  2161. break;
  2162. }
  2163. if ((size_t)(iend - ip) >= neededInSize) { /* decode directly from src */
  2164. const int isSkipFrame = ZSTD_isSkipFrame(zds->dctx);
  2165. size_t const decodedSize = ZSTD_decompressContinue(zds->dctx, zds->outBuff + zds->outStart,
  2166. (isSkipFrame ? 0 : zds->outBuffSize - zds->outStart), ip, neededInSize);
  2167. if (ZSTD_isError(decodedSize))
  2168. return decodedSize;
  2169. ip += neededInSize;
  2170. if (!decodedSize && !isSkipFrame)
  2171. break; /* this was just a header */
  2172. zds->outEnd = zds->outStart + decodedSize;
  2173. zds->stage = zdss_flush;
  2174. break;
  2175. }
  2176. if (ip == iend) {
  2177. someMoreWork = 0;
  2178. break;
  2179. } /* no more input */
  2180. zds->stage = zdss_load;
  2181. /* pass-through */
  2182. }
  2183. case zdss_load: {
  2184. size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds->dctx);
  2185. size_t const toLoad = neededInSize - zds->inPos; /* should always be <= remaining space within inBuff */
  2186. size_t loadedSize;
  2187. if (toLoad > zds->inBuffSize - zds->inPos)
  2188. return ERROR(corruption_detected); /* should never happen */
  2189. loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend - ip);
  2190. ip += loadedSize;
  2191. zds->inPos += loadedSize;
  2192. if (loadedSize < toLoad) {
  2193. someMoreWork = 0;
  2194. break;
  2195. } /* not enough input, wait for more */
  2196. /* decode loaded input */
  2197. {
  2198. const int isSkipFrame = ZSTD_isSkipFrame(zds->dctx);
  2199. size_t const decodedSize = ZSTD_decompressContinue(zds->dctx, zds->outBuff + zds->outStart, zds->outBuffSize - zds->outStart,
  2200. zds->inBuff, neededInSize);
  2201. if (ZSTD_isError(decodedSize))
  2202. return decodedSize;
  2203. zds->inPos = 0; /* input is consumed */
  2204. if (!decodedSize && !isSkipFrame) {
  2205. zds->stage = zdss_read;
  2206. break;
  2207. } /* this was just a header */
  2208. zds->outEnd = zds->outStart + decodedSize;
  2209. zds->stage = zdss_flush;
  2210. /* pass-through */
  2211. }
  2212. }
  2213. case zdss_flush: {
  2214. size_t const toFlushSize = zds->outEnd - zds->outStart;
  2215. size_t const flushedSize = ZSTD_limitCopy(op, oend - op, zds->outBuff + zds->outStart, toFlushSize);
  2216. op += flushedSize;
  2217. zds->outStart += flushedSize;
  2218. if (flushedSize == toFlushSize) { /* flush completed */
  2219. zds->stage = zdss_read;
  2220. if (zds->outStart + zds->blockSize > zds->outBuffSize)
  2221. zds->outStart = zds->outEnd = 0;
  2222. break;
  2223. }
  2224. /* cannot complete flush */
  2225. someMoreWork = 0;
  2226. break;
  2227. }
  2228. default:
  2229. return ERROR(GENERIC); /* impossible */
  2230. }
  2231. }
  2232. /* result */
  2233. input->pos += (size_t)(ip - istart);
  2234. output->pos += (size_t)(op - ostart);
  2235. {
  2236. size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds->dctx);
  2237. if (!nextSrcSizeHint) { /* frame fully decoded */
  2238. if (zds->outEnd == zds->outStart) { /* output fully flushed */
  2239. if (zds->hostageByte) {
  2240. if (input->pos >= input->size) {
  2241. zds->stage = zdss_read;
  2242. return 1;
  2243. } /* can't release hostage (not present) */
  2244. input->pos++; /* release hostage */
  2245. }
  2246. return 0;
  2247. }
  2248. if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
  2249. input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */
  2250. zds->hostageByte = 1;
  2251. }
  2252. return 1;
  2253. }
  2254. nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds->dctx) == ZSTDnit_block); /* preload header of next block */
  2255. if (zds->inPos > nextSrcSizeHint)
  2256. return ERROR(GENERIC); /* should never happen */
  2257. nextSrcSizeHint -= zds->inPos; /* already loaded*/
  2258. return nextSrcSizeHint;
  2259. }
  2260. }
  2261. EXPORT_SYMBOL(ZSTD_DCtxWorkspaceBound);
  2262. EXPORT_SYMBOL(ZSTD_initDCtx);
  2263. EXPORT_SYMBOL(ZSTD_decompressDCtx);
  2264. EXPORT_SYMBOL(ZSTD_decompress_usingDict);
  2265. EXPORT_SYMBOL(ZSTD_DDictWorkspaceBound);
  2266. EXPORT_SYMBOL(ZSTD_initDDict);
  2267. EXPORT_SYMBOL(ZSTD_decompress_usingDDict);
  2268. EXPORT_SYMBOL(ZSTD_DStreamWorkspaceBound);
  2269. EXPORT_SYMBOL(ZSTD_initDStream);
  2270. EXPORT_SYMBOL(ZSTD_initDStream_usingDDict);
  2271. EXPORT_SYMBOL(ZSTD_resetDStream);
  2272. EXPORT_SYMBOL(ZSTD_decompressStream);
  2273. EXPORT_SYMBOL(ZSTD_DStreamInSize);
  2274. EXPORT_SYMBOL(ZSTD_DStreamOutSize);
  2275. EXPORT_SYMBOL(ZSTD_findFrameCompressedSize);
  2276. EXPORT_SYMBOL(ZSTD_getFrameContentSize);
  2277. EXPORT_SYMBOL(ZSTD_findDecompressedSize);
  2278. EXPORT_SYMBOL(ZSTD_isFrame);
  2279. EXPORT_SYMBOL(ZSTD_getDictID_fromDict);
  2280. EXPORT_SYMBOL(ZSTD_getDictID_fromDDict);
  2281. EXPORT_SYMBOL(ZSTD_getDictID_fromFrame);
  2282. EXPORT_SYMBOL(ZSTD_getFrameParams);
  2283. EXPORT_SYMBOL(ZSTD_decompressBegin);
  2284. EXPORT_SYMBOL(ZSTD_decompressBegin_usingDict);
  2285. EXPORT_SYMBOL(ZSTD_copyDCtx);
  2286. EXPORT_SYMBOL(ZSTD_nextSrcSizeToDecompress);
  2287. EXPORT_SYMBOL(ZSTD_decompressContinue);
  2288. EXPORT_SYMBOL(ZSTD_nextInputType);
  2289. EXPORT_SYMBOL(ZSTD_decompressBlock);
  2290. EXPORT_SYMBOL(ZSTD_insertBlock);
  2291. MODULE_LICENSE("Dual BSD/GPL");
  2292. MODULE_DESCRIPTION("Zstd Decompressor");