lz4.c 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  1. /*
  2. LZ4 - Fast LZ compression algorithm
  3. Copyright (C) 2011-present, Yann Collet.
  4. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are
  7. met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above
  11. copyright notice, this list of conditions and the following disclaimer
  12. in the documentation and/or other materials provided with the
  13. distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. You can contact the author at :
  26. - LZ4 homepage : http://www.lz4.org
  27. - LZ4 source repository : https://github.com/lz4/lz4
  28. */
  29. /*-************************************
  30. * Tuning parameters
  31. **************************************/
  32. /*
  33. * LZ4_HEAPMODE :
  34. * Select how default compression functions will allocate memory for their hash table,
  35. * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
  36. */
  37. #include<arch/arch.h>
  38. #if ARCH(I386) || ARCH(X86_64)
  39. #if ARCH(I386) || ARCH(X86_64)
  40. #include <arch/x86_64/math/bitcount.h>
  41. #else
  42. #error Arch not supported.
  43. #endif
  44. #ifndef LZ4_HEAPMODE
  45. #define LZ4_HEAPMODE 0
  46. #endif
  47. /*
  48. * LZ4_ACCELERATION_DEFAULT :
  49. * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
  50. */
  51. #define LZ4_ACCELERATION_DEFAULT 1
  52. /*
  53. * LZ4_ACCELERATION_MAX :
  54. * Any "acceleration" value higher than this threshold
  55. * get treated as LZ4_ACCELERATION_MAX instead (fix #876)
  56. */
  57. #define LZ4_ACCELERATION_MAX 65537
  58. /*-************************************
  59. * CPU Feature Detection
  60. **************************************/
  61. /* LZ4_FORCE_MEMORY_ACCESS
  62. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  63. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  64. * The below switch allow to select different access method for improved performance.
  65. * Method 0 (default) : use `memcpy()`. Safe and portable.
  66. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  67. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  68. * Method 2 : direct access. This method is portable but violate C standard.
  69. * It can generate buggy code on targets which assembly generation depends on alignment.
  70. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  71. * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  72. * Prefer these methods in priority order (0 > 1 > 2)
  73. */
  74. #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */
  75. #if defined(__GNUC__) && \
  76. (defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__))
  77. #define LZ4_FORCE_MEMORY_ACCESS 2
  78. #elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
  79. #define LZ4_FORCE_MEMORY_ACCESS 1
  80. #endif
  81. #endif
  82. /*
  83. * LZ4_FORCE_SW_BITCOUNT
  84. * Define this parameter if your target system or compiler does not support hardware bit count
  85. */
  86. #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */
  87. #undef LZ4_FORCE_SW_BITCOUNT /* avoid double def */
  88. #define LZ4_FORCE_SW_BITCOUNT
  89. #endif
  90. /*-************************************
  91. * Dependency
  92. **************************************/
  93. /*
  94. * LZ4_SRC_INCLUDED:
  95. * Amalgamation flag, whether lz4.c is included
  96. */
  97. #ifndef LZ4_SRC_INCLUDED
  98. #define LZ4_SRC_INCLUDED 1
  99. #endif
  100. #ifndef LZ4_STATIC_LINKING_ONLY
  101. #define LZ4_STATIC_LINKING_ONLY
  102. #endif
  103. #ifndef LZ4_DISABLE_DEPRECATE_WARNINGS
  104. #define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
  105. #endif
  106. #define LZ4_STATIC_LINKING_ONLY /* LZ4_DISTANCE_MAX */
  107. #include <common/lz4.h>
  108. #include <common/glib.h>
  109. /* see also "memory routines" below */
  110. /*-************************************
  111. * Compiler Options
  112. **************************************/
  113. #if defined(_MSC_VER) && (_MSC_VER >= 1400) /* Visual Studio 2005+ */
  114. #include <intrin.h> /* only present in VS2005+ */
  115. #pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  116. #endif /* _MSC_VER */
  117. #ifndef LZ4_FORCE_INLINE
  118. #ifdef _MSC_VER /* Visual Studio */
  119. #define LZ4_FORCE_INLINE static __forceinline
  120. #else
  121. #if defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  122. #ifdef __GNUC__
  123. #define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
  124. #else
  125. #define LZ4_FORCE_INLINE static inline
  126. #endif
  127. #else
  128. #define LZ4_FORCE_INLINE static
  129. #endif /* __STDC_VERSION__ */
  130. #endif /* _MSC_VER */
  131. #endif /* LZ4_FORCE_INLINE */
  132. /* LZ4_FORCE_O2 and LZ4_FORCE_INLINE
  133. * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8,
  134. * together with a simple 8-byte copy loop as a fall-back path.
  135. * However, this optimization hurts the decompression speed by >30%,
  136. * because the execution does not go to the optimized loop
  137. * for typical compressible data, and all of the preamble checks
  138. * before going to the fall-back path become useless overhead.
  139. * This optimization happens only with the -O3 flag, and -O2 generates
  140. * a simple 8-byte copy loop.
  141. * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8
  142. * functions are annotated with __attribute__((optimize("O2"))),
  143. * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute
  144. * of LZ4_wildCopy8 does not affect the compression speed.
  145. */
  146. #if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__)
  147. #define LZ4_FORCE_O2 __attribute__((optimize("O2")))
  148. #undef LZ4_FORCE_INLINE
  149. #define LZ4_FORCE_INLINE static __inline __attribute__((optimize("O2"), always_inline))
  150. #else
  151. #define LZ4_FORCE_O2
  152. #endif
  153. #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
  154. #define expect(expr, value) (__builtin_expect((expr), (value)))
  155. #else
  156. #define expect(expr, value) (expr)
  157. #endif
  158. #ifndef likely
  159. #define likely(expr) expect((expr) != 0, 1)
  160. #endif
  161. #ifndef unlikely
  162. #define unlikely(expr) expect((expr) != 0, 0)
  163. #endif
  164. /* Should the alignment test prove unreliable, for some reason,
  165. * it can be disabled by setting LZ4_ALIGN_TEST to 0 */
  166. #ifndef LZ4_ALIGN_TEST /* can be externally provided */
  167. #define LZ4_ALIGN_TEST 1
  168. #endif
  169. /*-************************************
  170. * Memory routines
  171. **************************************/
  172. #ifdef LZ4_USER_MEMORY_FUNCTIONS
  173. /* memory management functions can be customized by user project.
  174. * Below functions must exist somewhere in the Project
  175. * and be available at link time */
  176. void *LZ4_malloc(size_t s);
  177. void *LZ4_calloc(size_t n, size_t s);
  178. void LZ4_free(void *p);
  179. #define ALLOC(s) LZ4_malloc(s)
  180. #define ALLOC_AND_ZERO(s) LZ4_calloc(1, s)
  181. #define FREEMEM(p) LZ4_free(p)
  182. #else
  183. #include <mm/slab.h> /* malloc, calloc, free */
  184. #define ALLOC(s) kmalloc(s, 0)
  185. #define ALLOC_AND_ZERO(s) kzalloc(s, 0)
  186. #define FREEMEM(p) kfree(p)
  187. #endif
  188. #include <common/string.h> /* memset, memcpy */
  189. #define MEM_INIT(p, v, s) memset((p), (v), (s))
  190. /*-************************************
  191. * Common Constants
  192. **************************************/
  193. #define MINMATCH 4
  194. #define WILDCOPYLENGTH 8
  195. #define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */
  196. #define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */
  197. #define MATCH_SAFEGUARD_DISTANCE ((2 * WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */
  198. #define FASTLOOP_SAFE_DISTANCE 64
  199. static const int LZ4_minLength = (MFLIMIT + 1);
  200. #define KB *(1 << 10)
  201. #define MB *(1 << 20)
  202. #define GB *(1U << 30)
  203. #define LZ4_DISTANCE_ABSOLUTE_MAX 65535
  204. #if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */
  205. #error "LZ4_DISTANCE_MAX is too big : must be <= 65535"
  206. #endif
  207. #define ML_BITS 4
  208. #define ML_MASK ((1U << ML_BITS) - 1)
  209. #define RUN_BITS (8 - ML_BITS)
  210. #define RUN_MASK ((1U << RUN_BITS) - 1)
  211. /*-************************************
  212. * Error detection
  213. **************************************/
  214. #if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 1)
  215. #include <assert.h>
  216. #else
  217. #ifndef assert
  218. #define assert(condition) ((void)0)
  219. #endif
  220. #endif
  221. #define LZ4_STATIC_ASSERT(c) \
  222. { \
  223. enum \
  224. { \
  225. LZ4_static_assert = 1 / (int)(!!(c)) \
  226. }; \
  227. } /* use after variable declarations */
  228. #if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 2)
  229. #include <stdio.h>
  230. static int g_debuglog_enable = 1;
  231. #define DEBUGLOG(l, ...) \
  232. { \
  233. if ((g_debuglog_enable) && (l <= LZ4_DEBUG)) \
  234. { \
  235. fprintf(stderr, __FILE__ ": "); \
  236. fprintf(stderr, __VA_ARGS__); \
  237. fprintf(stderr, " \n"); \
  238. } \
  239. }
  240. #else
  241. #define DEBUGLOG(l, ...) \
  242. { \
  243. } /* disabled */
  244. #endif
  245. static int LZ4_isAligned(const void *ptr, size_t alignment)
  246. {
  247. return ((size_t)ptr & (alignment - 1)) == 0;
  248. }
  249. /*-************************************
  250. * Types
  251. **************************************/
  252. #include <limits.h>
  253. #if defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  254. #include <DragonOS/stdint.h>
  255. typedef uint8_t BYTE;
  256. typedef uint16_t U16;
  257. typedef uint32_t U32;
  258. typedef int32_t S32;
  259. typedef uint64_t U64;
  260. typedef uintptr_t uptrval;
  261. #else
  262. #if UINT_MAX != 4294967295UL
  263. #error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4"
  264. #endif
  265. typedef unsigned char BYTE;
  266. typedef unsigned short U16;
  267. typedef unsigned int U32;
  268. typedef signed int S32;
  269. typedef unsigned long long U64;
  270. typedef size_t uptrval; /* generally true, except OpenVMS-64 */
  271. #endif
  272. #if defined(__x86_64__)
  273. typedef U64 reg_t; /* 64-bits in x32 mode */
  274. #else
  275. typedef size_t reg_t; /* 32-bits in x32 mode */
  276. #endif
  277. typedef enum
  278. {
  279. notLimited = 0,
  280. limitedOutput = 1,
  281. fillOutput = 2
  282. } limitedOutput_directive;
  283. /*-************************************
  284. * Reading and writing into memory
  285. **************************************/
  286. /**
  287. * LZ4 relies on memcpy with a constant size being inlined. In freestanding
  288. * environments, the compiler can't assume the implementation of memcpy() is
  289. * standard compliant, so it can't apply its specialized memcpy() inlining
  290. * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze
  291. * memcpy() as if it were standard compliant, so it can inline it in freestanding
  292. * environments. This is needed when decompressing the Linux Kernel, for example.
  293. */
  294. #define LZ4_memcpy(dst, src, size) memcpy(dst, src, size)
  295. static unsigned LZ4_isLittleEndian(void)
  296. {
  297. const union
  298. {
  299. U32 u;
  300. BYTE c[4];
  301. } one = {1}; /* don't use static : performance detrimental */
  302. return one.c[0];
  303. }
  304. #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS == 2)
  305. /* lie to the compiler about data alignment; use with caution */
  306. static U16 LZ4_read16(const void *memPtr) { return *(const U16 *)memPtr; }
  307. static U32 LZ4_read32(const void *memPtr) { return *(const U32 *)memPtr; }
  308. static reg_t LZ4_read_ARCH(const void *memPtr) { return *(const reg_t *)memPtr; }
  309. static void LZ4_write16(void *memPtr, U16 value) { *(U16 *)memPtr = value; }
  310. static void LZ4_write32(void *memPtr, U32 value) { *(U32 *)memPtr = value; }
  311. #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS == 1)
  312. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  313. /* currently only defined for gcc and icc */
  314. typedef union
  315. {
  316. U16 u16;
  317. U32 u32;
  318. reg_t uArch;
  319. } __attribute__((packed)) unalign;
  320. static U16 LZ4_read16(const void *ptr) { return ((const unalign *)ptr)->u16; }
  321. static U32 LZ4_read32(const void *ptr) { return ((const unalign *)ptr)->u32; }
  322. static reg_t LZ4_read_ARCH(const void *ptr) { return ((const unalign *)ptr)->uArch; }
  323. static void LZ4_write16(void *memPtr, U16 value) { ((unalign *)memPtr)->u16 = value; }
  324. static void LZ4_write32(void *memPtr, U32 value) { ((unalign *)memPtr)->u32 = value; }
  325. #else /* safe and portable access using memcpy() */
  326. static U16 LZ4_read16(const void *memPtr)
  327. {
  328. U16 val;
  329. LZ4_memcpy(&val, memPtr, sizeof(val));
  330. return val;
  331. }
  332. static U32 LZ4_read32(const void *memPtr)
  333. {
  334. U32 val;
  335. LZ4_memcpy(&val, memPtr, sizeof(val));
  336. return val;
  337. }
  338. static reg_t LZ4_read_ARCH(const void *memPtr)
  339. {
  340. reg_t val;
  341. LZ4_memcpy(&val, memPtr, sizeof(val));
  342. return val;
  343. }
  344. static void LZ4_write16(void *memPtr, U16 value)
  345. {
  346. LZ4_memcpy(memPtr, &value, sizeof(value));
  347. }
  348. static void LZ4_write32(void *memPtr, U32 value)
  349. {
  350. LZ4_memcpy(memPtr, &value, sizeof(value));
  351. }
  352. #endif /* LZ4_FORCE_MEMORY_ACCESS */
  353. static U16 LZ4_readLE16(const void *memPtr)
  354. {
  355. if (LZ4_isLittleEndian())
  356. {
  357. return LZ4_read16(memPtr);
  358. }
  359. else
  360. {
  361. const BYTE *p = (const BYTE *)memPtr;
  362. return (U16)((U16)p[0] + (p[1] << 8));
  363. }
  364. }
  365. static void LZ4_writeLE16(void *memPtr, U16 value)
  366. {
  367. if (LZ4_isLittleEndian())
  368. {
  369. LZ4_write16(memPtr, value);
  370. }
  371. else
  372. {
  373. BYTE *p = (BYTE *)memPtr;
  374. p[0] = (BYTE)value;
  375. p[1] = (BYTE)(value >> 8);
  376. }
  377. }
  378. /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
  379. LZ4_FORCE_INLINE
  380. void LZ4_wildCopy8(void *dstPtr, const void *srcPtr, void *dstEnd)
  381. {
  382. BYTE *d = (BYTE *)dstPtr;
  383. const BYTE *s = (const BYTE *)srcPtr;
  384. BYTE *const e = (BYTE *)dstEnd;
  385. do
  386. {
  387. LZ4_memcpy(d, s, 8);
  388. d += 8;
  389. s += 8;
  390. } while (d < e);
  391. }
  392. static const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};
  393. static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};
  394. #ifndef LZ4_FAST_DEC_LOOP
  395. #if defined __i386__ || defined _M_IX86 || defined __x86_64__ || defined _M_X64
  396. #define LZ4_FAST_DEC_LOOP 1
  397. #elif defined(__aarch64__) && !defined(__clang__)
  398. /* On aarch64, we disable this optimization for clang because on certain
  399. * mobile chipsets, performance is reduced with clang. For information
  400. * refer to https://github.com/lz4/lz4/pull/707 */
  401. #define LZ4_FAST_DEC_LOOP 1
  402. #else
  403. #define LZ4_FAST_DEC_LOOP 0
  404. #endif
  405. #endif
  406. #if LZ4_FAST_DEC_LOOP
  407. LZ4_FORCE_INLINE void
  408. LZ4_memcpy_using_offset_base(BYTE *dstPtr, const BYTE *srcPtr, BYTE *dstEnd, const size_t offset)
  409. {
  410. assert(srcPtr + offset == dstPtr);
  411. if (offset < 8)
  412. {
  413. LZ4_write32(dstPtr, 0); /* silence an msan warning when offset==0 */
  414. dstPtr[0] = srcPtr[0];
  415. dstPtr[1] = srcPtr[1];
  416. dstPtr[2] = srcPtr[2];
  417. dstPtr[3] = srcPtr[3];
  418. srcPtr += inc32table[offset];
  419. LZ4_memcpy(dstPtr + 4, srcPtr, 4);
  420. srcPtr -= dec64table[offset];
  421. dstPtr += 8;
  422. }
  423. else
  424. {
  425. LZ4_memcpy(dstPtr, srcPtr, 8);
  426. dstPtr += 8;
  427. srcPtr += 8;
  428. }
  429. LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);
  430. }
  431. /* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd
  432. * this version copies two times 16 bytes (instead of one time 32 bytes)
  433. * because it must be compatible with offsets >= 16. */
  434. LZ4_FORCE_INLINE void
  435. LZ4_wildCopy32(void *dstPtr, const void *srcPtr, void *dstEnd)
  436. {
  437. BYTE *d = (BYTE *)dstPtr;
  438. const BYTE *s = (const BYTE *)srcPtr;
  439. BYTE *const e = (BYTE *)dstEnd;
  440. do
  441. {
  442. LZ4_memcpy(d, s, 16);
  443. LZ4_memcpy(d + 16, s + 16, 16);
  444. d += 32;
  445. s += 32;
  446. } while (d < e);
  447. }
  448. /* LZ4_memcpy_using_offset() presumes :
  449. * - dstEnd >= dstPtr + MINMATCH
  450. * - there is at least 8 bytes available to write after dstEnd */
  451. LZ4_FORCE_INLINE void
  452. LZ4_memcpy_using_offset(BYTE *dstPtr, const BYTE *srcPtr, BYTE *dstEnd, const size_t offset)
  453. {
  454. BYTE v[8];
  455. assert(dstEnd >= dstPtr + MINMATCH);
  456. switch (offset)
  457. {
  458. case 1:
  459. MEM_INIT(v, *srcPtr, 8);
  460. break;
  461. case 2:
  462. LZ4_memcpy(v, srcPtr, 2);
  463. LZ4_memcpy(&v[2], srcPtr, 2);
  464. LZ4_memcpy(&v[4], v, 4);
  465. break;
  466. case 4:
  467. LZ4_memcpy(v, srcPtr, 4);
  468. LZ4_memcpy(&v[4], srcPtr, 4);
  469. break;
  470. default:
  471. LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);
  472. return;
  473. }
  474. LZ4_memcpy(dstPtr, v, 8);
  475. dstPtr += 8;
  476. while (dstPtr < dstEnd)
  477. {
  478. LZ4_memcpy(dstPtr, v, 8);
  479. dstPtr += 8;
  480. }
  481. }
  482. #endif
  483. /*-************************************
  484. * Common functions
  485. **************************************/
  486. static unsigned LZ4_NbCommonBytes(reg_t val)
  487. {
  488. assert(val != 0);
  489. if (LZ4_isLittleEndian())
  490. {
  491. if (sizeof(val) == 8)
  492. {
  493. #if defined(_MSC_VER) && (_MSC_VER >= 1800) && defined(_M_AMD64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  494. /* x64 CPUS without BMI support interpret `TZCNT` as `REP BSF` */
  495. return (unsigned)_tzcnt_u64(val) >> 3;
  496. #elif defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  497. unsigned long r = 0;
  498. _BitScanForward64(&r, (U64)val);
  499. return (unsigned)r >> 3;
  500. #elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
  501. ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
  502. !defined(LZ4_FORCE_SW_BITCOUNT)
  503. return (unsigned)__builtin_ctzll((U64)val) >> 3;
  504. #else
  505. const U64 m = 0x0101010101010101ULL;
  506. val ^= val - 1;
  507. return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56);
  508. #endif
  509. }
  510. else /* 32 bits */
  511. {
  512. #if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
  513. unsigned long r;
  514. _BitScanForward(&r, (U32)val);
  515. return (unsigned)r >> 3;
  516. #elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
  517. ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
  518. !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT)
  519. return (unsigned)__builtin_ctz((U32)val) >> 3;
  520. #else
  521. const U32 m = 0x01010101;
  522. return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;
  523. #endif
  524. }
  525. }
  526. else /* Big Endian CPU */
  527. {
  528. if (sizeof(val) == 8)
  529. {
  530. #if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
  531. ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
  532. !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT)
  533. return (unsigned)__clzll((U64)val) >> 3;
  534. #else
  535. #if 1
  536. /* this method is probably faster,
  537. * but adds a 128 bytes lookup table */
  538. static const unsigned char ctz7_tab[128] = {
  539. 7,
  540. 0,
  541. 1,
  542. 0,
  543. 2,
  544. 0,
  545. 1,
  546. 0,
  547. 3,
  548. 0,
  549. 1,
  550. 0,
  551. 2,
  552. 0,
  553. 1,
  554. 0,
  555. 4,
  556. 0,
  557. 1,
  558. 0,
  559. 2,
  560. 0,
  561. 1,
  562. 0,
  563. 3,
  564. 0,
  565. 1,
  566. 0,
  567. 2,
  568. 0,
  569. 1,
  570. 0,
  571. 5,
  572. 0,
  573. 1,
  574. 0,
  575. 2,
  576. 0,
  577. 1,
  578. 0,
  579. 3,
  580. 0,
  581. 1,
  582. 0,
  583. 2,
  584. 0,
  585. 1,
  586. 0,
  587. 4,
  588. 0,
  589. 1,
  590. 0,
  591. 2,
  592. 0,
  593. 1,
  594. 0,
  595. 3,
  596. 0,
  597. 1,
  598. 0,
  599. 2,
  600. 0,
  601. 1,
  602. 0,
  603. 6,
  604. 0,
  605. 1,
  606. 0,
  607. 2,
  608. 0,
  609. 1,
  610. 0,
  611. 3,
  612. 0,
  613. 1,
  614. 0,
  615. 2,
  616. 0,
  617. 1,
  618. 0,
  619. 4,
  620. 0,
  621. 1,
  622. 0,
  623. 2,
  624. 0,
  625. 1,
  626. 0,
  627. 3,
  628. 0,
  629. 1,
  630. 0,
  631. 2,
  632. 0,
  633. 1,
  634. 0,
  635. 5,
  636. 0,
  637. 1,
  638. 0,
  639. 2,
  640. 0,
  641. 1,
  642. 0,
  643. 3,
  644. 0,
  645. 1,
  646. 0,
  647. 2,
  648. 0,
  649. 1,
  650. 0,
  651. 4,
  652. 0,
  653. 1,
  654. 0,
  655. 2,
  656. 0,
  657. 1,
  658. 0,
  659. 3,
  660. 0,
  661. 1,
  662. 0,
  663. 2,
  664. 0,
  665. 1,
  666. 0,
  667. };
  668. U64 const mask = 0x0101010101010101ULL;
  669. U64 const t = (((val >> 8) - mask) | val) & mask;
  670. return ctz7_tab[(t * 0x0080402010080402ULL) >> 57];
  671. #else
  672. /* this method doesn't consume memory space like the previous one,
  673. * but it contains several branches,
  674. * that may end up slowing execution */
  675. static const U32 by32 = sizeof(val) * 4; /* 32 on 64 bits (goal), 16 on 32 bits.
  676. Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
  677. Note that this code path is never triggered in 32-bits mode. */
  678. unsigned r;
  679. if (!(val >> by32))
  680. {
  681. r = 4;
  682. }
  683. else
  684. {
  685. r = 0;
  686. val >>= by32;
  687. }
  688. if (!(val >> 16))
  689. {
  690. r += 2;
  691. val >>= 8;
  692. }
  693. else
  694. {
  695. val >>= 24;
  696. }
  697. r += (!val);
  698. return r;
  699. #endif
  700. #endif
  701. }
  702. else /* 32 bits */
  703. {
  704. #if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
  705. ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
  706. !defined(LZ4_FORCE_SW_BITCOUNT)
  707. return (unsigned)__clz((U32)val) >> 3;
  708. #else
  709. val >>= 8;
  710. val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) |
  711. (val + 0x00FF0000)) >>
  712. 24;
  713. return (unsigned)val ^ 3;
  714. #endif
  715. }
  716. }
  717. }
  718. #define STEPSIZE sizeof(reg_t)
  719. LZ4_FORCE_INLINE
  720. unsigned LZ4_count(const BYTE *pIn, const BYTE *pMatch, const BYTE *pInLimit)
  721. {
  722. const BYTE *const pStart = pIn;
  723. if (likely(pIn < pInLimit - (STEPSIZE - 1)))
  724. {
  725. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  726. if (!diff)
  727. {
  728. pIn += STEPSIZE;
  729. pMatch += STEPSIZE;
  730. }
  731. else
  732. {
  733. return LZ4_NbCommonBytes(diff);
  734. }
  735. }
  736. while (likely(pIn < pInLimit - (STEPSIZE - 1)))
  737. {
  738. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  739. if (!diff)
  740. {
  741. pIn += STEPSIZE;
  742. pMatch += STEPSIZE;
  743. continue;
  744. }
  745. pIn += LZ4_NbCommonBytes(diff);
  746. return (unsigned)(pIn - pStart);
  747. }
  748. if ((STEPSIZE == 8) && (pIn < (pInLimit - 3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn)))
  749. {
  750. pIn += 4;
  751. pMatch += 4;
  752. }
  753. if ((pIn < (pInLimit - 1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn)))
  754. {
  755. pIn += 2;
  756. pMatch += 2;
  757. }
  758. if ((pIn < pInLimit) && (*pMatch == *pIn))
  759. pIn++;
  760. return (unsigned)(pIn - pStart);
  761. }
  762. #ifndef LZ4_COMMONDEFS_ONLY
  763. /*-************************************
  764. * Local Constants
  765. **************************************/
  766. static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT - 1));
  767. static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
  768. /*-************************************
  769. * Local Structures and types
  770. **************************************/
  771. typedef enum
  772. {
  773. clearedTable = 0,
  774. byPtr,
  775. byU32,
  776. byU16
  777. } tableType_t;
  778. /**
  779. * This enum distinguishes several different modes of accessing previous
  780. * content in the stream.
  781. *
  782. * - noDict : There is no preceding content.
  783. * - withPrefix64k : Table entries up to ctx->dictSize before the current blob
  784. * blob being compressed are valid and refer to the preceding
  785. * content (of length ctx->dictSize), which is available
  786. * contiguously preceding in memory the content currently
  787. * being compressed.
  788. * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere
  789. * else in memory, starting at ctx->dictionary with length
  790. * ctx->dictSize.
  791. * - usingDictCtx : Like usingExtDict, but everything concerning the preceding
  792. * content is in a separate context, pointed to by
  793. * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table
  794. * entries in the current context that refer to positions
  795. * preceding the beginning of the current compression are
  796. * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx
  797. * ->dictSize describe the location and size of the preceding
  798. * content, and matches are found by looking in the ctx
  799. * ->dictCtx->hashTable.
  800. */
  801. typedef enum
  802. {
  803. noDict = 0,
  804. withPrefix64k,
  805. usingExtDict,
  806. usingDictCtx
  807. } dict_directive;
  808. typedef enum
  809. {
  810. noDictIssue = 0,
  811. dictSmall
  812. } dictIssue_directive;
  813. /*-************************************
  814. * Local Utils
  815. **************************************/
  816. int LZ4_versionNumber(void) { return LZ4_VERSION_NUMBER; }
  817. const char *LZ4_versionString(void) { return LZ4_VERSION_STRING; }
  818. int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  819. int LZ4_sizeofState(void) { return LZ4_STREAMSIZE; }
  820. /*-************************************
  821. * Internal Definitions used in Tests
  822. **************************************/
  823. #if defined(__cplusplus)
  824. extern "C"
  825. {
  826. #endif
  827. int LZ4_compress_forceExtDict(LZ4_stream_t *LZ4_dict, const char *source, char *dest, int srcSize);
  828. int LZ4_decompress_safe_forceExtDict(const char *source, char *dest,
  829. int compressedSize, int maxOutputSize,
  830. const void *dictStart, size_t dictSize);
  831. #if defined(__cplusplus)
  832. }
  833. #endif
  834. /*-******************************
  835. * Compression functions
  836. ********************************/
  837. LZ4_FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
  838. {
  839. if (tableType == byU16)
  840. return ((sequence * 2654435761U) >> ((MINMATCH * 8) - (LZ4_HASHLOG + 1)));
  841. else
  842. return ((sequence * 2654435761U) >> ((MINMATCH * 8) - LZ4_HASHLOG));
  843. }
  844. LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
  845. {
  846. const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG + 1 : LZ4_HASHLOG;
  847. if (LZ4_isLittleEndian())
  848. {
  849. const U64 prime5bytes = 889523592379ULL;
  850. return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
  851. }
  852. else
  853. {
  854. const U64 prime8bytes = 11400714785074694791ULL;
  855. return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
  856. }
  857. }
  858. LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void *const p, tableType_t const tableType)
  859. {
  860. if ((sizeof(reg_t) == 8) && (tableType != byU16))
  861. return LZ4_hash5(LZ4_read_ARCH(p), tableType);
  862. return LZ4_hash4(LZ4_read32(p), tableType);
  863. }
  864. LZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void *tableBase, tableType_t const tableType)
  865. {
  866. switch (tableType)
  867. {
  868. default: /* fallthrough */
  869. case clearedTable:
  870. { /* illegal! */
  871. assert(0);
  872. return;
  873. }
  874. case byPtr:
  875. {
  876. const BYTE **hashTable = (const BYTE **)tableBase;
  877. hashTable[h] = NULL;
  878. return;
  879. }
  880. case byU32:
  881. {
  882. U32 *hashTable = (U32 *)tableBase;
  883. hashTable[h] = 0;
  884. return;
  885. }
  886. case byU16:
  887. {
  888. U16 *hashTable = (U16 *)tableBase;
  889. hashTable[h] = 0;
  890. return;
  891. }
  892. }
  893. }
  894. LZ4_FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void *tableBase, tableType_t const tableType)
  895. {
  896. switch (tableType)
  897. {
  898. default: /* fallthrough */
  899. case clearedTable: /* fallthrough */
  900. case byPtr:
  901. { /* illegal! */
  902. assert(0);
  903. return;
  904. }
  905. case byU32:
  906. {
  907. U32 *hashTable = (U32 *)tableBase;
  908. hashTable[h] = idx;
  909. return;
  910. }
  911. case byU16:
  912. {
  913. U16 *hashTable = (U16 *)tableBase;
  914. assert(idx < 65536);
  915. hashTable[h] = (U16)idx;
  916. return;
  917. }
  918. }
  919. }
  920. LZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE *p, U32 h,
  921. void *tableBase, tableType_t const tableType,
  922. const BYTE *srcBase)
  923. {
  924. switch (tableType)
  925. {
  926. case clearedTable:
  927. { /* illegal! */
  928. assert(0);
  929. return;
  930. }
  931. case byPtr:
  932. {
  933. const BYTE **hashTable = (const BYTE **)tableBase;
  934. hashTable[h] = p;
  935. return;
  936. }
  937. case byU32:
  938. {
  939. U32 *hashTable = (U32 *)tableBase;
  940. hashTable[h] = (U32)(p - srcBase);
  941. return;
  942. }
  943. case byU16:
  944. {
  945. U16 *hashTable = (U16 *)tableBase;
  946. hashTable[h] = (U16)(p - srcBase);
  947. return;
  948. }
  949. }
  950. }
  951. LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE *p, void *tableBase, tableType_t tableType, const BYTE *srcBase)
  952. {
  953. U32 const h = LZ4_hashPosition(p, tableType);
  954. LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
  955. }
  956. /* LZ4_getIndexOnHash() :
  957. * Index of match position registered in hash table.
  958. * hash position must be calculated by using base+index, or dictBase+index.
  959. * Assumption 1 : only valid if tableType == byU32 or byU16.
  960. * Assumption 2 : h is presumed valid (within limits of hash table)
  961. */
  962. LZ4_FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void *tableBase, tableType_t tableType)
  963. {
  964. LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);
  965. if (tableType == byU32)
  966. {
  967. const U32 *const hashTable = (const U32 *)tableBase;
  968. assert(h < (1U << (LZ4_MEMORY_USAGE - 2)));
  969. return hashTable[h];
  970. }
  971. if (tableType == byU16)
  972. {
  973. const U16 *const hashTable = (const U16 *)tableBase;
  974. assert(h < (1U << (LZ4_MEMORY_USAGE - 1)));
  975. return hashTable[h];
  976. }
  977. assert(0);
  978. return 0; /* forbidden case */
  979. }
  980. static const BYTE *LZ4_getPositionOnHash(U32 h, const void *tableBase, tableType_t tableType, const BYTE *srcBase)
  981. {
  982. if (tableType == byPtr)
  983. {
  984. const BYTE *const *hashTable = (const BYTE *const *)tableBase;
  985. return hashTable[h];
  986. }
  987. if (tableType == byU32)
  988. {
  989. const U32 *const hashTable = (const U32 *)tableBase;
  990. return hashTable[h] + srcBase;
  991. }
  992. {
  993. const U16 *const hashTable = (const U16 *)tableBase;
  994. return hashTable[h] + srcBase;
  995. } /* default, to ensure a return */
  996. }
  997. LZ4_FORCE_INLINE const BYTE *
  998. LZ4_getPosition(const BYTE *p,
  999. const void *tableBase, tableType_t tableType,
  1000. const BYTE *srcBase)
  1001. {
  1002. U32 const h = LZ4_hashPosition(p, tableType);
  1003. return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
  1004. }
  1005. LZ4_FORCE_INLINE void
  1006. LZ4_prepareTable(LZ4_stream_t_internal *const cctx,
  1007. const int inputSize,
  1008. const tableType_t tableType)
  1009. {
  1010. /* If the table hasn't been used, it's guaranteed to be zeroed out, and is
  1011. * therefore safe to use no matter what mode we're in. Otherwise, we figure
  1012. * out if it's safe to leave as is or whether it needs to be reset.
  1013. */
  1014. if ((tableType_t)cctx->tableType != clearedTable)
  1015. {
  1016. assert(inputSize >= 0);
  1017. if ((tableType_t)cctx->tableType != tableType || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU) || ((tableType == byU32) && cctx->currentOffset > 1 GB) || tableType == byPtr || inputSize >= 4 KB)
  1018. {
  1019. DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx);
  1020. MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);
  1021. cctx->currentOffset = 0;
  1022. cctx->tableType = (U32)clearedTable;
  1023. }
  1024. else
  1025. {
  1026. DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)");
  1027. }
  1028. }
  1029. /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, is faster
  1030. * than compressing without a gap. However, compressing with
  1031. * currentOffset == 0 is faster still, so we preserve that case.
  1032. */
  1033. if (cctx->currentOffset != 0 && tableType == byU32)
  1034. {
  1035. DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset");
  1036. cctx->currentOffset += 64 KB;
  1037. }
  1038. /* Finally, clear history */
  1039. cctx->dictCtx = NULL;
  1040. cctx->dictionary = NULL;
  1041. cctx->dictSize = 0;
  1042. }
  1043. /** LZ4_compress_generic() :
  1044. * inlined, to ensure branches are decided at compilation time.
  1045. * Presumed already validated at this stage:
  1046. * - source != NULL
  1047. * - inputSize > 0
  1048. */
  1049. LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
  1050. LZ4_stream_t_internal *const cctx,
  1051. const char *const source,
  1052. char *const dest,
  1053. const int inputSize,
  1054. int *inputConsumed, /* only written when outputDirective == fillOutput */
  1055. const int maxOutputSize,
  1056. const limitedOutput_directive outputDirective,
  1057. const tableType_t tableType,
  1058. const dict_directive dictDirective,
  1059. const dictIssue_directive dictIssue,
  1060. const int acceleration)
  1061. {
  1062. int result;
  1063. const BYTE *ip = (const BYTE *)source;
  1064. U32 const startIndex = cctx->currentOffset;
  1065. const BYTE *base = (const BYTE *)source - startIndex;
  1066. const BYTE *lowLimit;
  1067. const LZ4_stream_t_internal *dictCtx = (const LZ4_stream_t_internal *)cctx->dictCtx;
  1068. const BYTE *const dictionary =
  1069. dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
  1070. const U32 dictSize =
  1071. dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
  1072. const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */
  1073. int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
  1074. U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */
  1075. const BYTE *const dictEnd = dictionary ? dictionary + dictSize : dictionary;
  1076. const BYTE *anchor = (const BYTE *)source;
  1077. const BYTE *const iend = ip + inputSize;
  1078. const BYTE *const mflimitPlusOne = iend - MFLIMIT + 1;
  1079. const BYTE *const matchlimit = iend - LASTLITERALS;
  1080. /* the dictCtx currentOffset is indexed on the start of the dictionary,
  1081. * while a dictionary in the current context precedes the currentOffset */
  1082. const BYTE *dictBase = !dictionary ? NULL : (dictDirective == usingDictCtx) ? dictionary + dictSize - dictCtx->currentOffset
  1083. : dictionary + dictSize - startIndex;
  1084. BYTE *op = (BYTE *)dest;
  1085. BYTE *const olimit = op + maxOutputSize;
  1086. U32 offset = 0;
  1087. U32 forwardH;
  1088. DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType);
  1089. assert(ip != NULL);
  1090. /* If init conditions are not met, we don't have to mark stream
  1091. * as having dirty context, since no action was taken yet */
  1092. if (outputDirective == fillOutput && maxOutputSize < 1)
  1093. {
  1094. return 0;
  1095. } /* Impossible to store anything */
  1096. if ((tableType == byU16) && (inputSize >= LZ4_64Klimit))
  1097. {
  1098. return 0;
  1099. } /* Size too large (not within 64K limit) */
  1100. if (tableType == byPtr)
  1101. assert(dictDirective == noDict); /* only supported use case with byPtr */
  1102. assert(acceleration >= 1);
  1103. lowLimit = (const BYTE *)source - (dictDirective == withPrefix64k ? dictSize : 0);
  1104. /* Update context state */
  1105. if (dictDirective == usingDictCtx)
  1106. {
  1107. /* Subsequent linked blocks can't use the dictionary. */
  1108. /* Instead, they use the block we just compressed. */
  1109. cctx->dictCtx = NULL;
  1110. cctx->dictSize = (U32)inputSize;
  1111. }
  1112. else
  1113. {
  1114. cctx->dictSize += (U32)inputSize;
  1115. }
  1116. cctx->currentOffset += (U32)inputSize;
  1117. cctx->tableType = (U32)tableType;
  1118. if (inputSize < LZ4_minLength)
  1119. goto _last_literals; /* Input too small, no compression (all literals) */
  1120. /* First Byte */
  1121. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  1122. ip++;
  1123. forwardH = LZ4_hashPosition(ip, tableType);
  1124. /* Main Loop */
  1125. for (;;)
  1126. {
  1127. const BYTE *match;
  1128. BYTE *token;
  1129. const BYTE *filledIp;
  1130. /* Find a match */
  1131. if (tableType == byPtr)
  1132. {
  1133. const BYTE *forwardIp = ip;
  1134. int step = 1;
  1135. int searchMatchNb = acceleration << LZ4_skipTrigger;
  1136. do
  1137. {
  1138. U32 const h = forwardH;
  1139. ip = forwardIp;
  1140. forwardIp += step;
  1141. step = (searchMatchNb++ >> LZ4_skipTrigger);
  1142. if (unlikely(forwardIp > mflimitPlusOne))
  1143. goto _last_literals;
  1144. assert(ip < mflimitPlusOne);
  1145. match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
  1146. forwardH = LZ4_hashPosition(forwardIp, tableType);
  1147. LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
  1148. } while ((match + LZ4_DISTANCE_MAX < ip) || (LZ4_read32(match) != LZ4_read32(ip)));
  1149. }
  1150. else
  1151. { /* byU32, byU16 */
  1152. const BYTE *forwardIp = ip;
  1153. int step = 1;
  1154. int searchMatchNb = acceleration << LZ4_skipTrigger;
  1155. do
  1156. {
  1157. U32 const h = forwardH;
  1158. U32 const current = (U32)(forwardIp - base);
  1159. U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
  1160. assert(matchIndex <= current);
  1161. assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));
  1162. ip = forwardIp;
  1163. forwardIp += step;
  1164. step = (searchMatchNb++ >> LZ4_skipTrigger);
  1165. if (unlikely(forwardIp > mflimitPlusOne))
  1166. goto _last_literals;
  1167. assert(ip < mflimitPlusOne);
  1168. if (dictDirective == usingDictCtx)
  1169. {
  1170. if (matchIndex < startIndex)
  1171. {
  1172. /* there was no match, try the dictionary */
  1173. assert(tableType == byU32);
  1174. matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
  1175. match = dictBase + matchIndex;
  1176. matchIndex += dictDelta; /* make dictCtx index comparable with current context */
  1177. lowLimit = dictionary;
  1178. }
  1179. else
  1180. {
  1181. match = base + matchIndex;
  1182. lowLimit = (const BYTE *)source;
  1183. }
  1184. }
  1185. else if (dictDirective == usingExtDict)
  1186. {
  1187. if (matchIndex < startIndex)
  1188. {
  1189. DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex);
  1190. assert(startIndex - matchIndex >= MINMATCH);
  1191. match = dictBase + matchIndex;
  1192. lowLimit = dictionary;
  1193. }
  1194. else
  1195. {
  1196. match = base + matchIndex;
  1197. lowLimit = (const BYTE *)source;
  1198. }
  1199. }
  1200. else
  1201. { /* single continuous memory segment */
  1202. match = base + matchIndex;
  1203. }
  1204. forwardH = LZ4_hashPosition(forwardIp, tableType);
  1205. LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
  1206. DEBUGLOG(7, "candidate at pos=%u (offset=%u \n", matchIndex, current - matchIndex);
  1207. if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit))
  1208. {
  1209. continue;
  1210. } /* match outside of valid area */
  1211. assert(matchIndex < current);
  1212. if (((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX)) && (matchIndex + LZ4_DISTANCE_MAX < current))
  1213. {
  1214. continue;
  1215. } /* too far */
  1216. assert((current - matchIndex) <= LZ4_DISTANCE_MAX); /* match now expected within distance */
  1217. if (LZ4_read32(match) == LZ4_read32(ip))
  1218. {
  1219. if (maybe_extMem)
  1220. offset = current - matchIndex;
  1221. break; /* match found */
  1222. }
  1223. } while (1);
  1224. }
  1225. /* Catch up */
  1226. filledIp = ip;
  1227. while (((ip > anchor) & (match > lowLimit)) && (unlikely(ip[-1] == match[-1])))
  1228. {
  1229. ip--;
  1230. match--;
  1231. }
  1232. /* Encode Literals */
  1233. {
  1234. unsigned const litLength = (unsigned)(ip - anchor);
  1235. token = op++;
  1236. if ((outputDirective == limitedOutput) && /* Check output buffer overflow */
  1237. (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength / 255) > olimit)))
  1238. {
  1239. return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
  1240. }
  1241. if ((outputDirective == fillOutput) &&
  1242. (unlikely(op + (litLength + 240) / 255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit)))
  1243. {
  1244. op--;
  1245. goto _last_literals;
  1246. }
  1247. if (litLength >= RUN_MASK)
  1248. {
  1249. int len = (int)(litLength - RUN_MASK);
  1250. *token = (RUN_MASK << ML_BITS);
  1251. for (; len >= 255; len -= 255)
  1252. *op++ = 255;
  1253. *op++ = (BYTE)len;
  1254. }
  1255. else
  1256. *token = (BYTE)(litLength << ML_BITS);
  1257. /* Copy Literals */
  1258. LZ4_wildCopy8(op, anchor, op + litLength);
  1259. op += litLength;
  1260. DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
  1261. (int)(anchor - (const BYTE *)source), litLength, (int)(ip - (const BYTE *)source));
  1262. }
  1263. _next_match:
  1264. /* at this stage, the following variables must be correctly set :
  1265. * - ip : at start of LZ operation
  1266. * - match : at start of previous pattern occurence; can be within current prefix, or within extDict
  1267. * - offset : if maybe_ext_memSegment==1 (constant)
  1268. * - lowLimit : must be == dictionary to mean "match is within extDict"; must be == source otherwise
  1269. * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written
  1270. */
  1271. if ((outputDirective == fillOutput) &&
  1272. (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))
  1273. {
  1274. /* the match was too close to the end, rewind and go to last literals */
  1275. op = token;
  1276. goto _last_literals;
  1277. }
  1278. /* Encode Offset */
  1279. if (maybe_extMem)
  1280. { /* static test */
  1281. DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE *)source));
  1282. assert(offset <= LZ4_DISTANCE_MAX && offset > 0);
  1283. LZ4_writeLE16(op, (U16)offset);
  1284. op += 2;
  1285. }
  1286. else
  1287. {
  1288. DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match));
  1289. assert(ip - match <= LZ4_DISTANCE_MAX);
  1290. LZ4_writeLE16(op, (U16)(ip - match));
  1291. op += 2;
  1292. }
  1293. /* Encode MatchLength */
  1294. {
  1295. unsigned matchCode;
  1296. if ((dictDirective == usingExtDict || dictDirective == usingDictCtx) && (lowLimit == dictionary) /* match within extDict */)
  1297. {
  1298. const BYTE *limit = ip + (dictEnd - match);
  1299. assert(dictEnd > match);
  1300. if (limit > matchlimit)
  1301. limit = matchlimit;
  1302. matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, limit);
  1303. ip += (size_t)matchCode + MINMATCH;
  1304. if (ip == limit)
  1305. {
  1306. unsigned const more = LZ4_count(limit, (const BYTE *)source, matchlimit);
  1307. matchCode += more;
  1308. ip += more;
  1309. }
  1310. DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode + MINMATCH);
  1311. }
  1312. else
  1313. {
  1314. matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, matchlimit);
  1315. ip += (size_t)matchCode + MINMATCH;
  1316. DEBUGLOG(6, " with matchLength=%u", matchCode + MINMATCH);
  1317. }
  1318. if ((outputDirective) && /* Check output buffer overflow */
  1319. (unlikely(op + (1 + LASTLITERALS) + (matchCode + 240) / 255 > olimit)))
  1320. {
  1321. if (outputDirective == fillOutput)
  1322. {
  1323. /* Match description too long : reduce it */
  1324. U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255;
  1325. ip -= matchCode - newMatchCode;
  1326. assert(newMatchCode < matchCode);
  1327. matchCode = newMatchCode;
  1328. if (unlikely(ip <= filledIp))
  1329. {
  1330. /* We have already filled up to filledIp so if ip ends up less than filledIp
  1331. * we have positions in the hash table beyond the current position. This is
  1332. * a problem if we reuse the hash table. So we have to remove these positions
  1333. * from the hash table.
  1334. */
  1335. const BYTE *ptr;
  1336. DEBUGLOG(5, "Clearing %u positions", (U32)(filledIp - ip));
  1337. for (ptr = ip; ptr <= filledIp; ++ptr)
  1338. {
  1339. U32 const h = LZ4_hashPosition(ptr, tableType);
  1340. LZ4_clearHash(h, cctx->hashTable, tableType);
  1341. }
  1342. }
  1343. }
  1344. else
  1345. {
  1346. assert(outputDirective == limitedOutput);
  1347. return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
  1348. }
  1349. }
  1350. if (matchCode >= ML_MASK)
  1351. {
  1352. *token += ML_MASK;
  1353. matchCode -= ML_MASK;
  1354. LZ4_write32(op, 0xFFFFFFFF);
  1355. while (matchCode >= 4 * 255)
  1356. {
  1357. op += 4;
  1358. LZ4_write32(op, 0xFFFFFFFF);
  1359. matchCode -= 4 * 255;
  1360. }
  1361. op += matchCode / 255;
  1362. *op++ = (BYTE)(matchCode % 255);
  1363. }
  1364. else
  1365. *token += (BYTE)(matchCode);
  1366. }
  1367. /* Ensure we have enough space for the last literals. */
  1368. assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit));
  1369. anchor = ip;
  1370. /* Test end of chunk */
  1371. if (ip >= mflimitPlusOne)
  1372. break;
  1373. /* Fill table */
  1374. LZ4_putPosition(ip - 2, cctx->hashTable, tableType, base);
  1375. /* Test next position */
  1376. if (tableType == byPtr)
  1377. {
  1378. match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
  1379. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  1380. if ((match + LZ4_DISTANCE_MAX >= ip) && (LZ4_read32(match) == LZ4_read32(ip)))
  1381. {
  1382. token = op++;
  1383. *token = 0;
  1384. goto _next_match;
  1385. }
  1386. }
  1387. else
  1388. { /* byU32, byU16 */
  1389. U32 const h = LZ4_hashPosition(ip, tableType);
  1390. U32 const current = (U32)(ip - base);
  1391. U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
  1392. assert(matchIndex < current);
  1393. if (dictDirective == usingDictCtx)
  1394. {
  1395. if (matchIndex < startIndex)
  1396. {
  1397. /* there was no match, try the dictionary */
  1398. matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
  1399. match = dictBase + matchIndex;
  1400. lowLimit = dictionary; /* required for match length counter */
  1401. matchIndex += dictDelta;
  1402. }
  1403. else
  1404. {
  1405. match = base + matchIndex;
  1406. lowLimit = (const BYTE *)source; /* required for match length counter */
  1407. }
  1408. }
  1409. else if (dictDirective == usingExtDict)
  1410. {
  1411. if (matchIndex < startIndex)
  1412. {
  1413. match = dictBase + matchIndex;
  1414. lowLimit = dictionary; /* required for match length counter */
  1415. }
  1416. else
  1417. {
  1418. match = base + matchIndex;
  1419. lowLimit = (const BYTE *)source; /* required for match length counter */
  1420. }
  1421. }
  1422. else
  1423. { /* single memory segment */
  1424. match = base + matchIndex;
  1425. }
  1426. LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
  1427. assert(matchIndex < current);
  1428. if (((dictIssue == dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) && (((tableType == byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex + LZ4_DISTANCE_MAX >= current)) && (LZ4_read32(match) == LZ4_read32(ip)))
  1429. {
  1430. token = op++;
  1431. *token = 0;
  1432. if (maybe_extMem)
  1433. offset = current - matchIndex;
  1434. DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
  1435. (int)(anchor - (const BYTE *)source), 0, (int)(ip - (const BYTE *)source));
  1436. goto _next_match;
  1437. }
  1438. }
  1439. /* Prepare next loop */
  1440. forwardH = LZ4_hashPosition(++ip, tableType);
  1441. }
  1442. _last_literals:
  1443. /* Encode Last Literals */
  1444. {
  1445. size_t lastRun = (size_t)(iend - anchor);
  1446. if ((outputDirective) && /* Check output buffer overflow */
  1447. (op + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > olimit))
  1448. {
  1449. if (outputDirective == fillOutput)
  1450. {
  1451. /* adapt lastRun to fill 'dst' */
  1452. assert(olimit >= op);
  1453. lastRun = (size_t)(olimit - op) - 1 /*token*/;
  1454. lastRun -= (lastRun + 256 - RUN_MASK) / 256; /*additional length tokens*/
  1455. }
  1456. else
  1457. {
  1458. assert(outputDirective == limitedOutput);
  1459. return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
  1460. }
  1461. }
  1462. DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun);
  1463. if (lastRun >= RUN_MASK)
  1464. {
  1465. size_t accumulator = lastRun - RUN_MASK;
  1466. *op++ = RUN_MASK << ML_BITS;
  1467. for (; accumulator >= 255; accumulator -= 255)
  1468. *op++ = 255;
  1469. *op++ = (BYTE)accumulator;
  1470. }
  1471. else
  1472. {
  1473. *op++ = (BYTE)(lastRun << ML_BITS);
  1474. }
  1475. LZ4_memcpy(op, anchor, lastRun);
  1476. ip = anchor + lastRun;
  1477. op += lastRun;
  1478. }
  1479. if (outputDirective == fillOutput)
  1480. {
  1481. *inputConsumed = (int)(((const char *)ip) - source);
  1482. }
  1483. result = (int)(((char *)op) - dest);
  1484. assert(result > 0);
  1485. DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, result);
  1486. return result;
  1487. }
  1488. /** LZ4_compress_generic() :
  1489. * inlined, to ensure branches are decided at compilation time;
  1490. * takes care of src == (NULL, 0)
  1491. * and forward the rest to LZ4_compress_generic_validated */
  1492. LZ4_FORCE_INLINE int LZ4_compress_generic(
  1493. LZ4_stream_t_internal *const cctx,
  1494. const char *const src,
  1495. char *const dst,
  1496. const int srcSize,
  1497. int *inputConsumed, /* only written when outputDirective == fillOutput */
  1498. const int dstCapacity,
  1499. const limitedOutput_directive outputDirective,
  1500. const tableType_t tableType,
  1501. const dict_directive dictDirective,
  1502. const dictIssue_directive dictIssue,
  1503. const int acceleration)
  1504. {
  1505. DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i",
  1506. srcSize, dstCapacity);
  1507. if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE)
  1508. {
  1509. return 0;
  1510. } /* Unsupported srcSize, too large (or negative) */
  1511. if (srcSize == 0)
  1512. { /* src == NULL supported if srcSize == 0 */
  1513. if (outputDirective != notLimited && dstCapacity <= 0)
  1514. return 0; /* no output, can't write anything */
  1515. DEBUGLOG(5, "Generating an empty block");
  1516. assert(outputDirective == notLimited || dstCapacity >= 1);
  1517. assert(dst != NULL);
  1518. dst[0] = 0;
  1519. if (outputDirective == fillOutput)
  1520. {
  1521. assert(inputConsumed != NULL);
  1522. *inputConsumed = 0;
  1523. }
  1524. return 1;
  1525. }
  1526. assert(src != NULL);
  1527. return LZ4_compress_generic_validated(cctx, src, dst, srcSize,
  1528. inputConsumed, /* only written into if outputDirective == fillOutput */
  1529. dstCapacity, outputDirective,
  1530. tableType, dictDirective, dictIssue, acceleration);
  1531. }
  1532. int LZ4_compress_fast_extState(void *state, const char *source, char *dest, int inputSize, int maxOutputSize, int acceleration)
  1533. {
  1534. LZ4_stream_t_internal *const ctx = &LZ4_initStream(state, sizeof(LZ4_stream_t))->internal_donotuse;
  1535. assert(ctx != NULL);
  1536. if (acceleration < 1)
  1537. acceleration = LZ4_ACCELERATION_DEFAULT;
  1538. if (acceleration > LZ4_ACCELERATION_MAX)
  1539. acceleration = LZ4_ACCELERATION_MAX;
  1540. if (maxOutputSize >= LZ4_compressBound(inputSize))
  1541. {
  1542. if (inputSize < LZ4_64Klimit)
  1543. {
  1544. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
  1545. }
  1546. else
  1547. {
  1548. const tableType_t tableType = ((sizeof(void *) == 4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1549. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
  1550. }
  1551. }
  1552. else
  1553. {
  1554. if (inputSize < LZ4_64Klimit)
  1555. {
  1556. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  1557. }
  1558. else
  1559. {
  1560. const tableType_t tableType = ((sizeof(void *) == 4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1561. return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
  1562. }
  1563. }
  1564. }
  1565. /**
  1566. * LZ4_compress_fast_extState_fastReset() :
  1567. * A variant of LZ4_compress_fast_extState().
  1568. *
  1569. * Using this variant avoids an expensive initialization step. It is only safe
  1570. * to call if the state buffer is known to be correctly initialized already
  1571. * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of
  1572. * "correctly initialized").
  1573. */
  1574. int LZ4_compress_fast_extState_fastReset(void *state, const char *src, char *dst, int srcSize, int dstCapacity, int acceleration)
  1575. {
  1576. LZ4_stream_t_internal *ctx = &((LZ4_stream_t *)state)->internal_donotuse;
  1577. if (acceleration < 1)
  1578. acceleration = LZ4_ACCELERATION_DEFAULT;
  1579. if (acceleration > LZ4_ACCELERATION_MAX)
  1580. acceleration = LZ4_ACCELERATION_MAX;
  1581. if (dstCapacity >= LZ4_compressBound(srcSize))
  1582. {
  1583. if (srcSize < LZ4_64Klimit)
  1584. {
  1585. const tableType_t tableType = byU16;
  1586. LZ4_prepareTable(ctx, srcSize, tableType);
  1587. if (ctx->currentOffset)
  1588. {
  1589. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);
  1590. }
  1591. else
  1592. {
  1593. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
  1594. }
  1595. }
  1596. else
  1597. {
  1598. const tableType_t tableType = ((sizeof(void *) == 4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1599. LZ4_prepareTable(ctx, srcSize, tableType);
  1600. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
  1601. }
  1602. }
  1603. else
  1604. {
  1605. if (srcSize < LZ4_64Klimit)
  1606. {
  1607. const tableType_t tableType = byU16;
  1608. LZ4_prepareTable(ctx, srcSize, tableType);
  1609. if (ctx->currentOffset)
  1610. {
  1611. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);
  1612. }
  1613. else
  1614. {
  1615. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
  1616. }
  1617. }
  1618. else
  1619. {
  1620. const tableType_t tableType = ((sizeof(void *) == 4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1621. LZ4_prepareTable(ctx, srcSize, tableType);
  1622. return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
  1623. }
  1624. }
  1625. }
  1626. int LZ4_compress_fast(const char *source, char *dest, int inputSize, int maxOutputSize, int acceleration)
  1627. {
  1628. int result;
  1629. #if (LZ4_HEAPMODE)
  1630. LZ4_stream_t *ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  1631. if (ctxPtr == NULL)
  1632. return 0;
  1633. #else
  1634. LZ4_stream_t ctx;
  1635. LZ4_stream_t *const ctxPtr = &ctx;
  1636. #endif
  1637. result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
  1638. #if (LZ4_HEAPMODE)
  1639. FREEMEM(ctxPtr);
  1640. #endif
  1641. return result;
  1642. }
  1643. int LZ4_compress_default(const char *src, char *dst, int srcSize, int maxOutputSize)
  1644. {
  1645. return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1);
  1646. }
  1647. /* Note!: This function leaves the stream in an unclean/broken state!
  1648. * It is not safe to subsequently use the same state with a _fastReset() or
  1649. * _continue() call without resetting it. */
  1650. static int LZ4_compress_destSize_extState(LZ4_stream_t *state, const char *src, char *dst, int *srcSizePtr, int targetDstSize)
  1651. {
  1652. void *const s = LZ4_initStream(state, sizeof(*state));
  1653. assert(s != NULL);
  1654. (void)s;
  1655. if (targetDstSize >= LZ4_compressBound(*srcSizePtr))
  1656. { /* compression success is guaranteed */
  1657. return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
  1658. }
  1659. else
  1660. {
  1661. if (*srcSizePtr < LZ4_64Klimit)
  1662. {
  1663. return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
  1664. }
  1665. else
  1666. {
  1667. tableType_t const addrMode = ((sizeof(void *) == 4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
  1668. return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);
  1669. }
  1670. }
  1671. }
  1672. int LZ4_compress_destSize(const char *src, char *dst, int *srcSizePtr, int targetDstSize)
  1673. {
  1674. #if (LZ4_HEAPMODE)
  1675. LZ4_stream_t *ctx = (LZ4_stream_t *)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  1676. if (ctx == NULL)
  1677. return 0;
  1678. #else
  1679. LZ4_stream_t ctxBody;
  1680. LZ4_stream_t *ctx = &ctxBody;
  1681. #endif
  1682. int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
  1683. #if (LZ4_HEAPMODE)
  1684. FREEMEM(ctx);
  1685. #endif
  1686. return result;
  1687. }
  1688. /*-******************************
  1689. * Streaming functions
  1690. ********************************/
  1691. LZ4_stream_t *LZ4_createStream(void)
  1692. {
  1693. LZ4_stream_t *const lz4s = (LZ4_stream_t *)ALLOC(sizeof(LZ4_stream_t));
  1694. LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
  1695. DEBUGLOG(4, "LZ4_createStream %p", lz4s);
  1696. if (lz4s == NULL)
  1697. return NULL;
  1698. LZ4_initStream(lz4s, sizeof(*lz4s));
  1699. return lz4s;
  1700. }
  1701. static size_t LZ4_stream_t_alignment(void)
  1702. {
  1703. #if LZ4_ALIGN_TEST
  1704. typedef struct
  1705. {
  1706. char c;
  1707. LZ4_stream_t t;
  1708. } t_a;
  1709. return sizeof(t_a) - sizeof(LZ4_stream_t);
  1710. #else
  1711. return 1; /* effectively disabled */
  1712. #endif
  1713. }
  1714. LZ4_stream_t *LZ4_initStream(void *buffer, size_t size)
  1715. {
  1716. DEBUGLOG(5, "LZ4_initStream");
  1717. if (buffer == NULL)
  1718. {
  1719. return NULL;
  1720. }
  1721. if (size < sizeof(LZ4_stream_t))
  1722. {
  1723. return NULL;
  1724. }
  1725. if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment()))
  1726. return NULL;
  1727. MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal));
  1728. return (LZ4_stream_t *)buffer;
  1729. }
  1730. /* resetStream is now deprecated,
  1731. * prefer initStream() which is more general */
  1732. void LZ4_resetStream(LZ4_stream_t *LZ4_stream)
  1733. {
  1734. DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream);
  1735. MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t_internal));
  1736. }
  1737. void LZ4_resetStream_fast(LZ4_stream_t *ctx)
  1738. {
  1739. LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32);
  1740. }
  1741. int LZ4_freeStream(LZ4_stream_t *LZ4_stream)
  1742. {
  1743. if (!LZ4_stream)
  1744. return 0; /* support free on NULL */
  1745. DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream);
  1746. FREEMEM(LZ4_stream);
  1747. return (0);
  1748. }
  1749. #define HASH_UNIT sizeof(reg_t)
  1750. int LZ4_loadDict(LZ4_stream_t *LZ4_dict, const char *dictionary, int dictSize)
  1751. {
  1752. LZ4_stream_t_internal *dict = &LZ4_dict->internal_donotuse;
  1753. const tableType_t tableType = byU32;
  1754. const BYTE *p = (const BYTE *)dictionary;
  1755. const BYTE *const dictEnd = p + dictSize;
  1756. const BYTE *base;
  1757. DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
  1758. /* It's necessary to reset the context,
  1759. * and not just continue it with prepareTable()
  1760. * to avoid any risk of generating overflowing matchIndex
  1761. * when compressing using this dictionary */
  1762. LZ4_resetStream(LZ4_dict);
  1763. /* We always increment the offset by 64 KB, since, if the dict is longer,
  1764. * we truncate it to the last 64k, and if it's shorter, we still want to
  1765. * advance by a whole window length so we can provide the guarantee that
  1766. * there are only valid offsets in the window, which allows an optimization
  1767. * in LZ4_compress_fast_continue() where it uses noDictIssue even when the
  1768. * dictionary isn't a full 64k. */
  1769. dict->currentOffset += 64 KB;
  1770. if (dictSize < (int)HASH_UNIT)
  1771. {
  1772. return 0;
  1773. }
  1774. if ((dictEnd - p) > 64 KB)
  1775. p = dictEnd - 64 KB;
  1776. base = dictEnd - dict->currentOffset;
  1777. dict->dictionary = p;
  1778. dict->dictSize = (U32)(dictEnd - p);
  1779. dict->tableType = (U32)tableType;
  1780. while (p <= dictEnd - HASH_UNIT)
  1781. {
  1782. LZ4_putPosition(p, dict->hashTable, tableType, base);
  1783. p += 3;
  1784. }
  1785. return (int)dict->dictSize;
  1786. }
  1787. void LZ4_attach_dictionary(LZ4_stream_t *workingStream, const LZ4_stream_t *dictionaryStream)
  1788. {
  1789. const LZ4_stream_t_internal *dictCtx = dictionaryStream == NULL ? NULL : &(dictionaryStream->internal_donotuse);
  1790. DEBUGLOG(4, "LZ4_attach_dictionary (%p, %p, size %u)",
  1791. workingStream, dictionaryStream,
  1792. dictCtx != NULL ? dictCtx->dictSize : 0);
  1793. if (dictCtx != NULL)
  1794. {
  1795. /* If the current offset is zero, we will never look in the
  1796. * external dictionary context, since there is no value a table
  1797. * entry can take that indicate a miss. In that case, we need
  1798. * to bump the offset to something non-zero.
  1799. */
  1800. if (workingStream->internal_donotuse.currentOffset == 0)
  1801. {
  1802. workingStream->internal_donotuse.currentOffset = 64 KB;
  1803. }
  1804. /* Don't actually attach an empty dictionary.
  1805. */
  1806. if (dictCtx->dictSize == 0)
  1807. {
  1808. dictCtx = NULL;
  1809. }
  1810. }
  1811. workingStream->internal_donotuse.dictCtx = dictCtx;
  1812. }
  1813. static void LZ4_renormDictT(LZ4_stream_t_internal *LZ4_dict, int nextSize)
  1814. {
  1815. assert(nextSize >= 0);
  1816. if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000)
  1817. { /* potential ptrdiff_t overflow (32-bits mode) */
  1818. /* rescale hash table */
  1819. U32 const delta = LZ4_dict->currentOffset - 64 KB;
  1820. const BYTE *dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
  1821. int i;
  1822. DEBUGLOG(4, "LZ4_renormDictT");
  1823. for (i = 0; i < LZ4_HASH_SIZE_U32; i++)
  1824. {
  1825. if (LZ4_dict->hashTable[i] < delta)
  1826. LZ4_dict->hashTable[i] = 0;
  1827. else
  1828. LZ4_dict->hashTable[i] -= delta;
  1829. }
  1830. LZ4_dict->currentOffset = 64 KB;
  1831. if (LZ4_dict->dictSize > 64 KB)
  1832. LZ4_dict->dictSize = 64 KB;
  1833. LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
  1834. }
  1835. }
  1836. int LZ4_compress_fast_continue(LZ4_stream_t *LZ4_stream,
  1837. const char *source, char *dest,
  1838. int inputSize, int maxOutputSize,
  1839. int acceleration)
  1840. {
  1841. const tableType_t tableType = byU32;
  1842. LZ4_stream_t_internal *streamPtr = &LZ4_stream->internal_donotuse;
  1843. const BYTE *dictEnd = streamPtr->dictionary + streamPtr->dictSize;
  1844. DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize);
  1845. LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */
  1846. if (acceleration < 1)
  1847. acceleration = LZ4_ACCELERATION_DEFAULT;
  1848. if (acceleration > LZ4_ACCELERATION_MAX)
  1849. acceleration = LZ4_ACCELERATION_MAX;
  1850. /* invalidate tiny dictionaries */
  1851. if ((streamPtr->dictSize - 1 < 4 - 1) /* intentional underflow */
  1852. && (dictEnd != (const BYTE *)source))
  1853. {
  1854. DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary);
  1855. streamPtr->dictSize = 0;
  1856. streamPtr->dictionary = (const BYTE *)source;
  1857. dictEnd = (const BYTE *)source;
  1858. }
  1859. /* Check overlapping input/dictionary space */
  1860. {
  1861. const BYTE *sourceEnd = (const BYTE *)source + inputSize;
  1862. if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd))
  1863. {
  1864. streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
  1865. if (streamPtr->dictSize > 64 KB)
  1866. streamPtr->dictSize = 64 KB;
  1867. if (streamPtr->dictSize < 4)
  1868. streamPtr->dictSize = 0;
  1869. streamPtr->dictionary = dictEnd - streamPtr->dictSize;
  1870. }
  1871. }
  1872. /* prefix mode : source data follows dictionary */
  1873. if (dictEnd == (const BYTE *)source)
  1874. {
  1875. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  1876. return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration);
  1877. else
  1878. return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration);
  1879. }
  1880. /* external dictionary mode */
  1881. {
  1882. int result;
  1883. if (streamPtr->dictCtx)
  1884. {
  1885. /* We depend here on the fact that dictCtx'es (produced by
  1886. * LZ4_loadDict) guarantee that their tables contain no references
  1887. * to offsets between dictCtx->currentOffset - 64 KB and
  1888. * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe
  1889. * to use noDictIssue even when the dict isn't a full 64 KB.
  1890. */
  1891. if (inputSize > 4 KB)
  1892. {
  1893. /* For compressing large blobs, it is faster to pay the setup
  1894. * cost to copy the dictionary's tables into the active context,
  1895. * so that the compression loop is only looking into one table.
  1896. */
  1897. LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr));
  1898. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
  1899. }
  1900. else
  1901. {
  1902. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);
  1903. }
  1904. }
  1905. else
  1906. {
  1907. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  1908. {
  1909. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);
  1910. }
  1911. else
  1912. {
  1913. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
  1914. }
  1915. }
  1916. streamPtr->dictionary = (const BYTE *)source;
  1917. streamPtr->dictSize = (U32)inputSize;
  1918. return result;
  1919. }
  1920. }
  1921. /* Hidden debug function, to force-test external dictionary mode */
  1922. int LZ4_compress_forceExtDict(LZ4_stream_t *LZ4_dict, const char *source, char *dest, int srcSize)
  1923. {
  1924. LZ4_stream_t_internal *streamPtr = &LZ4_dict->internal_donotuse;
  1925. int result;
  1926. LZ4_renormDictT(streamPtr, srcSize);
  1927. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  1928. {
  1929. result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);
  1930. }
  1931. else
  1932. {
  1933. result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
  1934. }
  1935. streamPtr->dictionary = (const BYTE *)source;
  1936. streamPtr->dictSize = (U32)srcSize;
  1937. return result;
  1938. }
  1939. /*! LZ4_saveDict() :
  1940. * If previously compressed data block is not guaranteed to remain available at its memory location,
  1941. * save it into a safer place (char* safeBuffer).
  1942. * Note : you don't need to call LZ4_loadDict() afterwards,
  1943. * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().
  1944. * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
  1945. */
  1946. int LZ4_saveDict(LZ4_stream_t *LZ4_dict, char *safeBuffer, int dictSize)
  1947. {
  1948. LZ4_stream_t_internal *const dict = &LZ4_dict->internal_donotuse;
  1949. const BYTE *const previousDictEnd = dict->dictionary + dict->dictSize;
  1950. if ((U32)dictSize > 64 KB)
  1951. {
  1952. dictSize = 64 KB;
  1953. } /* useless to define a dictionary > 64 KB */
  1954. if ((U32)dictSize > dict->dictSize)
  1955. {
  1956. dictSize = (int)dict->dictSize;
  1957. }
  1958. if (safeBuffer == NULL)
  1959. assert(dictSize == 0);
  1960. if (dictSize > 0)
  1961. memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
  1962. dict->dictionary = (const BYTE *)safeBuffer;
  1963. dict->dictSize = (U32)dictSize;
  1964. return dictSize;
  1965. }
  1966. /*-*******************************
  1967. * Decompression functions
  1968. ********************************/
  1969. typedef enum
  1970. {
  1971. endOnOutputSize = 0,
  1972. endOnInputSize = 1
  1973. } endCondition_directive;
  1974. typedef enum
  1975. {
  1976. decode_full_block = 0,
  1977. partial_decode = 1
  1978. } earlyEnd_directive;
  1979. #undef MIN
  1980. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  1981. /* Read the variable-length literal or match length.
  1982. *
  1983. * ip - pointer to use as input.
  1984. * lencheck - end ip. Return an error if ip advances >= lencheck.
  1985. * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so.
  1986. * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so.
  1987. * error (output) - error code. Should be set to 0 before call.
  1988. */
  1989. typedef enum
  1990. {
  1991. loop_error = -2,
  1992. initial_error = -1,
  1993. ok = 0
  1994. } variable_length_error;
  1995. LZ4_FORCE_INLINE unsigned
  1996. read_variable_length(const BYTE **ip, const BYTE *lencheck,
  1997. int loop_check, int initial_check,
  1998. variable_length_error *error)
  1999. {
  2000. U32 length = 0;
  2001. U32 s;
  2002. if (initial_check && unlikely((*ip) >= lencheck))
  2003. { /* overflow detection */
  2004. *error = initial_error;
  2005. return length;
  2006. }
  2007. do
  2008. {
  2009. s = **ip;
  2010. (*ip)++;
  2011. length += s;
  2012. if (loop_check && unlikely((*ip) >= lencheck))
  2013. { /* overflow detection */
  2014. *error = loop_error;
  2015. return length;
  2016. }
  2017. } while (s == 255);
  2018. return length;
  2019. }
  2020. /*! LZ4_decompress_generic() :
  2021. * This generic decompression function covers all use cases.
  2022. * It shall be instantiated several times, using different sets of directives.
  2023. * Note that it is important for performance that this function really get inlined,
  2024. * in order to remove useless branches during compilation optimization.
  2025. */
  2026. LZ4_FORCE_INLINE int
  2027. LZ4_decompress_generic(
  2028. const char *const src,
  2029. char *const dst,
  2030. int srcSize,
  2031. int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
  2032. endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */
  2033. earlyEnd_directive partialDecoding, /* full, partial */
  2034. dict_directive dict, /* noDict, withPrefix64k, usingExtDict */
  2035. const BYTE *const lowPrefix, /* always <= dst, == dst when no prefix */
  2036. const BYTE *const dictStart, /* only if dict==usingExtDict */
  2037. const size_t dictSize /* note : = 0 if noDict */
  2038. )
  2039. {
  2040. if (src == NULL)
  2041. {
  2042. return -1;
  2043. }
  2044. {
  2045. const BYTE *ip = (const BYTE *)src;
  2046. const BYTE *const iend = ip + srcSize;
  2047. BYTE *op = (BYTE *)dst;
  2048. BYTE *const oend = op + outputSize;
  2049. BYTE *cpy;
  2050. const BYTE *const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;
  2051. const int safeDecode = (endOnInput == endOnInputSize);
  2052. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  2053. /* Set up the "end" pointers for the shortcut. */
  2054. const BYTE *const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
  2055. const BYTE *const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
  2056. const BYTE *match;
  2057. size_t offset;
  2058. unsigned token;
  2059. size_t length;
  2060. DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
  2061. /* Special cases */
  2062. assert(lowPrefix <= op);
  2063. if ((endOnInput) && (unlikely(outputSize == 0)))
  2064. {
  2065. /* Empty output buffer */
  2066. if (partialDecoding)
  2067. return 0;
  2068. return ((srcSize == 1) && (*ip == 0)) ? 0 : -1;
  2069. }
  2070. if ((!endOnInput) && (unlikely(outputSize == 0)))
  2071. {
  2072. return (*ip == 0 ? 1 : -1);
  2073. }
  2074. if ((endOnInput) && unlikely(srcSize == 0))
  2075. {
  2076. return -1;
  2077. }
  2078. /* Currently the fast loop shows a regression on qualcomm arm chips. */
  2079. #if LZ4_FAST_DEC_LOOP
  2080. if ((oend - op) < FASTLOOP_SAFE_DISTANCE)
  2081. {
  2082. DEBUGLOG(6, "skip fast decode loop");
  2083. goto safe_decode;
  2084. }
  2085. /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */
  2086. while (1)
  2087. {
  2088. /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */
  2089. assert(oend - op >= FASTLOOP_SAFE_DISTANCE);
  2090. if (endOnInput)
  2091. {
  2092. assert(ip < iend);
  2093. }
  2094. token = *ip++;
  2095. length = token >> ML_BITS; /* literal length */
  2096. assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
  2097. /* decode literal length */
  2098. if (length == RUN_MASK)
  2099. {
  2100. variable_length_error error = ok;
  2101. length += read_variable_length(&ip, iend - RUN_MASK, (int)endOnInput, (int)endOnInput, &error);
  2102. if (error == initial_error)
  2103. {
  2104. goto _output_error;
  2105. }
  2106. if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)(op)))
  2107. {
  2108. goto _output_error;
  2109. } /* overflow detection */
  2110. if ((safeDecode) && unlikely((uptrval)(ip) + length < (uptrval)(ip)))
  2111. {
  2112. goto _output_error;
  2113. } /* overflow detection */
  2114. /* copy literals */
  2115. cpy = op + length;
  2116. LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
  2117. if (endOnInput)
  2118. { /* LZ4_decompress_safe() */
  2119. if ((cpy > oend - 32) || (ip + length > iend - 32))
  2120. {
  2121. goto safe_literal_copy;
  2122. }
  2123. LZ4_wildCopy32(op, ip, cpy);
  2124. }
  2125. else
  2126. { /* LZ4_decompress_fast() */
  2127. if (cpy > oend - 8)
  2128. {
  2129. goto safe_literal_copy;
  2130. }
  2131. LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :
  2132. * it doesn't know input length, and only relies on end-of-block properties */
  2133. }
  2134. ip += length;
  2135. op = cpy;
  2136. }
  2137. else
  2138. {
  2139. cpy = op + length;
  2140. if (endOnInput)
  2141. { /* LZ4_decompress_safe() */
  2142. DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
  2143. /* We don't need to check oend, since we check it once for each loop below */
  2144. if (ip > iend - (16 + 1 /*max lit + offset + nextToken*/))
  2145. {
  2146. goto safe_literal_copy;
  2147. }
  2148. /* Literals can only be 14, but hope compilers optimize if we copy by a register size */
  2149. LZ4_memcpy(op, ip, 16);
  2150. }
  2151. else
  2152. { /* LZ4_decompress_fast() */
  2153. /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :
  2154. * it doesn't know input length, and relies on end-of-block properties */
  2155. LZ4_memcpy(op, ip, 8);
  2156. if (length > 8)
  2157. {
  2158. LZ4_memcpy(op + 8, ip + 8, 8);
  2159. }
  2160. }
  2161. ip += length;
  2162. op = cpy;
  2163. }
  2164. /* get offset */
  2165. offset = LZ4_readLE16(ip);
  2166. ip += 2;
  2167. match = op - offset;
  2168. assert(match <= op);
  2169. /* get matchlength */
  2170. length = token & ML_MASK;
  2171. if (length == ML_MASK)
  2172. {
  2173. variable_length_error error = ok;
  2174. if ((checkOffset) && (unlikely(match + dictSize < lowPrefix)))
  2175. {
  2176. goto _output_error;
  2177. } /* Error : offset outside buffers */
  2178. length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error);
  2179. if (error != ok)
  2180. {
  2181. goto _output_error;
  2182. }
  2183. if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)op))
  2184. {
  2185. goto _output_error;
  2186. } /* overflow detection */
  2187. length += MINMATCH;
  2188. if (op + length >= oend - FASTLOOP_SAFE_DISTANCE)
  2189. {
  2190. goto safe_match_copy;
  2191. }
  2192. }
  2193. else
  2194. {
  2195. length += MINMATCH;
  2196. if (op + length >= oend - FASTLOOP_SAFE_DISTANCE)
  2197. {
  2198. goto safe_match_copy;
  2199. }
  2200. /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */
  2201. if ((dict == withPrefix64k) || (match >= lowPrefix))
  2202. {
  2203. if (offset >= 8)
  2204. {
  2205. assert(match >= lowPrefix);
  2206. assert(match <= op);
  2207. assert(op + 18 <= oend);
  2208. LZ4_memcpy(op, match, 8);
  2209. LZ4_memcpy(op + 8, match + 8, 8);
  2210. LZ4_memcpy(op + 16, match + 16, 2);
  2211. op += length;
  2212. continue;
  2213. }
  2214. }
  2215. }
  2216. if (checkOffset && (unlikely(match + dictSize < lowPrefix)))
  2217. {
  2218. goto _output_error;
  2219. } /* Error : offset outside buffers */
  2220. /* match starting within external dictionary */
  2221. if ((dict == usingExtDict) && (match < lowPrefix))
  2222. {
  2223. if (unlikely(op + length > oend - LASTLITERALS))
  2224. {
  2225. if (partialDecoding)
  2226. {
  2227. DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");
  2228. length = MIN(length, (size_t)(oend - op));
  2229. }
  2230. else
  2231. {
  2232. goto _output_error; /* end-of-block condition violated */
  2233. }
  2234. }
  2235. if (length <= (size_t)(lowPrefix - match))
  2236. {
  2237. /* match fits entirely within external dictionary : just copy */
  2238. memmove(op, dictEnd - (lowPrefix - match), length);
  2239. op += length;
  2240. }
  2241. else
  2242. {
  2243. /* match stretches into both external dictionary and current block */
  2244. size_t const copySize = (size_t)(lowPrefix - match);
  2245. size_t const restSize = length - copySize;
  2246. LZ4_memcpy(op, dictEnd - copySize, copySize);
  2247. op += copySize;
  2248. if (restSize > (size_t)(op - lowPrefix))
  2249. { /* overlap copy */
  2250. BYTE *const endOfMatch = op + restSize;
  2251. const BYTE *copyFrom = lowPrefix;
  2252. while (op < endOfMatch)
  2253. {
  2254. *op++ = *copyFrom++;
  2255. }
  2256. }
  2257. else
  2258. {
  2259. LZ4_memcpy(op, lowPrefix, restSize);
  2260. op += restSize;
  2261. }
  2262. }
  2263. continue;
  2264. }
  2265. /* copy match within block */
  2266. cpy = op + length;
  2267. assert((op <= oend) && (oend - op >= 32));
  2268. if (unlikely(offset < 16))
  2269. {
  2270. LZ4_memcpy_using_offset(op, match, cpy, offset);
  2271. }
  2272. else
  2273. {
  2274. LZ4_wildCopy32(op, match, cpy);
  2275. }
  2276. op = cpy; /* wildcopy correction */
  2277. }
  2278. safe_decode:
  2279. #endif
  2280. /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */
  2281. while (1)
  2282. {
  2283. token = *ip++;
  2284. length = token >> ML_BITS; /* literal length */
  2285. assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
  2286. /* A two-stage shortcut for the most common case:
  2287. * 1) If the literal length is 0..14, and there is enough space,
  2288. * enter the shortcut and copy 16 bytes on behalf of the literals
  2289. * (in the fast mode, only 8 bytes can be safely copied this way).
  2290. * 2) Further if the match length is 4..18, copy 18 bytes in a similar
  2291. * manner; but we ensure that there's enough space in the output for
  2292. * those 18 bytes earlier, upon entering the shortcut (in other words,
  2293. * there is a combined check for both stages).
  2294. */
  2295. if ((endOnInput ? length != RUN_MASK : length <= 8)
  2296. /* strictly "less than" on input, to re-enter the loop with at least one byte */
  2297. && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)))
  2298. {
  2299. /* Copy the literals */
  2300. LZ4_memcpy(op, ip, endOnInput ? 16 : 8);
  2301. op += length;
  2302. ip += length;
  2303. /* The second stage: prepare for match copying, decode full info.
  2304. * If it doesn't work out, the info won't be wasted. */
  2305. length = token & ML_MASK; /* match length */
  2306. offset = LZ4_readLE16(ip);
  2307. ip += 2;
  2308. match = op - offset;
  2309. assert(match <= op); /* check overflow */
  2310. /* Do not deal with overlapping matches. */
  2311. if ((length != ML_MASK) && (offset >= 8) && (dict == withPrefix64k || match >= lowPrefix))
  2312. {
  2313. /* Copy the match. */
  2314. LZ4_memcpy(op + 0, match + 0, 8);
  2315. LZ4_memcpy(op + 8, match + 8, 8);
  2316. LZ4_memcpy(op + 16, match + 16, 2);
  2317. op += length + MINMATCH;
  2318. /* Both stages worked, load the next token. */
  2319. continue;
  2320. }
  2321. /* The second stage didn't work out, but the info is ready.
  2322. * Propel it right to the point of match copying. */
  2323. goto _copy_match;
  2324. }
  2325. /* decode literal length */
  2326. if (length == RUN_MASK)
  2327. {
  2328. variable_length_error error = ok;
  2329. length += read_variable_length(&ip, iend - RUN_MASK, (int)endOnInput, (int)endOnInput, &error);
  2330. if (error == initial_error)
  2331. {
  2332. goto _output_error;
  2333. }
  2334. if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)(op)))
  2335. {
  2336. goto _output_error;
  2337. } /* overflow detection */
  2338. if ((safeDecode) && unlikely((uptrval)(ip) + length < (uptrval)(ip)))
  2339. {
  2340. goto _output_error;
  2341. } /* overflow detection */
  2342. }
  2343. /* copy literals */
  2344. cpy = op + length;
  2345. #if LZ4_FAST_DEC_LOOP
  2346. safe_literal_copy:
  2347. #endif
  2348. LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
  2349. if (((endOnInput) && ((cpy > oend - MFLIMIT) || (ip + length > iend - (2 + 1 + LASTLITERALS)))) || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH)))
  2350. {
  2351. /* We've either hit the input parsing restriction or the output parsing restriction.
  2352. * In the normal scenario, decoding a full block, it must be the last sequence,
  2353. * otherwise it's an error (invalid input or dimensions).
  2354. * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow.
  2355. */
  2356. if (partialDecoding)
  2357. {
  2358. /* Since we are partial decoding we may be in this block because of the output parsing
  2359. * restriction, which is not valid since the output buffer is allowed to be undersized.
  2360. */
  2361. assert(endOnInput);
  2362. DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end")
  2363. DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length);
  2364. DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op));
  2365. DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip));
  2366. /* Finishing in the middle of a literals segment,
  2367. * due to lack of input.
  2368. */
  2369. if (ip + length > iend)
  2370. {
  2371. length = (size_t)(iend - ip);
  2372. cpy = op + length;
  2373. }
  2374. /* Finishing in the middle of a literals segment,
  2375. * due to lack of output space.
  2376. */
  2377. if (cpy > oend)
  2378. {
  2379. cpy = oend;
  2380. assert(op <= oend);
  2381. length = (size_t)(oend - op);
  2382. }
  2383. }
  2384. else
  2385. {
  2386. /* We must be on the last sequence because of the parsing limitations so check
  2387. * that we exactly regenerate the original size (must be exact when !endOnInput).
  2388. */
  2389. if ((!endOnInput) && (cpy != oend))
  2390. {
  2391. goto _output_error;
  2392. }
  2393. /* We must be on the last sequence (or invalid) because of the parsing limitations
  2394. * so check that we exactly consume the input and don't overrun the output buffer.
  2395. */
  2396. if ((endOnInput) && ((ip + length != iend) || (cpy > oend)))
  2397. {
  2398. DEBUGLOG(6, "should have been last run of literals")
  2399. DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip + length, iend);
  2400. DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend);
  2401. goto _output_error;
  2402. }
  2403. }
  2404. memmove(op, ip, length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */
  2405. ip += length;
  2406. op += length;
  2407. /* Necessarily EOF when !partialDecoding.
  2408. * When partialDecoding, it is EOF if we've either
  2409. * filled the output buffer or
  2410. * can't proceed with reading an offset for following match.
  2411. */
  2412. if (!partialDecoding || (cpy == oend) || (ip >= (iend - 2)))
  2413. {
  2414. break;
  2415. }
  2416. }
  2417. else
  2418. {
  2419. LZ4_wildCopy8(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */
  2420. ip += length;
  2421. op = cpy;
  2422. }
  2423. /* get offset */
  2424. offset = LZ4_readLE16(ip);
  2425. ip += 2;
  2426. match = op - offset;
  2427. /* get matchlength */
  2428. length = token & ML_MASK;
  2429. _copy_match:
  2430. if (length == ML_MASK)
  2431. {
  2432. variable_length_error error = ok;
  2433. length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error);
  2434. if (error != ok)
  2435. goto _output_error;
  2436. if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)op))
  2437. goto _output_error; /* overflow detection */
  2438. }
  2439. length += MINMATCH;
  2440. #if LZ4_FAST_DEC_LOOP
  2441. safe_match_copy:
  2442. #endif
  2443. if ((checkOffset) && (unlikely(match + dictSize < lowPrefix)))
  2444. goto _output_error; /* Error : offset outside buffers */
  2445. /* match starting within external dictionary */
  2446. if ((dict == usingExtDict) && (match < lowPrefix))
  2447. {
  2448. if (unlikely(op + length > oend - LASTLITERALS))
  2449. {
  2450. if (partialDecoding)
  2451. length = MIN(length, (size_t)(oend - op));
  2452. else
  2453. goto _output_error; /* doesn't respect parsing restriction */
  2454. }
  2455. if (length <= (size_t)(lowPrefix - match))
  2456. {
  2457. /* match fits entirely within external dictionary : just copy */
  2458. memmove(op, dictEnd - (lowPrefix - match), length);
  2459. op += length;
  2460. }
  2461. else
  2462. {
  2463. /* match stretches into both external dictionary and current block */
  2464. size_t const copySize = (size_t)(lowPrefix - match);
  2465. size_t const restSize = length - copySize;
  2466. LZ4_memcpy(op, dictEnd - copySize, copySize);
  2467. op += copySize;
  2468. if (restSize > (size_t)(op - lowPrefix))
  2469. { /* overlap copy */
  2470. BYTE *const endOfMatch = op + restSize;
  2471. const BYTE *copyFrom = lowPrefix;
  2472. while (op < endOfMatch)
  2473. *op++ = *copyFrom++;
  2474. }
  2475. else
  2476. {
  2477. LZ4_memcpy(op, lowPrefix, restSize);
  2478. op += restSize;
  2479. }
  2480. }
  2481. continue;
  2482. }
  2483. assert(match >= lowPrefix);
  2484. /* copy match within block */
  2485. cpy = op + length;
  2486. /* partialDecoding : may end anywhere within the block */
  2487. assert(op <= oend);
  2488. if (partialDecoding && (cpy > oend - MATCH_SAFEGUARD_DISTANCE))
  2489. {
  2490. size_t const mlen = MIN(length, (size_t)(oend - op));
  2491. const BYTE *const matchEnd = match + mlen;
  2492. BYTE *const copyEnd = op + mlen;
  2493. if (matchEnd > op)
  2494. { /* overlap copy */
  2495. while (op < copyEnd)
  2496. {
  2497. *op++ = *match++;
  2498. }
  2499. }
  2500. else
  2501. {
  2502. LZ4_memcpy(op, match, mlen);
  2503. }
  2504. op = copyEnd;
  2505. if (op == oend)
  2506. {
  2507. break;
  2508. }
  2509. continue;
  2510. }
  2511. if (unlikely(offset < 8))
  2512. {
  2513. LZ4_write32(op, 0); /* silence msan warning when offset==0 */
  2514. op[0] = match[0];
  2515. op[1] = match[1];
  2516. op[2] = match[2];
  2517. op[3] = match[3];
  2518. match += inc32table[offset];
  2519. LZ4_memcpy(op + 4, match, 4);
  2520. match -= dec64table[offset];
  2521. }
  2522. else
  2523. {
  2524. LZ4_memcpy(op, match, 8);
  2525. match += 8;
  2526. }
  2527. op += 8;
  2528. if (unlikely(cpy > oend - MATCH_SAFEGUARD_DISTANCE))
  2529. {
  2530. BYTE *const oCopyLimit = oend - (WILDCOPYLENGTH - 1);
  2531. if (cpy > oend - LASTLITERALS)
  2532. {
  2533. goto _output_error;
  2534. } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
  2535. if (op < oCopyLimit)
  2536. {
  2537. LZ4_wildCopy8(op, match, oCopyLimit);
  2538. match += oCopyLimit - op;
  2539. op = oCopyLimit;
  2540. }
  2541. while (op < cpy)
  2542. {
  2543. *op++ = *match++;
  2544. }
  2545. }
  2546. else
  2547. {
  2548. LZ4_memcpy(op, match, 8);
  2549. if (length > 16)
  2550. {
  2551. LZ4_wildCopy8(op + 8, match + 8, cpy);
  2552. }
  2553. }
  2554. op = cpy; /* wildcopy correction */
  2555. }
  2556. /* end of decoding */
  2557. if (endOnInput)
  2558. {
  2559. DEBUGLOG(5, "decoded %i bytes", (int)(((char *)op) - dst));
  2560. return (int)(((char *)op) - dst); /* Nb of output bytes decoded */
  2561. }
  2562. else
  2563. {
  2564. return (int)(((const char *)ip) - src); /* Nb of input bytes read */
  2565. }
  2566. /* Overflow error detected */
  2567. _output_error:
  2568. return (int)(-(((const char *)ip) - src)) - 1;
  2569. }
  2570. }
  2571. /*===== Instantiate the API decoding functions. =====*/
  2572. LZ4_FORCE_O2
  2573. int LZ4_decompress_safe(const char *source, char *dest, int compressedSize, int maxDecompressedSize)
  2574. {
  2575. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,
  2576. endOnInputSize, decode_full_block, noDict,
  2577. (BYTE *)dest, NULL, 0);
  2578. }
  2579. LZ4_FORCE_O2
  2580. int LZ4_decompress_safe_partial(const char *src, char *dst, int compressedSize, int targetOutputSize, int dstCapacity)
  2581. {
  2582. dstCapacity = MIN(targetOutputSize, dstCapacity);
  2583. return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
  2584. endOnInputSize, partial_decode,
  2585. noDict, (BYTE *)dst, NULL, 0);
  2586. }
  2587. LZ4_FORCE_O2
  2588. int LZ4_decompress_fast(const char *source, char *dest, int originalSize)
  2589. {
  2590. return LZ4_decompress_generic(source, dest, 0, originalSize,
  2591. endOnOutputSize, decode_full_block, withPrefix64k,
  2592. (BYTE *)dest - 64 KB, NULL, 0);
  2593. }
  2594. /*===== Instantiate a few more decoding cases, used more than once. =====*/
  2595. LZ4_FORCE_O2 /* Exported, an obsolete API function. */
  2596. int
  2597. LZ4_decompress_safe_withPrefix64k(const char *source, char *dest, int compressedSize, int maxOutputSize)
  2598. {
  2599. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  2600. endOnInputSize, decode_full_block, withPrefix64k,
  2601. (BYTE *)dest - 64 KB, NULL, 0);
  2602. }
  2603. /* Another obsolete API function, paired with the previous one. */
  2604. int LZ4_decompress_fast_withPrefix64k(const char *source, char *dest, int originalSize)
  2605. {
  2606. /* LZ4_decompress_fast doesn't validate match offsets,
  2607. * and thus serves well with any prefixed dictionary. */
  2608. return LZ4_decompress_fast(source, dest, originalSize);
  2609. }
  2610. LZ4_FORCE_O2
  2611. static int LZ4_decompress_safe_withSmallPrefix(const char *source, char *dest, int compressedSize, int maxOutputSize,
  2612. size_t prefixSize)
  2613. {
  2614. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  2615. endOnInputSize, decode_full_block, noDict,
  2616. (BYTE *)dest - prefixSize, NULL, 0);
  2617. }
  2618. LZ4_FORCE_O2
  2619. int LZ4_decompress_safe_forceExtDict(const char *source, char *dest,
  2620. int compressedSize, int maxOutputSize,
  2621. const void *dictStart, size_t dictSize)
  2622. {
  2623. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  2624. endOnInputSize, decode_full_block, usingExtDict,
  2625. (BYTE *)dest, (const BYTE *)dictStart, dictSize);
  2626. }
  2627. LZ4_FORCE_O2
  2628. static int LZ4_decompress_fast_extDict(const char *source, char *dest, int originalSize,
  2629. const void *dictStart, size_t dictSize)
  2630. {
  2631. return LZ4_decompress_generic(source, dest, 0, originalSize,
  2632. endOnOutputSize, decode_full_block, usingExtDict,
  2633. (BYTE *)dest, (const BYTE *)dictStart, dictSize);
  2634. }
  2635. /* The "double dictionary" mode, for use with e.g. ring buffers: the first part
  2636. * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
  2637. * These routines are used only once, in LZ4_decompress_*_continue().
  2638. */
  2639. LZ4_FORCE_INLINE
  2640. int LZ4_decompress_safe_doubleDict(const char *source, char *dest, int compressedSize, int maxOutputSize,
  2641. size_t prefixSize, const void *dictStart, size_t dictSize)
  2642. {
  2643. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  2644. endOnInputSize, decode_full_block, usingExtDict,
  2645. (BYTE *)dest - prefixSize, (const BYTE *)dictStart, dictSize);
  2646. }
  2647. LZ4_FORCE_INLINE
  2648. int LZ4_decompress_fast_doubleDict(const char *source, char *dest, int originalSize,
  2649. size_t prefixSize, const void *dictStart, size_t dictSize)
  2650. {
  2651. return LZ4_decompress_generic(source, dest, 0, originalSize,
  2652. endOnOutputSize, decode_full_block, usingExtDict,
  2653. (BYTE *)dest - prefixSize, (const BYTE *)dictStart, dictSize);
  2654. }
  2655. /*===== streaming decompression functions =====*/
  2656. LZ4_streamDecode_t *LZ4_createStreamDecode(void)
  2657. {
  2658. LZ4_streamDecode_t *lz4s = (LZ4_streamDecode_t *)ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));
  2659. LZ4_STATIC_ASSERT(LZ4_STREAMDECODESIZE >= sizeof(LZ4_streamDecode_t_internal)); /* A compilation error here means LZ4_STREAMDECODESIZE is not large enough */
  2660. return lz4s;
  2661. }
  2662. int LZ4_freeStreamDecode(LZ4_streamDecode_t *LZ4_stream)
  2663. {
  2664. if (LZ4_stream == NULL)
  2665. {
  2666. return 0;
  2667. } /* support free on NULL */
  2668. FREEMEM(LZ4_stream);
  2669. return 0;
  2670. }
  2671. /*! LZ4_setStreamDecode() :
  2672. * Use this function to instruct where to find the dictionary.
  2673. * This function is not necessary if previous data is still available where it was decoded.
  2674. * Loading a size of 0 is allowed (same effect as no dictionary).
  2675. * @return : 1 if OK, 0 if error
  2676. */
  2677. int LZ4_setStreamDecode(LZ4_streamDecode_t *LZ4_streamDecode, const char *dictionary, int dictSize)
  2678. {
  2679. LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse;
  2680. lz4sd->prefixSize = (size_t)dictSize;
  2681. lz4sd->prefixEnd = (const BYTE *)dictionary + dictSize;
  2682. lz4sd->externalDict = NULL;
  2683. lz4sd->extDictSize = 0;
  2684. return 1;
  2685. }
  2686. /*! LZ4_decoderRingBufferSize() :
  2687. * when setting a ring buffer for streaming decompression (optional scenario),
  2688. * provides the minimum size of this ring buffer
  2689. * to be compatible with any source respecting maxBlockSize condition.
  2690. * Note : in a ring buffer scenario,
  2691. * blocks are presumed decompressed next to each other.
  2692. * When not enough space remains for next block (remainingSize < maxBlockSize),
  2693. * decoding resumes from beginning of ring buffer.
  2694. * @return : minimum ring buffer size,
  2695. * or 0 if there is an error (invalid maxBlockSize).
  2696. */
  2697. int LZ4_decoderRingBufferSize(int maxBlockSize)
  2698. {
  2699. if (maxBlockSize < 0)
  2700. return 0;
  2701. if (maxBlockSize > LZ4_MAX_INPUT_SIZE)
  2702. return 0;
  2703. if (maxBlockSize < 16)
  2704. maxBlockSize = 16;
  2705. return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
  2706. }
  2707. /*
  2708. *_continue() :
  2709. These decoding functions allow decompression of multiple blocks in "streaming" mode.
  2710. Previously decoded blocks must still be available at the memory position where they were decoded.
  2711. If it's not possible, save the relevant part of decoded data into a safe buffer,
  2712. and indicate where it stands using LZ4_setStreamDecode()
  2713. */
  2714. LZ4_FORCE_O2
  2715. int LZ4_decompress_safe_continue(LZ4_streamDecode_t *LZ4_streamDecode, const char *source, char *dest, int compressedSize, int maxOutputSize)
  2716. {
  2717. LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse;
  2718. int result;
  2719. if (lz4sd->prefixSize == 0)
  2720. {
  2721. /* The first call, no dictionary yet. */
  2722. assert(lz4sd->extDictSize == 0);
  2723. result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
  2724. if (result <= 0)
  2725. return result;
  2726. lz4sd->prefixSize = (size_t)result;
  2727. lz4sd->prefixEnd = (BYTE *)dest + result;
  2728. }
  2729. else if (lz4sd->prefixEnd == (BYTE *)dest)
  2730. {
  2731. /* They're rolling the current segment. */
  2732. if (lz4sd->prefixSize >= 64 KB - 1)
  2733. result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
  2734. else if (lz4sd->extDictSize == 0)
  2735. result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,
  2736. lz4sd->prefixSize);
  2737. else
  2738. result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,
  2739. lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  2740. if (result <= 0)
  2741. return result;
  2742. lz4sd->prefixSize += (size_t)result;
  2743. lz4sd->prefixEnd += result;
  2744. }
  2745. else
  2746. {
  2747. /* The buffer wraps around, or they're switching to another buffer. */
  2748. lz4sd->extDictSize = lz4sd->prefixSize;
  2749. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  2750. result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,
  2751. lz4sd->externalDict, lz4sd->extDictSize);
  2752. if (result <= 0)
  2753. return result;
  2754. lz4sd->prefixSize = (size_t)result;
  2755. lz4sd->prefixEnd = (BYTE *)dest + result;
  2756. }
  2757. return result;
  2758. }
  2759. LZ4_FORCE_O2
  2760. int LZ4_decompress_fast_continue(LZ4_streamDecode_t *LZ4_streamDecode, const char *source, char *dest, int originalSize)
  2761. {
  2762. LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse;
  2763. int result;
  2764. assert(originalSize >= 0);
  2765. if (lz4sd->prefixSize == 0)
  2766. {
  2767. assert(lz4sd->extDictSize == 0);
  2768. result = LZ4_decompress_fast(source, dest, originalSize);
  2769. if (result <= 0)
  2770. return result;
  2771. lz4sd->prefixSize = (size_t)originalSize;
  2772. lz4sd->prefixEnd = (BYTE *)dest + originalSize;
  2773. }
  2774. else if (lz4sd->prefixEnd == (BYTE *)dest)
  2775. {
  2776. if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0)
  2777. result = LZ4_decompress_fast(source, dest, originalSize);
  2778. else
  2779. result = LZ4_decompress_fast_doubleDict(source, dest, originalSize,
  2780. lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  2781. if (result <= 0)
  2782. return result;
  2783. lz4sd->prefixSize += (size_t)originalSize;
  2784. lz4sd->prefixEnd += originalSize;
  2785. }
  2786. else
  2787. {
  2788. lz4sd->extDictSize = lz4sd->prefixSize;
  2789. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  2790. result = LZ4_decompress_fast_extDict(source, dest, originalSize,
  2791. lz4sd->externalDict, lz4sd->extDictSize);
  2792. if (result <= 0)
  2793. return result;
  2794. lz4sd->prefixSize = (size_t)originalSize;
  2795. lz4sd->prefixEnd = (BYTE *)dest + originalSize;
  2796. }
  2797. return result;
  2798. }
  2799. /*
  2800. Advanced decoding functions :
  2801. *_usingDict() :
  2802. These decoding functions work the same as "_continue" ones,
  2803. the dictionary must be explicitly provided within parameters
  2804. */
  2805. int LZ4_decompress_safe_usingDict(const char *source, char *dest, int compressedSize, int maxOutputSize, const char *dictStart, int dictSize)
  2806. {
  2807. if (dictSize == 0)
  2808. return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
  2809. if (dictStart + dictSize == dest)
  2810. {
  2811. if (dictSize >= 64 KB - 1)
  2812. {
  2813. return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
  2814. }
  2815. assert(dictSize >= 0);
  2816. return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize);
  2817. }
  2818. assert(dictSize >= 0);
  2819. return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize);
  2820. }
  2821. int LZ4_decompress_fast_usingDict(const char *source, char *dest, int originalSize, const char *dictStart, int dictSize)
  2822. {
  2823. if (dictSize == 0 || dictStart + dictSize == dest)
  2824. return LZ4_decompress_fast(source, dest, originalSize);
  2825. assert(dictSize >= 0);
  2826. return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize);
  2827. }
  2828. /*=*************************************************
  2829. * Obsolete Functions
  2830. ***************************************************/
  2831. /* obsolete compression functions */
  2832. int LZ4_compress_limitedOutput(const char *source, char *dest, int inputSize, int maxOutputSize)
  2833. {
  2834. return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
  2835. }
  2836. int LZ4_compress(const char *src, char *dest, int srcSize)
  2837. {
  2838. return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize));
  2839. }
  2840. int LZ4_compress_limitedOutput_withState(void *state, const char *src, char *dst, int srcSize, int dstSize)
  2841. {
  2842. return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);
  2843. }
  2844. int LZ4_compress_withState(void *state, const char *src, char *dst, int srcSize)
  2845. {
  2846. return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);
  2847. }
  2848. int LZ4_compress_limitedOutput_continue(LZ4_stream_t *LZ4_stream, const char *src, char *dst, int srcSize, int dstCapacity)
  2849. {
  2850. return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);
  2851. }
  2852. int LZ4_compress_continue(LZ4_stream_t *LZ4_stream, const char *source, char *dest, int inputSize)
  2853. {
  2854. return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);
  2855. }
  2856. /*
  2857. These decompression functions are deprecated and should no longer be used.
  2858. They are only provided here for compatibility with older user programs.
  2859. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast
  2860. - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
  2861. */
  2862. int LZ4_uncompress(const char *source, char *dest, int outputSize)
  2863. {
  2864. return LZ4_decompress_fast(source, dest, outputSize);
  2865. }
  2866. int LZ4_uncompress_unknownOutputSize(const char *source, char *dest, int isize, int maxOutputSize)
  2867. {
  2868. return LZ4_decompress_safe(source, dest, isize, maxOutputSize);
  2869. }
  2870. /* Obsolete Streaming functions */
  2871. int LZ4_sizeofStreamState(void) { return LZ4_STREAMSIZE; }
  2872. int LZ4_resetStreamState(void *state, char *inputBuffer)
  2873. {
  2874. (void)inputBuffer;
  2875. LZ4_resetStream((LZ4_stream_t *)state);
  2876. return 0;
  2877. }
  2878. void *LZ4_create(char *inputBuffer)
  2879. {
  2880. (void)inputBuffer;
  2881. return LZ4_createStream();
  2882. }
  2883. char *LZ4_slideInputBuffer(void *state)
  2884. {
  2885. /* avoid const char * -> char * conversion warning */
  2886. return (char *)(uptrval)((LZ4_stream_t *)state)->internal_donotuse.dictionary;
  2887. }
  2888. #endif /* LZ4_COMMONDEFS_ONLY */
  2889. #else
  2890. #endif