Packet.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdint.h>
  19. #include <stddef.h>
  20. #include <string.h>
  21. #include <stdlib.h>
  22. #include <stdio.h>
  23. #include "Packet.hpp"
  24. #ifdef _MSC_VER
  25. #define FORCE_INLINE static __forceinline
  26. #include <intrin.h>
  27. #pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  28. #pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
  29. #else
  30. #define FORCE_INLINE static inline
  31. #endif
  32. namespace ZeroTier {
  33. /************************************************************************** */
  34. /************************************************************************** */
  35. /* LZ4 is shipped encapsulated into Packet in an anonymous namespace.
  36. *
  37. * We're doing this as a deliberate workaround for various Linux distribution
  38. * policies that forbid static linking of support libraries.
  39. *
  40. * The reason is that relying on distribution versions of LZ4 has been too
  41. * big a source of bugs and compatibility issues. The LZ4 API is not stable
  42. * enough across versions, and dependency hell ensues. So fark it. */
  43. /* Needless to say the code in this anonymous namespace should be considered
  44. * BSD 2-clause licensed. */
  45. namespace {
  46. /* lz4.h ------------------------------------------------------------------ */
  47. /*
  48. * LZ4 - Fast LZ compression algorithm
  49. * Header File
  50. * Copyright (C) 2011-2016, Yann Collet.
  51. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  52. Redistribution and use in source and binary forms, with or without
  53. modification, are permitted provided that the following conditions are
  54. met:
  55. * Redistributions of source code must retain the above copyright
  56. notice, this list of conditions and the following disclaimer.
  57. * Redistributions in binary form must reproduce the above
  58. copyright notice, this list of conditions and the following disclaimer
  59. in the documentation and/or other materials provided with the
  60. distribution.
  61. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  62. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  63. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  64. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  65. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  66. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  67. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  68. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  69. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  70. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  71. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  72. You can contact the author at :
  73. - LZ4 homepage : http://www.lz4.org
  74. - LZ4 source repository : https://github.com/lz4/lz4
  75. */
  76. /* --- Dependency --- */
  77. //#include <stddef.h> /* size_t */
  78. /**
  79. Introduction
  80. LZ4 is lossless compression algorithm, providing compression speed at 400 MB/s per core,
  81. scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
  82. multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
  83. The LZ4 compression library provides in-memory compression and decompression functions.
  84. Compression can be done in:
  85. - a single step (described as Simple Functions)
  86. - a single step, reusing a context (described in Advanced Functions)
  87. - unbounded multiple steps (described as Streaming compression)
  88. lz4.h provides block compression functions. It gives full buffer control to user.
  89. Decompressing an lz4-compressed block also requires metadata (such as compressed size).
  90. Each application is free to encode such metadata in whichever way it wants.
  91. An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md),
  92. take care of encoding standard metadata alongside LZ4-compressed blocks.
  93. If your application requires interoperability, it's recommended to use it.
  94. A library is provided to take care of it, see lz4frame.h.
  95. */
  96. /*^***************************************************************
  97. * Export parameters
  98. *****************************************************************/
  99. /*
  100. * LZ4_DLL_EXPORT :
  101. * Enable exporting of functions when building a Windows DLL
  102. */
  103. #if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)
  104. # define LZ4LIB_API __declspec(dllexport)
  105. #elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)
  106. # define LZ4LIB_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
  107. #else
  108. # define LZ4LIB_API
  109. #endif
  110. /*========== Version =========== */
  111. #define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
  112. #define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */
  113. #define LZ4_VERSION_RELEASE 5 /* for tweaks, bug-fixes, or development */
  114. #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
  115. #define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
  116. #define LZ4_QUOTE(str) #str
  117. #define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
  118. #define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION)
  119. //LZ4LIB_API int LZ4_versionNumber (void);
  120. //LZ4LIB_API const char* LZ4_versionString (void);
  121. /*-************************************
  122. * Tuning parameter
  123. **************************************/
  124. /*!
  125. * LZ4_MEMORY_USAGE :
  126. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  127. * Increasing memory usage improves compression ratio
  128. * Reduced memory usage can improve speed, due to cache effect
  129. * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
  130. */
  131. #define LZ4_MEMORY_USAGE 14
  132. /*-************************************
  133. * Simple Functions
  134. **************************************/
  135. /*! LZ4_compress_default() :
  136. Compresses 'sourceSize' bytes from buffer 'source'
  137. into already allocated 'dest' buffer of size 'maxDestSize'.
  138. Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize).
  139. It also runs faster, so it's a recommended setting.
  140. If the function cannot compress 'source' into a more limited 'dest' budget,
  141. compression stops *immediately*, and the function result is zero.
  142. As a consequence, 'dest' content is not valid.
  143. This function never writes outside 'dest' buffer, nor read outside 'source' buffer.
  144. sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
  145. maxDestSize : full or partial size of buffer 'dest' (which must be already allocated)
  146. return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize)
  147. or 0 if compression fails */
  148. //LZ4LIB_API int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize);
  149. /*! LZ4_decompress_safe() :
  150. compressedSize : is the precise full size of the compressed block.
  151. maxDecompressedSize : is the size of destination buffer, which must be already allocated.
  152. return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize)
  153. If destination buffer is not large enough, decoding will stop and output an error code (<0).
  154. If the source stream is detected malformed, the function will stop decoding and return a negative result.
  155. This function is protected against buffer overflow exploits, including malicious data packets.
  156. It never writes outside output buffer, nor reads outside input buffer.
  157. */
  158. LZ4LIB_API int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
  159. /*-************************************
  160. * Advanced Functions
  161. **************************************/
  162. #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
  163. #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
  164. /*!
  165. LZ4_compressBound() :
  166. Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
  167. This function is primarily useful for memory allocation purposes (destination buffer size).
  168. Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
  169. Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize)
  170. inputSize : max supported value is LZ4_MAX_INPUT_SIZE
  171. return : maximum output size in a "worst case" scenario
  172. or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)
  173. */
  174. LZ4LIB_API int LZ4_compressBound(int inputSize);
  175. /*!
  176. LZ4_compress_fast() :
  177. Same as LZ4_compress_default(), but allows to select an "acceleration" factor.
  178. The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
  179. It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
  180. An acceleration value of "1" is the same as regular LZ4_compress_default()
  181. Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1.
  182. */
  183. LZ4LIB_API int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration);
  184. /*!
  185. LZ4_compress_fast_extState() :
  186. Same compression function, just using an externally allocated memory space to store compression state.
  187. Use LZ4_sizeofState() to know how much memory must be allocated,
  188. and allocate it on 8-bytes boundaries (using malloc() typically).
  189. Then, provide it as 'void* state' to compression function.
  190. */
  191. //LZ4LIB_API int LZ4_sizeofState(void);
  192. LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration);
  193. /*!
  194. LZ4_compress_destSize() :
  195. Reverse the logic, by compressing as much data as possible from 'source' buffer
  196. into already allocated buffer 'dest' of size 'targetDestSize'.
  197. This function either compresses the entire 'source' content into 'dest' if it's large enough,
  198. or fill 'dest' buffer completely with as much data as possible from 'source'.
  199. *sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'.
  200. New value is necessarily <= old value.
  201. return : Nb bytes written into 'dest' (necessarily <= targetDestSize)
  202. or 0 if compression fails
  203. */
  204. //LZ4LIB_API int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize);
  205. /*!
  206. LZ4_decompress_fast() :
  207. originalSize : is the original and therefore uncompressed size
  208. return : the number of bytes read from the source buffer (in other words, the compressed size)
  209. If the source stream is detected malformed, the function will stop decoding and return a negative result.
  210. Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes.
  211. note : This function fully respect memory boundaries for properly formed compressed data.
  212. It is a bit faster than LZ4_decompress_safe().
  213. However, it does not provide any protection against intentionally modified data stream (malicious input).
  214. Use this function in trusted environment only (data to decode comes from a trusted source).
  215. */
  216. //LZ4LIB_API int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
  217. /*!
  218. LZ4_decompress_safe_partial() :
  219. This function decompress a compressed block of size 'compressedSize' at position 'source'
  220. into destination buffer 'dest' of size 'maxDecompressedSize'.
  221. The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached,
  222. reducing decompression time.
  223. return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize)
  224. Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller.
  225. Always control how many bytes were decoded.
  226. If the source stream is detected malformed, the function will stop decoding and return a negative result.
  227. This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets
  228. */
  229. //LZ4LIB_API int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize);
  230. /*-*********************************************
  231. * Streaming Compression Functions
  232. ***********************************************/
  233. typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */
  234. /*! LZ4_createStream() and LZ4_freeStream() :
  235. * LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure.
  236. * LZ4_freeStream() releases its memory.
  237. */
  238. //LZ4LIB_API LZ4_stream_t* LZ4_createStream(void);
  239. //LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr);
  240. /*! LZ4_resetStream() :
  241. * An LZ4_stream_t structure can be allocated once and re-used multiple times.
  242. * Use this function to init an allocated `LZ4_stream_t` structure and start a new compression.
  243. */
  244. LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr);
  245. /*! LZ4_loadDict() :
  246. * Use this function to load a static dictionary into LZ4_stream.
  247. * Any previous data will be forgotten, only 'dictionary' will remain in memory.
  248. * Loading a size of 0 is allowed.
  249. * Return : dictionary size, in bytes (necessarily <= 64 KB)
  250. */
  251. //LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
  252. /*! LZ4_compress_fast_continue() :
  253. * Compress buffer content 'src', using data from previously compressed blocks as dictionary to improve compression ratio.
  254. * Important : Previous data blocks are assumed to still be present and unmodified !
  255. * 'dst' buffer must be already allocated.
  256. * If maxDstSize >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
  257. * If not, and if compressed data cannot fit into 'dst' buffer size, compression stops, and function returns a zero.
  258. */
  259. //LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int maxDstSize, int acceleration);
  260. /*! LZ4_saveDict() :
  261. * If previously compressed data block is not guaranteed to remain available at its memory location,
  262. * save it into a safer place (char* safeBuffer).
  263. * Note : you don't need to call LZ4_loadDict() afterwards,
  264. * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().
  265. * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
  266. */
  267. //LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize);
  268. /*-**********************************************
  269. * Streaming Decompression Functions
  270. * Bufferless synchronous API
  271. ************************************************/
  272. typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* incomplete type (defined later) */
  273. /* creation / destruction of streaming decompression tracking structure */
  274. //LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void);
  275. //LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
  276. /*! LZ4_setStreamDecode() :
  277. * Use this function to instruct where to find the dictionary.
  278. * Setting a size of 0 is allowed (same effect as reset).
  279. * @return : 1 if OK, 0 if error
  280. */
  281. //LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
  282. /*!
  283. LZ4_decompress_*_continue() :
  284. These decoding functions allow decompression of multiple blocks in "streaming" mode.
  285. Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB)
  286. In the case of a ring buffers, decoding buffer must be either :
  287. - Exactly same size as encoding buffer, with same update rule (block boundaries at same positions)
  288. In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB).
  289. - Larger than encoding buffer, by a minimum of maxBlockSize more bytes.
  290. maxBlockSize is implementation dependent. It's the maximum size you intend to compress into a single block.
  291. In which case, encoding and decoding buffers do not need to be synchronized,
  292. and encoding ring buffer can have any size, including small ones ( < 64 KB).
  293. - _At least_ 64 KB + 8 bytes + maxBlockSize.
  294. In which case, encoding and decoding buffers do not need to be synchronized,
  295. and encoding ring buffer can have any size, including larger than decoding buffer.
  296. Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer,
  297. and indicate where it is saved using LZ4_setStreamDecode()
  298. */
  299. //LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
  300. //LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
  301. /*! LZ4_decompress_*_usingDict() :
  302. * These decoding functions work the same as
  303. * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
  304. * They are stand-alone, and don't need an LZ4_streamDecode_t structure.
  305. */
  306. //LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
  307. //LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
  308. /*^**********************************************
  309. * !!!!!! STATIC LINKING ONLY !!!!!!
  310. ***********************************************/
  311. /*-************************************
  312. * Private definitions
  313. **************************************
  314. * Do not use these definitions.
  315. * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
  316. * Using these definitions will expose code to API and/or ABI break in future versions of the library.
  317. **************************************/
  318. #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
  319. #define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
  320. #define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
  321. #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  322. //#include <stdint.h>
  323. typedef struct {
  324. uint32_t hashTable[LZ4_HASH_SIZE_U32];
  325. uint32_t currentOffset;
  326. uint32_t initCheck;
  327. const uint8_t* dictionary;
  328. uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */
  329. uint32_t dictSize;
  330. } LZ4_stream_t_internal;
  331. typedef struct {
  332. const uint8_t* externalDict;
  333. size_t extDictSize;
  334. const uint8_t* prefixEnd;
  335. size_t prefixSize;
  336. } LZ4_streamDecode_t_internal;
  337. #else
  338. typedef struct {
  339. unsigned int hashTable[LZ4_HASH_SIZE_U32];
  340. unsigned int currentOffset;
  341. unsigned int initCheck;
  342. const unsigned char* dictionary;
  343. unsigned char* bufferStart; /* obsolete, used for slideInputBuffer */
  344. unsigned int dictSize;
  345. } LZ4_stream_t_internal;
  346. typedef struct {
  347. const unsigned char* externalDict;
  348. size_t extDictSize;
  349. const unsigned char* prefixEnd;
  350. size_t prefixSize;
  351. } LZ4_streamDecode_t_internal;
  352. #endif
  353. /*!
  354. * LZ4_stream_t :
  355. * information structure to track an LZ4 stream.
  356. * init this structure before first use.
  357. * note : only use in association with static linking !
  358. * this definition is not API/ABI safe,
  359. * and may change in a future version !
  360. */
  361. #define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
  362. #define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long))
  363. union LZ4_stream_u {
  364. unsigned long long table[LZ4_STREAMSIZE_U64];
  365. LZ4_stream_t_internal internal_donotuse;
  366. } ; /* previously typedef'd to LZ4_stream_t */
  367. /*!
  368. * LZ4_streamDecode_t :
  369. * information structure to track an LZ4 stream during decompression.
  370. * init this structure using LZ4_setStreamDecode (or memset()) before first use
  371. * note : only use in association with static linking !
  372. * this definition is not API/ABI safe,
  373. * and may change in a future version !
  374. */
  375. #define LZ4_STREAMDECODESIZE_U64 4
  376. #define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
  377. union LZ4_streamDecode_u {
  378. unsigned long long table[LZ4_STREAMDECODESIZE_U64];
  379. LZ4_streamDecode_t_internal internal_donotuse;
  380. } ; /* previously typedef'd to LZ4_streamDecode_t */
  381. /* lz4.c ------------------------------------------------------------------ */
  382. /*
  383. LZ4 - Fast LZ compression algorithm
  384. Copyright (C) 2011-2016, Yann Collet.
  385. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  386. Redistribution and use in source and binary forms, with or without
  387. modification, are permitted provided that the following conditions are
  388. met:
  389. * Redistributions of source code must retain the above copyright
  390. notice, this list of conditions and the following disclaimer.
  391. * Redistributions in binary form must reproduce the above
  392. copyright notice, this list of conditions and the following disclaimer
  393. in the documentation and/or other materials provided with the
  394. distribution.
  395. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  396. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  397. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  398. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  399. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  400. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  401. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  402. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  403. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  404. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  405. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  406. You can contact the author at :
  407. - LZ4 homepage : http://www.lz4.org
  408. - LZ4 source repository : https://github.com/lz4/lz4
  409. */
  410. /*-************************************
  411. * Tuning parameters
  412. **************************************/
  413. /*
  414. * HEAPMODE :
  415. * Select how default compression functions will allocate memory for their hash table,
  416. * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
  417. */
  418. #ifndef HEAPMODE
  419. # define HEAPMODE 0
  420. #endif
  421. /*
  422. * ACCELERATION_DEFAULT :
  423. * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
  424. */
  425. #define ACCELERATION_DEFAULT 1
  426. /*-************************************
  427. * CPU Feature Detection
  428. **************************************/
  429. /* LZ4_FORCE_MEMORY_ACCESS
  430. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  431. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  432. * The below switch allow to select different access method for improved performance.
  433. * Method 0 (default) : use `memcpy()`. Safe and portable.
  434. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  435. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  436. * Method 2 : direct access. This method is portable but violate C standard.
  437. * It can generate buggy code on targets which generate assembly depending on alignment.
  438. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  439. * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  440. * Prefer these methods in priority order (0 > 1 > 2)
  441. */
  442. #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
  443. # if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
  444. # define LZ4_FORCE_MEMORY_ACCESS 2
  445. # elif defined(__INTEL_COMPILER) || \
  446. (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) ))
  447. # define LZ4_FORCE_MEMORY_ACCESS 1
  448. # endif
  449. #endif
  450. /*
  451. * LZ4_FORCE_SW_BITCOUNT
  452. * Define this parameter if your target system or compiler does not support hardware bit count
  453. */
  454. #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */
  455. # define LZ4_FORCE_SW_BITCOUNT
  456. #endif
  457. /*-************************************
  458. * Dependency
  459. **************************************/
  460. //#include "lz4.h"
  461. /* see also "memory routines" below */
  462. /*-************************************
  463. * Compiler Options
  464. **************************************/
  465. #if 0
  466. #ifdef _MSC_VER /* Visual Studio */
  467. # define FORCE_INLINE static __forceinline
  468. # include <intrin.h>
  469. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  470. # pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
  471. #else
  472. # if defined(__GNUC__) || defined(__clang__)
  473. # define FORCE_INLINE static inline __attribute__((always_inline))
  474. # elif defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  475. # define FORCE_INLINE static inline
  476. # else
  477. # define FORCE_INLINE static
  478. # endif
  479. #endif /* _MSC_VER */
  480. #endif
  481. #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
  482. # define expect(expr,value) (__builtin_expect ((expr),(value)) )
  483. #else
  484. # define expect(expr,value) (expr)
  485. #endif
  486. #define likely(expr) expect((expr) != 0, 1)
  487. #define unlikely(expr) expect((expr) != 0, 0)
  488. /*-************************************
  489. * Memory routines
  490. **************************************/
  491. //#include <stdlib.h> /* malloc, calloc, free */
  492. #define ALLOCATOR(n,s) calloc(n,s)
  493. #define FREEMEM free
  494. //#include <string.h> /* memset, memcpy */
  495. #define MEM_INIT memset
  496. /*-************************************
  497. * Basic Types
  498. **************************************/
  499. //#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  500. //# include <stdint.h>
  501. typedef uint8_t BYTE;
  502. typedef uint16_t U16;
  503. typedef uint32_t U32;
  504. typedef int32_t S32;
  505. typedef uint64_t U64;
  506. typedef uintptr_t uptrval;
  507. /*#else
  508. typedef unsigned char BYTE;
  509. typedef unsigned short U16;
  510. typedef unsigned int U32;
  511. typedef signed int S32;
  512. typedef unsigned long long U64;
  513. typedef size_t uptrval;
  514. #endif */
  515. typedef uintptr_t reg_t;
  516. //#if defined(__x86_64__)
  517. // typedef U64 reg_t; /* 64-bits in x32 mode */
  518. //#else
  519. // typedef size_t reg_t; /* 32-bits in x32 mode */
  520. //#endif
  521. /*-************************************
  522. * Reading and writing into memory
  523. **************************************/
  524. static unsigned LZ4_isLittleEndian(void)
  525. {
  526. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  527. return one.c[0];
  528. }
  529. #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
  530. /* lie to the compiler about data alignment; use with caution */
  531. static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
  532. static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
  533. static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
  534. static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  535. static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
  536. #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
  537. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  538. /* currently only defined for gcc and icc */
  539. typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
  540. static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  541. static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  542. static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
  543. static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  544. static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
  545. #else /* safe and portable access through memcpy() */
  546. static U16 LZ4_read16(const void* memPtr)
  547. {
  548. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  549. }
  550. static U32 LZ4_read32(const void* memPtr)
  551. {
  552. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  553. }
  554. static reg_t LZ4_read_ARCH(const void* memPtr)
  555. {
  556. reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
  557. }
  558. static void LZ4_write16(void* memPtr, U16 value)
  559. {
  560. memcpy(memPtr, &value, sizeof(value));
  561. }
  562. static void LZ4_write32(void* memPtr, U32 value)
  563. {
  564. memcpy(memPtr, &value, sizeof(value));
  565. }
  566. #endif /* LZ4_FORCE_MEMORY_ACCESS */
  567. static U16 LZ4_readLE16(const void* memPtr)
  568. {
  569. if (LZ4_isLittleEndian()) {
  570. return LZ4_read16(memPtr);
  571. } else {
  572. const BYTE* p = (const BYTE*)memPtr;
  573. return (U16)((U16)p[0] + (p[1]<<8));
  574. }
  575. }
  576. static void LZ4_writeLE16(void* memPtr, U16 value)
  577. {
  578. if (LZ4_isLittleEndian()) {
  579. LZ4_write16(memPtr, value);
  580. } else {
  581. BYTE* p = (BYTE*)memPtr;
  582. p[0] = (BYTE) value;
  583. p[1] = (BYTE)(value>>8);
  584. }
  585. }
  586. static void LZ4_copy8(void* dst, const void* src)
  587. {
  588. memcpy(dst,src,8);
  589. }
  590. /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
  591. static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
  592. {
  593. BYTE* d = (BYTE*)dstPtr;
  594. const BYTE* s = (const BYTE*)srcPtr;
  595. BYTE* const e = (BYTE*)dstEnd;
  596. do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);
  597. }
  598. /*-************************************
  599. * Common Constants
  600. **************************************/
  601. #define MINMATCH 4
  602. #define WILDCOPYLENGTH 8
  603. #define LASTLITERALS 5
  604. #define MFLIMIT (WILDCOPYLENGTH+MINMATCH)
  605. static const int LZ4_minLength = (MFLIMIT+1);
  606. #define KB *(1 <<10)
  607. #define MB *(1 <<20)
  608. #define GB *(1U<<30)
  609. #define MAXD_LOG 16
  610. #define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
  611. #define ML_BITS 4
  612. #define ML_MASK ((1U<<ML_BITS)-1)
  613. #define RUN_BITS (8-ML_BITS)
  614. #define RUN_MASK ((1U<<RUN_BITS)-1)
  615. /*-************************************
  616. * Common Utils
  617. **************************************/
  618. #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  619. /*-************************************
  620. * Common functions
  621. **************************************/
  622. static unsigned LZ4_NbCommonBytes (register reg_t val)
  623. {
  624. if (LZ4_isLittleEndian()) {
  625. if (sizeof(val)==8) {
  626. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  627. unsigned long r = 0;
  628. _BitScanForward64( &r, (U64)val );
  629. return (int)(r>>3);
  630. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  631. return (__builtin_ctzll((U64)val) >> 3);
  632. # else
  633. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
  634. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  635. # endif
  636. } else /* 32 bits */ {
  637. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  638. unsigned long r;
  639. _BitScanForward( &r, (U32)val );
  640. return (int)(r>>3);
  641. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  642. return (__builtin_ctz((U32)val) >> 3);
  643. # else
  644. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
  645. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  646. # endif
  647. }
  648. } else /* Big Endian CPU */ {
  649. if (sizeof(val)==8) {
  650. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  651. unsigned long r = 0;
  652. _BitScanReverse64( &r, val );
  653. return (unsigned)(r>>3);
  654. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  655. return (__builtin_clzll((U64)val) >> 3);
  656. # else
  657. unsigned r;
  658. if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
  659. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  660. r += (!val);
  661. return r;
  662. # endif
  663. } else /* 32 bits */ {
  664. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  665. unsigned long r = 0;
  666. _BitScanReverse( &r, (unsigned long)val );
  667. return (unsigned)(r>>3);
  668. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  669. return (__builtin_clz((U32)val) >> 3);
  670. # else
  671. unsigned r;
  672. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  673. r += (!val);
  674. return r;
  675. # endif
  676. }
  677. }
  678. }
  679. #define STEPSIZE sizeof(reg_t)
  680. static unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  681. {
  682. const BYTE* const pStart = pIn;
  683. while (likely(pIn<pInLimit-(STEPSIZE-1))) {
  684. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  685. if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
  686. pIn += LZ4_NbCommonBytes(diff);
  687. return (unsigned)(pIn - pStart);
  688. }
  689. if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
  690. if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
  691. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  692. return (unsigned)(pIn - pStart);
  693. }
  694. #ifndef LZ4_COMMONDEFS_ONLY
  695. /*-************************************
  696. * Local Constants
  697. **************************************/
  698. static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
  699. static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
  700. /*-************************************
  701. * Local Structures and types
  702. **************************************/
  703. typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive;
  704. typedef enum { byPtr, byU32, byU16 } tableType_t;
  705. typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
  706. typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
  707. typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
  708. typedef enum { full = 0, partial = 1 } earlyEnd_directive;
  709. /*-************************************
  710. * Local Utils
  711. **************************************/
  712. //int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
  713. //const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }
  714. int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  715. //int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
  716. /*-******************************
  717. * Compression functions
  718. ********************************/
  719. static U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
  720. {
  721. if (tableType == byU16)
  722. return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
  723. else
  724. return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
  725. }
  726. static U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
  727. {
  728. static const U64 prime5bytes = 889523592379ULL;
  729. static const U64 prime8bytes = 11400714785074694791ULL;
  730. const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
  731. if (LZ4_isLittleEndian())
  732. return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
  733. else
  734. return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
  735. }
  736. FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
  737. {
  738. if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
  739. return LZ4_hash4(LZ4_read32(p), tableType);
  740. }
  741. static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase)
  742. {
  743. switch (tableType)
  744. {
  745. case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
  746. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
  747. case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
  748. }
  749. }
  750. FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  751. {
  752. U32 const h = LZ4_hashPosition(p, tableType);
  753. LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
  754. }
  755. static const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  756. {
  757. if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; }
  758. if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; }
  759. { const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
  760. }
  761. FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  762. {
  763. U32 const h = LZ4_hashPosition(p, tableType);
  764. return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
  765. }
  766. /** LZ4_compress_generic() :
  767. inlined, to ensure branches are decided at compilation time */
  768. FORCE_INLINE int LZ4_compress_generic(
  769. LZ4_stream_t_internal* const cctx,
  770. const char* const source,
  771. char* const dest,
  772. const int inputSize,
  773. const int maxOutputSize,
  774. const limitedOutput_directive outputLimited,
  775. const tableType_t tableType,
  776. const dict_directive dict,
  777. const dictIssue_directive dictIssue,
  778. const U32 acceleration)
  779. {
  780. const BYTE* ip = (const BYTE*) source;
  781. const BYTE* base;
  782. const BYTE* lowLimit;
  783. const BYTE* const lowRefLimit = ip - cctx->dictSize;
  784. const BYTE* const dictionary = cctx->dictionary;
  785. const BYTE* const dictEnd = dictionary + cctx->dictSize;
  786. const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source;
  787. const BYTE* anchor = (const BYTE*) source;
  788. const BYTE* const iend = ip + inputSize;
  789. const BYTE* const mflimit = iend - MFLIMIT;
  790. const BYTE* const matchlimit = iend - LASTLITERALS;
  791. BYTE* op = (BYTE*) dest;
  792. BYTE* const olimit = op + maxOutputSize;
  793. U32 forwardH;
  794. /* Init conditions */
  795. if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */
  796. switch(dict)
  797. {
  798. case noDict:
  799. default:
  800. base = (const BYTE*)source;
  801. lowLimit = (const BYTE*)source;
  802. break;
  803. case withPrefix64k:
  804. base = (const BYTE*)source - cctx->currentOffset;
  805. lowLimit = (const BYTE*)source - cctx->dictSize;
  806. break;
  807. case usingExtDict:
  808. base = (const BYTE*)source - cctx->currentOffset;
  809. lowLimit = (const BYTE*)source;
  810. break;
  811. }
  812. if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
  813. if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  814. /* First Byte */
  815. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  816. ip++; forwardH = LZ4_hashPosition(ip, tableType);
  817. /* Main Loop */
  818. for ( ; ; ) {
  819. ptrdiff_t refDelta = 0;
  820. const BYTE* match;
  821. BYTE* token;
  822. /* Find a match */
  823. { const BYTE* forwardIp = ip;
  824. unsigned step = 1;
  825. unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
  826. do {
  827. U32 const h = forwardH;
  828. ip = forwardIp;
  829. forwardIp += step;
  830. step = (searchMatchNb++ >> LZ4_skipTrigger);
  831. if (unlikely(forwardIp > mflimit)) goto _last_literals;
  832. match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
  833. if (dict==usingExtDict) {
  834. if (match < (const BYTE*)source) {
  835. refDelta = dictDelta;
  836. lowLimit = dictionary;
  837. } else {
  838. refDelta = 0;
  839. lowLimit = (const BYTE*)source;
  840. } }
  841. forwardH = LZ4_hashPosition(forwardIp, tableType);
  842. LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
  843. } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)
  844. || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
  845. || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );
  846. }
  847. /* Catch up */
  848. while (((ip>anchor) & (match+refDelta > lowLimit)) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }
  849. /* Encode Literals */
  850. { unsigned const litLength = (unsigned)(ip - anchor);
  851. token = op++;
  852. if ((outputLimited) && /* Check output buffer overflow */
  853. (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
  854. return 0;
  855. if (litLength >= RUN_MASK) {
  856. int len = (int)litLength-RUN_MASK;
  857. *token = (RUN_MASK<<ML_BITS);
  858. for(; len >= 255 ; len-=255) *op++ = 255;
  859. *op++ = (BYTE)len;
  860. }
  861. else *token = (BYTE)(litLength<<ML_BITS);
  862. /* Copy Literals */
  863. LZ4_wildCopy(op, anchor, op+litLength);
  864. op+=litLength;
  865. }
  866. _next_match:
  867. /* Encode Offset */
  868. LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
  869. /* Encode MatchLength */
  870. { unsigned matchCode;
  871. if ((dict==usingExtDict) && (lowLimit==dictionary)) {
  872. const BYTE* limit;
  873. match += refDelta;
  874. limit = ip + (dictEnd-match);
  875. if (limit > matchlimit) limit = matchlimit;
  876. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
  877. ip += MINMATCH + matchCode;
  878. if (ip==limit) {
  879. unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit);
  880. matchCode += more;
  881. ip += more;
  882. }
  883. } else {
  884. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
  885. ip += MINMATCH + matchCode;
  886. }
  887. if ( outputLimited && /* Check output buffer overflow */
  888. (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) )
  889. return 0;
  890. if (matchCode >= ML_MASK) {
  891. *token += ML_MASK;
  892. matchCode -= ML_MASK;
  893. LZ4_write32(op, 0xFFFFFFFF);
  894. while (matchCode >= 4*255) op+=4, LZ4_write32(op, 0xFFFFFFFF), matchCode -= 4*255;
  895. op += matchCode / 255;
  896. *op++ = (BYTE)(matchCode % 255);
  897. } else
  898. *token += (BYTE)(matchCode);
  899. }
  900. anchor = ip;
  901. /* Test end of chunk */
  902. if (ip > mflimit) break;
  903. /* Fill table */
  904. LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
  905. /* Test next position */
  906. match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
  907. if (dict==usingExtDict) {
  908. if (match < (const BYTE*)source) {
  909. refDelta = dictDelta;
  910. lowLimit = dictionary;
  911. } else {
  912. refDelta = 0;
  913. lowLimit = (const BYTE*)source;
  914. } }
  915. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  916. if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1)
  917. && (match+MAX_DISTANCE>=ip)
  918. && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) )
  919. { token=op++; *token=0; goto _next_match; }
  920. /* Prepare next loop */
  921. forwardH = LZ4_hashPosition(++ip, tableType);
  922. }
  923. _last_literals:
  924. /* Encode Last Literals */
  925. { size_t const lastRun = (size_t)(iend - anchor);
  926. if ( (outputLimited) && /* Check output buffer overflow */
  927. ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) )
  928. return 0;
  929. if (lastRun >= RUN_MASK) {
  930. size_t accumulator = lastRun - RUN_MASK;
  931. *op++ = RUN_MASK << ML_BITS;
  932. for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
  933. *op++ = (BYTE) accumulator;
  934. } else {
  935. *op++ = (BYTE)(lastRun<<ML_BITS);
  936. }
  937. memcpy(op, anchor, lastRun);
  938. op += lastRun;
  939. }
  940. /* End */
  941. return (int) (((char*)op)-dest);
  942. }
  943. int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  944. {
  945. LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
  946. LZ4_resetStream((LZ4_stream_t*)state);
  947. if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  948. if (maxOutputSize >= LZ4_compressBound(inputSize)) {
  949. if (inputSize < LZ4_64Klimit)
  950. return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
  951. else
  952. return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  953. } else {
  954. if (inputSize < LZ4_64Klimit)
  955. return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  956. else
  957. return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  958. }
  959. }
  960. int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  961. {
  962. #if (HEAPMODE)
  963. void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  964. #else
  965. LZ4_stream_t ctx;
  966. void* const ctxPtr = &ctx;
  967. #endif
  968. int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
  969. #if (HEAPMODE)
  970. FREEMEM(ctxPtr);
  971. #endif
  972. return result;
  973. }
  974. #if 0
  975. int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize)
  976. {
  977. return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1);
  978. }
  979. /* hidden debug function */
  980. /* strangely enough, gcc generates faster code when this function is uncommented, even if unused */
  981. int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  982. {
  983. LZ4_stream_t ctx;
  984. LZ4_resetStream(&ctx);
  985. if (inputSize < LZ4_64Klimit)
  986. return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  987. else
  988. return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  989. }
  990. #endif
  991. /*-******************************
  992. * *_destSize() variant
  993. ********************************/
  994. #if 0
  995. static int LZ4_compress_destSize_generic(
  996. LZ4_stream_t_internal* const ctx,
  997. const char* const src,
  998. char* const dst,
  999. int* const srcSizePtr,
  1000. const int targetDstSize,
  1001. const tableType_t tableType)
  1002. {
  1003. const BYTE* ip = (const BYTE*) src;
  1004. const BYTE* base = (const BYTE*) src;
  1005. const BYTE* lowLimit = (const BYTE*) src;
  1006. const BYTE* anchor = ip;
  1007. const BYTE* const iend = ip + *srcSizePtr;
  1008. const BYTE* const mflimit = iend - MFLIMIT;
  1009. const BYTE* const matchlimit = iend - LASTLITERALS;
  1010. BYTE* op = (BYTE*) dst;
  1011. BYTE* const oend = op + targetDstSize;
  1012. BYTE* const oMaxLit = op + targetDstSize - 2 /* offset */ - 8 /* because 8+MINMATCH==MFLIMIT */ - 1 /* token */;
  1013. BYTE* const oMaxMatch = op + targetDstSize - (LASTLITERALS + 1 /* token */);
  1014. BYTE* const oMaxSeq = oMaxLit - 1 /* token */;
  1015. U32 forwardH;
  1016. /* Init conditions */
  1017. if (targetDstSize < 1) return 0; /* Impossible to store anything */
  1018. if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
  1019. if ((tableType == byU16) && (*srcSizePtr>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
  1020. if (*srcSizePtr<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  1021. /* First Byte */
  1022. *srcSizePtr = 0;
  1023. LZ4_putPosition(ip, ctx->hashTable, tableType, base);
  1024. ip++; forwardH = LZ4_hashPosition(ip, tableType);
  1025. /* Main Loop */
  1026. for ( ; ; ) {
  1027. const BYTE* match;
  1028. BYTE* token;
  1029. /* Find a match */
  1030. { const BYTE* forwardIp = ip;
  1031. unsigned step = 1;
  1032. unsigned searchMatchNb = 1 << LZ4_skipTrigger;
  1033. do {
  1034. U32 h = forwardH;
  1035. ip = forwardIp;
  1036. forwardIp += step;
  1037. step = (searchMatchNb++ >> LZ4_skipTrigger);
  1038. if (unlikely(forwardIp > mflimit)) goto _last_literals;
  1039. match = LZ4_getPositionOnHash(h, ctx->hashTable, tableType, base);
  1040. forwardH = LZ4_hashPosition(forwardIp, tableType);
  1041. LZ4_putPositionOnHash(ip, h, ctx->hashTable, tableType, base);
  1042. } while ( ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
  1043. || (LZ4_read32(match) != LZ4_read32(ip)) );
  1044. }
  1045. /* Catch up */
  1046. while ((ip>anchor) && (match > lowLimit) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
  1047. /* Encode Literal length */
  1048. { unsigned litLength = (unsigned)(ip - anchor);
  1049. token = op++;
  1050. if (op + ((litLength+240)/255) + litLength > oMaxLit) {
  1051. /* Not enough space for a last match */
  1052. op--;
  1053. goto _last_literals;
  1054. }
  1055. if (litLength>=RUN_MASK) {
  1056. unsigned len = litLength - RUN_MASK;
  1057. *token=(RUN_MASK<<ML_BITS);
  1058. for(; len >= 255 ; len-=255) *op++ = 255;
  1059. *op++ = (BYTE)len;
  1060. }
  1061. else *token = (BYTE)(litLength<<ML_BITS);
  1062. /* Copy Literals */
  1063. LZ4_wildCopy(op, anchor, op+litLength);
  1064. op += litLength;
  1065. }
  1066. _next_match:
  1067. /* Encode Offset */
  1068. LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
  1069. /* Encode MatchLength */
  1070. { size_t matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
  1071. if (op + ((matchLength+240)/255) > oMaxMatch) {
  1072. /* Match description too long : reduce it */
  1073. matchLength = (15-1) + (oMaxMatch-op) * 255;
  1074. }
  1075. ip += MINMATCH + matchLength;
  1076. if (matchLength>=ML_MASK) {
  1077. *token += ML_MASK;
  1078. matchLength -= ML_MASK;
  1079. while (matchLength >= 255) { matchLength-=255; *op++ = 255; }
  1080. *op++ = (BYTE)matchLength;
  1081. }
  1082. else *token += (BYTE)(matchLength);
  1083. }
  1084. anchor = ip;
  1085. /* Test end of block */
  1086. if (ip > mflimit) break;
  1087. if (op > oMaxSeq) break;
  1088. /* Fill table */
  1089. LZ4_putPosition(ip-2, ctx->hashTable, tableType, base);
  1090. /* Test next position */
  1091. match = LZ4_getPosition(ip, ctx->hashTable, tableType, base);
  1092. LZ4_putPosition(ip, ctx->hashTable, tableType, base);
  1093. if ( (match+MAX_DISTANCE>=ip)
  1094. && (LZ4_read32(match)==LZ4_read32(ip)) )
  1095. { token=op++; *token=0; goto _next_match; }
  1096. /* Prepare next loop */
  1097. forwardH = LZ4_hashPosition(++ip, tableType);
  1098. }
  1099. _last_literals:
  1100. /* Encode Last Literals */
  1101. { size_t lastRunSize = (size_t)(iend - anchor);
  1102. if (op + 1 /* token */ + ((lastRunSize+240)/255) /* litLength */ + lastRunSize /* literals */ > oend) {
  1103. /* adapt lastRunSize to fill 'dst' */
  1104. lastRunSize = (oend-op) - 1;
  1105. lastRunSize -= (lastRunSize+240)/255;
  1106. }
  1107. ip = anchor + lastRunSize;
  1108. if (lastRunSize >= RUN_MASK) {
  1109. size_t accumulator = lastRunSize - RUN_MASK;
  1110. *op++ = RUN_MASK << ML_BITS;
  1111. for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
  1112. *op++ = (BYTE) accumulator;
  1113. } else {
  1114. *op++ = (BYTE)(lastRunSize<<ML_BITS);
  1115. }
  1116. memcpy(op, anchor, lastRunSize);
  1117. op += lastRunSize;
  1118. }
  1119. /* End */
  1120. *srcSizePtr = (int) (((const char*)ip)-src);
  1121. return (int) (((char*)op)-dst);
  1122. }
  1123. static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
  1124. {
  1125. LZ4_resetStream(state);
  1126. if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */
  1127. return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
  1128. } else {
  1129. if (*srcSizePtr < LZ4_64Klimit)
  1130. return LZ4_compress_destSize_generic(&state->internal_donotuse, src, dst, srcSizePtr, targetDstSize, byU16);
  1131. else
  1132. return LZ4_compress_destSize_generic(&state->internal_donotuse, src, dst, srcSizePtr, targetDstSize, sizeof(void*)==8 ? byU32 : byPtr);
  1133. }
  1134. }
  1135. int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
  1136. {
  1137. #if (HEAPMODE)
  1138. LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  1139. #else
  1140. LZ4_stream_t ctxBody;
  1141. LZ4_stream_t* ctx = &ctxBody;
  1142. #endif
  1143. int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
  1144. #if (HEAPMODE)
  1145. FREEMEM(ctx);
  1146. #endif
  1147. return result;
  1148. }
  1149. #endif
  1150. /*-******************************
  1151. * Streaming functions
  1152. ********************************/
  1153. #if 0
  1154. LZ4_stream_t* LZ4_createStream(void)
  1155. {
  1156. LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64);
  1157. LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
  1158. LZ4_resetStream(lz4s);
  1159. return lz4s;
  1160. }
  1161. #endif
  1162. void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
  1163. {
  1164. MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
  1165. }
  1166. #if 0
  1167. int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
  1168. {
  1169. FREEMEM(LZ4_stream);
  1170. return (0);
  1171. }
  1172. #endif
  1173. #if 0
  1174. #define HASH_UNIT sizeof(reg_t)
  1175. int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
  1176. {
  1177. LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
  1178. const BYTE* p = (const BYTE*)dictionary;
  1179. const BYTE* const dictEnd = p + dictSize;
  1180. const BYTE* base;
  1181. if ((dict->initCheck) || (dict->currentOffset > 1 GB)) /* Uninitialized structure, or reuse overflow */
  1182. LZ4_resetStream(LZ4_dict);
  1183. if (dictSize < (int)HASH_UNIT) {
  1184. dict->dictionary = NULL;
  1185. dict->dictSize = 0;
  1186. return 0;
  1187. }
  1188. if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
  1189. dict->currentOffset += 64 KB;
  1190. base = p - dict->currentOffset;
  1191. dict->dictionary = p;
  1192. dict->dictSize = (U32)(dictEnd - p);
  1193. dict->currentOffset += dict->dictSize;
  1194. while (p <= dictEnd-HASH_UNIT) {
  1195. LZ4_putPosition(p, dict->hashTable, byU32, base);
  1196. p+=3;
  1197. }
  1198. return dict->dictSize;
  1199. }
  1200. static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)
  1201. {
  1202. if ((LZ4_dict->currentOffset > 0x80000000) ||
  1203. ((uptrval)LZ4_dict->currentOffset > (uptrval)src)) { /* address space overflow */
  1204. /* rescale hash table */
  1205. U32 const delta = LZ4_dict->currentOffset - 64 KB;
  1206. const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
  1207. int i;
  1208. for (i=0; i<LZ4_HASH_SIZE_U32; i++) {
  1209. if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;
  1210. else LZ4_dict->hashTable[i] -= delta;
  1211. }
  1212. LZ4_dict->currentOffset = 64 KB;
  1213. if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
  1214. LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
  1215. }
  1216. }
  1217. int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  1218. {
  1219. LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse;
  1220. const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
  1221. const BYTE* smallest = (const BYTE*) source;
  1222. if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */
  1223. if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd;
  1224. LZ4_renormDictT(streamPtr, smallest);
  1225. if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  1226. /* Check overlapping input/dictionary space */
  1227. { const BYTE* sourceEnd = (const BYTE*) source + inputSize;
  1228. if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) {
  1229. streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
  1230. if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
  1231. if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
  1232. streamPtr->dictionary = dictEnd - streamPtr->dictSize;
  1233. }
  1234. }
  1235. /* prefix mode : source data follows dictionary */
  1236. if (dictEnd == (const BYTE*)source) {
  1237. int result;
  1238. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  1239. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, dictSmall, acceleration);
  1240. else
  1241. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, noDictIssue, acceleration);
  1242. streamPtr->dictSize += (U32)inputSize;
  1243. streamPtr->currentOffset += (U32)inputSize;
  1244. return result;
  1245. }
  1246. /* external dictionary mode */
  1247. { int result;
  1248. if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
  1249. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, dictSmall, acceleration);
  1250. else
  1251. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, noDictIssue, acceleration);
  1252. streamPtr->dictionary = (const BYTE*)source;
  1253. streamPtr->dictSize = (U32)inputSize;
  1254. streamPtr->currentOffset += (U32)inputSize;
  1255. return result;
  1256. }
  1257. }
  1258. /* Hidden debug function, to force external dictionary mode */
  1259. int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize)
  1260. {
  1261. LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
  1262. int result;
  1263. const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
  1264. const BYTE* smallest = dictEnd;
  1265. if (smallest > (const BYTE*) source) smallest = (const BYTE*) source;
  1266. LZ4_renormDictT(streamPtr, smallest);
  1267. result = LZ4_compress_generic(streamPtr, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
  1268. streamPtr->dictionary = (const BYTE*)source;
  1269. streamPtr->dictSize = (U32)inputSize;
  1270. streamPtr->currentOffset += (U32)inputSize;
  1271. return result;
  1272. }
  1273. /*! LZ4_saveDict() :
  1274. * If previously compressed data block is not guaranteed to remain available at its memory location,
  1275. * save it into a safer place (char* safeBuffer).
  1276. * Note : you don't need to call LZ4_loadDict() afterwards,
  1277. * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().
  1278. * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
  1279. */
  1280. int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
  1281. {
  1282. LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
  1283. const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize;
  1284. if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */
  1285. if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
  1286. memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
  1287. dict->dictionary = (const BYTE*)safeBuffer;
  1288. dict->dictSize = (U32)dictSize;
  1289. return dictSize;
  1290. }
  1291. #endif
  1292. /*-*****************************
  1293. * Decompression functions
  1294. *******************************/
  1295. /*! LZ4_decompress_generic() :
  1296. * This generic decompression function cover all use cases.
  1297. * It shall be instantiated several times, using different sets of directives
  1298. * Note that it is important this generic function is really inlined,
  1299. * in order to remove useless branches during compilation optimization.
  1300. */
  1301. FORCE_INLINE int LZ4_decompress_generic(
  1302. const char* const source,
  1303. char* const dest,
  1304. int inputSize,
  1305. int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */
  1306. int endOnInput, /* endOnOutputSize, endOnInputSize */
  1307. int partialDecoding, /* full, partial */
  1308. int targetOutputSize, /* only used if partialDecoding==partial */
  1309. int dict, /* noDict, withPrefix64k, usingExtDict */
  1310. const BYTE* const lowPrefix, /* == dest when no prefix */
  1311. const BYTE* const dictStart, /* only if dict==usingExtDict */
  1312. const size_t dictSize /* note : = 0 if noDict */
  1313. )
  1314. {
  1315. /* Local Variables */
  1316. const BYTE* ip = (const BYTE*) source;
  1317. const BYTE* const iend = ip + inputSize;
  1318. BYTE* op = (BYTE*) dest;
  1319. BYTE* const oend = op + outputSize;
  1320. BYTE* cpy;
  1321. BYTE* oexit = op + targetOutputSize;
  1322. const BYTE* const lowLimit = lowPrefix - dictSize;
  1323. const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
  1324. const unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4};
  1325. const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
  1326. const int safeDecode = (endOnInput==endOnInputSize);
  1327. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  1328. /* Special cases */
  1329. if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */
  1330. if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
  1331. if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1);
  1332. /* Main Loop : decode sequences */
  1333. while (1) {
  1334. size_t length;
  1335. const BYTE* match;
  1336. size_t offset;
  1337. /* get literal length */
  1338. unsigned const token = *ip++;
  1339. if ((length=(token>>ML_BITS)) == RUN_MASK) {
  1340. unsigned s;
  1341. do {
  1342. s = *ip++;
  1343. length += s;
  1344. } while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) );
  1345. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error; /* overflow detection */
  1346. if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error; /* overflow detection */
  1347. }
  1348. /* copy literals */
  1349. cpy = op+length;
  1350. if ( ((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) )
  1351. || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
  1352. {
  1353. if (partialDecoding) {
  1354. if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */
  1355. if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
  1356. } else {
  1357. if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
  1358. if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
  1359. }
  1360. memcpy(op, ip, length);
  1361. ip += length;
  1362. op += length;
  1363. break; /* Necessarily EOF, due to parsing restrictions */
  1364. }
  1365. LZ4_wildCopy(op, ip, cpy);
  1366. ip += length; op = cpy;
  1367. /* get offset */
  1368. offset = LZ4_readLE16(ip); ip+=2;
  1369. match = op - offset;
  1370. if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside buffers */
  1371. LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */
  1372. /* get matchlength */
  1373. length = token & ML_MASK;
  1374. if (length == ML_MASK) {
  1375. unsigned s;
  1376. do {
  1377. s = *ip++;
  1378. if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
  1379. length += s;
  1380. } while (s==255);
  1381. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */
  1382. }
  1383. length += MINMATCH;
  1384. /* check external dictionary */
  1385. if ((dict==usingExtDict) && (match < lowPrefix)) {
  1386. if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */
  1387. if (length <= (size_t)(lowPrefix-match)) {
  1388. /* match can be copied as a single segment from external dictionary */
  1389. memmove(op, dictEnd - (lowPrefix-match), length);
  1390. op += length;
  1391. } else {
  1392. /* match encompass external dictionary and current block */
  1393. size_t const copySize = (size_t)(lowPrefix-match);
  1394. size_t const restSize = length - copySize;
  1395. memcpy(op, dictEnd - copySize, copySize);
  1396. op += copySize;
  1397. if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */
  1398. BYTE* const endOfMatch = op + restSize;
  1399. const BYTE* copyFrom = lowPrefix;
  1400. while (op < endOfMatch) *op++ = *copyFrom++;
  1401. } else {
  1402. memcpy(op, lowPrefix, restSize);
  1403. op += restSize;
  1404. } }
  1405. continue;
  1406. }
  1407. /* copy match within block */
  1408. cpy = op + length;
  1409. if (unlikely(offset<8)) {
  1410. const int dec64 = dec64table[offset];
  1411. op[0] = match[0];
  1412. op[1] = match[1];
  1413. op[2] = match[2];
  1414. op[3] = match[3];
  1415. match += dec32table[offset];
  1416. memcpy(op+4, match, 4);
  1417. match -= dec64;
  1418. } else { LZ4_copy8(op, match); match+=8; }
  1419. op += 8;
  1420. if (unlikely(cpy>oend-12)) {
  1421. BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1);
  1422. if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
  1423. if (op < oCopyLimit) {
  1424. LZ4_wildCopy(op, match, oCopyLimit);
  1425. match += oCopyLimit - op;
  1426. op = oCopyLimit;
  1427. }
  1428. while (op<cpy) *op++ = *match++;
  1429. } else {
  1430. LZ4_copy8(op, match);
  1431. if (length>16) LZ4_wildCopy(op+8, match+8, cpy);
  1432. }
  1433. op=cpy; /* correction */
  1434. }
  1435. /* end of decoding */
  1436. if (endOnInput)
  1437. return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
  1438. else
  1439. return (int) (((const char*)ip)-source); /* Nb of input bytes read */
  1440. /* Overflow error detected */
  1441. _output_error:
  1442. return (int) (-(((const char*)ip)-source))-1;
  1443. }
  1444. int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
  1445. {
  1446. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0);
  1447. }
  1448. #if 0
  1449. int LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize)
  1450. {
  1451. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, partial, targetOutputSize, noDict, (BYTE*)dest, NULL, 0);
  1452. }
  1453. int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
  1454. {
  1455. return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)(dest - 64 KB), NULL, 64 KB);
  1456. }
  1457. #endif
  1458. /*===== streaming decompression functions =====*/
  1459. #if 0
  1460. /*
  1461. * If you prefer dynamic allocation methods,
  1462. * LZ4_createStreamDecode()
  1463. * provides a pointer (void*) towards an initialized LZ4_streamDecode_t structure.
  1464. */
  1465. LZ4_streamDecode_t* LZ4_createStreamDecode(void)
  1466. {
  1467. LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOCATOR(1, sizeof(LZ4_streamDecode_t));
  1468. return lz4s;
  1469. }
  1470. int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
  1471. {
  1472. FREEMEM(LZ4_stream);
  1473. return 0;
  1474. }
  1475. /*!
  1476. * LZ4_setStreamDecode() :
  1477. * Use this function to instruct where to find the dictionary.
  1478. * This function is not necessary if previous data is still available where it was decoded.
  1479. * Loading a size of 0 is allowed (same effect as no dictionary).
  1480. * Return : 1 if OK, 0 if error
  1481. */
  1482. int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
  1483. {
  1484. LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
  1485. lz4sd->prefixSize = (size_t) dictSize;
  1486. lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
  1487. lz4sd->externalDict = NULL;
  1488. lz4sd->extDictSize = 0;
  1489. return 1;
  1490. }
  1491. /*
  1492. *_continue() :
  1493. These decoding functions allow decompression of multiple blocks in "streaming" mode.
  1494. Previously decoded blocks must still be available at the memory position where they were decoded.
  1495. If it's not possible, save the relevant part of decoded data into a safe buffer,
  1496. and indicate where it stands using LZ4_setStreamDecode()
  1497. */
  1498. int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
  1499. {
  1500. LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
  1501. int result;
  1502. if (lz4sd->prefixEnd == (BYTE*)dest) {
  1503. result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1504. endOnInputSize, full, 0,
  1505. usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  1506. if (result <= 0) return result;
  1507. lz4sd->prefixSize += result;
  1508. lz4sd->prefixEnd += result;
  1509. } else {
  1510. lz4sd->extDictSize = lz4sd->prefixSize;
  1511. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  1512. result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
  1513. endOnInputSize, full, 0,
  1514. usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);
  1515. if (result <= 0) return result;
  1516. lz4sd->prefixSize = result;
  1517. lz4sd->prefixEnd = (BYTE*)dest + result;
  1518. }
  1519. return result;
  1520. }
  1521. int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)
  1522. {
  1523. LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
  1524. int result;
  1525. if (lz4sd->prefixEnd == (BYTE*)dest) {
  1526. result = LZ4_decompress_generic(source, dest, 0, originalSize,
  1527. endOnOutputSize, full, 0,
  1528. usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
  1529. if (result <= 0) return result;
  1530. lz4sd->prefixSize += originalSize;
  1531. lz4sd->prefixEnd += originalSize;
  1532. } else {
  1533. lz4sd->extDictSize = lz4sd->prefixSize;
  1534. lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
  1535. result = LZ4_decompress_generic(source, dest, 0, originalSize,
  1536. endOnOutputSize, full, 0,
  1537. usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);
  1538. if (result <= 0) return result;
  1539. lz4sd->prefixSize = originalSize;
  1540. lz4sd->prefixEnd = (BYTE*)dest + originalSize;
  1541. }
  1542. return result;
  1543. }
  1544. /*
  1545. Advanced decoding functions :
  1546. *_usingDict() :
  1547. These decoding functions work the same as "_continue" ones,
  1548. the dictionary must be explicitly provided within parameters
  1549. */
  1550. FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize)
  1551. {
  1552. if (dictSize==0)
  1553. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0);
  1554. if (dictStart+dictSize == dest) {
  1555. if (dictSize >= (int)(64 KB - 1))
  1556. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0);
  1557. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0);
  1558. }
  1559. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize);
  1560. }
  1561. int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
  1562. {
  1563. return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize);
  1564. }
  1565. int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
  1566. {
  1567. return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize);
  1568. }
  1569. /* debug function */
  1570. int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
  1571. {
  1572. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize);
  1573. }
  1574. #endif
  1575. #if 0
  1576. /*=*************************************************
  1577. * Obsolete Functions
  1578. ***************************************************/
  1579. /* obsolete compression functions */
  1580. int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); }
  1581. int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); }
  1582. int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); }
  1583. int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); }
  1584. int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, maxDstSize, 1); }
  1585. int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); }
  1586. /*
  1587. These function names are deprecated and should no longer be used.
  1588. They are only provided here for compatibility with older user programs.
  1589. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast
  1590. - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
  1591. */
  1592. int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); }
  1593. int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); }
  1594. /* Obsolete Streaming functions */
  1595. int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
  1596. static void LZ4_init(LZ4_stream_t* lz4ds, BYTE* base)
  1597. {
  1598. MEM_INIT(lz4ds, 0, sizeof(LZ4_stream_t));
  1599. lz4ds->internal_donotuse.bufferStart = base;
  1600. }
  1601. int LZ4_resetStreamState(void* state, char* inputBuffer)
  1602. {
  1603. if ((((uptrval)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */
  1604. LZ4_init((LZ4_stream_t*)state, (BYTE*)inputBuffer);
  1605. return 0;
  1606. }
  1607. void* LZ4_create (char* inputBuffer)
  1608. {
  1609. LZ4_stream_t* lz4ds = (LZ4_stream_t*)ALLOCATOR(8, sizeof(LZ4_stream_t));
  1610. LZ4_init (lz4ds, (BYTE*)inputBuffer);
  1611. return lz4ds;
  1612. }
  1613. char* LZ4_slideInputBuffer (void* LZ4_Data)
  1614. {
  1615. LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)LZ4_Data)->internal_donotuse;
  1616. int dictSize = LZ4_saveDict((LZ4_stream_t*)LZ4_Data, (char*)ctx->bufferStart, 64 KB);
  1617. return (char*)(ctx->bufferStart + dictSize);
  1618. }
  1619. /* Obsolete streaming decompression functions */
  1620. int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
  1621. {
  1622. return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
  1623. }
  1624. int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
  1625. {
  1626. return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
  1627. }
  1628. #endif
  1629. #endif /* LZ4_COMMONDEFS_ONLY */
  1630. } // anonymous namespace
  1631. /************************************************************************** */
  1632. /************************************************************************** */
  1633. const unsigned char Packet::ZERO_KEY[32] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
  1634. #ifdef ZT_TRACE
  1635. const char *Packet::verbString(Verb v)
  1636. {
  1637. switch(v) {
  1638. case VERB_NOP: return "NOP";
  1639. case VERB_HELLO: return "HELLO";
  1640. case VERB_ERROR: return "ERROR";
  1641. case VERB_OK: return "OK";
  1642. case VERB_WHOIS: return "WHOIS";
  1643. case VERB_RENDEZVOUS: return "RENDEZVOUS";
  1644. case VERB_FRAME: return "FRAME";
  1645. case VERB_EXT_FRAME: return "EXT_FRAME";
  1646. case VERB_ECHO: return "ECHO";
  1647. case VERB_MULTICAST_LIKE: return "MULTICAST_LIKE";
  1648. case VERB_NETWORK_CREDENTIALS: return "NETWORK_CREDENTIALS";
  1649. case VERB_NETWORK_CONFIG_REQUEST: return "NETWORK_CONFIG_REQUEST";
  1650. case VERB_NETWORK_CONFIG: return "NETWORK_CONFIG";
  1651. case VERB_MULTICAST_GATHER: return "MULTICAST_GATHER";
  1652. case VERB_MULTICAST_FRAME: return "MULTICAST_FRAME";
  1653. case VERB_PUSH_DIRECT_PATHS: return "PUSH_DIRECT_PATHS";
  1654. case VERB_CIRCUIT_TEST: return "CIRCUIT_TEST";
  1655. case VERB_CIRCUIT_TEST_REPORT: return "CIRCUIT_TEST_REPORT";
  1656. case VERB_USER_MESSAGE: return "USER_MESSAGE";
  1657. }
  1658. return "(unknown)";
  1659. }
  1660. const char *Packet::errorString(ErrorCode e)
  1661. {
  1662. switch(e) {
  1663. case ERROR_NONE: return "NONE";
  1664. case ERROR_INVALID_REQUEST: return "INVALID_REQUEST";
  1665. case ERROR_BAD_PROTOCOL_VERSION: return "BAD_PROTOCOL_VERSION";
  1666. case ERROR_OBJ_NOT_FOUND: return "OBJECT_NOT_FOUND";
  1667. case ERROR_IDENTITY_COLLISION: return "IDENTITY_COLLISION";
  1668. case ERROR_UNSUPPORTED_OPERATION: return "UNSUPPORTED_OPERATION";
  1669. case ERROR_NEED_MEMBERSHIP_CERTIFICATE: return "NEED_MEMBERSHIP_CERTIFICATE";
  1670. case ERROR_NETWORK_ACCESS_DENIED_: return "NETWORK_ACCESS_DENIED";
  1671. case ERROR_UNWANTED_MULTICAST: return "UNWANTED_MULTICAST";
  1672. }
  1673. return "(unknown)";
  1674. }
  1675. #endif // ZT_TRACE
  1676. void Packet::armor(const void *key,bool encryptPayload,unsigned int counter)
  1677. {
  1678. uint8_t mangledKey[32],macKey[32],mac[16];
  1679. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  1680. // Mask least significant 3 bits of packet ID with counter to embed packet send counter for QoS use
  1681. data[7] = (data[7] & 0xf8) | ((uint8_t)counter & 0x07);
  1682. // Set flag now, since it affects key mangle function
  1683. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  1684. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  1685. Salsa20 s20(mangledKey,256,data + ZT_PACKET_IDX_IV);
  1686. // MAC key is always the first 32 bytes of the Salsa20 key stream
  1687. // This is the same construction DJB's NaCl library uses
  1688. s20.crypt12(ZERO_KEY,macKey,sizeof(macKey));
  1689. uint8_t *const payload = data + ZT_PACKET_IDX_VERB;
  1690. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  1691. if (encryptPayload)
  1692. s20.crypt12(payload,payload,payloadLen);
  1693. Poly1305::compute(mac,payload,payloadLen,macKey);
  1694. memcpy(data + ZT_PACKET_IDX_MAC,mac,8);
  1695. }
  1696. bool Packet::dearmor(const void *key)
  1697. {
  1698. uint8_t mangledKey[32],macKey[32],mac[16];
  1699. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  1700. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  1701. unsigned char *const payload = data + ZT_PACKET_IDX_VERB;
  1702. const unsigned int cs = cipher();
  1703. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  1704. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  1705. Salsa20 s20(mangledKey,256,data + ZT_PACKET_IDX_IV);
  1706. s20.crypt12(ZERO_KEY,macKey,sizeof(macKey));
  1707. Poly1305::compute(mac,payload,payloadLen,macKey);
  1708. if (!Utils::secureEq(mac,data + ZT_PACKET_IDX_MAC,8))
  1709. return false; // MAC failed, packet is corrupt, modified, or is not from the sender
  1710. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1711. s20.crypt12(payload,payload,payloadLen);
  1712. return true;
  1713. } else {
  1714. return false; // unrecognized cipher suite
  1715. }
  1716. }
  1717. void Packet::cryptField(const void *key,unsigned int start,unsigned int len)
  1718. {
  1719. unsigned char discard[32];
  1720. Salsa20 s20(key,256,field(ZT_PACKET_IDX_IV,8));
  1721. s20.crypt12(ZERO_KEY,discard,sizeof(discard)); // discard the first 32 bytes of key stream (the ones use for MAC in armor()) as a precaution
  1722. unsigned char *const ptr = field(start,len);
  1723. s20.crypt12(ptr,ptr,len);
  1724. }
  1725. bool Packet::compress()
  1726. {
  1727. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  1728. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  1729. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  1730. int cl = LZ4_compress_fast((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl,ZT_PROTO_MAX_PACKET_LENGTH * 2,2);
  1731. if ((cl > 0)&&(cl < pl)) {
  1732. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  1733. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  1734. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  1735. return true;
  1736. }
  1737. }
  1738. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1739. return false;
  1740. }
  1741. bool Packet::uncompress()
  1742. {
  1743. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  1744. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  1745. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  1746. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  1747. int ucl = LZ4_decompress_safe((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  1748. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  1749. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  1750. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  1751. } else return false;
  1752. }
  1753. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1754. }
  1755. return true;
  1756. }
  1757. } // namespace ZeroTier