A bunch of little warning removal and format fix things.

This commit is contained in:
Adam Ierymenko 2020-12-04 15:52:30 -05:00
parent ec76f6e1d2
commit 7d951783ca
No known key found for this signature in database
GPG key ID: C8877CF2D7A5D7F3
16 changed files with 484 additions and 376 deletions

View file

@ -32,7 +32,7 @@ struct SHA384Hash
uint64_t data[6]; uint64_t data[6];
ZT_INLINE SHA384Hash() noexcept ZT_INLINE SHA384Hash() noexcept
{ Utils::zero<sizeof(data)>(data); } { Utils::zero< sizeof(data) >(data); }
explicit ZT_INLINE SHA384Hash(const void *const d) noexcept explicit ZT_INLINE SHA384Hash(const void *const d) noexcept
{ Utils::copy< 48 >(data, d); } { Utils::copy< 48 >(data, d); }
@ -73,7 +73,7 @@ struct UniqueID
uint64_t data[2]; uint64_t data[2];
ZT_INLINE UniqueID() noexcept ZT_INLINE UniqueID() noexcept
{ Utils::zero<sizeof(data)>(data); } { Utils::zero< sizeof(data) >(data); }
ZT_INLINE UniqueID(const uint64_t a, const uint64_t b) noexcept 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); } { return (memcmp(data, b.data, 16) >= 0); }
}; };
static_assert(sizeof(SHA384Hash) == 48,"SHA384Hash contains unnecessary padding"); static_assert(sizeof(SHA384Hash) == 48, "SHA384Hash contains unnecessary padding");
static_assert(sizeof(UniqueID) == 16,"UniqueID contains unnecessary padding"); static_assert(sizeof(UniqueID) == 16, "UniqueID contains unnecessary padding");
template<unsigned long S> template< unsigned long S >
struct Blob struct Blob
{ {
uint8_t data[S]; uint8_t data[S];

View file

@ -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 #ifndef ZT_C25519_HPP
#define ZT_C25519_HPP #define ZT_C25519_HPP

View file

@ -24,8 +24,8 @@ extern "C" {
// These macros make the idiom of passing buffers to outside code via the API work properly even // 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 // if the first address of Buf does not overlap with its data field, since the C++ standard does
// not absolutely guarantee this. // not absolutely guarantee this.
#define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->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]))) #define ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
void *ZT_getBuffer() 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 // 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. // wrapped in a SharedPtr<> to be passed into the core.
try { try {
return _ZT_BUFTOPTR(new ZeroTier::Buf()); return ZT_BUFTOPTR(new ZeroTier::Buf());
} catch (...) { } catch (...) {
return nullptr; // can only happen on out of memory condition return nullptr; // can only happen on out of memory condition
} }
@ -44,7 +44,7 @@ void *ZT_getBuffer()
void ZT_freeBuffer(void *b) void ZT_freeBuffer(void *b)
{ {
if (b) if (b)
delete _ZT_PTRTOBUF(b); delete ZT_PTRTOBUF(b);
} }
struct p_queryResultBase 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) 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 { try {
*node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now)); *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now));
return ZT_RESULT_OK; return ZT_RESULT_OK;
@ -107,7 +107,7 @@ enum ZT_ResultCode ZT_Node_processWirePacket(
volatile int64_t *nextBackgroundTaskDeadline) volatile int64_t *nextBackgroundTaskDeadline)
{ {
try { 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<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline); return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
@ -133,7 +133,7 @@ enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
volatile int64_t *nextBackgroundTaskDeadline) volatile int64_t *nextBackgroundTaskDeadline)
{ {
try { 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<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline); return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;

View file

@ -112,7 +112,7 @@ public:
* *
* @param RR Runtime environment to provide for peer lookup, etc. * @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; } 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; int marshal(uint8_t data[ZT_CAPABILITY_MARSHAL_SIZE_MAX],bool forSign = false) const noexcept;

View file

@ -58,7 +58,7 @@ public:
Certificate &operator=(const ZT_Certificate &cert); 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)) { if (likely(&cert != this)) {
const ZT_Certificate *const sup = &cert; const ZT_Certificate *const sup = &cert;

View file

@ -26,7 +26,7 @@
((uint64_t)ZEROTIER_VERSION_MAJOR << 48U) | \ ((uint64_t)ZEROTIER_VERSION_MAJOR << 48U) | \
((uint64_t)ZEROTIER_VERSION_MINOR << 32U) | \ ((uint64_t)ZEROTIER_VERSION_MINOR << 32U) | \
((uint64_t)ZEROTIER_VERSION_REVISION << 16U) | \ ((uint64_t)ZEROTIER_VERSION_REVISION << 16U) | \
((uint64_t)ZEROTIER_VERSION_BUILD) ) ((uint64_t)ZEROTIER_VERSION_BUILD) )
/** /**
* Length of a ZeroTier address in bytes * Length of a ZeroTier address in bytes

View file

@ -43,7 +43,7 @@
namespace ZeroTier { namespace ZeroTier {
template<typename CRED> template<typename CRED>
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]; 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; 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::s_verify(const RuntimeEnvironment *RR, void *tPtr, const RevocationCredential &credential) { return p_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::s_verify(const RuntimeEnvironment *RR, void *tPtr, const TagCredential &credential) { return p_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::s_verify(const RuntimeEnvironment *RR, void *tPtr, const CapabilityCredential &credential) { return p_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 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. // Sanity check network ID.
if ((!credential.m_signedBy) || (credential.m_signedBy != Network::controllerFor(credential.m_networkId))) if ((!credential.m_signedBy) || (credential.m_signedBy != Network::controllerFor(credential.m_networkId)))

View file

@ -52,11 +52,11 @@ public:
}; };
protected: protected:
VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const MembershipCredential &credential) const; static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const MembershipCredential &credential);
VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const RevocationCredential &credential) const; static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const RevocationCredential &credential);
VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const TagCredential &credential) const; static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const TagCredential &credential);
VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const OwnershipCredential &credential) const; static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const OwnershipCredential &credential);
VerifyResult _verify(const RuntimeEnvironment *RR,void *tPtr,const CapabilityCredential &credential) const; static VerifyResult s_verify(const RuntimeEnvironment *RR, void *tPtr, const CapabilityCredential &credential);
}; };
} // namespace ZeroTier } // namespace ZeroTier

View file

@ -30,14 +30,12 @@ class Identity;
* This data structure is used for network configurations, node meta-data, * This data structure is used for network configurations, node meta-data,
* and other open-definition protocol objects. * and other open-definition protocol objects.
* *
* If this seems a little odd, it is. It dates back to the very first alpha * This is technically a binary encoding, but with delimiters chosen so that
* versions of ZeroTier and if it were redesigned today we'd use some kind * it looks like a series of key=value lines of the keys and values are
* of simple or standardized binary encoding. Nevertheless it is efficient * human-readable strings.
* 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 * The fastest way to build a dictionary to send is to use the append
* dictionary for creating outbound packets. * static functions, not to populate and then encode a Dictionary.
*/ */
class Dictionary class Dictionary
{ {
@ -408,7 +406,7 @@ private:
{ {
switch (c) { switch (c) {
case 0: case 0:
out.push_back(92); // backslash out.push_back(92);
out.push_back(48); out.push_back(48);
break; break;
case 10: case 10:

View file

@ -11,10 +11,21 @@
*/ */
/****/ /****/
// This is glue code to ease the use of the NIST P-384 elliptic curve. /*
* The contents of ECC384.cpp are third party code and are licensed under
// Note that the code inside ECC384.cpp is third party code and * the BSD 2-clause license.
// is under the BSD 2-clause license rather than ZeroTier's 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 #ifndef ZT_ECC384_HPP
#define ZT_ECC384_HPP #define ZT_ECC384_HPP

View file

@ -60,43 +60,47 @@ namespace {
// #define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */ // #define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */
// #define LZ4_VERSION_RELEASE 5 /* for tweaks, bug-fixes, or development */ // #define LZ4_VERSION_RELEASE 5 /* for tweaks, bug-fixes, or development */
#define LZ4_MEMORY_USAGE 14 #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) #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) */ 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_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 hashTable[LZ4_HASH_SIZE_U32];
uint32_t currentOffset; uint32_t currentOffset;
uint32_t initCheck; uint32_t initCheck;
const uint8_t* dictionary; const uint8_t *dictionary;
uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */ uint8_t *bufferStart; /* obsolete, used for slideInputBuffer */
uint32_t dictSize; uint32_t dictSize;
} LZ4_stream_t_internal; } LZ4_stream_t_internal;
typedef struct { typedef struct
const uint8_t* externalDict; {
const uint8_t *externalDict;
size_t extDictSize; size_t extDictSize;
const uint8_t* prefixEnd; const uint8_t *prefixEnd;
size_t prefixSize; size_t prefixSize;
} LZ4_streamDecode_t_internal; } LZ4_streamDecode_t_internal;
#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) #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]; unsigned long long table[LZ4_STREAMSIZE_U64];
LZ4_stream_t_internal internal_donotuse; 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 #define LZ4_STREAMDECODESIZE_U64 4
union LZ4_streamDecode_u { union LZ4_streamDecode_u
{
unsigned long long table[LZ4_STREAMDECODESIZE_U64]; unsigned long long table[LZ4_STREAMDECODESIZE_U64];
LZ4_streamDecode_t_internal internal_donotuse; LZ4_streamDecode_t_internal internal_donotuse;
} ; /* previously typedef'd to LZ4_streamDecode_t */ }; /* previously typedef'd to LZ4_streamDecode_t */
#ifndef HEAPMODE #ifndef HEAPMODE
#define HEAPMODE 0 #define HEAPMODE 0
@ -112,13 +116,13 @@ union LZ4_streamDecode_u {
#define LZ4_FORCE_SW_BITCOUNT #define LZ4_FORCE_SW_BITCOUNT
#endif #endif
#define ALLOCATOR(n,s) calloc(n,s) #define ALLOCATOR(n, s) calloc(n,s)
#define FREEMEM free #define FREEMEM free
typedef uint8_t BYTE; typedef uint8_t BYTE;
typedef uint16_t U16; typedef uint16_t U16;
typedef uint32_t U32; typedef uint32_t U32;
typedef int32_t S32; typedef int32_t S32;
typedef uint64_t U64; typedef uint64_t U64;
typedef uintptr_t uptrval; typedef uintptr_t uptrval;
typedef uintptr_t reg_t; typedef uintptr_t reg_t;
@ -129,13 +133,23 @@ typedef uintptr_t reg_t;
#define LZ4_isLittleEndian() (0) #define LZ4_isLittleEndian() (0)
#endif #endif
#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) #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 U16 LZ4_read16(const void *memPtr)
FORCE_INLINE U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } { return *(const U16 *)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 U32 LZ4_read32(const void *memPtr)
FORCE_INLINE void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } { return *(const U32 *)memPtr; }
#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
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; 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 U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
FORCE_INLINE U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } 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 */ #endif /* LZ4_FORCE_MEMORY_ACCESS */
FORCE_INLINE U16 LZ4_readLE16(const void* memPtr) FORCE_INLINE U16 LZ4_readLE16(const void *memPtr)
{ {
if (LZ4_isLittleEndian()) { if (LZ4_isLittleEndian()) {
return LZ4_read16(memPtr); return LZ4_read16(memPtr);
} else { } else {
const BYTE* p = (const BYTE*)memPtr; const BYTE *p = (const BYTE *)memPtr;
return (U16)((U16)p[0] + (p[1]<<8)); 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()) { if (LZ4_isLittleEndian()) {
LZ4_write16(memPtr, value); LZ4_write16(memPtr, value);
} else { } else {
BYTE* p = (BYTE*)memPtr; BYTE *p = (BYTE *)memPtr;
p[0] = (BYTE) value; p[0] = (BYTE)value;
p[1] = (BYTE)(value>>8); 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; BYTE *d = (BYTE *)dstPtr;
const BYTE* s = (const BYTE*)srcPtr; const BYTE *s = (const BYTE *)srcPtr;
BYTE* const e = (BYTE*)dstEnd; BYTE *const e = (BYTE *)dstEnd;
do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e); do {
LZ4_copy8(d, s);
d += 8;
s += 8;
}
while (d < e);
} }
#define MINMATCH 4 #define MINMATCH 4
@ -204,7 +223,7 @@ FORCE_INLINE void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
#define WILDCOPYLENGTH 8 #define WILDCOPYLENGTH 8
#define LASTLITERALS 5 #define LASTLITERALS 5
#define MFLIMIT (WILDCOPYLENGTH+MINMATCH) #define MFLIMIT (WILDCOPYLENGTH+MINMATCH)
static const int LZ4_minLength = (MFLIMIT+1); static const int LZ4_minLength = (MFLIMIT + 1);
#define KB *(1 <<10) #define KB *(1 <<10)
// #define MB *(1 <<20) // #define MB *(1 <<20)
@ -220,15 +239,15 @@ static const int LZ4_minLength = (MFLIMIT+1);
// #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ // #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val) FORCE_INLINE unsigned LZ4_NbCommonBytes(reg_t val)
{ {
if (LZ4_isLittleEndian()) { if (LZ4_isLittleEndian()) {
if (sizeof(val)==8) { if (sizeof(val) == 8) {
# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r = 0; unsigned long r = 0;
_BitScanForward64( &r, (U64)val ); _BitScanForward64( &r, (U64)val );
return (int)(r>>3); 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_ctzll((U64)val) >> 3); return (__builtin_ctzll((U64)val) >> 3);
# else # 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 }; 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; unsigned long r;
_BitScanForward( &r, (U32)val ); _BitScanForward( &r, (U32)val );
return (int)(r>>3); 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); return (__builtin_ctz((U32)val) >> 3);
# else # 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 }; 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 # endif
} }
} else /* Big Endian CPU */ { } else /* Big Endian CPU */ {
if (sizeof(val)==8) { if (sizeof(val) == 8) {
# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
unsigned long r = 0; unsigned long r = 0;
_BitScanReverse64( &r, val ); _BitScanReverse64( &r, val );
return (unsigned)(r>>3); 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); return (__builtin_clzll((U64)val) >> 3);
# else # else
unsigned r; unsigned r;
@ -266,7 +285,7 @@ FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val)
unsigned long r = 0; unsigned long r = 0;
_BitScanReverse( &r, (unsigned long)val ); _BitScanReverse( &r, (unsigned long)val );
return (unsigned)(r>>3); 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); return (__builtin_clz((U32)val) >> 3);
# else # else
unsigned r; unsigned r;
@ -279,95 +298,144 @@ FORCE_INLINE unsigned LZ4_NbCommonBytes (reg_t val)
} }
#define STEPSIZE sizeof(reg_t) #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<pInLimit-(STEPSIZE-1))) { while (likely(pIn < pInLimit - (STEPSIZE - 1))) {
reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); reg_t const diff = LZ4_read_ARCH(pMatch) ^LZ4_read_ARCH(pIn);
if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; } if (!diff) {
pIn += STEPSIZE;
pMatch += STEPSIZE;
continue;
}
pIn += LZ4_NbCommonBytes(diff); pIn += LZ4_NbCommonBytes(diff);
return (unsigned)(pIn - pStart); return (unsigned)(pIn - pStart);
} }
if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; } if ((STEPSIZE == 8) && (pIn < (pInLimit - 3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) {
if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; } pIn += 4;
if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++; pMatch += 4;
}
if ((pIn < (pInLimit - 1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) {
pIn += 2;
pMatch += 2;
}
if ((pIn < pInLimit) && (*pMatch == *pIn)) pIn++;
return (unsigned)(pIn - pStart); return (unsigned)(pIn - pStart);
} }
static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1)); static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT - 1));
static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */ static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive; typedef enum
typedef enum { byPtr, byU32, byU16 } tableType_t; {
notLimited = 0, limitedOutput = 1
} limitedOutput_directive;
typedef enum
{
byPtr, byU32, byU16
} tableType_t;
typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive; typedef enum
typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; {
noDict = 0, withPrefix64k, usingExtDict
} dict_directive;
typedef enum
{
noDictIssue = 0, dictSmall
} dictIssue_directive;
typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; typedef enum
typedef enum { full = 0, partial = 1 } earlyEnd_directive; {
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) FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
{ {
if (tableType == byU16) if (tableType == byU16)
return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); return ((sequence * 2654435761U) >> ((MINMATCH * 8) - (LZ4_HASHLOG + 1)));
else 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) FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
{ {
static const U64 prime5bytes = 889523592379ULL; static const U64 prime5bytes = 889523592379ULL;
static const U64 prime8bytes = 11400714785074694791ULL; 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()) if (LZ4_isLittleEndian())
return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
else else
return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); 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); 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) switch (tableType) {
{ case byPtr: {
case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } const BYTE **hashTable = (const BYTE **)tableBase;
case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } hashTable[h] = p;
case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } 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); U32 const h = LZ4_hashPosition(p, tableType);
LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); 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 == byPtr) {
if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; } const BYTE **hashTable = (const BYTE **)tableBase;
{ const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ 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); U32 const h = LZ4_hashPosition(p, tableType);
return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
} }
FORCE_INLINE int LZ4_compress_generic( FORCE_INLINE int LZ4_compress_generic(
LZ4_stream_t_internal* const cctx, LZ4_stream_t_internal *const cctx,
const char* const source, const char *const source,
char* const dest, char *const dest,
const int inputSize, const int inputSize,
const int maxOutputSize, const int maxOutputSize,
const limitedOutput_directive outputLimited, const limitedOutput_directive outputLimited,
@ -376,56 +444,57 @@ FORCE_INLINE int LZ4_compress_generic(
const dictIssue_directive dictIssue, const dictIssue_directive dictIssue,
const U32 acceleration) const U32 acceleration)
{ {
const BYTE* ip = (const BYTE*) source; const BYTE *ip = (const BYTE *)source;
const BYTE* base; const BYTE *base;
const BYTE* lowLimit; const BYTE *lowLimit;
const BYTE* const lowRefLimit = ip - cctx->dictSize; const BYTE *const lowRefLimit = ip - cctx->dictSize;
const BYTE* const dictionary = cctx->dictionary; const BYTE *const dictionary = cctx->dictionary;
const BYTE* const dictEnd = dictionary + cctx->dictSize; const BYTE *const dictEnd = dictionary + cctx->dictSize;
const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source; const ptrdiff_t dictDelta = dictEnd - (const BYTE *)source;
const BYTE* anchor = (const BYTE*) source; const BYTE *anchor = (const BYTE *)source;
const BYTE* const iend = ip + inputSize; const BYTE *const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT; const BYTE *const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = iend - LASTLITERALS; const BYTE *const matchlimit = iend - LASTLITERALS;
BYTE* op = (BYTE*) dest; BYTE *op = (BYTE *)dest;
BYTE* const olimit = op + maxOutputSize; BYTE *const olimit = op + maxOutputSize;
U32 forwardH; U32 forwardH;
/* Init conditions */ /* Init conditions */
if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */
switch(dict) switch (dict) {
{
case noDict: case noDict:
default: default:
base = (const BYTE*)source; base = (const BYTE *)source;
lowLimit = (const BYTE*)source; lowLimit = (const BYTE *)source;
break; break;
case withPrefix64k: case withPrefix64k:
base = (const BYTE*)source - cctx->currentOffset; base = (const BYTE *)source - cctx->currentOffset;
lowLimit = (const BYTE*)source - cctx->dictSize; lowLimit = (const BYTE *)source - cctx->dictSize;
break; break;
case usingExtDict: case usingExtDict:
base = (const BYTE*)source - cctx->currentOffset; base = (const BYTE *)source - cctx->currentOffset;
lowLimit = (const BYTE*)source; lowLimit = (const BYTE *)source;
break; break;
} }
if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ if ((tableType == byU16) && (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) */ if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
/* First Byte */ /* First Byte */
LZ4_putPosition(ip, cctx->hashTable, tableType, base); LZ4_putPosition(ip, cctx->hashTable, tableType, base);
ip++; forwardH = LZ4_hashPosition(ip, tableType); ip++;
forwardH = LZ4_hashPosition(ip, tableType);
/* Main Loop */ /* Main Loop */
for ( ; ; ) { for (;;) {
ptrdiff_t refDelta = 0; ptrdiff_t refDelta = 0;
const BYTE* match; const BYTE *match;
BYTE* token; BYTE *token;
/* Find a match */ /* Find a match */
{ const BYTE* forwardIp = ip; {
const BYTE *forwardIp = ip;
unsigned step = 1; unsigned step = 1;
unsigned searchMatchNb = acceleration << LZ4_skipTrigger; unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
do { do {
@ -437,76 +506,82 @@ FORCE_INLINE int LZ4_compress_generic(
if (unlikely(forwardIp > mflimit)) goto _last_literals; if (unlikely(forwardIp > mflimit)) goto _last_literals;
match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
if (dict==usingExtDict) { if (dict == usingExtDict) {
if (match < (const BYTE*)source) { if (match < (const BYTE *)source) {
refDelta = dictDelta; refDelta = dictDelta;
lowLimit = dictionary; lowLimit = dictionary;
} else { } else {
refDelta = 0; refDelta = 0;
lowLimit = (const BYTE*)source; lowLimit = (const BYTE *)source;
} } }
}
forwardH = LZ4_hashPosition(forwardIp, tableType); forwardH = LZ4_hashPosition(forwardIp, tableType);
LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
} while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0) } while (((dictIssue == dictSmall) ? (match < lowRefLimit) : 0)
|| ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) || ((tableType == byU16) ? 0 : (match + MAX_DISTANCE < ip))
|| (LZ4_read32(match+refDelta) != LZ4_read32(ip)) ); || (LZ4_read32(match + refDelta) != LZ4_read32(ip)));
} }
/* Catch up */ /* 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 */ /* Encode Literals */
{ unsigned const litLength = (unsigned)(ip - anchor); {
unsigned const litLength = (unsigned)(ip - anchor);
token = op++; token = op++;
if ((outputLimited) && /* Check output buffer overflow */ 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; return 0;
if (litLength >= RUN_MASK) { if (litLength >= RUN_MASK) {
int len = (int)litLength-RUN_MASK; int len = (int)litLength - RUN_MASK;
*token = (RUN_MASK<<ML_BITS); *token = (RUN_MASK << ML_BITS);
for(; len >= 255 ; len-=255) *op++ = 255; for (; len >= 255; len -= 255) *op++ = 255;
*op++ = (BYTE)len; *op++ = (BYTE)len;
} } else *token = (BYTE)(litLength << ML_BITS);
else *token = (BYTE)(litLength<<ML_BITS);
/* Copy Literals */ /* Copy Literals */
LZ4_wildCopy(op, anchor, op+litLength); LZ4_wildCopy(op, anchor, op + litLength);
op+=litLength; op += litLength;
} }
_next_match: _next_match:
/* Encode Offset */ /* Encode Offset */
LZ4_writeLE16(op, (U16)(ip-match)); op+=2; LZ4_writeLE16(op, (U16)(ip - match));
op += 2;
/* Encode MatchLength */ /* Encode MatchLength */
{ unsigned matchCode; {
unsigned matchCode;
if ((dict==usingExtDict) && (lowLimit==dictionary)) { if ((dict == usingExtDict) && (lowLimit == dictionary)) {
const BYTE* limit; const BYTE *limit;
match += refDelta; match += refDelta;
limit = ip + (dictEnd-match); limit = ip + (dictEnd - match);
if (limit > matchlimit) limit = matchlimit; if (limit > matchlimit) limit = matchlimit;
matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, limit);
ip += MINMATCH + matchCode; ip += MINMATCH + matchCode;
if (ip==limit) { if (ip == limit) {
unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit); unsigned const more = LZ4_count(ip, (const BYTE *)source, matchlimit);
matchCode += more; matchCode += more;
ip += more; ip += more;
} }
} else { } else {
matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); matchCode = LZ4_count(ip + MINMATCH, match + MINMATCH, matchlimit);
ip += MINMATCH + matchCode; ip += MINMATCH + matchCode;
} }
if ( outputLimited && /* Check output buffer overflow */ if (outputLimited && /* Check output buffer overflow */
(unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) (unlikely(op + (1 + LASTLITERALS) + (matchCode >> 8) > olimit)))
return 0; return 0;
if (matchCode >= ML_MASK) { if (matchCode >= ML_MASK) {
*token += ML_MASK; *token += ML_MASK;
matchCode -= ML_MASK; matchCode -= ML_MASK;
LZ4_write32(op, 0xFFFFFFFF); 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 += matchCode / 255;
*op++ = (BYTE)(matchCode % 255); *op++ = (BYTE)(matchCode % 255);
} else } else
@ -519,23 +594,27 @@ FORCE_INLINE int LZ4_compress_generic(
if (ip > mflimit) break; if (ip > mflimit) break;
/* Fill table */ /* Fill table */
LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); LZ4_putPosition(ip - 2, cctx->hashTable, tableType, base);
/* Test next position */ /* Test next position */
match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
if (dict==usingExtDict) { if (dict == usingExtDict) {
if (match < (const BYTE*)source) { if (match < (const BYTE *)source) {
refDelta = dictDelta; refDelta = dictDelta;
lowLimit = dictionary; lowLimit = dictionary;
} else { } else {
refDelta = 0; refDelta = 0;
lowLimit = (const BYTE*)source; lowLimit = (const BYTE *)source;
} } }
}
LZ4_putPosition(ip, cctx->hashTable, tableType, base); LZ4_putPosition(ip, cctx->hashTable, tableType, base);
if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1) if (((dictIssue == dictSmall) ? (match >= lowRefLimit) : 1)
&& (match+MAX_DISTANCE>=ip) && (match + MAX_DISTANCE >= ip)
&& (LZ4_read32(match+refDelta)==LZ4_read32(ip)) ) && (LZ4_read32(match + refDelta) == LZ4_read32(ip))) {
{ token=op++; *token=0; goto _next_match; } token = op++;
*token = 0;
goto _next_match;
}
/* Prepare next loop */ /* Prepare next loop */
forwardH = LZ4_hashPosition(++ip, tableType); forwardH = LZ4_hashPosition(++ip, tableType);
@ -543,128 +622,130 @@ FORCE_INLINE int LZ4_compress_generic(
_last_literals: _last_literals:
/* Encode Last Literals */ /* Encode Last Literals */
{ size_t const lastRun = (size_t)(iend - anchor); {
if ( (outputLimited) && /* Check output buffer overflow */ size_t const lastRun = (size_t)(iend - anchor);
((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) ) if ((outputLimited) && /* Check output buffer overflow */
((op - (BYTE *)dest) + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > (U32)maxOutputSize))
return 0; return 0;
if (lastRun >= RUN_MASK) { if (lastRun >= RUN_MASK) {
size_t accumulator = lastRun - RUN_MASK; size_t accumulator = lastRun - RUN_MASK;
*op++ = RUN_MASK << ML_BITS; *op++ = RUN_MASK << ML_BITS;
for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; for (; accumulator >= 255; accumulator -= 255) *op++ = 255;
*op++ = (BYTE) accumulator; *op++ = (BYTE)accumulator;
} else { } else {
*op++ = (BYTE)(lastRun<<ML_BITS); *op++ = (BYTE)(lastRun << ML_BITS);
} }
Utils::copy(op, anchor, lastRun); Utils::copy(op, anchor, lastRun);
op += lastRun; op += lastRun;
} }
/* End */ /* End */
return (int) (((char*)op)-dest); return (int)(((char *)op) - dest);
} }
ZT_INLINE int LZ4_compress_fast_extState(void* state,const char* source,char* dest,int inputSize,int maxOutputSize,int acceleration) ZT_INLINE int LZ4_compress_fast_extState(void *state, const char *source, char *dest, int inputSize, int maxOutputSize, int acceleration)
{ {
LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; LZ4_stream_t_internal *ctx = &((LZ4_stream_t *)state)->internal_donotuse;
LZ4_resetStream((LZ4_stream_t*)state); LZ4_resetStream((LZ4_stream_t *)state);
//if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; //if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
if (maxOutputSize >= LZ4_compressBound(inputSize)) { if (maxOutputSize >= LZ4_compressBound(inputSize)) {
if (inputSize < LZ4_64Klimit) 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 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 { } else {
if (inputSize < LZ4_64Klimit) 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 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<sizeof(LZ4_stream_t)>(LZ4_stream); Utils::zero< sizeof(LZ4_stream_t) >(LZ4_stream);
} }
FORCE_INLINE int LZ4_decompress_generic( FORCE_INLINE int LZ4_decompress_generic(
const char* const source, const char *const source,
char* const dest, char *const dest,
int inputSize, 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 endOnInput, /* endOnOutputSize, endOnInputSize */
int partialDecoding, /* full, partial */ int partialDecoding, /* full, partial */
int targetOutputSize, /* only used if partialDecoding==partial */ int targetOutputSize, /* only used if partialDecoding==partial */
int dict, /* noDict, withPrefix64k, usingExtDict */ int dict, /* noDict, withPrefix64k, usingExtDict */
const BYTE* const lowPrefix, /* == dest when no prefix */ const BYTE *const lowPrefix, /* == dest when no prefix */
const BYTE* const dictStart, /* only if dict==usingExtDict */ const BYTE *const dictStart, /* only if dict==usingExtDict */
const size_t dictSize /* note : = 0 if noDict */ const size_t dictSize /* note : = 0 if noDict */
) )
{ {
/* Local Variables */ /* Local Variables */
const BYTE* ip = (const BYTE*) source; const BYTE *ip = (const BYTE *)source;
const BYTE* const iend = ip + inputSize; const BYTE *const iend = ip + inputSize;
BYTE* op = (BYTE*) dest; BYTE *op = (BYTE *)dest;
BYTE* const oend = op + outputSize; BYTE *const oend = op + outputSize;
BYTE* cpy; BYTE *cpy;
BYTE* oexit = op + targetOutputSize; BYTE *oexit = op + targetOutputSize;
const BYTE* const lowLimit = lowPrefix - dictSize; 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 unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4};
const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3}; 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))); const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
/* Special cases */ /* Special cases */
if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */ 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 ((inputSize == 1) && (*ip == 0)) ? 0 : -1; /* Empty output buffer */
if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); if ((!endOnInput) && (unlikely(outputSize == 0))) return (*ip == 0 ? 1 : -1);
/* Main Loop : decode sequences */ /* Main Loop : decode sequences */
while (1) { while (1) {
size_t length; size_t length;
const BYTE* match; const BYTE *match;
size_t offset; size_t offset;
/* get literal length */ /* get literal length */
unsigned const token = *ip++; unsigned const token = *ip++;
if ((length=(token>>ML_BITS)) == RUN_MASK) { if ((length = (token >> ML_BITS)) == RUN_MASK) {
unsigned s; unsigned s;
do { do {
s = *ip++; s = *ip++;
length += s; length += s;
} while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) ); } while (likely(endOnInput ? ip < iend - RUN_MASK : 1) & (s == 255));
if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error; /* overflow detection */ if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)(op))) goto _output_error; /* overflow detection */
if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error; /* overflow detection */ if ((safeDecode) && unlikely((uptrval)(ip) + length < (uptrval)(ip))) goto _output_error; /* overflow detection */
} }
/* copy literals */ /* copy literals */
cpy = op+length; cpy = op + length;
if ( ((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) if (((endOnInput) && ((cpy > (partialDecoding ? oexit : oend - MFLIMIT)) || (ip + length > iend - (2 + 1 + LASTLITERALS))))
|| ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) {
{
if (partialDecoding) { if (partialDecoding) {
if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output 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 */ if ((endOnInput) && (ip + length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
} else { } else {
if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ 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) && ((ip + length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
} }
Utils::copy(op, ip, length); Utils::copy(op, ip, length);
ip += length; ip += length;
op += length; op += length;
break; /* Necessarily EOF, due to parsing restrictions */ break; /* Necessarily EOF, due to parsing restrictions */
} }
LZ4_wildCopy(op, ip, cpy); LZ4_wildCopy(op, ip, cpy);
ip += length; op = cpy; ip += length;
op = cpy;
/* get offset */ /* get offset */
offset = LZ4_readLE16(ip); ip+=2; offset = LZ4_readLE16(ip);
ip += 2;
match = op - offset; match = op - offset;
if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside buffers */ 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 */ 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; unsigned s;
do { do {
s = *ip++; s = *ip++;
if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; if ((endOnInput) && (ip > iend - LASTLITERALS)) goto _output_error;
length += s; length += s;
} while (s==255); } while (s == 255);
if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ if ((safeDecode) && unlikely((uptrval)(op) + length < (uptrval)op)) goto _output_error; /* overflow detection */
} }
length += MINMATCH; length += MINMATCH;
/* check external dictionary */ /* check external dictionary */
if ((dict==usingExtDict) && (match < lowPrefix)) { if ((dict == usingExtDict) && (match < lowPrefix)) {
if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ 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 */ /* 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; op += length;
} else { } else {
/* match encompass external dictionary and current block */ /* 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; size_t const restSize = length - copySize;
Utils::copy(op, dictEnd - copySize, copySize); Utils::copy(op, dictEnd - copySize, copySize);
op += copySize; op += copySize;
if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */ if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */
BYTE* const endOfMatch = op + restSize; BYTE *const endOfMatch = op + restSize;
const BYTE* copyFrom = lowPrefix; const BYTE *copyFrom = lowPrefix;
while (op < endOfMatch) *op++ = *copyFrom++; while (op < endOfMatch) *op++ = *copyFrom++;
} else { } else {
Utils::copy(op, lowPrefix, restSize); Utils::copy(op, lowPrefix, restSize);
op += restSize; op += restSize;
} } }
}
continue; continue;
} }
/* copy match within block */ /* copy match within block */
cpy = op + length; cpy = op + length;
if (unlikely(offset<8)) { if (unlikely(offset < 8)) {
const int dec64 = dec64table[offset]; const int dec64 = dec64table[offset];
op[0] = match[0]; op[0] = match[0];
op[1] = match[1]; op[1] = match[1];
op[2] = match[2]; op[2] = match[2];
op[3] = match[3]; op[3] = match[3];
match += dec32table[offset]; match += dec32table[offset];
Utils::copy<4>(op+4, match); Utils::copy< 4 >(op + 4, match);
match -= dec64; match -= dec64;
} else { LZ4_copy8(op, match); match+=8; } } else {
LZ4_copy8(op, match);
match += 8;
}
op += 8; op += 8;
if (unlikely(cpy>oend-12)) { if (unlikely(cpy > oend - 12)) {
BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1); BYTE *const oCopyLimit = oend - (WILDCOPYLENGTH - 1);
if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ if (cpy > oend - LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
if (op < oCopyLimit) { if (op < oCopyLimit) {
LZ4_wildCopy(op, match, oCopyLimit); LZ4_wildCopy(op, match, oCopyLimit);
match += oCopyLimit - op; match += oCopyLimit - op;
op = oCopyLimit; op = oCopyLimit;
} }
while (op<cpy) *op++ = *match++; while (op < cpy) *op++ = *match++;
} else { } else {
LZ4_copy8(op, match); LZ4_copy8(op, match);
if (length>16) 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 */ /* end of decoding */
if (endOnInput) if (endOnInput)
return (int) (((char*)op)-dest); /* Nb of output bytes decoded */ return (int)(((char *)op) - dest); /* Nb of output bytes decoded */
else 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 */ /* Overflow error detected */
_output_error: _output_error:
return (int) (-(((const char*)ip)-source))-1; return (int)(-(((const char *)ip) - source)) - 1;
} }
} // anonymous namespace } // 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) #if (HEAPMODE)
void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
#else #else
LZ4_stream_t ctx; LZ4_stream_t ctx;
void* const ctxPtr = &ctx; void *const ctxPtr = &ctx;
#endif #endif
int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); 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; 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 } // namespace ZeroTier

