diff --git a/core/Blob.hpp b/core/Blob.hpp index e3e824e8d..a6f062879 100644 --- a/core/Blob.hpp +++ b/core/Blob.hpp @@ -32,7 +32,7 @@ struct SHA384Hash uint64_t data[6]; ZT_INLINE SHA384Hash() noexcept - { Utils::zero(data); } + { Utils::zero< sizeof(data) >(data); } explicit ZT_INLINE SHA384Hash(const void *const d) noexcept { Utils::copy< 48 >(data, d); } @@ -73,7 +73,7 @@ struct UniqueID uint64_t data[2]; ZT_INLINE UniqueID() noexcept - { Utils::zero(data); } + { Utils::zero< sizeof(data) >(data); } ZT_INLINE UniqueID(const uint64_t a, const uint64_t b) noexcept { @@ -112,10 +112,10 @@ struct UniqueID { return (memcmp(data, b.data, 16) >= 0); } }; -static_assert(sizeof(SHA384Hash) == 48,"SHA384Hash contains unnecessary padding"); -static_assert(sizeof(UniqueID) == 16,"UniqueID contains unnecessary padding"); +static_assert(sizeof(SHA384Hash) == 48, "SHA384Hash contains unnecessary padding"); +static_assert(sizeof(UniqueID) == 16, "UniqueID contains unnecessary padding"); -template +template< unsigned long S > struct Blob { uint8_t data[S]; diff --git a/core/C25519.hpp b/core/C25519.hpp index fa7aef915..4741d2113 100644 --- a/core/C25519.hpp +++ b/core/C25519.hpp @@ -11,8 +11,11 @@ */ /****/ -// Note that the actual code in C25519.cpp is in the public domain as per -// its original license. +/* + * The code in C25519.cpp is in the public domain rather than being under + * ZeroTier's license. Other than ZeroTier shims it contains public domain + * C25519/Ed25519 code by D. J. Bernstein and Matthew Dempsky. + */ #ifndef ZT_C25519_HPP #define ZT_C25519_HPP diff --git a/core/CAPI.cpp b/core/CAPI.cpp index 4df85768f..dd3a16d0f 100644 --- a/core/CAPI.cpp +++ b/core/CAPI.cpp @@ -24,8 +24,8 @@ extern "C" { // These macros make the idiom of passing buffers to outside code via the API work properly even // if the first address of Buf does not overlap with its data field, since the C++ standard does // not absolutely guarantee this. -#define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) )) -#define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0]))) +#define ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) )) +#define ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0]))) void *ZT_getBuffer() { @@ -35,7 +35,7 @@ void *ZT_getBuffer() // When this occurs it's either sent back to the pool with Buf's delete operator or // wrapped in a SharedPtr<> to be passed into the core. try { - return _ZT_BUFTOPTR(new ZeroTier::Buf()); + return ZT_BUFTOPTR(new ZeroTier::Buf()); } catch (...) { return nullptr; // can only happen on out of memory condition } @@ -44,7 +44,7 @@ void *ZT_getBuffer() void ZT_freeBuffer(void *b) { if (b) - delete _ZT_PTRTOBUF(b); + delete ZT_PTRTOBUF(b); } struct p_queryResultBase @@ -74,7 +74,7 @@ void ZT_version(int *major, int *minor, int *revision, int *build) enum ZT_ResultCode ZT_Node_new(ZT_Node **node, void *uptr, void *tptr, const struct ZT_Node_Callbacks *callbacks, int64_t now) { - *node = (ZT_Node *)0; + *node = nullptr; try { *node = reinterpret_cast(new ZeroTier::Node(uptr, tptr, callbacks, now)); return ZT_RESULT_OK; @@ -107,7 +107,7 @@ enum ZT_ResultCode ZT_Node_processWirePacket( volatile int64_t *nextBackgroundTaskDeadline) { try { - ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK)); + ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK)); return reinterpret_cast(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline); } catch (std::bad_alloc &exc) { return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY; @@ -133,7 +133,7 @@ enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame( volatile int64_t *nextBackgroundTaskDeadline) { try { - ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK)); + ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK)); return reinterpret_cast(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline); } catch (std::bad_alloc &exc) { return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY; diff --git a/core/CapabilityCredential.hpp b/core/CapabilityCredential.hpp index 93f222e53..1c5b23020 100644 --- a/core/CapabilityCredential.hpp +++ b/core/CapabilityCredential.hpp @@ -112,7 +112,7 @@ public: * * @param RR Runtime environment to provide for peer lookup, etc. */ - ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const noexcept { return _verify(RR,tPtr,*this); } + ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const noexcept { return s_verify(RR, tPtr, *this); } static constexpr int marshalSizeMax() noexcept { return ZT_CAPABILITY_MARSHAL_SIZE_MAX; } int marshal(uint8_t data[ZT_CAPABILITY_MARSHAL_SIZE_MAX],bool forSign = false) const noexcept; diff --git a/core/Certificate.hpp b/core/Certificate.hpp index d7d635b41..d1962aea9 100644 --- a/core/Certificate.hpp +++ b/core/Certificate.hpp @@ -58,7 +58,7 @@ public: Certificate &operator=(const ZT_Certificate &cert); - ZT_INLINE Certificate &operator=(const Certificate &cert) + ZT_INLINE Certificate &operator=(const Certificate &cert) noexcept { if (likely(&cert != this)) { const ZT_Certificate *const sup = &cert; diff --git a/core/Constants.hpp b/core/Constants.hpp index 0a7e1c951..771f49478 100644 --- a/core/Constants.hpp +++ b/core/Constants.hpp @@ -26,7 +26,7 @@ ((uint64_t)ZEROTIER_VERSION_MAJOR << 48U) | \ ((uint64_t)ZEROTIER_VERSION_MINOR << 32U) | \ ((uint64_t)ZEROTIER_VERSION_REVISION << 16U) | \ - ((uint64_t)ZEROTIER_VERSION_BUILD) ) + ((uint64_t)ZEROTIER_VERSION_BUILD) ) /** * Length of a ZeroTier address in bytes diff --git a/core/Credential.cpp b/core/Credential.cpp index 948dd6702..afd5a9a67 100644 --- a/core/Credential.cpp +++ b/core/Credential.cpp @@ -43,7 +43,7 @@ namespace ZeroTier { template -static ZT_INLINE Credential::VerifyResult _credVerify(const RuntimeEnvironment *RR,void *tPtr,CRED credential) +static ZT_INLINE Credential::VerifyResult p_credVerify(const RuntimeEnvironment *RR,void *tPtr,CRED credential) { uint8_t tmp[ZT_BUF_MEM_SIZE + 16]; @@ -66,12 +66,12 @@ static ZT_INLINE Credential::VerifyResult _credVerify(const RuntimeEnvironment * return Credential::VERIFY_BAD_SIGNATURE; } -Credential::VerifyResult Credential::_verify(const RuntimeEnvironment *const RR,void *tPtr,const RevocationCredential &credential) const { return _credVerify(RR, tPtr, credential); } -Credential::VerifyResult Credential::_verify(const RuntimeEnvironment *const RR,void *tPtr,const TagCredential &credential) const { return _credVerify(RR, tPtr, credential); } -Credential::VerifyResult Credential::_verify(const RuntimeEnvironment *const RR,void *tPtr,const CapabilityCredential &credential) const { return _credVerify(RR, tPtr, credential); } -Credential::VerifyResult Credential::_verify(const RuntimeEnvironment *const RR,void *tPtr,const OwnershipCredential &credential) const { return _credVerify(RR, tPtr, credential); } +Credential::VerifyResult Credential::s_verify(const RuntimeEnvironment *RR, void *tPtr, const RevocationCredential &credential) { return p_credVerify(RR, tPtr, credential); } +Credential::VerifyResult Credential::s_verify(const RuntimeEnvironment *RR, void *tPtr, const TagCredential &credential) { return p_credVerify(RR, tPtr, credential); } +Credential::VerifyResult Credential::s_verify(const RuntimeEnvironment *RR, void *tPtr, const CapabilityCredential &credential) { return p_credVerify(RR, tPtr, credential); } +Credential::VerifyResult Credential::s_verify(const RuntimeEnvironment *RR, void *tPtr, const OwnershipCredential &credential) { return p_credVerify(RR, tPtr, credential); } -Credential::VerifyResult Credential::_verify(const RuntimeEnvironment *const RR,void *tPtr,const MembershipCredential &credential) const +Credential::VerifyResult Credential::s_verify(const RuntimeEnvironment *RR, void *tPtr, const MembershipCredential &credential) { // Sanity check network ID. if ((!credential.m_signedBy) || (credential.m_signedBy != Network::controllerFor(credential.m_networkId))) diff --git a/core/Credential.hpp b/core/Credential.hpp index 9c38007d2..74245b2cc 100644 --- a/core/Credential.hpp +++ b/core/Credential.hpp @@ -52,11 +52,11 @@ public: }; protected: - VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const MembershipCredential &credential) const; - VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const RevocationCredential &credential) const; - VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const TagCredential &credential) const; - VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const OwnershipCredential &credential) const; - VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const CapabilityCredential &credential) const; + static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const MembershipCredential &credential); + static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const RevocationCredential &credential); + static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const TagCredential &credential); + static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const OwnershipCredential &credential); + static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const CapabilityCredential &credential); }; } // namespace ZeroTier diff --git a/core/Dictionary.hpp b/core/Dictionary.hpp index bb8b347e0..faccf4922 100644 --- a/core/Dictionary.hpp +++ b/core/Dictionary.hpp @@ -30,14 +30,12 @@ class Identity; * This data structure is used for network configurations, node meta-data, * and other open-definition protocol objects. * - * If this seems a little odd, it is. It dates back to the very first alpha - * versions of ZeroTier and if it were redesigned today we'd use some kind - * of simple or standardized binary encoding. Nevertheless it is efficient - * and it works so there is no need to change it and break backward - * compatibility. - * - * Use of the append functions is faster than building and then encoding a - * dictionary for creating outbound packets. + * This is technically a binary encoding, but with delimiters chosen so that + * it looks like a series of key=value lines of the keys and values are + * human-readable strings. + * + * The fastest way to build a dictionary to send is to use the append + * static functions, not to populate and then encode a Dictionary. */ class Dictionary { @@ -408,7 +406,7 @@ private: { switch (c) { case 0: - out.push_back(92); // backslash + out.push_back(92); out.push_back(48); break; case 10: diff --git a/core/ECC384.hpp b/core/ECC384.hpp index ffb7e0292..192e5a6f5 100644 --- a/core/ECC384.hpp +++ b/core/ECC384.hpp @@ -11,10 +11,21 @@ */ /****/ -// This is glue code to ease the use of the NIST P-384 elliptic curve. - -// Note that the code inside ECC384.cpp is third party code and -// is under the BSD 2-clause license rather than ZeroTier's license. +/* + * The contents of ECC384.cpp are third party code and are licensed under + * the BSD 2-clause license. + * + * The built-in implementation is easy-ecc by Kenneth MacKay and can be found + * here: https://github.com/esxgx/easy-ecc + * + * Our copy is trimmed down with unused stuff removed and also contains a few + * ZeroTier shims to implement these function interfaces. Otherwise it is + * unmodified from the original. It's a nice and fairly fast portable + * implementation that should build everywhere. + * + * For FIPS-compliant builds this will eventually link against FIPS-compliant + * crypto libraries instead of using the built-in version. + */ #ifndef ZT_ECC384_HPP #define ZT_ECC384_HPP diff --git a/core/LZ4.cpp b/core/LZ4.cpp index bfdaae97d..66407c645 100644 --- a/core/LZ4.cpp +++ b/core/LZ4.cpp @@ -60,43 +60,47 @@ namespace { // #define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */ // #define LZ4_VERSION_RELEASE 5 /* for tweaks, bug-fixes, or development */ #define LZ4_MEMORY_USAGE 14 -#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ +#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ -FORCE_INLINE void LZ4_resetStream (LZ4_stream_t* streamPtr); +FORCE_INLINE void LZ4_resetStream(LZ4_stream_t *streamPtr); #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) -#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ +#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ -typedef struct { +typedef struct +{ uint32_t hashTable[LZ4_HASH_SIZE_U32]; uint32_t currentOffset; uint32_t initCheck; - const uint8_t* dictionary; - uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */ + const uint8_t *dictionary; + uint8_t *bufferStart; /* obsolete, used for slideInputBuffer */ uint32_t dictSize; } LZ4_stream_t_internal; -typedef struct { - const uint8_t* externalDict; +typedef struct +{ + const uint8_t *externalDict; size_t extDictSize; - const uint8_t* prefixEnd; + const uint8_t *prefixEnd; size_t prefixSize; } LZ4_streamDecode_t_internal; #define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) -union LZ4_stream_u { +union LZ4_stream_u +{ unsigned long long table[LZ4_STREAMSIZE_U64]; LZ4_stream_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_stream_t */ +}; /* previously typedef'd to LZ4_stream_t */ #define LZ4_STREAMDECODESIZE_U64 4 -union LZ4_streamDecode_u { +union LZ4_streamDecode_u +{ unsigned long long table[LZ4_STREAMDECODESIZE_U64]; LZ4_streamDecode_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_streamDecode_t */ +}; /* previously typedef'd to LZ4_streamDecode_t */ #ifndef HEAPMODE #define HEAPMODE 0 @@ -112,13 +116,13 @@ union LZ4_streamDecode_u { #define LZ4_FORCE_SW_BITCOUNT #endif -#define ALLOCATOR(n,s) calloc(n,s) -#define FREEMEM free +#define ALLOCATOR(n, s) calloc(n,s) +#define FREEMEM free -typedef uint8_t BYTE; +typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; -typedef int32_t S32; +typedef int32_t S32; typedef uint64_t U64; typedef uintptr_t uptrval; typedef uintptr_t reg_t; @@ -129,13 +133,23 @@ typedef uintptr_t reg_t; #define LZ4_isLittleEndian() (0) #endif -#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) -FORCE_INLINE U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } -FORCE_INLINE U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } -FORCE_INLINE reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } -FORCE_INLINE void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } -FORCE_INLINE void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } -#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) +#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS == 2) +FORCE_INLINE U16 LZ4_read16(const void *memPtr) +{ return *(const U16 *)memPtr; } + +FORCE_INLINE U32 LZ4_read32(const void *memPtr) +{ return *(const U32 *)memPtr; } + +FORCE_INLINE reg_t LZ4_read_ARCH(const void *memPtr) +{ return *(const reg_t *)memPtr; } + +FORCE_INLINE void LZ4_write16(void *memPtr, U16 value) +{ *(U16 *)memPtr = value; } + +FORCE_INLINE void LZ4_write32(void *memPtr, U32 value) +{ *(U32 *)memPtr = value; } + +#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS == 1) typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign; FORCE_INLINE U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } FORCE_INLINE U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } @@ -165,38 +179,43 @@ FORCE_INLINE void LZ4_write32(void* memPtr, U32 value) } #endif /* LZ4_FORCE_MEMORY_ACCESS */ -FORCE_INLINE U16 LZ4_readLE16(const void* memPtr) +FORCE_INLINE U16 LZ4_readLE16(const void *memPtr) { if (LZ4_isLittleEndian()) { return LZ4_read16(memPtr); } else { - const BYTE* p = (const BYTE*)memPtr; - return (U16)((U16)p[0] + (p[1]<<8)); + const BYTE *p = (const BYTE *)memPtr; + return (U16)((U16)p[0] + (p[1] << 8)); } } -FORCE_INLINE void LZ4_writeLE16(void* memPtr, U16 value) +FORCE_INLINE void LZ4_writeLE16(void *memPtr, U16 value) { if (LZ4_isLittleEndian()) { LZ4_write16(memPtr, value); } else { - BYTE* p = (BYTE*)memPtr; - p[0] = (BYTE) value; - p[1] = (BYTE)(value>>8); + BYTE *p = (BYTE *)memPtr; + p[0] = (BYTE)value; + p[1] = (BYTE)(value >> 8); } } -FORCE_INLINE void LZ4_copy8(void* dst, const void* src) +FORCE_INLINE void LZ4_copy8(void *dst, const void *src) { - Utils::copy<8>(dst,src); + Utils::copy< 8 >(dst, src); } -FORCE_INLINE void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd) +FORCE_INLINE void LZ4_wildCopy(void *dstPtr, const void *srcPtr, void *dstEnd) { - BYTE* d = (BYTE*)dstPtr; - const BYTE* s = (const BYTE*)srcPtr; - BYTE* const e = (BYTE*)dstEnd; - do { LZ4_copy8(d,s); d+=8; s+=8; } while (d>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_ctzll((U64)val) >> 3); # else 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 }; @@ -239,7 +258,7 @@ FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val) unsigned long r; _BitScanForward( &r, (U32)val ); return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_ctz((U32)val) >> 3); # else 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 }; @@ -247,12 +266,12 @@ FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val) # endif } } else /* Big Endian CPU */ { - if (sizeof(val)==8) { + if (sizeof(val) == 8) { # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r = 0; _BitScanReverse64( &r, val ); return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_clzll((U64)val) >> 3); # else unsigned r; @@ -266,7 +285,7 @@ FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val) unsigned long r = 0; _BitScanReverse( &r, (unsigned long)val ); return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_clz((U32)val) >> 3); # else unsigned r; @@ -279,95 +298,144 @@ FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val) } #define STEPSIZE sizeof(reg_t) -FORCE_INLINE unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) +FORCE_INLINE unsigned LZ4_count(const BYTE *pIn, const BYTE *pMatch, const BYTE *pInLimit) { - const BYTE* const pStart = pIn; + const BYTE *const pStart = pIn; - while (likely(pIn compression run slower on incompressible data */ -typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive; -typedef enum { byPtr, byU32, byU16 } tableType_t; +typedef enum +{ + notLimited = 0, limitedOutput = 1 +} limitedOutput_directive; +typedef enum +{ + byPtr, byU32, byU16 +} tableType_t; -typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive; -typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; +typedef enum +{ + noDict = 0, withPrefix64k, usingExtDict +} dict_directive; +typedef enum +{ + noDictIssue = 0, dictSmall +} dictIssue_directive; -typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; -typedef enum { full = 0, partial = 1 } earlyEnd_directive; +typedef enum +{ + endOnOutputSize = 0, endOnInputSize = 1 +} endCondition_directive; +typedef enum +{ + full = 0, partial = 1 +} earlyEnd_directive; -FORCE_INLINE int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } +FORCE_INLINE int LZ4_compressBound(int isize) +{ return LZ4_COMPRESSBOUND(isize); } FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType) { if (tableType == byU16) - return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); + return ((sequence * 2654435761U) >> ((MINMATCH * 8) - (LZ4_HASHLOG + 1))); else - return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); + return ((sequence * 2654435761U) >> ((MINMATCH * 8) - LZ4_HASHLOG)); } FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType) { static const U64 prime5bytes = 889523592379ULL; static const U64 prime8bytes = 11400714785074694791ULL; - const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; + const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG + 1 : LZ4_HASHLOG; if (LZ4_isLittleEndian()) return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); else return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); } -FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) +FORCE_INLINE U32 LZ4_hashPosition(const void *const p, tableType_t const tableType) { - if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); + if ((sizeof(reg_t) == 8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); return LZ4_hash4(LZ4_read32(p), tableType); } -FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase) +FORCE_INLINE void LZ4_putPositionOnHash(const BYTE *p, U32 h, void *tableBase, tableType_t const tableType, const BYTE *srcBase) { - switch (tableType) - { - case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } - case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } - case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } + switch (tableType) { + case byPtr: { + const BYTE **hashTable = (const BYTE **)tableBase; + hashTable[h] = p; + return; + } + case byU32: { + U32 *hashTable = (U32 *)tableBase; + hashTable[h] = (U32)(p - srcBase); + return; + } + case byU16: { + U16 *hashTable = (U16 *)tableBase; + hashTable[h] = (U16)(p - srcBase); + return; + } } } -FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +FORCE_INLINE void LZ4_putPosition(const BYTE *p, void *tableBase, tableType_t tableType, const BYTE *srcBase) { U32 const h = LZ4_hashPosition(p, tableType); LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); } -FORCE_INLINE const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase) +FORCE_INLINE const BYTE *LZ4_getPositionOnHash(U32 h, void *tableBase, tableType_t tableType, const BYTE *srcBase) { - if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; } - if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; } - { const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ + if (tableType == byPtr) { + const BYTE **hashTable = (const BYTE **)tableBase; + return hashTable[h]; + } + if (tableType == byU32) { + const U32 *const hashTable = (U32 *)tableBase; + return hashTable[h] + srcBase; + } + { + const U16 *const hashTable = (U16 *)tableBase; + return hashTable[h] + srcBase; + } /* default, to ensure a return */ } -FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +FORCE_INLINE const BYTE *LZ4_getPosition(const BYTE *p, void *tableBase, tableType_t tableType, const BYTE *srcBase) { U32 const h = LZ4_hashPosition(p, tableType); return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); } FORCE_INLINE int LZ4_compress_generic( - LZ4_stream_t_internal* const cctx, - const char* const source, - char* const dest, + LZ4_stream_t_internal *const cctx, + const char *const source, + char *const dest, const int inputSize, const int maxOutputSize, const limitedOutput_directive outputLimited, @@ -376,56 +444,57 @@ FORCE_INLINE int LZ4_compress_generic( const dictIssue_directive dictIssue, const U32 acceleration) { - const BYTE* ip = (const BYTE*) source; - const BYTE* base; - const BYTE* lowLimit; - const BYTE* const lowRefLimit = ip - cctx->dictSize; - const BYTE* const dictionary = cctx->dictionary; - const BYTE* const dictEnd = dictionary + cctx->dictSize; - const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source; - const BYTE* anchor = (const BYTE*) source; - const BYTE* const iend = ip + inputSize; - const BYTE* const mflimit = iend - MFLIMIT; - const BYTE* const matchlimit = iend - LASTLITERALS; + const BYTE *ip = (const BYTE *)source; + const BYTE *base; + const BYTE *lowLimit; + const BYTE *const lowRefLimit = ip - cctx->dictSize; + const BYTE *const dictionary = cctx->dictionary; + const BYTE *const dictEnd = dictionary + cctx->dictSize; + const ptrdiff_t dictDelta = dictEnd - (const BYTE *)source; + const BYTE *anchor = (const BYTE *)source; + const BYTE *const iend = ip + inputSize; + const BYTE *const mflimit = iend - MFLIMIT; + const BYTE *const matchlimit = iend - LASTLITERALS; - BYTE* op = (BYTE*) dest; - BYTE* const olimit = op + maxOutputSize; + BYTE *op = (BYTE *)dest; + BYTE *const olimit = op + maxOutputSize; U32 forwardH; /* Init conditions */ if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ - switch(dict) - { + switch (dict) { case noDict: default: - base = (const BYTE*)source; - lowLimit = (const BYTE*)source; + base = (const BYTE *)source; + lowLimit = (const BYTE *)source; break; case withPrefix64k: - base = (const BYTE*)source - cctx->currentOffset; - lowLimit = (const BYTE*)source - cctx->dictSize; + base = (const BYTE *)source - cctx->currentOffset; + lowLimit = (const BYTE *)source - cctx->dictSize; break; case usingExtDict: - base = (const BYTE*)source - cctx->currentOffset; - lowLimit = (const BYTE*)source; + base = (const BYTE *)source - cctx->currentOffset; + lowLimit = (const BYTE *)source; break; } - if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (inputSize= LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ + if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */ /* First Byte */ LZ4_putPosition(ip, cctx->hashTable, tableType, base); - ip++; forwardH = LZ4_hashPosition(ip, tableType); + ip++; + forwardH = LZ4_hashPosition(ip, tableType); /* Main Loop */ - for ( ; ; ) { + for (;;) { ptrdiff_t refDelta = 0; - const BYTE* match; - BYTE* token; + const BYTE *match; + BYTE *token; /* Find a match */ - { const BYTE* forwardIp = ip; + { + const BYTE *forwardIp = ip; unsigned step = 1; unsigned searchMatchNb = acceleration << LZ4_skipTrigger; do { @@ -437,76 +506,82 @@ FORCE_INLINE int LZ4_compress_generic( if (unlikely(forwardIp > mflimit)) goto _last_literals; match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); - if (dict==usingExtDict) { - if (match < (const BYTE*)source) { + if (dict == usingExtDict) { + if (match < (const BYTE *)source) { refDelta = dictDelta; lowLimit = dictionary; } else { refDelta = 0; - lowLimit = (const BYTE*)source; - } } + lowLimit = (const BYTE *)source; + } + } forwardH = LZ4_hashPosition(forwardIp, tableType); LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); - } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0) - || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) ); + } while (((dictIssue == dictSmall) ? (match < lowRefLimit) : 0) + || ((tableType == byU16) ? 0 : (match + MAX_DISTANCE < ip)) + || (LZ4_read32(match + refDelta) != LZ4_read32(ip))); } /* Catch up */ - while (((ip>anchor) & (match+refDelta > lowLimit)) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; } + while (((ip > anchor) & (match + refDelta > lowLimit)) && (unlikely(ip[-1] == match[refDelta - 1]))) { + ip--; + match--; + } /* Encode Literals */ - { unsigned const litLength = (unsigned)(ip - anchor); + { + unsigned const litLength = (unsigned)(ip - anchor); token = op++; if ((outputLimited) && /* Check output buffer overflow */ - (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) + (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength / 255) > olimit))) return 0; if (litLength >= RUN_MASK) { - int len = (int)litLength-RUN_MASK; - *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; + int len = (int)litLength - RUN_MASK; + *token = (RUN_MASK << ML_BITS); + for (; len >= 255; len -= 255) *op++ = 255; *op++ = (BYTE)len; - } - else *token = (BYTE)(litLength< matchlimit) limit = matchlimit; - matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); + matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, limit); ip += MINMATCH + matchCode; - if (ip==limit) { - unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit); + if (ip == limit) { + unsigned const more = LZ4_count(ip, (const BYTE *)source, matchlimit); matchCode += more; ip += more; } } else { - matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); + matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, matchlimit); ip += MINMATCH + matchCode; } - if ( outputLimited && /* Check output buffer overflow */ - (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) + if (outputLimited && /* Check output buffer overflow */ + (unlikely(op + (1 + LASTLITERALS) + (matchCode >> 8) > olimit))) return 0; if (matchCode >= ML_MASK) { *token += ML_MASK; matchCode -= ML_MASK; LZ4_write32(op, 0xFFFFFFFF); - while (matchCode >= 4*255) op+=4, LZ4_write32(op, 0xFFFFFFFF), matchCode -= 4*255; + while (matchCode >= 4 * 255) op += 4, LZ4_write32(op, 0xFFFFFFFF), matchCode -= 4 * 255; op += matchCode / 255; *op++ = (BYTE)(matchCode % 255); } else @@ -519,23 +594,27 @@ FORCE_INLINE int LZ4_compress_generic( if (ip > mflimit) break; /* Fill table */ - LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); + LZ4_putPosition(ip - 2, cctx->hashTable, tableType, base); /* Test next position */ match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); - if (dict==usingExtDict) { - if (match < (const BYTE*)source) { + if (dict == usingExtDict) { + if (match < (const BYTE *)source) { refDelta = dictDelta; lowLimit = dictionary; } else { refDelta = 0; - lowLimit = (const BYTE*)source; - } } + lowLimit = (const BYTE *)source; + } + } LZ4_putPosition(ip, cctx->hashTable, tableType, base); - if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1) - && (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } + if (((dictIssue == dictSmall) ? (match >= lowRefLimit) : 1) + && (match + MAX_DISTANCE >= ip) + && (LZ4_read32(match + refDelta) == LZ4_read32(ip))) { + token = op++; + *token = 0; + goto _next_match; + } /* Prepare next loop */ forwardH = LZ4_hashPosition(++ip, tableType); @@ -543,128 +622,130 @@ FORCE_INLINE int LZ4_compress_generic( _last_literals: /* Encode Last Literals */ - { size_t const lastRun = (size_t)(iend - anchor); - if ( (outputLimited) && /* Check output buffer overflow */ - ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) ) + { + size_t const lastRun = (size_t)(iend - anchor); + if ((outputLimited) && /* Check output buffer overflow */ + ((op - (BYTE *)dest) + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > (U32)maxOutputSize)) return 0; if (lastRun >= RUN_MASK) { size_t accumulator = lastRun - RUN_MASK; *op++ = RUN_MASK << ML_BITS; - for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; - *op++ = (BYTE) accumulator; + for (; accumulator >= 255; accumulator -= 255) *op++ = 255; + *op++ = (BYTE)accumulator; } else { - *op++ = (BYTE)(lastRun<internal_donotuse; - LZ4_resetStream((LZ4_stream_t*)state); + LZ4_stream_t_internal *ctx = &((LZ4_stream_t *)state)->internal_donotuse; + LZ4_resetStream((LZ4_stream_t *)state); //if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; if (maxOutputSize >= LZ4_compressBound(inputSize)) { if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration); + return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration); else - return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); + return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void *) == 8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); } else { if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); + return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); else - return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); + return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void *) == 8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); } } -FORCE_INLINE void LZ4_resetStream (LZ4_stream_t* LZ4_stream) +FORCE_INLINE void LZ4_resetStream(LZ4_stream_t *LZ4_stream) { - Utils::zero(LZ4_stream); + Utils::zero< sizeof(LZ4_stream_t) >(LZ4_stream); } FORCE_INLINE int LZ4_decompress_generic( - const char* const source, - char* const dest, + const char *const source, + char *const dest, int inputSize, - int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */ + int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */ - int endOnInput, /* endOnOutputSize, endOnInputSize */ - int partialDecoding, /* full, partial */ + int endOnInput, /* endOnOutputSize, endOnInputSize */ + int partialDecoding, /* full, partial */ int targetOutputSize, /* only used if partialDecoding==partial */ - int dict, /* noDict, withPrefix64k, usingExtDict */ - const BYTE* const lowPrefix, /* == dest when no prefix */ - const BYTE* const dictStart, /* only if dict==usingExtDict */ - const size_t dictSize /* note : = 0 if noDict */ + int dict, /* noDict, withPrefix64k, usingExtDict */ + const BYTE *const lowPrefix, /* == dest when no prefix */ + const BYTE *const dictStart, /* only if dict==usingExtDict */ + const size_t dictSize /* note : = 0 if noDict */ ) { /* Local Variables */ - const BYTE* ip = (const BYTE*) source; - const BYTE* const iend = ip + inputSize; + const BYTE *ip = (const BYTE *)source; + const BYTE *const iend = ip + inputSize; - BYTE* op = (BYTE*) dest; - BYTE* const oend = op + outputSize; - BYTE* cpy; - BYTE* oexit = op + targetOutputSize; - const BYTE* const lowLimit = lowPrefix - dictSize; + BYTE *op = (BYTE *)dest; + BYTE *const oend = op + outputSize; + BYTE *cpy; + BYTE *oexit = op + targetOutputSize; + const BYTE *const lowLimit = lowPrefix - dictSize; - const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize; + const BYTE *const dictEnd = (const BYTE *)dictStart + dictSize; const unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3}; - const int safeDecode = (endOnInput==endOnInputSize); + const int safeDecode = (endOnInput == endOnInputSize); const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); /* Special cases */ - if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */ - if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ - if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); + if ((partialDecoding) && (oexit > oend - MFLIMIT)) oexit = oend - MFLIMIT; /* targetOutputSize too high => decode everything */ + if ((endOnInput) && (unlikely(outputSize == 0))) return ((inputSize == 1) && (*ip == 0)) ? 0 : -1; /* Empty output buffer */ + if ((!endOnInput) && (unlikely(outputSize == 0))) return (*ip == 0 ? 1 : -1); /* Main Loop : decode sequences */ while (1) { size_t length; - const BYTE* match; + const BYTE *match; size_t offset; /* get literal length */ unsigned const token = *ip++; - if ((length=(token>>ML_BITS)) == RUN_MASK) { + if ((length = (token >> ML_BITS)) == RUN_MASK) { unsigned s; do { s = *ip++; length += s; - } while ( likely(endOnInput ? ip(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) - || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) - { + cpy = op + length; + if (((endOnInput) && ((cpy > (partialDecoding ? oexit : oend - MFLIMIT)) || (ip + length > iend - (2 + 1 + LASTLITERALS)))) + || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) { if (partialDecoding) { - if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ - if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ + if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ + if ((endOnInput) && (ip + length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ } else { - if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ - if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ + if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ + if ((endOnInput) && ((ip + length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ } Utils::copy(op, ip, length); ip += length; op += length; - break; /* Necessarily EOF, due to parsing restrictions */ + break; /* Necessarily EOF, due to parsing restrictions */ } LZ4_wildCopy(op, ip, cpy); - ip += length; op = cpy; + ip += length; + op = cpy; /* get offset */ - offset = LZ4_readLE16(ip); ip+=2; + offset = LZ4_readLE16(ip); + ip += 2; match = op - offset; if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside buffers */ LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */ @@ -675,88 +756,92 @@ FORCE_INLINE int LZ4_decompress_generic( unsigned s; do { s = *ip++; - if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; + if ((endOnInput) && (ip > iend - LASTLITERALS)) goto _output_error; length += s; - } while (s==255); - if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ + } while (s == 255); + if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)op)) goto _output_error; /* overflow detection */ } length += MINMATCH; /* check external dictionary */ - if ((dict==usingExtDict) && (match < lowPrefix)) { - if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ + if ((dict == usingExtDict) && (match < lowPrefix)) { + if (unlikely(op + length > oend - LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ - if (length <= (size_t)(lowPrefix-match)) { + if (length <= (size_t)(lowPrefix - match)) { /* match can be copied as a single segment from external dictionary */ - memmove(op, dictEnd - (lowPrefix-match), length); + memmove(op, dictEnd - (lowPrefix - match), length); op += length; } else { /* match encompass external dictionary and current block */ - size_t const copySize = (size_t)(lowPrefix-match); + size_t const copySize = (size_t)(lowPrefix - match); size_t const restSize = length - copySize; Utils::copy(op, dictEnd - copySize, copySize); op += copySize; - if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */ - BYTE* const endOfMatch = op + restSize; - const BYTE* copyFrom = lowPrefix; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE *const endOfMatch = op + restSize; + const BYTE *copyFrom = lowPrefix; while (op < endOfMatch) *op++ = *copyFrom++; } else { Utils::copy(op, lowPrefix, restSize); op += restSize; - } } + } + } continue; } /* copy match within block */ cpy = op + length; - if (unlikely(offset<8)) { + if (unlikely(offset < 8)) { const int dec64 = dec64table[offset]; op[0] = match[0]; op[1] = match[1]; op[2] = match[2]; op[3] = match[3]; match += dec32table[offset]; - Utils::copy<4>(op+4, match); + Utils::copy< 4 >(op + 4, match); match -= dec64; - } else { LZ4_copy8(op, match); match+=8; } + } else { + LZ4_copy8(op, match); + match += 8; + } op += 8; - if (unlikely(cpy>oend-12)) { - BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1); - if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ + if (unlikely(cpy > oend - 12)) { + BYTE *const oCopyLimit = oend - (WILDCOPYLENGTH - 1); + if (cpy > oend - LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ if (op < oCopyLimit) { LZ4_wildCopy(op, match, oCopyLimit); match += oCopyLimit - op; op = oCopyLimit; } - while (op16) LZ4_wildCopy(op+8, match+8, cpy); + if (length > 16) LZ4_wildCopy(op + 8, match + 8, cpy); } - op=cpy; /* correction */ + op = cpy; /* correction */ } /* end of decoding */ if (endOnInput) - return (int) (((char*)op)-dest); /* Nb of output bytes decoded */ + return (int)(((char *)op) - dest); /* Nb of output bytes decoded */ else - return (int) (((const char*)ip)-source); /* Nb of input bytes read */ + return (int)(((const char *)ip) - source); /* Nb of input bytes read */ /* Overflow error detected */ _output_error: - return (int) (-(((const char*)ip)-source))-1; + return (int)(-(((const char *)ip) - source)) - 1; } } // anonymous namespace -int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) noexcept +int LZ4_compress_fast(const char *source, char *dest, int inputSize, int maxOutputSize, int acceleration) noexcept { #if (HEAPMODE) void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ #else LZ4_stream_t ctx; - void* const ctxPtr = &ctx; + void *const ctxPtr = &ctx; #endif int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); @@ -767,9 +852,9 @@ int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutp return result; } -int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize) noexcept +int LZ4_decompress_safe(const char *source, char *dest, int compressedSize, int maxDecompressedSize) noexcept { - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0); + return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE *)dest, NULL, 0); } } // namespace ZeroTier diff --git a/core/MembershipCredential.hpp b/core/MembershipCredential.hpp index 4ce816a33..233c8acba 100644 --- a/core/MembershipCredential.hpp +++ b/core/MembershipCredential.hpp @@ -14,8 +14,6 @@ #ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP #define ZT_CERTIFICATEOFMEMBERSHIP_HPP -// TODO: redo - #include #include #include @@ -179,7 +177,7 @@ public: * @param RR Runtime environment for looking up peers * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call */ - ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const { return _verify(RR,tPtr,*this); } + ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const { return s_verify(RR, tPtr, *this); } // NOTE: right now we use v1 serialization format which works with both ZeroTier 1.x and 2.x. V2 format // will be switched on once 1.x is pretty much dead and out of support. diff --git a/core/OS.hpp b/core/OS.hpp index a882c901f..dad99fa1a 100644 --- a/core/OS.hpp +++ b/core/OS.hpp @@ -11,31 +11,43 @@ */ /****/ -// This include file uses various macros and other tricks to auto-detect, define, and -// canonicalize a bunch of macros and types used throughout the ZeroTier core. - #ifndef ZT_OS_HPP #define ZT_OS_HPP -#include -#include -#include -#include +/* Uncomment this to force a whole lot of debug output. */ +#define ZT_DEBUG_SPEW + +#if !defined(__GNUC__) && (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || defined(__INTEL_COMPILER) || defined(__clang__)) +#define __GNUC__ 3 +#endif #if defined(_WIN32) || defined(_WIN64) + +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x06010000 +#endif + #ifdef _MSC_VER #pragma warning(disable : 4290) #pragma warning(disable : 4996) #pragma warning(disable : 4101) #endif + #ifndef __WINDOWS__ #define __WINDOWS__ 1 #endif + #ifndef NOMINMAX #define NOMINMAX #endif + +#ifdef __UNIX_LIKE__ #undef __UNIX_LIKE__ +#endif +#ifdef __BSD__ #undef __BSD__ +#endif + #include #include #include @@ -43,68 +55,13 @@ #include #include #include -#endif -#ifdef SOCKET -#define ZT_SOCKET SOCKET -#else -#define ZT_SOCKET int -#endif -#ifdef INVALID_SOCKET -#define ZT_INVALID_SOCKET INVALID_SOCKET -#else -#define ZT_INVALID_SOCKET (-1) -#endif +#endif /* Microsoft Windows */ -#if !defined(__GNUC__) && (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || defined(__INTEL_COMPILER) || defined(__clang__)) -#define __GNUC__ 3 -#endif - -#ifdef __cplusplus -#if __cplusplus > 199711L -#include -#ifndef __CPP11__ -#define __CPP11__ -#endif -#endif -#ifndef __CPP11__ -// Beyond that defining nullptr, constexpr, and noexcept should allow us to still build on these. So far we've -// avoided deeper C++11 features like lambdas in the core until we're 100% sure all the ancient targets are gone. -#error TODO: to build on pre-c++11 compilers we will need to make a subset of std::atomic for integers -#define nullptr (0) -#define constexpr ZT_INLINE -#define noexcept throw() -#endif -#endif - -#ifdef __GNUC__ -#ifndef ZT_DEBUG -#ifdef __clang__ -#define ZT_INLINE __attribute__((always_inline)) inline -#else -#define ZT_INLINE inline -#endif -#endif -#ifndef restrict -#define restrict __restrict__ -#endif -#ifndef likely -#define likely(x) __builtin_expect((x),1) -#endif -#ifndef unlikely -#define unlikely(x) __builtin_expect((x),0) -#endif -#else /* not GCC-like */ -#ifndef restrict -#define restrict -#endif -#ifndef likely -#define likely(x) (x) -#endif -#ifndef unlikely -#define unlikely(x) (x) -#endif -#endif +#include +#include +#include +#include #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64)) #define ZT_ARCH_X64 1 @@ -112,7 +69,6 @@ #include #include #endif - #if defined(ZT_ARCH_X64) || defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) || defined(__I86__) || defined(__INTEL__) || defined(__386) #define ZT_ARCH_X86 1 #endif @@ -123,7 +79,7 @@ #endif #endif -#if (defined(__ARM_NEON) || defined(__ARM_NEON__) || defined(ZT_ARCH_ARM_HAS_NEON)) +#if defined(__ARM_NEON) || defined(__ARM_NEON__) || defined(ZT_ARCH_ARM_HAS_NEON) #if (defined(__APPLE__) && !defined(__LP64__)) || (defined(__ANDROID__) && defined(__arm__)) #ifdef ZT_ARCH_ARM_HAS_NEON #undef ZT_ARCH_ARM_HAS_NEON @@ -132,30 +88,10 @@ #ifndef ZT_ARCH_ARM_HAS_NEON #define ZT_ARCH_ARM_HAS_NEON 1 #endif +#endif #include /*#include */ #endif -#endif - -#if defined(__SIZEOF_INT128__) || ((defined(ZT_ARCH_X64) || defined(__aarch64__)) && defined(__GNUC__)) -#ifdef __SIZEOF_INT128__ -#define ZT_HAVE_UINT128 1 -typedef unsigned __int128 uint128_t; -#else -#define ZT_HAVE_UINT128 1 -typedef unsigned uint128_t __attribute__((mode(TI))); -#endif -#endif - -#if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux) -#ifndef __LINUX__ -#define __LINUX__ 1 -#endif -#ifndef __UNIX_LIKE__ -#define __UNIX_LIKE__ 1 -#endif -#include -#endif #ifdef __APPLE__ #include @@ -173,6 +109,16 @@ typedef unsigned uint128_t __attribute__((mode(TI))); #endif #endif +#if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux) +#ifndef __LINUX__ +#define __LINUX__ 1 +#endif +#ifndef __UNIX_LIKE__ +#define __UNIX_LIKE__ 1 +#endif +#include +#endif + #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) #ifndef __UNIX_LIKE__ #define __UNIX_LIKE__ 1 @@ -196,6 +142,81 @@ typedef unsigned uint128_t __attribute__((mode(TI))); #define ZT_EOL_S "\n" #endif +#ifdef SOCKET +#define ZT_SOCKET SOCKET +#else +#define ZT_SOCKET int +#endif +#ifdef INVALID_SOCKET +#define ZT_INVALID_SOCKET INVALID_SOCKET +#else +#define ZT_INVALID_SOCKET (-1) +#endif + +#ifdef __cplusplus +#if __cplusplus > 199711L +#include +#ifndef __CPP11__ +#define __CPP11__ 1 +#endif +#endif + +/* Right now we fail if no C++11. The core could be ported to old C++ compilers + * if a shim for were included. */ +#ifndef __CPP11__ +#error TODO: to build on pre-c++11 compilers we will need to make a subset of std::atomic for integers +#define nullptr (0) +#define constexpr ZT_INLINE +#define noexcept throw() +#endif +#endif + +#ifndef ZT_INLINE +#ifdef ZT_DEBUG +#define ZT_INLINE +#else +#if defined(__GNUC__) || defined(__clang__) +#define ZT_INLINE __attribute__((always_inline)) inline +#else +#define ZT_INLINE inline +#endif +#endif +#endif + +#ifndef restrict +#if defined(__GNUC__) || defined(__clang__) +#define restrict __restrict__ +#else +#define restrict +#endif +#endif + +#ifndef likely +#if defined(__GNUC__) || defined(__clang__) +#define likely(x) __builtin_expect((x),1) +#else +#define likely(x) x +#endif +#endif + +#ifndef unlikely +#if defined(__GNUC__) || defined(__clang__) +#define unlikely(x) __builtin_expect((x),0) +#else +#define unlikely(x) x +#endif +#endif + +#if defined(__SIZEOF_INT128__) || ((defined(ZT_ARCH_X64) || defined(__aarch64__)) && defined(__GNUC__)) +#ifdef __SIZEOF_INT128__ +#define ZT_HAVE_UINT128 1 +typedef unsigned __int128 uint128_t; +#else +#define ZT_HAVE_UINT128 1 +typedef unsigned uint128_t __attribute__((mode(TI))); +#endif +#endif + #if !defined(__BYTE_ORDER) && defined(__BYTE_ORDER__) #define __BYTE_ORDER __BYTE_ORDER__ #define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ @@ -212,17 +233,9 @@ typedef unsigned uint128_t __attribute__((mode(TI))); #define __BIG_ENDIAN _BIG_ENDIAN #endif -#ifndef ZT_INLINE -#ifdef ZT_DEBUG -#define ZT_INLINE -#else -#define ZT_INLINE inline -#endif -#endif - -#define ZT_DEBUG_SPEW -#ifdef ZT_DEBUG_SPEW #define ZT_VA_ARGS(...) , ##__VA_ARGS__ + +#ifdef ZT_DEBUG_SPEW #define ZT_SPEW(f,...) fprintf(stderr,"%s:%d(%s): " f ZT_EOL_S,__FILE__,__LINE__,__FUNCTION__ ZT_VA_ARGS(__VA_ARGS__)) #else #define ZT_SPEW(f,...) diff --git a/core/OwnershipCredential.hpp b/core/OwnershipCredential.hpp index 259145197..d7fbdef00 100644 --- a/core/OwnershipCredential.hpp +++ b/core/OwnershipCredential.hpp @@ -127,7 +127,7 @@ public: * @param tPtr That pointer we pass around * @return Credential verification result: OK, bad signature, or identity needed */ - ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const { return _verify(RR,tPtr,*this); } + ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const { return s_verify(RR, tPtr, *this); } static constexpr int marshalSizeMax() noexcept { return ZT_CERTIFICATEOFOWNERSHIP_MARSHAL_SIZE_MAX; } int marshal(uint8_t data[ZT_CERTIFICATEOFOWNERSHIP_MARSHAL_SIZE_MAX],bool forSign = false) const noexcept; diff --git a/core/RevocationCredential.hpp b/core/RevocationCredential.hpp index 024fc2edc..0786e67da 100644 --- a/core/RevocationCredential.hpp +++ b/core/RevocationCredential.hpp @@ -111,7 +111,7 @@ public: * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call */ ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR, void *tPtr) const noexcept - { return _verify(RR, tPtr, *this); } + { return s_verify(RR, tPtr, *this); } static constexpr int marshalSizeMax() noexcept { return ZT_REVOCATION_MARSHAL_SIZE_MAX; } diff --git a/core/TagCredential.hpp b/core/TagCredential.hpp index 7ccf5dbea..bf4b76c18 100644 --- a/core/TagCredential.hpp +++ b/core/TagCredential.hpp @@ -111,7 +111,7 @@ public: * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call */ ZT_INLINE Credential::VerifyResult verify(const RuntimeEnvironment *RR, void *tPtr) const noexcept - { return _verify(RR, tPtr, *this); } + { return s_verify(RR, tPtr, *this); } static constexpr int marshalSizeMax() noexcept { return ZT_TAG_MARSHAL_SIZE_MAX; }