View file

@ -14,8 +14,6 @@
#ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP #ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP
#define ZT_CERTIFICATEOFMEMBERSHIP_HPP #define ZT_CERTIFICATEOFMEMBERSHIP_HPP
// TODO: redo
#include <string> #include <string>
#include <stdexcept> #include <stdexcept>
#include <algorithm> #include <algorithm>
@ -179,7 +177,7 @@ public:
* @param RR Runtime environment for looking up peers * @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 * @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 // 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. // will be switched on once 1.x is pretty much dead and out of support.

View file

@ -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 #ifndef ZT_OS_HPP
#define ZT_OS_HPP #define ZT_OS_HPP
#include <stdint.h> /* Uncomment this to force a whole lot of debug output. */
#include <stdlib.h> #define ZT_DEBUG_SPEW
#include <string.h>
#include <stdio.h> #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) #if defined(_WIN32) || defined(_WIN64)
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x06010000
#endif
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(disable : 4290) #pragma warning(disable : 4290)
#pragma warning(disable : 4996) #pragma warning(disable : 4996)
#pragma warning(disable : 4101) #pragma warning(disable : 4101)
#endif #endif
#ifndef __WINDOWS__ #ifndef __WINDOWS__
#define __WINDOWS__ 1 #define __WINDOWS__ 1
#endif #endif
#ifndef NOMINMAX #ifndef NOMINMAX
#define NOMINMAX #define NOMINMAX
#endif #endif
#ifdef __UNIX_LIKE__
#undef __UNIX_LIKE__ #undef __UNIX_LIKE__
#endif
#ifdef __BSD__
#undef __BSD__ #undef __BSD__
#endif
#include <WinSock2.h> #include <WinSock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#include <Windows.h> #include <Windows.h>
@ -43,68 +55,13 @@
#include <shlwapi.h> #include <shlwapi.h>
#include <Shlobj.h> #include <Shlobj.h>
#include <sys/param.h> #include <sys/param.h>
#endif
#ifdef SOCKET #endif /* Microsoft Windows */
#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
#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__)) #include <stdint.h>
#define __GNUC__ 3 #include <stdlib.h>
#endif #include <string.h>
#include <stdio.h>
#ifdef __cplusplus
#if __cplusplus > 199711L
#include <atomic>
#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
#if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64)) #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
#define ZT_ARCH_X64 1 #define ZT_ARCH_X64 1
@ -112,7 +69,6 @@
#include <emmintrin.h> #include <emmintrin.h>
#include <immintrin.h> #include <immintrin.h>
#endif #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) #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 #define ZT_ARCH_X86 1
#endif #endif
@ -123,7 +79,7 @@
#endif #endif
#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__)) #if (defined(__APPLE__) && !defined(__LP64__)) || (defined(__ANDROID__) && defined(__arm__))
#ifdef ZT_ARCH_ARM_HAS_NEON #ifdef ZT_ARCH_ARM_HAS_NEON
#undef ZT_ARCH_ARM_HAS_NEON #undef ZT_ARCH_ARM_HAS_NEON
@ -132,30 +88,10 @@
#ifndef ZT_ARCH_ARM_HAS_NEON #ifndef ZT_ARCH_ARM_HAS_NEON
#define ZT_ARCH_ARM_HAS_NEON 1 #define ZT_ARCH_ARM_HAS_NEON 1
#endif #endif
#endif
#include <arm_neon.h> #include <arm_neon.h>
/*#include <arm_acle.h>*/ /*#include <arm_acle.h>*/
#endif #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 <endian.h>
#endif
#ifdef __APPLE__ #ifdef __APPLE__
#include <TargetConditionals.h> #include <TargetConditionals.h>
@ -173,6 +109,16 @@ typedef unsigned uint128_t __attribute__((mode(TI)));
#endif #endif
#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 <endian.h>
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#ifndef __UNIX_LIKE__ #ifndef __UNIX_LIKE__
#define __UNIX_LIKE__ 1 #define __UNIX_LIKE__ 1
@ -196,6 +142,81 @@ typedef unsigned uint128_t __attribute__((mode(TI)));
#define ZT_EOL_S "\n" #define ZT_EOL_S "\n"
#endif #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 <atomic>
#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 <atomic> 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__) #if !defined(__BYTE_ORDER) && defined(__BYTE_ORDER__)
#define __BYTE_ORDER __BYTE_ORDER__ #define __BYTE_ORDER __BYTE_ORDER__
#define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ #define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__
@ -212,17 +233,9 @@ typedef unsigned uint128_t __attribute__((mode(TI)));
#define __BIG_ENDIAN _BIG_ENDIAN #define __BIG_ENDIAN _BIG_ENDIAN
#endif #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__ #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__)) #define ZT_SPEW(f,...) fprintf(stderr,"%s:%d(%s): " f ZT_EOL_S,__FILE__,__LINE__,__FUNCTION__ ZT_VA_ARGS(__VA_ARGS__))
#else #else
#define ZT_SPEW(f,...) #define ZT_SPEW(f,...)

View file

@ -127,7 +127,7 @@ public:
* @param tPtr That pointer we pass around * @param tPtr That pointer we pass around
* @return Credential verification result: OK, bad signature, or identity needed * @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; } 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; int marshal(uint8_t data[ZT_CERTIFICATEOFOWNERSHIP_MARSHAL_SIZE_MAX],bool forSign = false) const noexcept;

View file

@ -111,7 +111,7 @@ public:
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call * @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 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 static constexpr int marshalSizeMax() noexcept
{ return ZT_REVOCATION_MARSHAL_SIZE_MAX; } { return ZT_REVOCATION_MARSHAL_SIZE_MAX; }

View file

@ -111,7 +111,7 @@ public:
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call * @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 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 static constexpr int marshalSizeMax() noexcept
{ return ZT_TAG_MARSHAL_SIZE_MAX; } { return ZT_TAG_MARSHAL_SIZE_MAX; }