diff options
Diffstat (limited to 'src/google/protobuf/stubs')
61 files changed, 1731 insertions, 5943 deletions
diff --git a/src/google/protobuf/stubs/atomic_sequence_num.h b/src/google/protobuf/stubs/atomic_sequence_num.h deleted file mode 100644 index bb20942f..00000000 --- a/src/google/protobuf/stubs/atomic_sequence_num.h +++ /dev/null @@ -1,54 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2014 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#ifndef GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_ -#define GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_ - -#include <google/protobuf/stubs/atomicops.h> - -namespace google { -namespace protobuf { -namespace internal { - -class SequenceNumber { - public: - SequenceNumber() : word_(0) {} - - AtomicWord GetNext() { - return NoBarrier_AtomicIncrement(&word_, 1) - 1; - } - private: - AtomicWord word_; -}; - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMIC_SEQUENCE_NUM_H_ diff --git a/src/google/protobuf/stubs/atomicops.h b/src/google/protobuf/stubs/atomicops.h deleted file mode 100644 index cb93227f..00000000 --- a/src/google/protobuf/stubs/atomicops.h +++ /dev/null @@ -1,244 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// The routines exported by this module are subtle. If you use them, even if -// you get the code right, it will depend on careful reasoning about atomicity -// and memory ordering; it will be less readable, and harder to maintain. If -// you plan to use these routines, you should have a good reason, such as solid -// evidence that performance would otherwise suffer, or there being no -// alternative. You should assume only properties explicitly guaranteed by the -// specifications in this file. You are almost certainly _not_ writing code -// just for the x86; if you assume x86 semantics, x86 hardware bugs and -// implementations on other archtectures will cause your code to break. If you -// do not know what you are doing, avoid these routines, and use a Mutex. -// -// It is incorrect to make direct assignments to/from an atomic variable. -// You should use one of the Load or Store routines. The NoBarrier -// versions are provided when no barriers are needed: -// NoBarrier_Store() -// NoBarrier_Load() -// Although there are currently no compiler enforcement, you are encouraged -// to use these. - -// This header and the implementations for each platform (located in -// atomicops_internals_*) must be kept in sync with the upstream code (V8). - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_H_ - -// Don't include this file for people not concerned about thread safety. -#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/platform_macros.h> - -namespace google { -namespace protobuf { -namespace internal { - -#if defined(GOOGLE_PROTOBUF_ARCH_POWER) -#if defined(_LP64) || defined(__LP64__) -typedef int32 Atomic32; -typedef intptr_t Atomic64; -#else -typedef intptr_t Atomic32; -typedef int64 Atomic64; -#endif -#else -typedef int32 Atomic32; -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -// We need to be able to go between Atomic64 and AtomicWord implicitly. This -// means Atomic64 and AtomicWord should be the same type on 64-bit. -#if defined(__ILP32__) || defined(GOOGLE_PROTOBUF_OS_NACL) -// NaCl's intptr_t is not actually 64-bits on 64-bit! -// http://code.google.com/p/nativeclient/issues/detail?id=1162 -// sparcv9's pointer type is 32bits -typedef int64 Atomic64; -#else -typedef intptr_t Atomic64; -#endif -#endif -#endif - -// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or -// Atomic64 routines below, depending on your architecture. -typedef intptr_t AtomicWord; - -// Atomically execute: -// result = *ptr; -// if (*ptr == old_value) -// *ptr = new_value; -// return result; -// -// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". -// Always return the old value of "*ptr" -// -// This routine implies no memory barriers. -Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value); - -// Atomically store new_value into *ptr, returning the previous value held in -// *ptr. This routine implies no memory barriers. -Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value); - -// Atomically increment *ptr by "increment". Returns the new value of -// *ptr with the increment applied. This routine implies no memory barriers. -Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); - -Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment); - -// These following lower-level operations are typically useful only to people -// implementing higher-level synchronization operations like spinlocks, -// mutexes, and condition-variables. They combine CompareAndSwap(), a load, or -// a store with appropriate memory-ordering instructions. "Acquire" operations -// ensure that no later memory access can be reordered ahead of the operation. -// "Release" operations ensure that no previous memory access can be reordered -// after the operation. "Barrier" operations have both "Acquire" and "Release" -// semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory -// access. -Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value); -Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value); - -#if defined(__MINGW32__) && defined(MemoryBarrier) -#undef MemoryBarrier -#endif -void MemoryBarrier(); -void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value); -void Acquire_Store(volatile Atomic32* ptr, Atomic32 value); -void Release_Store(volatile Atomic32* ptr, Atomic32 value); - -Atomic32 NoBarrier_Load(volatile const Atomic32* ptr); -Atomic32 Acquire_Load(volatile const Atomic32* ptr); -Atomic32 Release_Load(volatile const Atomic32* ptr); - -// 64-bit atomic operations (only available on 64-bit processors). -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value); -Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value); -Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); -Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); - -Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value); -Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value); -void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value); -void Acquire_Store(volatile Atomic64* ptr, Atomic64 value); -void Release_Store(volatile Atomic64* ptr, Atomic64 value); -Atomic64 NoBarrier_Load(volatile const Atomic64* ptr); -Atomic64 Acquire_Load(volatile const Atomic64* ptr); -Atomic64 Release_Load(volatile const Atomic64* ptr); -#endif // GOOGLE_PROTOBUF_ARCH_64_BIT - -} // namespace internal -} // namespace protobuf -} // namespace google - -// Include our platform specific implementation. -#define GOOGLE_PROTOBUF_ATOMICOPS_ERROR \ -"Atomic operations are not supported on your platform" - -// ThreadSanitizer, http://clang.llvm.org/docs/ThreadSanitizer.html. -#if defined(THREAD_SANITIZER) -#include <google/protobuf/stubs/atomicops_internals_tsan.h> -// MSVC. -#elif defined(_MSC_VER) -#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64) -#include <google/protobuf/stubs/atomicops_internals_x86_msvc.h> -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif - -// Solaris -#elif defined(GOOGLE_PROTOBUF_OS_SOLARIS) -#include <google/protobuf/stubs/atomicops_internals_solaris.h> - -// AIX -#elif defined(GOOGLE_PROTOBUF_OS_AIX) -#include <google/protobuf/stubs/atomicops_internals_power.h> - -// Apple. -#elif defined(GOOGLE_PROTOBUF_OS_APPLE) -#include <google/protobuf/stubs/atomicops_internals_macosx.h> - -// GCC. -#elif defined(__GNUC__) -#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64) -#include <google/protobuf/stubs/atomicops_internals_x86_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_ARM) && defined(__linux__) -#include <google/protobuf/stubs/atomicops_internals_arm_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_AARCH64) -#include <google/protobuf/stubs/atomicops_internals_arm64_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_ARM_QNX) -#include <google/protobuf/stubs/atomicops_internals_arm_qnx.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_MIPS) || defined(GOOGLE_PROTOBUF_ARCH_MIPS64) -#include <google/protobuf/stubs/atomicops_internals_mips_gcc.h> -#elif defined(GOOGLE_PROTOBUF_ARCH_POWER) -#include <google/protobuf/stubs/atomicops_internals_power.h> -#elif defined(__native_client__) -#include <google/protobuf/stubs/atomicops_internals_pnacl.h> -#elif (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4)) -#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h> -#elif defined(__clang__) -#if __has_extension(c_atomic) -#include <google/protobuf/stubs/atomicops_internals_generic_gcc.h> -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif - -// Unknown. -#else -#error GOOGLE_PROTOBUF_ATOMICOPS_ERROR -#endif - -// On some platforms we need additional declarations to make AtomicWord -// compatible with our other Atomic* types. -#if defined(GOOGLE_PROTOBUF_OS_APPLE) -#include <google/protobuf/stubs/atomicops_internals_atomicword_compat.h> -#endif - -#undef GOOGLE_PROTOBUF_ATOMICOPS_ERROR - -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h b/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h deleted file mode 100644 index 0a2d2b89..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_arm64_gcc.h +++ /dev/null @@ -1,325 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline void MemoryBarrier() { - __asm__ __volatile__ ("dmb ish" ::: "memory"); // NOLINT -} - -// NoBarrier versions of the operation include "memory" in the clobber list. -// This is not required for direct usage of the NoBarrier versions of the -// operations. However this is required for correctness when they are used as -// part of the Acquire or Release versions, to ensure that nothing from outside -// the call is reordered between the operation and the memory barrier. This does -// not change the code generated, so has no or minimal impact on the -// NoBarrier operations. - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %w[prev], %[ptr] \n\t" // Load the previous value. - "cmp %w[prev], %w[old_value] \n\t" - "bne 1f \n\t" - "stxr %w[temp], %w[new_value], %[ptr] \n\t" // Try to store the new value. - "cbnz %w[temp], 0b \n\t" // Retry if it did not work. - "1: \n\t" - : [prev]"=&r" (prev), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [old_value]"IJr" (old_value), - [new_value]"r" (new_value) - : "cc", "memory" - ); // NOLINT - - return prev; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %w[result], %[ptr] \n\t" // Load the previous value. - "stxr %w[temp], %w[new_value], %[ptr] \n\t" // Try to store the new value. - "cbnz %w[temp], 0b \n\t" // Retry if it did not work. - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [new_value]"r" (new_value) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %w[result], %[ptr] \n\t" // Load the previous value. - "add %w[result], %w[result], %w[increment]\n\t" - "stxr %w[temp], %w[result], %[ptr] \n\t" // Try to store the result. - "cbnz %w[temp], 0b \n\t" // Retry on failure. - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [increment]"IJr" (increment) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - MemoryBarrier(); - Atomic32 result = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrier(); - - return result; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrier(); - - return prev; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - MemoryBarrier(); - Atomic32 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - - return prev; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - __asm__ __volatile__ ( // NOLINT - "stlr %w[value], %[ptr] \n\t" - : [ptr]"=Q" (*ptr) - : [value]"r" (value) - : "memory" - ); // NOLINT -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value; - - __asm__ __volatile__ ( // NOLINT - "ldar %w[value], %[ptr] \n\t" - : [value]"=r" (value) - : [ptr]"Q" (*ptr) - : "memory" - ); // NOLINT - - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -// 64-bit versions of the operations. -// See the 32-bit versions for comments. - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %[prev], %[ptr] \n\t" - "cmp %[prev], %[old_value] \n\t" - "bne 1f \n\t" - "stxr %w[temp], %[new_value], %[ptr] \n\t" - "cbnz %w[temp], 0b \n\t" - "1: \n\t" - : [prev]"=&r" (prev), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [old_value]"IJr" (old_value), - [new_value]"r" (new_value) - : "cc", "memory" - ); // NOLINT - - return prev; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %[result], %[ptr] \n\t" - "stxr %w[temp], %[new_value], %[ptr] \n\t" - "cbnz %w[temp], 0b \n\t" - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [new_value]"r" (new_value) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 result; - int32_t temp; - - __asm__ __volatile__ ( // NOLINT - "0: \n\t" - "ldxr %[result], %[ptr] \n\t" - "add %[result], %[result], %[increment] \n\t" - "stxr %w[temp], %[result], %[ptr] \n\t" - "cbnz %w[temp], 0b \n\t" - : [result]"=&r" (result), - [temp]"=&r" (temp), - [ptr]"+Q" (*ptr) - : [increment]"IJr" (increment) - : "memory" - ); // NOLINT - - return result; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - MemoryBarrier(); - Atomic64 result = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrier(); - - return result; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrier(); - - return prev; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - MemoryBarrier(); - Atomic64 prev = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - - return prev; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - __asm__ __volatile__ ( // NOLINT - "stlr %x[value], %[ptr] \n\t" - : [ptr]"=Q" (*ptr) - : [value]"r" (value) - : "memory" - ); // NOLINT -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value; - - __asm__ __volatile__ ( // NOLINT - "ldar %x[value], %[ptr] \n\t" - : [value]"=r" (value) - : [ptr]"Q" (*ptr) - : "memory" - ); // NOLINT - - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrier(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM64_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h b/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h deleted file mode 100644 index 90e727b0..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_arm_gcc.h +++ /dev/null @@ -1,151 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. -// -// LinuxKernelCmpxchg and Barrier_AtomicIncrement are from Google Gears. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -// 0xffff0fc0 is the hard coded address of a function provided by -// the kernel which implements an atomic compare-exchange. On older -// ARM architecture revisions (pre-v6) this may be implemented using -// a syscall. This address is stable, and in active use (hard coded) -// by at least glibc-2.7 and the Android C library. -typedef Atomic32 (*LinuxKernelCmpxchgFunc)(Atomic32 old_value, - Atomic32 new_value, - volatile Atomic32* ptr); -LinuxKernelCmpxchgFunc pLinuxKernelCmpxchg __attribute__((weak)) = - (LinuxKernelCmpxchgFunc) 0xffff0fc0; - -typedef void (*LinuxKernelMemoryBarrierFunc)(void); -LinuxKernelMemoryBarrierFunc pLinuxKernelMemoryBarrier __attribute__((weak)) = - (LinuxKernelMemoryBarrierFunc) 0xffff0fa0; - - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev_value = *ptr; - do { - if (!pLinuxKernelCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 old_value; - do { - old_value = *ptr; - } while (pLinuxKernelCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - for (;;) { - // Atomic exchange the old value with an incremented one. - Atomic32 old_value = *ptr; - Atomic32 new_value = old_value + increment; - if (pLinuxKernelCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr)) == 0) { - // The exchange took place as expected. - return new_value; - } - // Otherwise, *ptr changed mid-loop and we need to retry. - } -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrier() { - pLinuxKernelMemoryBarrier(); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrier(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrier(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h b/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h deleted file mode 100644 index 17dfaa51..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_arm_qnx.h +++ /dev/null @@ -1,146 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_ - -// For _smp_cmpxchg() -#include <pthread.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 QNXCmpxchg(Atomic32 old_value, - Atomic32 new_value, - volatile Atomic32* ptr) { - return static_cast<Atomic32>( - _smp_cmpxchg((volatile unsigned *)ptr, - (unsigned)old_value, - (unsigned)new_value)); -} - - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev_value = *ptr; - do { - if (!QNXCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 old_value; - do { - old_value = *ptr; - } while (QNXCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr))); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - for (;;) { - // Atomic exchange the old value with an incremented one. - Atomic32 old_value = *ptr; - Atomic32 new_value = old_value + increment; - if (QNXCmpxchg(old_value, new_value, - const_cast<Atomic32*>(ptr)) == 0) { - // The exchange took place as expected. - return new_value; - } - // Otherwise, *ptr changed mid-loop and we need to retry. - } -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrier() { - __sync_synchronize(); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrier(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrier(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ARM_QNX_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_atomicword_compat.h b/src/google/protobuf/stubs/atomicops_internals_atomicword_compat.h deleted file mode 100644 index eb198ff5..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_atomicword_compat.h +++ /dev/null @@ -1,122 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ATOMICWORD_COMPAT_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ATOMICWORD_COMPAT_H_ - -// AtomicWord is a synonym for intptr_t, and Atomic32 is a synonym for int32, -// which in turn means int. On some LP32 platforms, intptr_t is an int, but -// on others, it's a long. When AtomicWord and Atomic32 are based on different -// fundamental types, their pointers are incompatible. -// -// This file defines function overloads to allow both AtomicWord and Atomic32 -// data to be used with this interface. -// -// On LP64 platforms, AtomicWord and Atomic64 are both always long, -// so this problem doesn't occur. - -#if !defined(GOOGLE_PROTOBUF_ARCH_64_BIT) - -namespace google { -namespace protobuf { -namespace internal { - -inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr, - AtomicWord old_value, - AtomicWord new_value) { - return NoBarrier_CompareAndSwap( - reinterpret_cast<volatile Atomic32*>(ptr), old_value, new_value); -} - -inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr, - AtomicWord new_value) { - return NoBarrier_AtomicExchange( - reinterpret_cast<volatile Atomic32*>(ptr), new_value); -} - -inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr, - AtomicWord increment) { - return NoBarrier_AtomicIncrement( - reinterpret_cast<volatile Atomic32*>(ptr), increment); -} - -inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr, - AtomicWord increment) { - return Barrier_AtomicIncrement( - reinterpret_cast<volatile Atomic32*>(ptr), increment); -} - -inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, - AtomicWord old_value, - AtomicWord new_value) { - return Acquire_CompareAndSwap( - reinterpret_cast<volatile Atomic32*>(ptr), old_value, new_value); -} - -inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, - AtomicWord old_value, - AtomicWord new_value) { - return Release_CompareAndSwap( - reinterpret_cast<volatile Atomic32*>(ptr), old_value, new_value); -} - -inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) { - NoBarrier_Store(reinterpret_cast<volatile Atomic32*>(ptr), value); -} - -inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { - return Acquire_Store(reinterpret_cast<volatile Atomic32*>(ptr), value); -} - -inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { - return Release_Store(reinterpret_cast<volatile Atomic32*>(ptr), value); -} - -inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) { - return NoBarrier_Load(reinterpret_cast<volatile const Atomic32*>(ptr)); -} - -inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { - return Acquire_Load(reinterpret_cast<volatile const Atomic32*>(ptr)); -} - -inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { - return Release_Load(reinterpret_cast<volatile const Atomic32*>(ptr)); -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // !defined(GOOGLE_PROTOBUF_ARCH_64_BIT) - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_ATOMICWORD_COMPAT_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h b/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h deleted file mode 100644 index a0116a60..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2013 Red Hat Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Red Hat Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, true, - __ATOMIC_RELAXED, __ATOMIC_RELAXED); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - return __atomic_exchange_n(ptr, new_value, __ATOMIC_RELAXED); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return __atomic_add_fetch(ptr, increment, __ATOMIC_RELAXED); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return __atomic_add_fetch(ptr, increment, __ATOMIC_SEQ_CST); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, true, - __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE); - return old_value; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, true, - __ATOMIC_RELEASE, __ATOMIC_ACQUIRE); - return old_value; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELAXED); -} - -inline void MemoryBarrier() { - __sync_synchronize(); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELEASE); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return __atomic_load_n(ptr, __ATOMIC_RELAXED); -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - return __atomic_load_n(ptr, __ATOMIC_ACQUIRE); -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - return __atomic_load_n(ptr, __ATOMIC_SEQ_CST); -} - -#ifdef __LP64__ - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - __atomic_store_n(ptr, value, __ATOMIC_RELEASE); -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - return __atomic_load_n(ptr, __ATOMIC_ACQUIRE); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, true, - __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE); - return old_value; -} - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - __atomic_compare_exchange_n(ptr, &old_value, new_value, true, - __ATOMIC_RELAXED, __ATOMIC_RELAXED); - return old_value; -} - -#endif // defined(__LP64__) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_macosx.h b/src/google/protobuf/stubs/atomicops_internals_macosx.h deleted file mode 100644 index 79633241..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_macosx.h +++ /dev/null @@ -1,225 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MACOSX_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MACOSX_H_ - -#include <libkern/OSAtomic.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev_value; - do { - if (OSAtomicCompareAndSwap32(old_value, new_value, - const_cast<Atomic32*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 old_value; - do { - old_value = *ptr; - } while (!OSAtomicCompareAndSwap32(old_value, new_value, - const_cast<Atomic32*>(ptr))); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return OSAtomicAdd32(increment, const_cast<Atomic32*>(ptr)); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return OSAtomicAdd32Barrier(increment, const_cast<Atomic32*>(ptr)); -} - -inline void MemoryBarrier() { - OSMemoryBarrier(); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev_value; - do { - if (OSAtomicCompareAndSwap32Barrier(old_value, new_value, - const_cast<Atomic32*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return Acquire_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrier(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrier(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -#ifdef __LP64__ - -// 64-bit implementation on 64-bit platform - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev_value; - do { - if (OSAtomicCompareAndSwap64(old_value, new_value, - reinterpret_cast<volatile int64_t*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 old_value; - do { - old_value = *ptr; - } while (!OSAtomicCompareAndSwap64(old_value, new_value, - reinterpret_cast<volatile int64_t*>(ptr))); - return old_value; -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return OSAtomicAdd64(increment, reinterpret_cast<volatile int64_t*>(ptr)); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return OSAtomicAdd64Barrier(increment, - reinterpret_cast<volatile int64_t*>(ptr)); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev_value; - do { - if (OSAtomicCompareAndSwap64Barrier( - old_value, new_value, reinterpret_cast<volatile int64_t*>(ptr))) { - return old_value; - } - prev_value = *ptr; - } while (prev_value == old_value); - return prev_value; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - // The lib kern interface does not distinguish between - // Acquire and Release memory barriers; they are equivalent. - return Acquire_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - MemoryBarrier(); - *ptr = value; -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; - MemoryBarrier(); - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrier(); - return *ptr; -} - -#endif // defined(__LP64__) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MACOSX_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h b/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h deleted file mode 100644 index f5837c9e..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_mips_gcc.h +++ /dev/null @@ -1,313 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_ - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -namespace google { -namespace protobuf { -namespace internal { - -// Atomically execute: -// result = *ptr; -// if (*ptr == old_value) -// *ptr = new_value; -// return result; -// -// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". -// Always return the old value of "*ptr" -// -// This routine implies no memory barriers. -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev, tmp; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "ll %0, %5\n" // prev = *ptr - "bne %0, %3, 2f\n" // if (prev != old_value) goto 2 - "move %2, %4\n" // tmp = new_value - "sc %2, %1\n" // *ptr = tmp (with atomic check) - "beqz %2, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - "2:\n" - ".set pop\n" - : "=&r" (prev), "=m" (*ptr), "=&r" (tmp) - : "r" (old_value), "r" (new_value), "m" (*ptr) - : "memory"); - return prev; -} - -// Atomically store new_value into *ptr, returning the previous value held in -// *ptr. This routine implies no memory barriers. -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 temp, old; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "ll %1, %4\n" // old = *ptr - "move %0, %3\n" // temp = new_value - "sc %0, %2\n" // *ptr = temp (with atomic check) - "beqz %0, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - ".set pop\n" - : "=&r" (temp), "=&r" (old), "=m" (*ptr) - : "r" (new_value), "m" (*ptr) - : "memory"); - - return old; -} - -// Atomically increment *ptr by "increment". Returns the new value of -// *ptr with the increment applied. This routine implies no memory barriers. -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 temp, temp2; - - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "ll %0, %4\n" // temp = *ptr - "addu %1, %0, %3\n" // temp2 = temp + increment - "sc %1, %2\n" // *ptr = temp2 (with atomic check) - "beqz %1, 1b\n" // start again on atomic error - "addu %1, %0, %3\n" // temp2 = temp + increment - ".set pop\n" - : "=&r" (temp), "=&r" (temp2), "=m" (*ptr) - : "Ir" (increment), "m" (*ptr) - : "memory"); - // temp2 now holds the final value. - return temp2; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - ATOMICOPS_COMPILER_BARRIER(); - Atomic32 res = NoBarrier_AtomicIncrement(ptr, increment); - ATOMICOPS_COMPILER_BARRIER(); - return res; -} - -// "Acquire" operations -// ensure that no later memory access can be reordered ahead of the operation. -// "Release" operations ensure that no previous memory access can be reordered -// after the operation. "Barrier" operations have both "Acquire" and "Release" -// semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory -// access. -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ATOMICOPS_COMPILER_BARRIER(); - Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - ATOMICOPS_COMPILER_BARRIER(); - return res; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ATOMICOPS_COMPILER_BARRIER(); - Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - ATOMICOPS_COMPILER_BARRIER(); - return res; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void MemoryBarrier() { - __asm__ __volatile__("sync" : : : "memory"); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - MemoryBarrier(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - MemoryBarrier(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -#if defined(__LP64__) -// 64-bit versions of the atomic ops. - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev, tmp; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "lld %0, %5\n" // prev = *ptr - "bne %0, %3, 2f\n" // if (prev != old_value) goto 2 - "move %2, %4\n" // tmp = new_value - "scd %2, %1\n" // *ptr = tmp (with atomic check) - "beqz %2, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - "2:\n" - ".set pop\n" - : "=&r" (prev), "=m" (*ptr), "=&r" (tmp) - : "r" (old_value), "r" (new_value), "m" (*ptr) - : "memory"); - return prev; -} - -// Atomically store new_value into *ptr, returning the previous value held in -// *ptr. This routine implies no memory barriers. -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 temp, old; - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "lld %1, %4\n" // old = *ptr - "move %0, %3\n" // temp = new_value - "scd %0, %2\n" // *ptr = temp (with atomic check) - "beqz %0, 1b\n" // start again on atomic error - "nop\n" // delay slot nop - ".set pop\n" - : "=&r" (temp), "=&r" (old), "=m" (*ptr) - : "r" (new_value), "m" (*ptr) - : "memory"); - - return old; -} - -// Atomically increment *ptr by "increment". Returns the new value of -// *ptr with the increment applied. This routine implies no memory barriers. -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 temp, temp2; - - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "1:\n" - "lld %0, %4\n" // temp = *ptr - "daddu %1, %0, %3\n" // temp2 = temp + increment - "scd %1, %2\n" // *ptr = temp2 (with atomic check) - "beqz %1, 1b\n" // start again on atomic error - "daddu %1, %0, %3\n" // temp2 = temp + increment - ".set pop\n" - : "=&r" (temp), "=&r" (temp2), "=m" (*ptr) - : "Ir" (increment), "m" (*ptr) - : "memory"); - // temp2 now holds the final value. - return temp2; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - MemoryBarrier(); - Atomic64 res = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrier(); - return res; -} - -// "Acquire" operations -// ensure that no later memory access can be reordered ahead of the operation. -// "Release" operations ensure that no previous memory access can be reordered -// after the operation. "Barrier" operations have both "Acquire" and "Release" -// semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory -// access. -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrier(); - return res; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - MemoryBarrier(); - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - MemoryBarrier(); - *ptr = value; -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; - MemoryBarrier(); - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrier(); - return *ptr; -} -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_MIPS_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_pnacl.h b/src/google/protobuf/stubs/atomicops_internals_pnacl.h deleted file mode 100644 index 3b314fd0..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_pnacl.h +++ /dev/null @@ -1,231 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PNACL_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PNACL_H_ - -#include <atomic> - -namespace google { -namespace protobuf { -namespace internal { - -// This implementation is transitional and maintains the original API for -// atomicops.h. This requires casting memory locations to the atomic types, and -// assumes that the API and the C++11 implementation are layout-compatible, -// which isn't true for all implementations or hardware platforms. The static -// assertion should detect this issue, were it to fire then this header -// shouldn't be used. -// -// TODO(jfb) If this header manages to stay committed then the API should be -// modified, and all call sites updated. -typedef volatile std::atomic<Atomic32>* AtomicLocation32; -static_assert(sizeof(*(AtomicLocation32) nullptr) == sizeof(Atomic32), - "incompatible 32-bit atomic layout"); - -inline void MemoryBarrier() { -#if defined(__GLIBCXX__) - // Work around libstdc++ bug 51038 where atomic_thread_fence was declared but - // not defined, leading to the linker complaining about undefined references. - __atomic_thread_fence(std::memory_order_seq_cst); -#else - std::atomic_thread_fence(std::memory_order_seq_cst); -#endif -} - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ((AtomicLocation32)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_relaxed, - std::memory_order_relaxed); - return old_value; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - return ((AtomicLocation32)ptr) - ->exchange(new_value, std::memory_order_relaxed); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return increment + - ((AtomicLocation32)ptr) - ->fetch_add(increment, std::memory_order_relaxed); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return increment + ((AtomicLocation32)ptr)->fetch_add(increment); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ((AtomicLocation32)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_acquire, - std::memory_order_acquire); - return old_value; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - ((AtomicLocation32)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_release, - std::memory_order_relaxed); - return old_value; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed); - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - ((AtomicLocation32)ptr)->store(value, std::memory_order_release); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed); -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - return ((AtomicLocation32)ptr)->load(std::memory_order_acquire); -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed); -} - -#if defined(GOOGLE_PROTOBUF_ARCH_64_BIT) - -typedef volatile std::atomic<Atomic64>* AtomicLocation64; -static_assert(sizeof(*(AtomicLocation64) nullptr) == sizeof(Atomic64), - "incompatible 64-bit atomic layout"); - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - ((AtomicLocation64)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_relaxed, - std::memory_order_relaxed); - return old_value; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - return ((AtomicLocation64)ptr) - ->exchange(new_value, std::memory_order_relaxed); -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return increment + - ((AtomicLocation64)ptr) - ->fetch_add(increment, std::memory_order_relaxed); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return increment + ((AtomicLocation64)ptr)->fetch_add(increment); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - ((AtomicLocation64)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_acquire, - std::memory_order_acquire); - return old_value; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - ((AtomicLocation64)ptr) - ->compare_exchange_strong(old_value, - new_value, - std::memory_order_release, - std::memory_order_relaxed); - return old_value; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed); - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - ((AtomicLocation64)ptr)->store(value, std::memory_order_release); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed); -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - return ((AtomicLocation64)ptr)->load(std::memory_order_acquire); -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrier(); - return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed); -} - -#endif // defined(GOOGLE_PROTOBUF_ARCH_64_BIT) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PNACL_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_power.h b/src/google/protobuf/stubs/atomicops_internals_power.h deleted file mode 100644 index b8a42f21..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_power.h +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright 2014 Bloomberg Finance LP. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Bloomberg Finance LP. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_AIX_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_AIX_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpw %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" // store new value - " bne- 1b \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[val], %[res] \n\t" // add the operand - " stwcx. %[res], %[zero], %[obj] \n\t" // store old value - // if still reserved - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline void MemoryBarrier(void) { - asm volatile ( - " lwsync \n\t" - " isync \n\t" - : - : - : "memory"); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 result; - - asm volatile ( - " lwsync \n\t" - - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[val], %[res] \n\t" // add the operand - " stwcx. %[res], %[zero], %[obj] \n\t" // store old value - // if still reserved - " bne- 1b \n\t" - " isync \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpw %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" // store new value - " bne- 1b \n\t" - - " isync \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 result; - - asm volatile ( - " lwsync \n\t" - - "1: lwarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpw %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - " stwcx. %[val], %[zero], %[obj] \n\t" // store new value - " bne- 1b \n\t" - - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - asm volatile ( - " stw %[val], %[obj] \n\t" - " isync \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - asm volatile ( - " lwsync \n\t" - " stw %[val], %[obj] \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 result; - - asm volatile ( - "1: lwz %[res], %[obj] \n\t" - " cmpw %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - - " isync \n\t" - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - Atomic32 result; - - asm volatile ( - " lwsync \n\t" - - "1: lwz %[res], %[obj] \n\t" - " cmpw %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpd %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - - " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value - " bne- 1b \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" - " stdcx. %[val], %[zero], %[obj] \n\t" - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[res], %[val] \n\t" // add the operand - " stdcx. %[res], %[zero], %[obj] \n\t" // store old value if - // still reserved - - " bne- 1b \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - - Atomic64 result; - - asm volatile ( - " lwsync \n\t" - - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " add %[res], %[res], %[val] \n\t" // add the operand - " stdcx. %[res], %[zero], %[obj] \n\t" // store old value if - // still reserved - - " bne- 1b \n\t" - - " isync \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [val] "b" (increment), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpd %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - - " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value - " bne- 1b \n\t" - " isync \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 result; - - asm volatile ( - " lwsync \n\t" - - "1: ldarx %[res], %[zero], %[obj] \n\t" // load and reserve - " cmpd %[cmp], %[res] \n\t" // compare values - " bne- 2f \n\t" - - " stdcx. %[val], %[zero], %[obj] \n\t" // store the new value - " bne- 1b \n\t" - "2: \n\t" - : [res] "=&b" (result) - : [obj] "b" (ptr), - [cmp] "b" (old_value), - [val] "b" (new_value), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - asm volatile ( - " std %[val], %[obj] \n\t" - " isync \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - asm volatile ( - " lwsync \n\t" - " std %[val], %[obj] \n\t" - : [obj] "=m" (*ptr) - : [val] "b" (value)); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 result; - - asm volatile ( - "1: ld %[res], %[obj] \n\t" - " cmpd %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - - " isync \n\t" - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - Atomic64 result; - - asm volatile ( - " lwsync \n\t" - - "1: ld %[res], %[obj] \n\t" - " cmpd %[res], %[res] \n\t" // create data - // dependency for - // load/load ordering - " bne- 1b \n\t" // never taken - : [res] "=b" (result) - : [obj] "m" (*ptr), - [zero] "i" (0) - : "cr0", "ctr"); - - return result; -} -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_solaris.h b/src/google/protobuf/stubs/atomicops_internals_solaris.h deleted file mode 100644 index d8057ecd..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_solaris.h +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ - -#include <atomic.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return (Atomic32)atomic_cas_32((volatile uint32_t*)ptr, (uint32_t)old_value, (uint32_t)new_value); -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - return (Atomic32)atomic_swap_32((volatile uint32_t*)ptr, (uint32_t)new_value); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return (Atomic32)atomic_add_32_nv((volatile uint32_t*)ptr, (uint32_t)increment); -} - -inline void MemoryBarrier(void) { - membar_producer(); - membar_consumer(); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - MemoryBarrier(); - Atomic32 ret = NoBarrier_AtomicIncrement(ptr, increment); - MemoryBarrier(); - - return ret; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 ret = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrier(); - - return ret; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - MemoryBarrier(); - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - membar_producer(); -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - membar_consumer(); - *ptr = value; -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 val = *ptr; - membar_consumer(); - return val; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - membar_producer(); - return *ptr; -} - -#ifdef GOOGLE_PROTOBUF_ARCH_64_BIT -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return atomic_cas_64((volatile uint64_t*)ptr, (uint64_t)old_value, (uint64_t)new_value); -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) { - return atomic_swap_64((volatile uint64_t*)ptr, (uint64_t)new_value); -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { - return atomic_add_64_nv((volatile uint64_t*)ptr, increment); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { - MemoryBarrier(); - Atomic64 ret = atomic_add_64_nv((volatile uint64_t*)ptr, increment); - MemoryBarrier(); - return ret; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 ret = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - MemoryBarrier(); - return ret; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - MemoryBarrier(); - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - membar_producer(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - membar_consumer(); - *ptr = value; -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 ret = *ptr; - membar_consumer(); - return ret; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - membar_producer(); - return *ptr; -} -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_SPARC_GCC_H_ - diff --git a/src/google/protobuf/stubs/atomicops_internals_tsan.h b/src/google/protobuf/stubs/atomicops_internals_tsan.h deleted file mode 100644 index 0c903545..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_tsan.h +++ /dev/null @@ -1,219 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2013 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation for compiler-based -// ThreadSanitizer (http://clang.llvm.org/docs/ThreadSanitizer.html). -// Use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_ - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -#include <sanitizer/tsan_interface_atomic.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 cmp = old_value; - __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_relaxed, __tsan_memory_order_relaxed); - return cmp; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - return __tsan_atomic32_exchange(ptr, new_value, - __tsan_memory_order_relaxed); -} - -inline Atomic32 Acquire_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - return __tsan_atomic32_exchange(ptr, new_value, - __tsan_memory_order_acquire); -} - -inline Atomic32 Release_AtomicExchange(volatile Atomic32 *ptr, - Atomic32 new_value) { - return __tsan_atomic32_exchange(ptr, new_value, - __tsan_memory_order_release); -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32 *ptr, - Atomic32 increment) { - return increment + __tsan_atomic32_fetch_add(ptr, increment, - __tsan_memory_order_relaxed); -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32 *ptr, - Atomic32 increment) { - return increment + __tsan_atomic32_fetch_add(ptr, increment, - __tsan_memory_order_acq_rel); -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 cmp = old_value; - __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_acquire, __tsan_memory_order_acquire); - return cmp; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32 *ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 cmp = old_value; - __tsan_atomic32_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_release, __tsan_memory_order_relaxed); - return cmp; -} - -inline void NoBarrier_Store(volatile Atomic32 *ptr, Atomic32 value) { - __tsan_atomic32_store(ptr, value, __tsan_memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic32 *ptr, Atomic32 value) { - __tsan_atomic32_store(ptr, value, __tsan_memory_order_relaxed); - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); -} - -inline void Release_Store(volatile Atomic32 *ptr, Atomic32 value) { - __tsan_atomic32_store(ptr, value, __tsan_memory_order_release); -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32 *ptr) { - return __tsan_atomic32_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic32 Acquire_Load(volatile const Atomic32 *ptr) { - return __tsan_atomic32_load(ptr, __tsan_memory_order_acquire); -} - -inline Atomic32 Release_Load(volatile const Atomic32 *ptr) { - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); - return __tsan_atomic32_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64 *ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 cmp = old_value; - __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_relaxed, __tsan_memory_order_relaxed); - return cmp; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64 *ptr, - Atomic64 new_value) { - return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_relaxed); -} - -inline Atomic64 Acquire_AtomicExchange(volatile Atomic64 *ptr, - Atomic64 new_value) { - return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_acquire); -} - -inline Atomic64 Release_AtomicExchange(volatile Atomic64 *ptr, - Atomic64 new_value) { - return __tsan_atomic64_exchange(ptr, new_value, __tsan_memory_order_release); -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64 *ptr, - Atomic64 increment) { - return increment + __tsan_atomic64_fetch_add(ptr, increment, - __tsan_memory_order_relaxed); -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64 *ptr, - Atomic64 increment) { - return increment + __tsan_atomic64_fetch_add(ptr, increment, - __tsan_memory_order_acq_rel); -} - -inline void NoBarrier_Store(volatile Atomic64 *ptr, Atomic64 value) { - __tsan_atomic64_store(ptr, value, __tsan_memory_order_relaxed); -} - -inline void Acquire_Store(volatile Atomic64 *ptr, Atomic64 value) { - __tsan_atomic64_store(ptr, value, __tsan_memory_order_relaxed); - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); -} - -inline void Release_Store(volatile Atomic64 *ptr, Atomic64 value) { - __tsan_atomic64_store(ptr, value, __tsan_memory_order_release); -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64 *ptr) { - return __tsan_atomic64_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic64 Acquire_Load(volatile const Atomic64 *ptr) { - return __tsan_atomic64_load(ptr, __tsan_memory_order_acquire); -} - -inline Atomic64 Release_Load(volatile const Atomic64 *ptr) { - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); - return __tsan_atomic64_load(ptr, __tsan_memory_order_relaxed); -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64 *ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 cmp = old_value; - __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_acquire, __tsan_memory_order_acquire); - return cmp; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64 *ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 cmp = old_value; - __tsan_atomic64_compare_exchange_strong(ptr, &cmp, new_value, - __tsan_memory_order_release, __tsan_memory_order_relaxed); - return cmp; -} - -inline void MemoryBarrier() { - __tsan_atomic_thread_fence(__tsan_memory_order_seq_cst); -} - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_TSAN_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc b/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc deleted file mode 100644 index 53c9eae0..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc +++ /dev/null @@ -1,137 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This module gets enough CPU information to optimize the -// atomicops module on x86. - -#include <cstring> - -#include <google/protobuf/stubs/atomicops.h> - -// This file only makes sense with atomicops_internals_x86_gcc.h -- it -// depends on structs that are defined in that file. If atomicops.h -// doesn't sub-include that file, then we aren't needed, and shouldn't -// try to do anything. -#ifdef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ - -// Inline cpuid instruction. In PIC compilations, %ebx contains the address -// of the global offset table. To avoid breaking such executables, this code -// must preserve that register's value across cpuid instructions. -#if defined(__i386__) -#define cpuid(a, b, c, d, inp) \ - asm("mov %%ebx, %%edi\n" \ - "cpuid\n" \ - "xchg %%edi, %%ebx\n" \ - : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) -#elif defined(__x86_64__) -#define cpuid(a, b, c, d, inp) \ - asm("mov %%rbx, %%rdi\n" \ - "cpuid\n" \ - "xchg %%rdi, %%rbx\n" \ - : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) -#endif - -#if defined(cpuid) // initialize the struct only on x86 - -namespace google { -namespace protobuf { -namespace internal { - -// Set the flags so that code will run correctly and conservatively, so even -// if we haven't been initialized yet, we're probably single threaded, and our -// default values should hopefully be pretty safe. -struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures = { - false, // bug can't exist before process spawns multiple threads - false, // no SSE2 -}; - -namespace { - -// Initialize the AtomicOps_Internalx86CPUFeatures struct. -void AtomicOps_Internalx86CPUFeaturesInit() { - uint32_t eax; - uint32_t ebx; - uint32_t ecx; - uint32_t edx; - - // Get vendor string (issue CPUID with eax = 0) - cpuid(eax, ebx, ecx, edx, 0); - char vendor[13]; - memcpy(vendor, &ebx, 4); - memcpy(vendor + 4, &edx, 4); - memcpy(vendor + 8, &ecx, 4); - vendor[12] = 0; - - // get feature flags in ecx/edx, and family/model in eax - cpuid(eax, ebx, ecx, edx, 1); - - int family = (eax >> 8) & 0xf; // family and model fields - int model = (eax >> 4) & 0xf; - if (family == 0xf) { // use extended family and model fields - family += (eax >> 20) & 0xff; - model += ((eax >> 16) & 0xf) << 4; - } - - // Opteron Rev E has a bug in which on very rare occasions a locked - // instruction doesn't act as a read-acquire barrier if followed by a - // non-locked read-modify-write instruction. Rev F has this bug in - // pre-release versions, but not in versions released to customers, - // so we test only for Rev E, which is family 15, model 32..63 inclusive. - if (strcmp(vendor, "AuthenticAMD") == 0 && // AMD - family == 15 && - 32 <= model && model <= 63) { - AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = true; - } else { - AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = false; - } - - // edx bit 26 is SSE2 which we use to tell use whether we can use mfence - AtomicOps_Internalx86CPUFeatures.has_sse2 = ((edx >> 26) & 1); -} - -class AtomicOpsx86Initializer { - public: - AtomicOpsx86Initializer() { - AtomicOps_Internalx86CPUFeaturesInit(); - } -}; - -// A global to get use initialized on startup via static initialization :/ -AtomicOpsx86Initializer g_initer; - -} // namespace - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // __i386__ - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h b/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h deleted file mode 100644 index edccc59d..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_gcc.h +++ /dev/null @@ -1,293 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -// This struct is not part of the public API of this module; clients may not -// use it. -// Features of this x86. Values may not be correct before main() is run, -// but are set conservatively. -struct AtomicOps_x86CPUFeatureStruct { - bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence - // after acquire compare-and-swap. - bool has_sse2; // Processor has SSE2. -}; -extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures; - -#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") - -// 32-bit low-level operations on any platform. - -inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 prev; - __asm__ __volatile__("lock; cmpxchgl %1,%2" - : "=a" (prev) - : "q" (new_value), "m" (*ptr), "0" (old_value) - : "memory"); - return prev; -} - -inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - __asm__ __volatile__("xchgl %1,%0" // The lock prefix is implicit for xchg. - : "=r" (new_value) - : "m" (*ptr), "0" (new_value) - : "memory"); - return new_value; // Now it's the previous value. -} - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 temp = increment; - __asm__ __volatile__("lock; xaddl %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now holds the old value of *ptr - return temp + increment; -} - -inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - Atomic32 temp = increment; - __asm__ __volatile__("lock; xaddl %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now holds the old value of *ptr - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return temp + increment; -} - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return x; -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -#if defined(__x86_64__) - -// 64-bit implementations of memory barrier can be simpler, because it -// "mfence" is guaranteed to exist. -inline void MemoryBarrier() { - __asm__ __volatile__("mfence" : : : "memory"); -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; - MemoryBarrier(); -} - -#else - -inline void MemoryBarrier() { - if (AtomicOps_Internalx86CPUFeatures.has_sse2) { - __asm__ __volatile__("mfence" : : : "memory"); - } else { // mfence is faster but not present on PIII - Atomic32 x = 0; - NoBarrier_AtomicExchange(&x, 0); // acts as a barrier on PIII - } -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - if (AtomicOps_Internalx86CPUFeatures.has_sse2) { - *ptr = value; - __asm__ __volatile__("mfence" : : : "memory"); - } else { - NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier on PIII - } -} -#endif - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - ATOMICOPS_COMPILER_BARRIER(); - *ptr = value; // An x86 store acts as a release barrier. - // See comments in Atomic64 version of Release_Store(), below. -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; // An x86 load acts as a acquire barrier. - // See comments in Atomic64 version of Release_Store(), below. - ATOMICOPS_COMPILER_BARRIER(); - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -#if defined(__x86_64__) - -// 64-bit low-level operations on 64-bit platform. - -inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 prev; - __asm__ __volatile__("lock; cmpxchgq %1,%2" - : "=a" (prev) - : "q" (new_value), "m" (*ptr), "0" (old_value) - : "memory"); - return prev; -} - -inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - __asm__ __volatile__("xchgq %1,%0" // The lock prefix is implicit for xchg. - : "=r" (new_value) - : "m" (*ptr), "0" (new_value) - : "memory"); - return new_value; // Now it's the previous value. -} - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 temp = increment; - __asm__ __volatile__("lock; xaddq %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now contains the previous value of *ptr - return temp + increment; -} - -inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - Atomic64 temp = increment; - __asm__ __volatile__("lock; xaddq %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); - // temp now contains the previous value of *ptr - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return temp + increment; -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; - MemoryBarrier(); -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - ATOMICOPS_COMPILER_BARRIER(); - - *ptr = value; // An x86 store acts as a release barrier - // for current AMD/Intel chips as of Jan 2008. - // See also Acquire_Load(), below. - - // When new chips come out, check: - // IA-32 Intel Architecture Software Developer's Manual, Volume 3: - // System Programming Guide, Chatper 7: Multiple-processor management, - // Section 7.2, Memory Ordering. - // Last seen at: - // http://developer.intel.com/design/pentium4/manuals/index_new.htm - // - // x86 stores/loads fail to act as barriers for a few instructions (clflush - // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are - // not generated by the compiler, and are rare. Users of these instructions - // need to know about cache behaviour in any case since all of these involve - // either flushing cache lines or non-temporal cache hints. -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; // An x86 load acts as a acquire barrier, - // for current AMD/Intel chips as of Jan 2008. - // See also Release_Store(), above. - ATOMICOPS_COMPILER_BARRIER(); - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrier(); - return *ptr; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); - if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { - __asm__ __volatile__("lfence" : : : "memory"); - } - return x; -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -#endif // defined(__x86_64__) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#undef ATOMICOPS_COMPILER_BARRIER - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_GCC_H_ diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc b/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc deleted file mode 100644 index 741b164f..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc +++ /dev/null @@ -1,112 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// The compilation of extension_set.cc fails when windows.h is included. -// Therefore we move the code depending on windows.h to this separate cc file. - -// Don't compile this file for people not concerned about thread safety. -#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#include <google/protobuf/stubs/atomicops.h> - -#ifdef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ - -#include <windows.h> - -namespace google { -namespace protobuf { -namespace internal { - -inline void MemoryBarrier() { - // We use MemoryBarrier from WinNT.h - ::MemoryBarrier(); -} - -Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - LONG result = InterlockedCompareExchange( - reinterpret_cast<volatile LONG*>(ptr), - static_cast<LONG>(new_value), - static_cast<LONG>(old_value)); - return static_cast<Atomic32>(result); -} - -Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, - Atomic32 new_value) { - LONG result = InterlockedExchange( - reinterpret_cast<volatile LONG*>(ptr), - static_cast<LONG>(new_value)); - return static_cast<Atomic32>(result); -} - -Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return InterlockedExchangeAdd( - reinterpret_cast<volatile LONG*>(ptr), - static_cast<LONG>(increment)) + increment; -} - -#if defined(_WIN64) - -// 64-bit low-level operations on 64-bit platform. - -Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - PVOID result = InterlockedCompareExchangePointer( - reinterpret_cast<volatile PVOID*>(ptr), - reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value)); - return reinterpret_cast<Atomic64>(result); -} - -Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, - Atomic64 new_value) { - PVOID result = InterlockedExchangePointer( - reinterpret_cast<volatile PVOID*>(ptr), - reinterpret_cast<PVOID>(new_value)); - return reinterpret_cast<Atomic64>(result); -} - -Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return InterlockedExchangeAdd64( - reinterpret_cast<volatile LONGLONG*>(ptr), - static_cast<LONGLONG>(increment)) + increment; -} - -#endif // defined(_WIN64) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY diff --git a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h b/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h deleted file mode 100644 index e53a641f..00000000 --- a/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h +++ /dev/null @@ -1,150 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is an internal atomic implementation, use atomicops.h instead. - -#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ -#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ - -namespace google { -namespace protobuf { -namespace internal { - -inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -#if !(defined(_MSC_VER) && _MSC_VER >= 1400) -#error "We require at least vs2005 for MemoryBarrier" -#endif - -inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, - Atomic32 old_value, - Atomic32 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { - NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier in this implementation -} - -inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; // works w/o barrier for current Intel chips as of June 2005 - // See comments in Atomic64 version of Release_Store() below. -} - -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { - return *ptr; -} - -inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; - return value; -} - -inline Atomic32 Release_Load(volatile const Atomic32* ptr) { - MemoryBarrier(); - return *ptr; -} - -#if defined(_WIN64) - -// 64-bit low-level operations on 64-bit platform. - -inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, - Atomic64 increment) { - return Barrier_AtomicIncrement(ptr, increment); -} - -inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; -} - -inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { - NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier in this implementation -} - -inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; // works w/o barrier for current Intel chips as of June 2005 - - // When new chips come out, check: - // IA-32 Intel Architecture Software Developer's Manual, Volume 3: - // System Programming Guide, Chatper 7: Multiple-processor management, - // Section 7.2, Memory Ordering. - // Last seen at: - // http://developer.intel.com/design/pentium4/manuals/index_new.htm -} - -inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { - return *ptr; -} - -inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; - return value; -} - -inline Atomic64 Release_Load(volatile const Atomic64* ptr) { - MemoryBarrier(); - return *ptr; -} - -inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, - Atomic64 old_value, - Atomic64 new_value) { - return NoBarrier_CompareAndSwap(ptr, old_value, new_value); -} - -#endif // defined(_WIN64) - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_X86_MSVC_H_ diff --git a/src/google/protobuf/stubs/bytestream.h b/src/google/protobuf/stubs/bytestream.h index de8e0204..86510d14 100644 --- a/src/google/protobuf/stubs/bytestream.h +++ b/src/google/protobuf/stubs/bytestream.h @@ -64,7 +64,7 @@ namespace protobuf { namespace strings { // An abstract interface for an object that consumes a sequence of bytes. This -// interface offers 3 different ways to append data, and a Flush() function. +// interface offers a way to append data as well as a Flush() function. // // Example: // @@ -208,7 +208,7 @@ class LIBPROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink { }; // Implementation of ByteSink that allocates an internal buffer (a char array) -// and expands it as needed to accomodate appended data (similar to a string), +// and expands it as needed to accommodate appended data (similar to a string), // and allows the caller to take ownership of the internal buffer via the // GetBuffer() method. The buffer returned from GetBuffer() must be deleted by // the caller with delete[]. GetBuffer() also sets the internal buffer to be diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h index 87271c5e..6888f136 100644 --- a/src/google/protobuf/stubs/callback.h +++ b/src/google/protobuf/stubs/callback.h @@ -1,8 +1,9 @@ #ifndef GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ #define GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ +#include <type_traits> + #include <google/protobuf/stubs/macros.h> -#include <google/protobuf/stubs/type_traits.h> // =================================================================== // emulates google3/base/callback.h @@ -342,10 +343,33 @@ class FunctionResultCallback_1_1 : public ResultCallback1<R, A1> { template <typename T> struct InternalConstRef { - typedef typename remove_reference<T>::type base_type; + typedef typename std::remove_reference<T>::type base_type; typedef const base_type& type; }; +template<typename R, typename T> +class MethodResultCallback_0_0 : public ResultCallback<R> { + public: + typedef R (T::*MethodType)(); + MethodResultCallback_0_0(T* object, MethodType method, bool self_deleting) + : object_(object), + method_(method), + self_deleting_(self_deleting) {} + ~MethodResultCallback_0_0() {} + + R Run() { + bool needs_delete = self_deleting_; + R result = (object_->*method_)(); + if (needs_delete) delete this; + return result; + } + + private: + T* object_; + MethodType method_; + bool self_deleting_; +}; + template <typename R, typename T, typename P1, typename P2, typename P3, typename P4, typename P5, typename A1, typename A2> class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> { @@ -374,13 +398,15 @@ class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> { T* object_; MethodType method_; bool self_deleting_; - typename remove_reference<P1>::type p1_; - typename remove_reference<P2>::type p2_; - typename remove_reference<P3>::type p3_; - typename remove_reference<P4>::type p4_; - typename remove_reference<P5>::type p5_; + typename std::remove_reference<P1>::type p1_; + typename std::remove_reference<P2>::type p2_; + typename std::remove_reference<P3>::type p3_; + typename std::remove_reference<P4>::type p4_; + typename std::remove_reference<P5>::type p5_; }; +} // namespace internal + // See Closure. inline Closure* NewCallback(void (*function)()) { return new internal::FunctionClosure0(function, true); @@ -518,6 +544,13 @@ inline ResultCallback1<R, A1>* NewPermanentCallback( function, false, p1); } +// See MethodResultCallback_0_0 +template <typename R, typename T1, typename T2> +inline ResultCallback<R>* NewPermanentCallback( + T1* object, R (T2::*function)()) { + return new internal::MethodResultCallback_0_0<R, T1>(object, function, false); +} + // See MethodResultCallback_5_2 template <typename R, typename T, typename P1, typename P2, typename P3, typename P4, typename P5, typename A1, typename A2> @@ -533,8 +566,6 @@ inline ResultCallback2<R, A1, A2>* NewPermanentCallback( p2, p3, p4, p5); } -} // namespace internal - // A function which does nothing. Useful for creating no-op callbacks, e.g.: // Closure* nothing = NewCallback(&DoNothing); void LIBPROTOBUF_EXPORT DoNothing(); diff --git a/src/google/protobuf/stubs/casts.h b/src/google/protobuf/stubs/casts.h index be652849..35e2dba0 100644 --- a/src/google/protobuf/stubs/casts.h +++ b/src/google/protobuf/stubs/casts.h @@ -31,8 +31,9 @@ #ifndef GOOGLE_PROTOBUF_CASTS_H__ #define GOOGLE_PROTOBUF_CASTS_H__ +#include <type_traits> + #include <google/protobuf/stubs/common.h> -#include <google/protobuf/stubs/type_traits.h> namespace google { namespace protobuf { @@ -95,7 +96,7 @@ inline To down_cast(From* f) { // so we only accept pointers template<typename To, typename From> // use like this: down_cast<T&>(foo); inline To down_cast(From& f) { - typedef typename remove_reference<To>::type* ToAsPointer; + typedef typename std::remove_reference<To>::type* ToAsPointer; // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc index 54dbafab..33d24c57 100644..100755 --- a/src/google/protobuf/stubs/common.cc +++ b/src/google/protobuf/stubs/common.cc @@ -30,6 +30,7 @@ // Author: kenton@google.com (Kenton Varda) +#include <google/protobuf/message_lite.h> // TODO(gerbens) ideally remove this. #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/stubs/status.h> @@ -108,11 +109,17 @@ string VersionString(int version) { // =================================================================== // emulates google3/base/logging.cc +// If the minimum logging level is not set, we default to logging messages for +// all levels. +#ifndef GOOGLE_PROTOBUF_MIN_LOG_LEVEL +#define GOOGLE_PROTOBUF_MIN_LOG_LEVEL LOGLEVEL_INFO +#endif + namespace internal { + #if defined(__ANDROID__) inline void DefaultLogHandler(LogLevel level, const char* filename, int line, const string& message) { -#ifdef GOOGLE_PROTOBUF_MIN_LOG_LEVEL if (level < GOOGLE_PROTOBUF_MIN_LOG_LEVEL) { return; } @@ -143,11 +150,14 @@ inline void DefaultLogHandler(LogLevel level, const char* filename, int line, __android_log_write(ANDROID_LOG_FATAL, "libprotobuf-native", "terminating.\n"); } -#endif } + #else void DefaultLogHandler(LogLevel level, const char* filename, int line, const string& message) { + if (level < GOOGLE_PROTOBUF_MIN_LOG_LEVEL) { + return; + } static const char* level_names[] = { "INFO", "WARNING", "ERROR", "FATAL" }; // We use fprintf() instead of cerr because we want this to work at static @@ -304,86 +314,6 @@ namespace internal { FunctionClosure0::~FunctionClosure0() {} } void DoNothing() {} // =================================================================== -// emulates google3/base/mutex.cc - -#ifdef _WIN32 - -struct Mutex::Internal { - CRITICAL_SECTION mutex; -#ifndef NDEBUG - // Used only to implement AssertHeld(). - DWORD thread_id; -#endif -}; - -Mutex::Mutex() - : mInternal(new Internal) { - InitializeCriticalSection(&mInternal->mutex); -} - -Mutex::~Mutex() { - DeleteCriticalSection(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - EnterCriticalSection(&mInternal->mutex); -#ifndef NDEBUG - mInternal->thread_id = GetCurrentThreadId(); -#endif -} - -void Mutex::Unlock() { -#ifndef NDEBUG - mInternal->thread_id = 0; -#endif - LeaveCriticalSection(&mInternal->mutex); -} - -void Mutex::AssertHeld() { -#ifndef NDEBUG - GOOGLE_DCHECK_EQ(mInternal->thread_id, GetCurrentThreadId()); -#endif -} - -#elif defined(HAVE_PTHREAD) - -struct Mutex::Internal { - pthread_mutex_t mutex; -}; - -Mutex::Mutex() - : mInternal(new Internal) { - pthread_mutex_init(&mInternal->mutex, NULL); -} - -Mutex::~Mutex() { - pthread_mutex_destroy(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - int result = pthread_mutex_lock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_lock: " << strerror(result); - } -} - -void Mutex::Unlock() { - int result = pthread_mutex_unlock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_unlock: " << strerror(result); - } -} - -void Mutex::AssertHeld() { - // pthreads dosn't provide a way to check which thread holds the mutex. - // TODO(kenton): Maybe keep track of locking thread ID like with WIN32? -} - -#endif - -// =================================================================== // emulates google3/util/endian/endian.h // // TODO(xiaofeng): PROTOBUF_LITTLE_ENDIAN is unfortunately defined in @@ -407,13 +337,30 @@ uint32 ghtonl(uint32 x) { namespace internal { typedef void OnShutdownFunc(); -vector<void (*)()>* shutdown_functions = NULL; -Mutex* shutdown_functions_mutex = NULL; +struct ShutdownData { + ~ShutdownData() { + for (int i = 0; i < functions.size(); i++) { + functions[i](); + } + for (int i = 0; i < strings.size(); i++) { + strings[i]->~string(); + } + for (int i = 0; i < messages.size(); i++) { + messages[i]->~MessageLite(); + } + } + + std::vector<void (*)()> functions; + std::vector<const std::string*> strings; + std::vector<const MessageLite*> messages; + Mutex mutex; +}; + +ShutdownData* shutdown_data = NULL; GOOGLE_PROTOBUF_DECLARE_ONCE(shutdown_functions_init); void InitShutdownFunctions() { - shutdown_functions = new vector<void (*)()>; - shutdown_functions_mutex = new Mutex; + shutdown_data = new ShutdownData; } inline void InitShutdownFunctionsOnce() { @@ -422,8 +369,20 @@ inline void InitShutdownFunctionsOnce() { void OnShutdown(void (*func)()) { InitShutdownFunctionsOnce(); - MutexLock lock(shutdown_functions_mutex); - shutdown_functions->push_back(func); + MutexLock lock(&shutdown_data->mutex); + shutdown_data->functions.push_back(func); +} + +void OnShutdownDestroyString(const std::string* ptr) { + InitShutdownFunctionsOnce(); + MutexLock lock(&shutdown_data->mutex); + shutdown_data->strings.push_back(ptr); +} + +void OnShutdownDestroyMessage(const void* ptr) { + InitShutdownFunctionsOnce(); + MutexLock lock(&shutdown_data->mutex); + shutdown_data->messages.push_back(static_cast<const MessageLite*>(ptr)); } } // namespace internal @@ -436,15 +395,10 @@ void ShutdownProtobufLibrary() { // called. // Make it safe to call this multiple times. - if (internal::shutdown_functions == NULL) return; + if (internal::shutdown_data == NULL) return; - for (int i = 0; i < internal::shutdown_functions->size(); i++) { - internal::shutdown_functions->at(i)(); - } - delete internal::shutdown_functions; - internal::shutdown_functions = NULL; - delete internal::shutdown_functions_mutex; - internal::shutdown_functions_mutex = NULL; + delete internal::shutdown_data; + internal::shutdown_data = NULL; } #if PROTOBUF_USE_EXCEPTIONS diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index 9c05cac3..c336383d 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h @@ -35,7 +35,13 @@ #ifndef GOOGLE_PROTOBUF_COMMON_H__ #define GOOGLE_PROTOBUF_COMMON_H__ +#include <algorithm> +#include <iostream> +#include <map> +#include <memory> +#include <set> #include <string> +#include <vector> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/macros.h> @@ -43,7 +49,6 @@ // TODO(liujisi): Remove the following includes after the include clean-up. #include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/scoped_ptr.h> #include <google/protobuf/stubs/mutex.h> #include <google/protobuf/stubs/callback.h> @@ -96,24 +101,27 @@ namespace internal { // The current version, represented as a single integer to make comparison // easier: major * 10^6 + minor * 10^3 + micro -#define GOOGLE_PROTOBUF_VERSION 3000000 +#define GOOGLE_PROTOBUF_VERSION 3005001 + +// A suffix string for alpha, beta or rc releases. Empty for stable releases. +#define GOOGLE_PROTOBUF_VERSION_SUFFIX "" // The minimum library version which works with the current version of the // headers. -#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3000000 +#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3005000 // The minimum header version which works with the current version of // the library. This constant should only be used by protoc's C++ code // generator. -static const int kMinHeaderVersionForLibrary = 3000000; +static const int kMinHeaderVersionForLibrary = 3005000; // The minimum protoc version which works with the current version of the // headers. -#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3000000 +#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3005000 // The minimum header version which works with the current version of // protoc. This constant should only be used in VerifyVersion(). -static const int kMinHeaderVersionForProtoc = 3000000; +static const int kMinHeaderVersionForProtoc = 3005000; // Verifies that the headers and libraries are compatible. Use the macro // below to call this. @@ -192,6 +200,10 @@ namespace internal { // Register a function to be called when ShutdownProtocolBuffers() is called. LIBPROTOBUF_EXPORT void OnShutdown(void (*func)()); +// Destroy the string (call string destructor) +LIBPROTOBUF_EXPORT void OnShutdownDestroyString(const std::string* ptr); +// Destroy (not delete) the message +LIBPROTOBUF_EXPORT void OnShutdownDestroyMessage(const void* ptr); } // namespace internal @@ -217,7 +229,7 @@ class FatalException : public std::exception { // This is at the end of the file instead of the beginning to work around a bug // in some versions of MSVC. -using namespace std; // Don't do this at home, kids. +using std::string; } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/common_unittest.cc b/src/google/protobuf/stubs/common_unittest.cc index 25bae9b0..798a2a27 100644 --- a/src/google/protobuf/stubs/common_unittest.cc +++ b/src/google/protobuf/stubs/common_unittest.cc @@ -41,8 +41,6 @@ namespace google { namespace protobuf { -using internal::NewCallback; -using internal::NewPermanentCallback; namespace { // TODO(kenton): More tests. @@ -77,7 +75,7 @@ TEST(CommonTest, IntMinMaxConstants) { EXPECT_EQ(0, kuint64max + 1); } -vector<string> captured_messages_; +std::vector<string> captured_messages_; void CaptureLog(LogLevel level, const char* filename, int line, const string& message) { diff --git a/src/google/protobuf/stubs/fastmem.h b/src/google/protobuf/stubs/fastmem.h index 763a6e60..1f1f6ed3 100644 --- a/src/google/protobuf/stubs/fastmem.h +++ b/src/google/protobuf/stubs/fastmem.h @@ -111,7 +111,8 @@ inline int fastmemcmp_inlined(const char *a, const char *b, size_t n) { b += sizeof(uint32); } while (a < a_limit) { - int d = static_cast<uint32>(*a++) - static_cast<uint32>(*b++); + int d = + static_cast<int>(static_cast<uint32>(*a++) - static_cast<uint32>(*b++)); if (d) return d; } return 0; diff --git a/src/google/protobuf/stubs/hash.h b/src/google/protobuf/stubs/hash.h index 58334322..fd8ba156 100755..100644 --- a/src/google/protobuf/stubs/hash.h +++ b/src/google/protobuf/stubs/hash.h @@ -41,15 +41,10 @@ #define GOOGLE_PROTOBUF_HAVE_HASH_MAP 1 #define GOOGLE_PROTOBUF_HAVE_HASH_SET 1 -// Android -#if defined(__ANDROID__) -# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP -# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP - // Use C++11 unordered_{map|set} if available. -#elif ((_LIBCPP_STD_VER >= 11) || \ - (((__cplusplus >= 201103L) || defined(__GXX_EXPERIMENTAL_CXX0X)) && \ - (__GLIBCXX__ > 20090421))) +#if ((defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) || \ + (((__cplusplus >= 201103L) || defined(__GXX_EXPERIMENTAL_CXX0X)) && \ + (__GLIBCXX__ > 20090421))) # define GOOGLE_PROTOBUF_HAS_CXX11_HASH // For XCode >= 4.6: the compiler is clang with libc++. @@ -97,6 +92,13 @@ # define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set # endif +// GCC <= 4.1 does not define std::tr1::hash for `long long int` or `long long unsigned int` +# if __GNUC__ == 4 && defined(__GNUC_MINOR__) && __GNUC_MINOR__ <= 1 +# undef GOOGLE_PROTOBUF_HAS_TR1 +# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP +# undef GOOGLE_PROTOBUF_HAVE_HASH_SET +# endif + // Version checks for MSC. // Apparently Microsoft decided to move hash_map *back* to the std namespace in // MSVC 2010: @@ -108,8 +110,13 @@ # define GOOGLE_PROTOBUF_HAS_CXX11_HASH # define GOOGLE_PROTOBUF_HASH_COMPARE std::hash_compare # elif _MSC_VER >= 1500 // Since Visual Studio 2008 -# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP -# undef GOOGLE_PROTOBUF_HAVE_HASH_SET +# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext +# include <hash_map> +# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map +# include <hash_set> +# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set +# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare +# define GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE # elif _MSC_VER >= 1310 # define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext # include <hash_map> @@ -214,6 +221,8 @@ class hash_map : public std::map<Key, Data, HashFcn, Alloc> { hash_map(int a = 0, const HashFcn& b = HashFcn(), const EqualKey& c = EqualKey(), const Alloc& d = Alloc()) : BaseClass(b, d) {} + + HashFcn hash_function() const { return HashFcn(); } }; template <typename Key, @@ -222,9 +231,12 @@ template <typename Key, class hash_set : public std::set<Key, HashFcn> { public: hash_set(int = 0) {} + + HashFcn hash_function() const { return HashFcn(); } }; -#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) +#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) && \ + !(defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) template <typename Key> struct hash : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> { @@ -243,6 +255,52 @@ template <> struct hash<const char*> : public GOOGLE_PROTOBUF_HASH_COMPARE<const char*, CstringLess> {}; +#ifdef GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE + +template <typename Key, typename HashFcn, typename EqualKey> +struct InternalHashCompare : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> { + InternalHashCompare() {} + InternalHashCompare(HashFcn hashfcn, EqualKey equalkey) + : hashfcn_(hashfcn), equalkey_(equalkey) {} + size_t operator()(const Key& key) const { return hashfcn_(key); } + bool operator()(const Key& key1, const Key& key2) const { + return !equalkey_(key1, key2); + } + HashFcn hashfcn_; + EqualKey equalkey_; +}; + +template <typename Key, typename Data, + typename HashFcn = hash<Key>, + typename EqualKey = std::equal_to<Key>, + typename Alloc = std::allocator< std::pair<const Key, Data> > > +class hash_map + : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< + Key, Data, InternalHashCompare<Key, HashFcn, EqualKey>, Alloc> { + typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS< + Key, Data, InternalHashCompare<Key, HashFcn, EqualKey>, Alloc> BaseClass; + + public: + hash_map(int a = 0, const HashFcn& b = HashFcn(), + const EqualKey& c = EqualKey(), const Alloc& d = Alloc()) + : BaseClass(InternalHashCompare<Key, HashFcn, EqualKey>(b, c), d) {} + + HashFcn hash_function() const { return HashFcn(); } +}; + +template <typename Key, typename HashFcn = hash<Key>, + typename EqualKey = std::equal_to<Key> > +class hash_set + : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS< + Key, InternalHashCompare<Key, HashFcn, EqualKey> > { + public: + hash_set(int = 0) {} + + HashFcn hash_function() const { return HashFcn(); } +}; + +#else // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE + template <typename Key, typename Data, typename HashFcn = hash<Key>, typename EqualKey = std::equal_to<Key>, @@ -257,6 +315,8 @@ class hash_map hash_map(int a = 0, const HashFcn& b = HashFcn(), const EqualKey& c = EqualKey(), const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {} + + HashFcn hash_function() const { return HashFcn(); } }; template <typename Key, typename HashFcn = hash<Key>, @@ -266,9 +326,12 @@ class hash_set Key, HashFcn, EqualKey> { public: hash_set(int = 0) {} + + HashFcn hash_function() const { return HashFcn(); } }; +#endif // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE -#else +#else // defined(_MSC_VER) && !defined(_STLPORT_VERSION) template <typename Key> struct hash : public GOOGLE_PROTOBUF_HASH_NAMESPACE::hash<Key> { @@ -288,7 +351,7 @@ struct hash<const char*> { inline size_t operator()(const char* str) const { size_t result = 0; for (; *str != '\0'; str++) { - result = 5 * result + *str; + result = 5 * result + static_cast<size_t>(*str); } return result; } @@ -315,6 +378,8 @@ class hash_map hash_map(int a = 0, const HashFcn& b = HashFcn(), const EqualKey& c = EqualKey(), const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {} + + HashFcn hash_function() const { return HashFcn(); } }; template <typename Key, typename HashFcn = hash<Key>, @@ -324,6 +389,8 @@ class hash_set Key, HashFcn, EqualKey> { public: hash_set(int = 0) {} + + HashFcn hash_function() const { return HashFcn(); } }; #endif // !GOOGLE_PROTOBUF_MISSING_HASH @@ -342,8 +409,8 @@ struct hash<string> { }; template <typename First, typename Second> -struct hash<pair<First, Second> > { - inline size_t operator()(const pair<First, Second>& key) const { +struct hash<std::pair<First, Second> > { + inline size_t operator()(const std::pair<First, Second>& key) const { size_t first_hash = hash<First>()(key.first); size_t second_hash = hash<Second>()(key.second); @@ -354,8 +421,8 @@ struct hash<pair<First, Second> > { static const size_t bucket_size = 4; static const size_t min_buckets = 8; - inline bool operator()(const pair<First, Second>& a, - const pair<First, Second>& b) const { + inline bool operator()(const std::pair<First, Second>& a, + const std::pair<First, Second>& b) const { return a < b; } }; diff --git a/src/google/protobuf/stubs/int128.cc b/src/google/protobuf/stubs/int128.cc index d80c64f2..7b993e8f 100644 --- a/src/google/protobuf/stubs/int128.cc +++ b/src/google/protobuf/stubs/int128.cc @@ -31,7 +31,7 @@ #include <google/protobuf/stubs/int128.h> #include <iomanip> -#include <iostream> // NOLINT(readability/streams) +#include <ostream> // NOLINT(readability/streams) #include <sstream> namespace google { @@ -76,52 +76,36 @@ static inline int Fls128(uint128 n) { return Fls64(Uint128Low64(n)); } -// Long division/modulo for uint128 implemented using the shift-subtract -// division algorithm adapted from: -// http://stackoverflow.com/questions/5386377/division-without-using void uint128::DivModImpl(uint128 dividend, uint128 divisor, uint128* quotient_ret, uint128* remainder_ret) { if (divisor == 0) { GOOGLE_LOG(FATAL) << "Division or mod by zero: dividend.hi=" << dividend.hi_ << ", lo=" << dividend.lo_; - } - - if (divisor > dividend) { + } else if (dividend < divisor) { *quotient_ret = 0; *remainder_ret = dividend; return; - } - - if (divisor == dividend) { - *quotient_ret = 1; - *remainder_ret = 0; - return; - } - - uint128 denominator = divisor; - uint128 position = 1; - uint128 quotient = 0; - - // Left aligns the MSB of the denominator and the dividend. - int shift = Fls128(dividend) - Fls128(denominator); - denominator <<= shift; - position <<= shift; - - // Uses shift-subtract algorithm to divide dividend by denominator. The - // remainder will be left in dividend. - while (position > 0) { - if (dividend >= denominator) { - dividend -= denominator; - quotient |= position; + } else { + int dividend_bit_length = Fls128(dividend); + int divisor_bit_length = Fls128(divisor); + int difference = dividend_bit_length - divisor_bit_length; + uint128 quotient = 0; + while (difference >= 0) { + quotient <<= 1; + uint128 shifted_divisor = divisor << difference; + if (shifted_divisor <= dividend) { + dividend -= shifted_divisor; + quotient += 1; + } + difference -= 1; } - position >>= 1; - denominator >>= 1; + //record the final quotient and remainder + *quotient_ret = quotient; + *remainder_ret = dividend; } - - *quotient_ret = quotient; - *remainder_ret = dividend; } + uint128& uint128::operator/=(const uint128& divisor) { uint128 quotient = 0; uint128 remainder = 0; @@ -145,15 +129,15 @@ std::ostream& operator<<(std::ostream& o, const uint128& b) { std::streamsize div_base_log; switch (flags & std::ios::basefield) { case std::ios::hex: - div = GOOGLE_ULONGLONG(0x1000000000000000); // 16^15 + div = static_cast<uint64>(GOOGLE_ULONGLONG(0x1000000000000000)); // 16^15 div_base_log = 15; break; case std::ios::oct: - div = GOOGLE_ULONGLONG(01000000000000000000000); // 8^21 + div = static_cast<uint64>(GOOGLE_ULONGLONG(01000000000000000000000)); // 8^21 div_base_log = 21; break; default: // std::ios::dec - div = GOOGLE_ULONGLONG(10000000000000000000); // 10^19 + div = static_cast<uint64>(GOOGLE_ULONGLONG(10000000000000000000)); // 10^19 div_base_log = 19; break; } diff --git a/src/google/protobuf/stubs/int128_unittest.cc b/src/google/protobuf/stubs/int128_unittest.cc index 5d33292c..1ec899ad 100644 --- a/src/google/protobuf/stubs/int128_unittest.cc +++ b/src/google/protobuf/stubs/int128_unittest.cc @@ -370,29 +370,29 @@ TEST(Int128, DivideAndMod) { EXPECT_EQ(r, result_r); // Try the other way around. - swap(q, b); + std::swap(q, b); result_q = a / b; result_r = a % b; EXPECT_EQ(q, result_q); EXPECT_EQ(r, result_r); // Restore. - swap(b, q); + std::swap(b, q); // Dividend < divisor; result should be q:0 r:<dividend>. - swap(a, b); + std::swap(a, b); result_q = a / b; result_r = a % b; EXPECT_EQ(0, result_q); EXPECT_EQ(a, result_r); // Try the other way around. - swap(a, q); + std::swap(a, q); result_q = a / b; result_r = a % b; EXPECT_EQ(0, result_q); EXPECT_EQ(a, result_r); // Restore. - swap(q, a); - swap(b, a); + std::swap(q, a); + std::swap(b, a); // Try a large remainder. b = a / 2 + 1; @@ -501,7 +501,7 @@ TEST(Int128, OStream) { {uint128(12345), std::ios::dec | std::ios::left, 6, '_', "12345_"}, }; for (size_t i = 0; i < GOOGLE_ARRAYSIZE(cases); ++i) { - ostringstream os; + std::ostringstream os; os.flags(cases[i].flags); os.width(cases[i].width); os.fill(cases[i].fill); diff --git a/src/google/protobuf/stubs/io_win32.cc b/src/google/protobuf/stubs/io_win32.cc new file mode 100644 index 00000000..4407facb --- /dev/null +++ b/src/google/protobuf/stubs/io_win32.cc @@ -0,0 +1,414 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: laszlocsomor@google.com (Laszlo Csomor) +// +// Implementation for long-path-aware open/mkdir/access/etc. on Windows, as well +// as for the supporting utility functions. +// +// These functions convert the input path to an absolute Windows path +// with "\\?\" prefix, then pass that to _wopen/_wmkdir/_waccess/etc. +// (declared in <io.h>) respectively. This allows working with files/directories +// whose paths are longer than MAX_PATH (260 chars). +// +// This file is only used on Windows, it's empty on other platforms. + +#if defined(_WIN32) + +// Comment this out to fall back to using the ANSI versions (open, mkdir, ...) +// instead of the Unicode ones (_wopen, _wmkdir, ...). Doing so can be useful to +// debug failing tests if that's caused by the long path support. +#define SUPPORT_LONGPATHS + +#include <ctype.h> +#include <direct.h> +#include <errno.h> +#include <fcntl.h> +#include <io.h> +#include <memory> +#include <sys/stat.h> +#include <sys/types.h> +#include <wctype.h> +#include <windows.h> + +#include <google/protobuf/stubs/io_win32.h> + +#include <memory> +#include <sstream> +#include <string> +#include <vector> + +namespace google { +namespace protobuf { +namespace internal { +namespace win32 { +namespace { + +using std::string; +using std::wstring; + +template <typename char_type> +struct CharTraits { + static bool is_alpha(char_type ch); +}; + +template <> +struct CharTraits<char> { + static bool is_alpha(char ch) { return isalpha(ch); } +}; + +template <> +struct CharTraits<wchar_t> { + static bool is_alpha(wchar_t ch) { return iswalpha(ch); } +}; + +template <typename char_type> +bool null_or_empty(const char_type* s) { + return s == NULL || *s == 0; +} + +// Returns true if the path starts with a drive letter, e.g. "c:". +// Note that this won't check for the "\" after the drive letter, so this also +// returns true for "c:foo" (which is "c:\${PWD}\foo"). +// This check requires that a path not have a longpath prefix ("\\?\"). +template <typename char_type> +bool has_drive_letter(const char_type* ch) { + return CharTraits<char_type>::is_alpha(ch[0]) && ch[1] == ':'; +} + +// Returns true if the path starts with a longpath prefix ("\\?\"). +template <typename char_type> +bool has_longpath_prefix(const char_type* path) { + return path[0] == '\\' && path[1] == '\\' && path[2] == '?' && + path[3] == '\\'; +} + +template <typename char_type> +bool is_separator(char_type c) { + return c == '/' || c == '\\'; +} + +// Returns true if the path starts with a drive specifier (e.g. "c:\"). +template <typename char_type> +bool is_path_absolute(const char_type* path) { + return has_drive_letter(path) && is_separator(path[2]); +} + +template <typename char_type> +bool is_drive_relative(const char_type* path) { + return has_drive_letter(path) && (path[2] == 0 || !is_separator(path[2])); +} + +wstring join_paths(const wstring& path1, const wstring& path2) { + if (path1.empty() || is_path_absolute(path2.c_str()) || + has_longpath_prefix(path2.c_str())) { + return path2; + } + if (path2.empty()) { + return path1; + } + + if (is_separator(path1[path1.size() - 1])) { + return is_separator(path2[0]) ? (path1 + path2.substr(1)) + : (path1 + path2); + } else { + return is_separator(path2[0]) ? (path1 + path2) + : (path1 + L'\\' + path2); + } +} + +wstring normalize(wstring path) { + if (has_longpath_prefix(path.c_str())) { + path = path.substr(4); + } + + static const wstring dot(L"."); + static const wstring dotdot(L".."); + const WCHAR* p = path.c_str(); + + std::vector<wstring> segments; + int segment_start = -1; + // Find the path segments in `path` (separated by "/"). + for (int i = 0;; ++i) { + if (!is_separator(p[i]) && p[i] != L'\0') { + // The current character does not end a segment, so start one unless it's + // already started. + if (segment_start < 0) { + segment_start = i; + } + } else if (segment_start >= 0 && i > segment_start) { + // The current character is "/" or "\0", so this ends a segment. + // Add that to `segments` if there's anything to add; handle "." and "..". + wstring segment(p, segment_start, i - segment_start); + segment_start = -1; + if (segment == dotdot) { + if (!segments.empty() && + (!has_drive_letter(segments[0].c_str()) || segments.size() > 1)) { + segments.pop_back(); + } + } else if (segment != dot && !segment.empty()) { + segments.push_back(segment); + } + } + if (p[i] == L'\0') { + break; + } + } + + // Handle the case when `path` is just a drive specifier (or some degenerate + // form of it, e.g. "c:\.."). + if (segments.size() == 1 && segments[0].size() == 2 && + has_drive_letter(segments[0].c_str())) { + return segments[0] + L'\\'; + } + + // Join all segments. + bool first = true; + std::wstringstream result; + for (int i = 0; i < segments.size(); ++i) { + if (!first) { + result << L'\\'; + } + first = false; + result << segments[i]; + } + // Preserve trailing separator if the input contained it. + if (!path.empty() && is_separator(p[path.size() - 1])) { + result << L'\\'; + } + return result.str(); +} + +bool as_windows_path(const char* path, wstring* result) { + if (null_or_empty(path)) { + result->clear(); + return true; + } + wstring wpath; + if (!strings::utf8_to_wcs(path, &wpath)) { + return false; + } + if (has_longpath_prefix(wpath.c_str())) { + *result = wpath; + return true; + } + if (is_separator(path[0]) || is_drive_relative(path)) { + return false; + } + + + if (!is_path_absolute(wpath.c_str())) { + int size = ::GetCurrentDirectoryW(0, NULL); + if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + return false; + } + std::unique_ptr<WCHAR[]> wcwd(new WCHAR[size]); + ::GetCurrentDirectoryW(size, wcwd.get()); + wpath = join_paths(wcwd.get(), wpath); + } + wpath = normalize(wpath); + if (!has_longpath_prefix(wpath.c_str())) { + // Add the "\\?\" prefix unconditionally. This way we prevent the Win32 API + // from processing the path and "helpfully" removing trailing dots from the + // path, for example. + // See https://github.com/bazelbuild/bazel/issues/2935 + wpath = wstring(L"\\\\?\\") + wpath; + } + *result = wpath; + return true; +} + +} // namespace + +int open(const char* path, int flags, int mode) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wopen(wpath.c_str(), flags, mode); +#else + return ::_open(path, flags, mode); +#endif +} + +int mkdir(const char* path, int _mode) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wmkdir(wpath.c_str()); +#else // not SUPPORT_LONGPATHS + return ::_mkdir(path); +#endif // not SUPPORT_LONGPATHS +} + +int access(const char* path, int mode) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_waccess(wpath.c_str(), mode); +#else + return ::_access(path, mode); +#endif +} + +int chdir(const char* path) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wchdir(wpath.c_str()); +#else + return ::_chdir(path); +#endif +} + +int stat(const char* path, struct _stat* buffer) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wstat(wpath.c_str(), buffer); +#else // not SUPPORT_LONGPATHS + return ::_stat(path, buffer); +#endif // not SUPPORT_LONGPATHS +} + +FILE* fopen(const char* path, const char* mode) { +#ifdef SUPPORT_LONGPATHS + if (null_or_empty(path)) { + errno = EINVAL; + return NULL; + } + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return NULL; + } + wstring wmode; + if (!strings::utf8_to_wcs(mode, &wmode)) { + errno = EINVAL; + return NULL; + } + return ::_wfopen(wpath.c_str(), wmode.c_str()); +#else + return ::fopen(path, mode); +#endif +} + +int close(int fd) { return ::close(fd); } + +int dup(int fd) { return ::_dup(fd); } + +int dup2(int fd1, int fd2) { return ::_dup2(fd1, fd2); } + +int read(int fd, void* buffer, size_t size) { + return ::_read(fd, buffer, size); +} + +int setmode(int fd, int mode) { return ::_setmode(fd, mode); } + +int write(int fd, const void* buffer, size_t size) { + return ::_write(fd, buffer, size); +} + +wstring testonly_utf8_to_winpath(const char* path) { + wstring wpath; + return as_windows_path(path, &wpath) ? wpath : wstring(); +} + +namespace strings { + +bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) { + if (null_or_empty(s)) { + out->clear(); + return true; + } + BOOL usedDefaultChar = FALSE; + SetLastError(0); + int size = WideCharToMultiByte( + outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0, NULL, + outUtf8 ? NULL : &usedDefaultChar); + if ((size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) + || usedDefaultChar) { + return false; + } + std::unique_ptr<CHAR[]> astr(new CHAR[size]); + WideCharToMultiByte( + outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, NULL, NULL); + out->assign(astr.get()); + return true; +} + +bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) { + if (null_or_empty(s)) { + out->clear(); + return true; + } + + SetLastError(0); + int size = + MultiByteToWideChar(inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0); + if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + return false; + } + std::unique_ptr<WCHAR[]> wstr(new WCHAR[size]); + MultiByteToWideChar( + inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, wstr.get(), size + 1); + out->assign(wstr.get()); + return true; +} + +bool utf8_to_wcs(const char* input, wstring* out) { + return mbs_to_wcs(input, out, true); +} + +bool wcs_to_utf8(const wchar_t* input, string* out) { + return wcs_to_mbs(input, out, true); +} + +} // namespace strings +} // namespace win32 +} // namespace internal +} // namespace protobuf +} // namespace google + +#endif // defined(_WIN32) diff --git a/src/google/protobuf/stubs/io_win32.h b/src/google/protobuf/stubs/io_win32.h new file mode 100644 index 00000000..9e17d253 --- /dev/null +++ b/src/google/protobuf/stubs/io_win32.h @@ -0,0 +1,115 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: laszlocsomor@google.com (Laszlo Csomor) +// +// This file contains the declarations for Windows implementations of +// commonly used POSIX functions such as open(2) and access(2), as well +// as macro definitions for flags of these functions. +// +// By including this file you'll redefine open/access/etc. to +// ::google::protobuf::internal::win32::{open/access/etc.}. +// Make sure you don't include a header that attempts to redeclare or +// redefine these functions, that'll lead to confusing compilation +// errors. It's best to #include this file as the last one to ensure that. +// +// This file is only used on Windows, it's empty on other platforms. + +#ifndef GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__ +#define GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__ + +#if defined(_WIN32) + +#include <string> +#include <google/protobuf/stubs/port.h> + +// Compilers on Windows other than MSVC (e.g. Cygwin, MinGW32) define the +// following functions already, except for mkdir. +namespace google { +namespace protobuf { +namespace internal { +namespace win32 { + +LIBPROTOBUF_EXPORT FILE* fopen(const char* path, const char* mode); +LIBPROTOBUF_EXPORT int access(const char* path, int mode); +LIBPROTOBUF_EXPORT int chdir(const char* path); +LIBPROTOBUF_EXPORT int close(int fd); +LIBPROTOBUF_EXPORT int dup(int fd); +LIBPROTOBUF_EXPORT int dup2(int fd1, int fd2); +LIBPROTOBUF_EXPORT int mkdir(const char* path, int _mode); +LIBPROTOBUF_EXPORT int open(const char* path, int flags, int mode = 0); +LIBPROTOBUF_EXPORT int read(int fd, void* buffer, size_t size); +LIBPROTOBUF_EXPORT int setmode(int fd, int mode); +LIBPROTOBUF_EXPORT int stat(const char* path, struct _stat* buffer); +LIBPROTOBUF_EXPORT int write(int fd, const void* buffer, size_t size); +LIBPROTOBUF_EXPORT std::wstring testonly_utf8_to_winpath(const char* path); + +namespace strings { + +// Convert from UTF-16 to Active-Code-Page-encoded or to UTF-8-encoded text. +LIBPROTOBUF_EXPORT bool wcs_to_mbs( + const wchar_t* s, std::string* out, bool outUtf8); + +// Convert from Active-Code-Page-encoded or UTF-8-encoded text to UTF-16. +LIBPROTOBUF_EXPORT bool mbs_to_wcs( + const char* s, std::wstring* out, bool inUtf8); + +// Convert from UTF-8-encoded text to UTF-16. +LIBPROTOBUF_EXPORT bool utf8_to_wcs(const char* input, std::wstring* out); + +// Convert from UTF-16-encoded text to UTF-8. +LIBPROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out); + +} // namespace strings + +} // namespace win32 +} // namespace internal +} // namespace protobuf +} // namespace google + +#ifndef W_OK +#define W_OK 02 // not defined by MSVC for whatever reason +#endif + +#ifndef F_OK +#define F_OK 00 // not defined by MSVC for whatever reason +#endif + +#ifndef STDIN_FILENO +#define STDIN_FILENO 0 +#endif + +#ifndef STDOUT_FILENO +#define STDOUT_FILENO 1 +#endif + +#endif // defined(_WIN32) + +#endif // GOOGLE_PROTOBUF_STUBS_IO_WIN32_H__ diff --git a/src/google/protobuf/stubs/io_win32_unittest.cc b/src/google/protobuf/stubs/io_win32_unittest.cc new file mode 100644 index 00000000..c933757c --- /dev/null +++ b/src/google/protobuf/stubs/io_win32_unittest.cc @@ -0,0 +1,452 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: laszlocsomor@google.com (Laszlo Csomor) +// +// Unit tests for long-path-aware open/mkdir/access/etc. on Windows, as well as +// for the supporting utility functions. +// +// This file is only used on Windows, it's empty on other platforms. + +#if defined(_WIN32) + +#define WIN32_LEAN_AND_MEAN +#include <errno.h> +#include <fcntl.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <wchar.h> +#include <windows.h> + +#include <google/protobuf/stubs/io_win32.h> +#include <gtest/gtest.h> + +#include <memory> +#include <sstream> +#include <string> + +namespace google { +namespace protobuf { +namespace internal { +namespace win32 { +namespace { + +const char kUtf8Text[] = { + 'h', 'i', ' ', + // utf-8: 11010000 10011111, utf-16: 100 0001 1111 = 0x041F + 0xd0, 0x9f, + // utf-8: 11010001 10000000, utf-16: 100 0100 0000 = 0x0440 + 0xd1, 0x80, + // utf-8: 11010000 10111000, utf-16: 100 0011 1000 = 0x0438 + 0xd0, 0xb8, + // utf-8: 11010000 10110010, utf-16: 100 0011 0010 = 0x0432 + 0xd0, 0xb2, + // utf-8: 11010000 10110101, utf-16: 100 0011 0101 = 0x0435 + 0xd0, 0xb5, + // utf-8: 11010001 10000010, utf-16: 100 0100 0010 = 0x0442 + 0xd1, 0x82, 0 +}; + +const wchar_t kUtf16Text[] = { + L'h', L'i', L' ', + L'\x41f', L'\x440', L'\x438', L'\x432', L'\x435', L'\x442', 0 +}; + +using std::string; +using std::wstring; + +class IoWin32Test : public ::testing::Test { + public: + void SetUp(); + void TearDown(); + + protected: + bool CreateAllUnder(wstring path); + bool DeleteAllUnder(wstring path); + + WCHAR working_directory[MAX_PATH]; + string test_tmpdir; + wstring wtest_tmpdir; +}; + +#define ASSERT_INITIALIZED \ + { \ + EXPECT_FALSE(test_tmpdir.empty()); \ + EXPECT_FALSE(wtest_tmpdir.empty()); \ + } + +namespace { +void StripTrailingSlashes(string* str) { + int i = str->size() - 1; + for (; i >= 0 && ((*str)[i] == '/' || (*str)[i] == '\\'); --i) {} + str->resize(i+1); +} + +bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { + DWORD size = ::GetEnvironmentVariableW(name, NULL, 0); + if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) { + std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]); + ::GetEnvironmentVariableW(name, wcs.get(), size); + // GetEnvironmentVariableA retrieves an Active-Code-Page-encoded text which + // we'd first need to convert to UTF-16 then to UTF-8, because there seems + // to be no API function to do that conversion directly. + // GetEnvironmentVariableW retrieves an UTF-16-encoded text, which we need + // to convert to UTF-8. + return strings::wcs_to_utf8(wcs.get(), result); + } else { + return false; + } +} + +bool GetCwdAsUtf8(string* result) { + DWORD size = ::GetCurrentDirectoryW(0, NULL); + if (size > 0) { + std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]); + ::GetCurrentDirectoryW(size, wcs.get()); + // GetCurrentDirectoryA retrieves an Active-Code-Page-encoded text which + // we'd first need to convert to UTF-16 then to UTF-8, because there seems + // to be no API function to do that conversion directly. + // GetCurrentDirectoryW retrieves an UTF-16-encoded text, which we need + // to convert to UTF-8. + return strings::wcs_to_utf8(wcs.get(), result); + } else { + return false; + } +} + +} // namespace + +void IoWin32Test::SetUp() { + test_tmpdir.clear(); + wtest_tmpdir.clear(); + EXPECT_GT(::GetCurrentDirectoryW(MAX_PATH, working_directory), 0); + + string tmp; + bool ok = false; + if (!ok) { + // Bazel sets this environment variable when it runs tests. + ok = GetEnvVarAsUtf8(L"TEST_TMPDIR", &tmp); + } + if (!ok) { + // Bazel 0.8.0 sets this environment for every build and test action. + ok = GetEnvVarAsUtf8(L"TEMP", &tmp); + } + if (!ok) { + // Bazel 0.8.0 sets this environment for every build and test action. + ok = GetEnvVarAsUtf8(L"TMP", &tmp); + } + if (!ok) { + // Fall back to using the current directory. + ok = GetCwdAsUtf8(&tmp); + } + if (!ok || tmp.empty()) { + FAIL() << "Cannot find a temp directory."; + } + + StripTrailingSlashes(&tmp); + std::stringstream result; + // Deleting files and directories is asynchronous on Windows, and if TearDown + // just deleted the previous temp directory, sometimes we cannot recreate the + // same directory. + // Use a counter so every test method gets its own temp directory. + static unsigned int counter = 0; + result << tmp << "\\w32tst" << counter++ << ".tmp"; + test_tmpdir = result.str(); + wtest_tmpdir = testonly_utf8_to_winpath(test_tmpdir.c_str()); + ASSERT_FALSE(wtest_tmpdir.empty()); + ASSERT_TRUE(DeleteAllUnder(wtest_tmpdir)); + ASSERT_TRUE(CreateAllUnder(wtest_tmpdir)); +} + +void IoWin32Test::TearDown() { + if (!wtest_tmpdir.empty()) { + DeleteAllUnder(wtest_tmpdir); + } + ::SetCurrentDirectoryW(working_directory); +} + +bool IoWin32Test::CreateAllUnder(wstring path) { + // Prepend UNC prefix if the path doesn't have it already. Don't bother + // checking if the path is shorter than MAX_PATH, let's just do it + // unconditionally. + if (path.find(L"\\\\?\\") != 0) { + path = wstring(L"\\\\?\\") + path; + } + if (::CreateDirectoryW(path.c_str(), NULL) || + GetLastError() == ERROR_ALREADY_EXISTS || + GetLastError() == ERROR_ACCESS_DENIED) { + return true; + } + if (GetLastError() == ERROR_PATH_NOT_FOUND) { + size_t pos = path.find_last_of(L'\\'); + if (pos != wstring::npos) { + wstring parent(path, 0, pos); + if (CreateAllUnder(parent) && CreateDirectoryW(path.c_str(), NULL)) { + return true; + } + } + } + return false; +} + +bool IoWin32Test::DeleteAllUnder(wstring path) { + static const wstring kDot(L"."); + static const wstring kDotDot(L".."); + + // Prepend UNC prefix if the path doesn't have it already. Don't bother + // checking if the path is shorter than MAX_PATH, let's just do it + // unconditionally. + if (path.find(L"\\\\?\\") != 0) { + path = wstring(L"\\\\?\\") + path; + } + // Append "\" if necessary. + if (path[path.size() - 1] != L'\\') { + path.push_back(L'\\'); + } + + WIN32_FIND_DATAW metadata; + HANDLE handle = ::FindFirstFileW((path + L"*").c_str(), &metadata); + if (handle == INVALID_HANDLE_VALUE) { + return true; // directory doesn't exist + } + + bool result = true; + do { + wstring childname = metadata.cFileName; + if (kDot != childname && kDotDot != childname) { + wstring childpath = path + childname; + if ((metadata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { + // If this is not a junction, delete its contents recursively. + // Finally delete this directory/junction too. + if (((metadata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 && + !DeleteAllUnder(childpath)) || + !::RemoveDirectoryW(childpath.c_str())) { + result = false; + break; + } + } else { + if (!::DeleteFileW(childpath.c_str())) { + result = false; + break; + } + } + } + } while (::FindNextFileW(handle, &metadata)); + ::FindClose(handle); + return result; +} + +TEST_F(IoWin32Test, AccessTest) { + ASSERT_INITIALIZED; + + string path = test_tmpdir; + while (path.size() < MAX_PATH - 30) { + path += "\\accesstest"; + EXPECT_EQ(mkdir(path.c_str(), 0644), 0); + } + string file = path + "\\file.txt"; + int fd = open(file.c_str(), O_CREAT | O_WRONLY, 0644); + if (fd > 0) { + EXPECT_EQ(close(fd), 0); + } else { + EXPECT_TRUE(false); + } + + EXPECT_EQ(access(test_tmpdir.c_str(), F_OK), 0); + EXPECT_EQ(access(path.c_str(), F_OK), 0); + EXPECT_EQ(access(path.c_str(), W_OK), 0); + EXPECT_EQ(access(file.c_str(), F_OK | W_OK), 0); + EXPECT_NE(access((file + ".blah").c_str(), F_OK), 0); + EXPECT_NE(access((file + ".blah").c_str(), W_OK), 0); + + EXPECT_EQ(access(".", F_OK), 0); + EXPECT_EQ(access(".", W_OK), 0); + EXPECT_EQ(access((test_tmpdir + "/accesstest").c_str(), F_OK | W_OK), 0); + ASSERT_EQ(access((test_tmpdir + "/./normalize_me/.././accesstest").c_str(), + F_OK | W_OK), + 0); + EXPECT_NE(access("io_win32_unittest.AccessTest.nonexistent", F_OK), 0); + EXPECT_NE(access("io_win32_unittest.AccessTest.nonexistent", W_OK), 0); + + ASSERT_EQ(access("c:bad", F_OK), -1); + ASSERT_EQ(errno, ENOENT); + ASSERT_EQ(access("/tmp/bad", F_OK), -1); + ASSERT_EQ(errno, ENOENT); + ASSERT_EQ(access("\\bad", F_OK), -1); + ASSERT_EQ(errno, ENOENT); +} + +TEST_F(IoWin32Test, OpenTest) { + ASSERT_INITIALIZED; + + string path = test_tmpdir; + while (path.size() < MAX_PATH) { + path += "\\opentest"; + EXPECT_EQ(mkdir(path.c_str(), 0644), 0); + } + string file = path + "\\file.txt"; + int fd = open(file.c_str(), O_CREAT | O_WRONLY, 0644); + if (fd > 0) { + EXPECT_EQ(write(fd, "hello", 5), 5); + EXPECT_EQ(close(fd), 0); + } else { + EXPECT_TRUE(false); + } + + ASSERT_EQ(open("c:bad.txt", O_CREAT | O_WRONLY, 0644), -1); + ASSERT_EQ(errno, ENOENT); + ASSERT_EQ(open("/tmp/bad.txt", O_CREAT | O_WRONLY, 0644), -1); + ASSERT_EQ(errno, ENOENT); + ASSERT_EQ(open("\\bad.txt", O_CREAT | O_WRONLY, 0644), -1); + ASSERT_EQ(errno, ENOENT); +} + +TEST_F(IoWin32Test, MkdirTest) { + ASSERT_INITIALIZED; + + string path = test_tmpdir; + do { + path += "\\mkdirtest"; + ASSERT_EQ(mkdir(path.c_str(), 0644), 0); + } while (path.size() <= MAX_PATH); + + ASSERT_EQ(mkdir("c:bad", 0644), -1); + ASSERT_EQ(errno, ENOENT); + ASSERT_EQ(mkdir("/tmp/bad", 0644), -1); + ASSERT_EQ(errno, ENOENT); + ASSERT_EQ(mkdir("\\bad", 0644), -1); + ASSERT_EQ(errno, ENOENT); +} + +TEST_F(IoWin32Test, MkdirTestNonAscii) { + ASSERT_INITIALIZED; + + // Create a non-ASCII path. + // Ensure that we can create the directory using SetCurrentDirectoryW. + EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), NULL)); + EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), NULL)); + // Ensure that we can create a very similarly named directory using mkdir. + // We don't attemp to delete and recreate the same directory, because on + // Windows, deleting files and directories seems to be asynchronous. + EXPECT_EQ(mkdir((test_tmpdir + "\\2").c_str(), 0644), 0); + EXPECT_EQ(mkdir((test_tmpdir + "\\2\\" + kUtf8Text).c_str(), 0644), 0); +} + +TEST_F(IoWin32Test, ChdirTest) { + string path("C:\\"); + EXPECT_EQ(access(path.c_str(), F_OK), 0); + ASSERT_EQ(chdir(path.c_str()), 0); + + // Do not try to chdir into the test_tmpdir, it may already contain directory + // names with trailing dots. + // Instead test here with an obviously dot-trailed path. If the win32_chdir + // function would not convert the path to absolute and prefix with "\\?\" then + // the Win32 API would ignore the trailing dot, but because of the prefixing + // there'll be no path processing done, so we'll actually attempt to chdir + // into "C:\some\path\foo." + path = test_tmpdir + "/foo."; + EXPECT_EQ(mkdir(path.c_str(), 644), 0); + EXPECT_EQ(access(path.c_str(), F_OK), 0); + ASSERT_NE(chdir(path.c_str()), 0); +} + +TEST_F(IoWin32Test, ChdirTestNonAscii) { + ASSERT_INITIALIZED; + + // Create a directory with a non-ASCII path and ensure we can cd into it. + wstring wNonAscii(wtest_tmpdir + L"\\" + kUtf16Text); + string nonAscii; + EXPECT_TRUE(strings::wcs_to_utf8(wNonAscii.c_str(), &nonAscii)); + EXPECT_TRUE(CreateDirectoryW(wNonAscii.c_str(), NULL)); + WCHAR cwd[MAX_PATH]; + EXPECT_TRUE(GetCurrentDirectoryW(MAX_PATH, cwd)); + // Ensure that we can cd into the path using SetCurrentDirectoryW. + EXPECT_TRUE(SetCurrentDirectoryW(wNonAscii.c_str())); + EXPECT_TRUE(SetCurrentDirectoryW(cwd)); + // Ensure that we can cd into the path using chdir. + ASSERT_EQ(chdir(nonAscii.c_str()), 0); + // Ensure that the GetCurrentDirectoryW returns the desired path. + EXPECT_TRUE(GetCurrentDirectoryW(MAX_PATH, cwd)); + ASSERT_EQ(wNonAscii, cwd); +} + +TEST_F(IoWin32Test, AsWindowsPathTest) { + DWORD size = GetCurrentDirectoryW(0, NULL); + std::unique_ptr<wchar_t[]> cwd_str(new wchar_t[size]); + EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0); + wstring cwd = wstring(L"\\\\?\\") + cwd_str.get(); + + ASSERT_EQ(testonly_utf8_to_winpath("relative_mkdirtest"), + cwd + L"\\relative_mkdirtest"); + ASSERT_EQ(testonly_utf8_to_winpath("preserve//\\trailing///"), + cwd + L"\\preserve\\trailing\\"); + ASSERT_EQ(testonly_utf8_to_winpath("./normalize_me\\/../blah"), + cwd + L"\\blah"); + std::ostringstream relpath; + for (wchar_t* p = cwd_str.get(); *p; ++p) { + if (*p == '/' || *p == '\\') { + relpath << "../"; + } + } + relpath << ".\\/../\\./beyond-toplevel"; + ASSERT_EQ(testonly_utf8_to_winpath(relpath.str().c_str()), + wstring(L"\\\\?\\") + cwd_str.get()[0] + L":\\beyond-toplevel"); + + // Absolute unix paths lack drive letters, driveless absolute windows paths + // do too. Neither can be converted to a drive-specifying absolute Windows + // path. + ASSERT_EQ(testonly_utf8_to_winpath("/absolute/unix/path"), L""); + // Though valid on Windows, we also don't support UNC paths (\\UNC\\blah). + ASSERT_EQ(testonly_utf8_to_winpath("\\driveless\\absolute"), L""); + // Though valid in cmd.exe, drive-relative paths are not supported. + ASSERT_EQ(testonly_utf8_to_winpath("c:foo"), L""); + ASSERT_EQ(testonly_utf8_to_winpath("c:/foo"), L"\\\\?\\c:\\foo"); + ASSERT_EQ(testonly_utf8_to_winpath("\\\\?\\C:\\foo"), L"\\\\?\\C:\\foo"); +} + +TEST_F(IoWin32Test, Utf8Utf16ConversionTest) { + string mbs; + wstring wcs; + ASSERT_TRUE(strings::utf8_to_wcs(kUtf8Text, &wcs)); + ASSERT_TRUE(strings::wcs_to_utf8(kUtf16Text, &mbs)); + ASSERT_EQ(wcs, kUtf16Text); + ASSERT_EQ(mbs, kUtf8Text); +} + +} // namespace +} // namespace win32 +} // namespace internal +} // namespace protobuf +} // namespace google + +#endif // defined(_WIN32) + diff --git a/src/google/protobuf/stubs/logging.h b/src/google/protobuf/stubs/logging.h index 3108db8c..f69605d9 100644 --- a/src/google/protobuf/stubs/logging.h +++ b/src/google/protobuf/stubs/logging.h @@ -174,7 +174,7 @@ T* CheckNotNull(const char* /* file */, int /* line */, #ifdef NDEBUG -#define GOOGLE_DLOG GOOGLE_LOG_IF(INFO, false) +#define GOOGLE_DLOG(LEVEL) GOOGLE_LOG_IF(LEVEL, false) #define GOOGLE_DCHECK(EXPRESSION) while(false) GOOGLE_CHECK(EXPRESSION) #define GOOGLE_DCHECK_OK(E) GOOGLE_DCHECK(::google::protobuf::internal::IsOk(E)) diff --git a/src/google/protobuf/stubs/map_util.h b/src/google/protobuf/stubs/map_util.h index 4cccbbed..3e6d381f 100644 --- a/src/google/protobuf/stubs/map_util.h +++ b/src/google/protobuf/stubs/map_util.h @@ -208,7 +208,7 @@ typename Collection::value_type::second_type::element_type& FindLinkedPtrOrDie(const Collection& collection, const typename Collection::value_type::first_type& key) { typename Collection::const_iterator it = collection.find(key); - CHECK(it != collection.end()) << "key not found: " << key; + GOOGLE_CHECK(it != collection.end()) << "key not found: " << key; // Since linked_ptr::operator*() is a const member returning a non const, // we do not need a version of this function taking a non const collection. return *it->second; @@ -337,14 +337,15 @@ bool InsertIfNotPresent( template <class Collection> void InsertOrDie(Collection* const collection, const typename Collection::value_type& value) { - CHECK(InsertIfNotPresent(collection, value)) << "duplicate value: " << value; + GOOGLE_CHECK(InsertIfNotPresent(collection, value)) + << "duplicate value: " << value; } // Same as above except doesn't log the value on error. template <class Collection> void InsertOrDieNoPrint(Collection* const collection, const typename Collection::value_type& value) { - CHECK(InsertIfNotPresent(collection, value)) << "duplicate value."; + GOOGLE_CHECK(InsertIfNotPresent(collection, value)) << "duplicate value."; } // Inserts the key-value pair into the collection. Dies if key was already @@ -653,7 +654,8 @@ InsertOrReturnExisting( // delete EraseKeyReturnValuePtr(&my_map, "abc"); // // Use returned value: -// scoped_ptr<MyType> value_ptr(EraseKeyReturnValuePtr(&my_map, "abc")); +// std::unique_ptr<MyType> value_ptr( +// EraseKeyReturnValuePtr(&my_map, "abc")); // if (value_ptr.get()) // value_ptr->DoSomething(); // @@ -707,7 +709,7 @@ void AppendKeysFromMap(const MapContainer& map_container, // without the complexity of a SFINAE-based solution.) template <class MapContainer, class KeyType> void AppendKeysFromMap(const MapContainer& map_container, - vector<KeyType>* key_container) { + std::vector<KeyType>* key_container) { GOOGLE_CHECK(key_container != NULL); // We now have the opportunity to call reserve(). Calling reserve() every // time is a bad idea for some use cases: libstdc++'s implementation of @@ -751,7 +753,7 @@ void AppendValuesFromMap(const MapContainer& map_container, // without the complexity of a SFINAE-based solution.) template <class MapContainer, class ValueType> void AppendValuesFromMap(const MapContainer& map_container, - vector<ValueType>* value_container) { + std::vector<ValueType>* value_container) { GOOGLE_CHECK(value_container != NULL); // See AppendKeysFromMap for why this is done. if (value_container->empty()) { diff --git a/src/google/protobuf/stubs/mathlimits.h b/src/google/protobuf/stubs/mathlimits.h index d9846940..9c9d0e9a 100644 --- a/src/google/protobuf/stubs/mathlimits.h +++ b/src/google/protobuf/stubs/mathlimits.h @@ -43,12 +43,23 @@ #ifndef UTIL_MATH_MATHLIMITS_H__ #define UTIL_MATH_MATHLIMITS_H__ -// <math.h> lacks a lot of prototypes. However, this file needs <math.h> to -// access old-fashioned isinf et al. Even worse more: this file must not -// include <cmath> because that breaks the definition of isinf with gcc 4.9. -// -// TODO(mec): after C++11 everywhere, use <cmath> and std::isinf in this file. +// Note that for Windows we do something different because it does not support +// the plain isinf and isnan. +#if __cplusplus >= 201103L +// GCC 4.9 has a bug that makes isinf and isnan ambigious when both <math.h> +// and <cmath> get pulled into the same translation unit. We use the ones in +// std:: namespace explicitly for C++11 +#include <cmath> +#define GOOGLE_PROTOBUF_USE_STD_CMATH +#elif _GLIBCXX_USE_C99_MATH && !_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC +// libstdc++ <cmath> header undefines the global macros and put functions in +// std:: namespace even before C++11. Use the ones in std:: instead too. +#include <cmath> +#define GOOGLE_PROTOBUF_USE_STD_CMATH +#else #include <math.h> +#endif + #include <string.h> #include <cfloat> @@ -220,8 +231,19 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int) #undef UNSIGNED_MAX_10_EXP #undef DECL_INT_LIMIT_FUNCS +// For non-Windows builds we use the std:: versions of isinf and isnan if they +// are available; see the comment about <cmath> at the top of this file for the +// details on why we need to do this. +#ifdef GOOGLE_PROTOBUF_USE_STD_CMATH +#define ISINF std::isinf +#define ISNAN std::isnan +#else +#define ISINF isinf +#define ISNAN isnan +#endif + // ========================================================================= // -#ifdef WIN32 // Lacks built-in isnan() and isinf() +#if WIN32 && !__MINGW32__ // Lacks built-in isnan() and isinf() #define DECL_FP_LIMIT_FUNCS \ static bool IsFinite(const Type x) { return _finite(x); } \ static bool IsNaN(const Type x) { return _isnan(x); } \ @@ -230,11 +252,11 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int) static bool IsNegInf(const Type x) { return _fpclass(x) == _FPCLASS_NINF; } #else #define DECL_FP_LIMIT_FUNCS \ - static bool IsFinite(const Type x) { return !isinf(x) && !isnan(x); } \ - static bool IsNaN(const Type x) { return isnan(x); } \ - static bool IsInf(const Type x) { return isinf(x); } \ - static bool IsPosInf(const Type x) { return isinf(x) && x > 0; } \ - static bool IsNegInf(const Type x) { return isinf(x) && x < 0; } + static bool IsFinite(const Type x) { return !ISINF(x) && !ISNAN(x); } \ + static bool IsNaN(const Type x) { return ISNAN(x); } \ + static bool IsInf(const Type x) { return ISINF(x); } \ + static bool IsPosInf(const Type x) { return ISINF(x) && x > 0; } \ + static bool IsNegInf(const Type x) { return ISINF(x) && x < 0; } #endif // We can't put floating-point constant values in the header here because @@ -269,6 +291,8 @@ DECL_FP_LIMITS(float, FLT) DECL_FP_LIMITS(double, DBL) DECL_FP_LIMITS(long double, LDBL) +#undef ISINF +#undef ISNAN #undef DECL_FP_LIMITS #undef DECL_FP_LIMIT_FUNCS diff --git a/src/google/protobuf/stubs/mathutil.h b/src/google/protobuf/stubs/mathutil.h index 3a1ef8a8..8a9f69a0 100644 --- a/src/google/protobuf/stubs/mathutil.h +++ b/src/google/protobuf/stubs/mathutil.h @@ -41,27 +41,6 @@ namespace google { namespace protobuf { namespace internal { template<typename T> -bool IsNan(T value) { - return false; -} -template<> -inline bool IsNan(float value) { -#ifdef _MSC_VER - return _isnan(value); -#else - return isnan(value); -#endif -} -template<> -inline bool IsNan(double value) { -#ifdef _MSC_VER - return _isnan(value); -#else - return isnan(value); -#endif -} - -template<typename T> bool AlmostEquals(T a, T b) { return a == b; } @@ -80,10 +59,10 @@ class MathUtil { public: template<typename T> static T Sign(T value) { - if (value == T(0) || ::google::protobuf::internal::IsNan<T>(value)) { + if (value == T(0) || MathLimits<T>::IsNaN(value)) { return value; } - return value > T(0) ? value : -value; + return value > T(0) ? 1 : -1; } template<typename T> diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h index 7ef1cb69..47edb7a3 100644 --- a/src/google/protobuf/stubs/mutex.h +++ b/src/google/protobuf/stubs/mutex.h @@ -30,53 +30,47 @@ #ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_ #define GOOGLE_PROTOBUF_STUBS_MUTEX_H_ -#ifdef GOOGLE_PROTOBUF_NO_THREADLOCAL -#include <pthread.h> -#endif +#include <mutex> #include <google/protobuf/stubs/macros.h> +// Define thread-safety annotations for use below, if we are building with +// Clang. +#if defined(__clang__) && !defined(SWIG) +#define GOOGLE_PROTOBUF_ACQUIRE(...) \ + __attribute__((acquire_capability(__VA_ARGS__))) +#define GOOGLE_PROTOBUF_RELEASE(...) \ + __attribute__((release_capability(__VA_ARGS__))) +#else +#define GOOGLE_PROTOBUF_ACQUIRE(...) +#define GOOGLE_PROTOBUF_RELEASE(...) +#endif + // =================================================================== // emulates google3/base/mutex.h namespace google { namespace protobuf { namespace internal { -// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T -// may hold a mutex at a given time. If T attempts to Lock() the same Mutex -// while holding it, T will deadlock. -class LIBPROTOBUF_EXPORT Mutex { - public: - // Create a Mutex that is not held by anybody. - Mutex(); - - // Destructor - ~Mutex(); - - // Block if necessary until this Mutex is free, then acquire it exclusively. - void Lock(); - - // Release this Mutex. Caller must hold it exclusively. - void Unlock(); +#define GOOGLE_PROTOBUF_LINKER_INITIALIZED +// Mutex is a natural type to wrap. As both google and other organization have +// specialized mutexes. gRPC also provides an injection mechanism for custom +// mutexes. +class LIBPROTOBUF_EXPORT WrappedMutex { + public: + WrappedMutex() = default; + void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); } + void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); } // Crash if this Mutex is not held exclusively by this thread. // May fail to crash when it should; will never crash when it should not. - void AssertHeld(); + void AssertHeld() const {} private: - struct Internal; - Internal* mInternal; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex); + std::mutex mu_; }; -// Undefine the macros to workaround the conflicts with Google internal -// MutexLock implementation. -// TODO(liujisi): Remove the undef once internal macros are removed. -#undef MutexLock -#undef ReaderMutexLock -#undef WriterMutexLock -#undef MutexLockMaybe +using Mutex = WrappedMutex; // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class LIBPROTOBUF_EXPORT MutexLock { @@ -141,8 +135,10 @@ using internal::ReaderMutexLock; using internal::WriterMutexLock; using internal::MutexLockMaybe; - } // namespace protobuf } // namespace google +#undef GOOGLE_PROTOBUF_ACQUIRE +#undef GOOGLE_PROTOBUF_RELEASE + #endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_ diff --git a/src/google/protobuf/stubs/once.cc b/src/google/protobuf/stubs/once.cc deleted file mode 100644 index 889c6476..00000000 --- a/src/google/protobuf/stubs/once.cc +++ /dev/null @@ -1,99 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// -// emulates google3/base/once.h -// -// This header is intended to be included only by internal .cc files and -// generated .pb.cc files. Users should not use this directly. - -#include <google/protobuf/stubs/once.h> - -#ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -#ifdef _WIN32 -#include <windows.h> -#else -#include <sched.h> -#endif - -#include <google/protobuf/stubs/atomicops.h> - -namespace google { -namespace protobuf { - -namespace { - -void SchedYield() { -#ifdef _WIN32 - Sleep(0); -#else // POSIX - sched_yield(); -#endif -} - -} // namespace - -void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure) { - internal::AtomicWord state = internal::Acquire_Load(once); - // Fast path. The provided closure was already executed. - if (state == ONCE_STATE_DONE) { - return; - } - // The closure execution did not complete yet. The once object can be in one - // of the two following states: - // - UNINITIALIZED: We are the first thread calling this function. - // - EXECUTING_CLOSURE: Another thread is already executing the closure. - // - // First, try to change the state from UNINITIALIZED to EXECUTING_CLOSURE - // atomically. - state = internal::Acquire_CompareAndSwap( - once, ONCE_STATE_UNINITIALIZED, ONCE_STATE_EXECUTING_CLOSURE); - if (state == ONCE_STATE_UNINITIALIZED) { - // We are the first thread to call this function, so we have to call the - // closure. - closure->Run(); - internal::Release_Store(once, ONCE_STATE_DONE); - } else { - // Another thread has already started executing the closure. We need to - // wait until it completes the initialization. - while (state == ONCE_STATE_EXECUTING_CLOSURE) { - // Note that futex() could be used here on Linux as an improvement. - SchedYield(); - state = internal::Acquire_Load(once); - } - } -} - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY diff --git a/src/google/protobuf/stubs/once.h b/src/google/protobuf/stubs/once.h index 1f082c37..f3835ccd 100644 --- a/src/google/protobuf/stubs/once.h +++ b/src/google/protobuf/stubs/once.h @@ -78,88 +78,51 @@ #ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__ #define GOOGLE_PROTOBUF_STUBS_ONCE_H__ -#include <google/protobuf/stubs/atomicops.h> -#include <google/protobuf/stubs/callback.h> -#include <google/protobuf/stubs/common.h> +#include <mutex> +#include <utility> namespace google { namespace protobuf { +namespace internal { -#ifdef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -typedef bool ProtobufOnceType; - -#define GOOGLE_PROTOBUF_ONCE_INIT false - -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - if (!*once) { - *once = true; - init_func(); - } +using once_flag = std::once_flag; +template <typename... Args> +void call_once(Args&&... args ) { + std::call_once(std::forward<Args>(args)...); } -template <typename Arg> -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg), - Arg arg) { - if (!*once) { - *once = true; - init_func(arg); - } -} +} // namespace internal -#else - -enum { - ONCE_STATE_UNINITIALIZED = 0, - ONCE_STATE_EXECUTING_CLOSURE = 1, - ONCE_STATE_DONE = 2 -}; - -typedef internal::AtomicWord ProtobufOnceType; - -#define GOOGLE_PROTOBUF_ONCE_INIT ::google::protobuf::ONCE_STATE_UNINITIALIZED - -LIBPROTOBUF_EXPORT -void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure); +// TODO(gerbens) remove this once third_party is fully extracted +using ProtobufOnceType = internal::once_flag; inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - if (internal::Acquire_Load(once) != ONCE_STATE_DONE) { - internal::FunctionClosure0 func(init_func, false); - GoogleOnceInitImpl(once, &func); - } + std::call_once(*once, init_func); } template <typename Arg> -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg*), - Arg* arg) { - if (internal::Acquire_Load(once) != ONCE_STATE_DONE) { - internal::FunctionClosure1<Arg*> func(init_func, false, arg); - GoogleOnceInitImpl(once, &func); - } +inline void GoogleOnceInitArg(ProtobufOnceType* once, void (*init_func)(Arg*), + Arg* arg) { + std::call_once(*once, init_func, arg); } -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY - class GoogleOnceDynamic { public: - GoogleOnceDynamic() : state_(GOOGLE_PROTOBUF_ONCE_INIT) { } - // If this->Init() has not been called before by any thread, // execute (*func_with_arg)(arg) then return. // Otherwise, wait until that prior invocation has finished // executing its function, then return. template<typename T> void Init(void (*func_with_arg)(T*), T* arg) { - GoogleOnceInit<T>(&this->state_, - func_with_arg, - arg); + GoogleOnceInitArg<T>(&this->state_, func_with_arg, arg); } private: ProtobufOnceType state_; }; +#define GOOGLE_PROTOBUF_ONCE_TYPE ::google::protobuf::ProtobufOnceType #define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \ - ::google::protobuf::ProtobufOnceType NAME = GOOGLE_PROTOBUF_ONCE_INIT + ::google::protobuf::ProtobufOnceType NAME } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/once_unittest.cc b/src/google/protobuf/stubs/once_unittest.cc deleted file mode 100644 index 37def58d..00000000 --- a/src/google/protobuf/stubs/once_unittest.cc +++ /dev/null @@ -1,255 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) - -#ifdef _WIN32 -#include <windows.h> -#else -#include <unistd.h> -#include <pthread.h> -#endif - -#include <google/protobuf/stubs/once.h> -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> - -namespace google { -namespace protobuf { -using internal::NewCallback; -namespace { - -class OnceInitTest : public testing::Test { - protected: - void SetUp() { - state_ = INIT_NOT_STARTED; - current_test_ = this; - } - - // Since ProtobufOnceType is only allowed to be allocated in static storage, - // each test must use a different pair of ProtobufOnceType objects which it - // must declare itself. - void SetOnces(ProtobufOnceType* once, ProtobufOnceType* recursive_once) { - once_ = once; - recursive_once_ = recursive_once; - } - - void InitOnce() { - GoogleOnceInit(once_, &InitStatic); - } - void InitRecursiveOnce() { - GoogleOnceInit(recursive_once_, &InitRecursiveStatic); - } - - void BlockInit() { init_blocker_.Lock(); } - void UnblockInit() { init_blocker_.Unlock(); } - - class TestThread { - public: - TestThread(Closure* callback) - : done_(false), joined_(false), callback_(callback) { -#ifdef _WIN32 - thread_ = CreateThread(NULL, 0, &Start, this, 0, NULL); -#else - pthread_create(&thread_, NULL, &Start, this); -#endif - } - ~TestThread() { - if (!joined_) Join(); - } - - bool IsDone() { - MutexLock lock(&done_mutex_); - return done_; - } - void Join() { - joined_ = true; -#ifdef _WIN32 - WaitForSingleObject(thread_, INFINITE); - CloseHandle(thread_); -#else - pthread_join(thread_, NULL); -#endif - } - - private: -#ifdef _WIN32 - HANDLE thread_; -#else - pthread_t thread_; -#endif - - Mutex done_mutex_; - bool done_; - bool joined_; - Closure* callback_; - -#ifdef _WIN32 - static DWORD WINAPI Start(LPVOID arg) { -#else - static void* Start(void* arg) { -#endif - reinterpret_cast<TestThread*>(arg)->Run(); - return 0; - } - - void Run() { - callback_->Run(); - MutexLock lock(&done_mutex_); - done_ = true; - } - }; - - TestThread* RunInitOnceInNewThread() { - return new TestThread(internal::NewCallback(this, &OnceInitTest::InitOnce)); - } - TestThread* RunInitRecursiveOnceInNewThread() { - return new TestThread( - internal::NewCallback(this, &OnceInitTest::InitRecursiveOnce)); - } - - enum State { - INIT_NOT_STARTED, - INIT_STARTED, - INIT_DONE - }; - State CurrentState() { - MutexLock lock(&mutex_); - return state_; - } - - void WaitABit() { -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } - - private: - Mutex mutex_; - Mutex init_blocker_; - State state_; - ProtobufOnceType* once_; - ProtobufOnceType* recursive_once_; - - void Init() { - MutexLock lock(&mutex_); - EXPECT_EQ(INIT_NOT_STARTED, state_); - state_ = INIT_STARTED; - mutex_.Unlock(); - init_blocker_.Lock(); - init_blocker_.Unlock(); - mutex_.Lock(); - state_ = INIT_DONE; - } - - static OnceInitTest* current_test_; - static void InitStatic() { current_test_->Init(); } - static void InitRecursiveStatic() { current_test_->InitOnce(); } -}; - -OnceInitTest* OnceInitTest::current_test_ = NULL; - -GOOGLE_PROTOBUF_DECLARE_ONCE(simple_once); - -TEST_F(OnceInitTest, Simple) { - SetOnces(&simple_once, NULL); - - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - InitOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); - - // Calling again has no effect. - InitOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once1); -GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once2); - -TEST_F(OnceInitTest, Recursive) { - SetOnces(&recursive_once1, &recursive_once2); - - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - InitRecursiveOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_once); - -TEST_F(OnceInitTest, MultipleThreads) { - SetOnces(&multiple_threads_once, NULL); - - scoped_ptr<TestThread> threads[4]; - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - for (int i = 0; i < 4; i++) { - threads[i].reset(RunInitOnceInNewThread()); - } - for (int i = 0; i < 4; i++) { - threads[i]->Join(); - } - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once1); -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once2); - -TEST_F(OnceInitTest, MultipleThreadsBlocked) { - SetOnces(&multiple_threads_blocked_once1, &multiple_threads_blocked_once2); - - scoped_ptr<TestThread> threads[8]; - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - - BlockInit(); - for (int i = 0; i < 4; i++) { - threads[i].reset(RunInitOnceInNewThread()); - } - for (int i = 4; i < 8; i++) { - threads[i].reset(RunInitRecursiveOnceInNewThread()); - } - - WaitABit(); - - // We should now have one thread blocked inside Init(), four blocked waiting - // for Init() to complete, and three blocked waiting for InitRecursive() to - // complete. - EXPECT_EQ(INIT_STARTED, CurrentState()); - UnblockInit(); - - for (int i = 0; i < 8; i++) { - threads[i]->Join(); - } - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/stubs/platform_macros.h b/src/google/protobuf/stubs/platform_macros.h index 980c54b2..ff4dea7b 100644 --- a/src/google/protobuf/stubs/platform_macros.h +++ b/src/google/protobuf/stubs/platform_macros.h @@ -47,9 +47,12 @@ #elif defined(__QNX__) #define GOOGLE_PROTOBUF_ARCH_ARM_QNX 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 -#elif defined(__ARMEL__) +#elif defined(_M_ARM) || defined(__ARMEL__) #define GOOGLE_PROTOBUF_ARCH_ARM 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 +#elif defined(_M_ARM64) +#define GOOGLE_PROTOBUF_ARCH_ARM 1 +#define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #elif defined(__aarch64__) #define GOOGLE_PROTOBUF_ARCH_AARCH64 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 @@ -73,6 +76,9 @@ #elif defined(_POWER) || defined(__powerpc64__) || defined(__PPC64__) #define GOOGLE_PROTOBUF_ARCH_POWER 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 +#elif defined(__PPC__) +#define GOOGLE_PROTOBUF_ARCH_PPC 1 +#define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #elif defined(__GNUC__) # if (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4)) // We fallback to the generic Clang/GCC >= 4.7 implementation in atomicops.h @@ -112,11 +118,11 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR #undef GOOGLE_PROTOBUF_PLATFORM_ERROR -#if defined(GOOGLE_PROTOBUF_OS_ANDROID) || defined(GOOGLE_PROTOBUF_OS_IPHONE) +#if defined(GOOGLE_PROTOBUF_OS_ANDROID) || defined(GOOGLE_PROTOBUF_OS_IPHONE) || defined(__OpenBSD__) // Android ndk does not support the __thread keyword very well yet. Here // we use pthread_key_create()/pthread_getspecific()/... methods for // TLS support on android. -// iOS also does not support the __thread keyword. +// iOS and OpenBSD also do not support the __thread keyword. #define GOOGLE_PROTOBUF_NO_THREADLOCAL #endif diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h index 1036dff1..6b52305f 100644 --- a/src/google/protobuf/stubs/port.h +++ b/src/google/protobuf/stubs/port.h @@ -44,6 +44,8 @@ #include <stdint.h> #endif +#include <google/protobuf/stubs/platform_macros.h> + #undef PROTOBUF_LITTLE_ENDIAN #ifdef _WIN32 // Assuming windows is always little-endian. @@ -60,8 +62,12 @@ #endif #else #include <sys/param.h> // __BYTE_ORDER + #if defined(__OpenBSD__) + #include <endian.h> + #endif #if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ - (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \ + (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN) || \ + (defined(BYTE_ORDER) && BYTE_ORDER == LITTLE_ENDIAN)) && \ !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) #define PROTOBUF_LITTLE_ENDIAN 1 #endif @@ -85,14 +91,38 @@ // These #includes are for the byte swap functions declared later on. #ifdef _MSC_VER #include <stdlib.h> // NOLINT(build/include) +#include <intrin.h> #elif defined(__APPLE__) #include <libkern/OSByteOrder.h> -#elif defined(__GLIBC__) || defined(__CYGWIN__) +#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__) #include <byteswap.h> // IWYU pragma: export #endif +#define PROTOBUF_RUNTIME_DEPRECATED(message) + // =================================================================== // from google3/base/port.h + +#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \ + (defined(_MSC_VER) && _MSC_VER >= 1900)) +// Define this to 1 if the code is compiled in C++11 mode; leave it +// undefined otherwise. Do NOT define it to 0 -- that causes +// '#ifdef LANG_CXX11' to behave differently from '#if LANG_CXX11'. +#define LANG_CXX11 1 +#endif + +#if LANG_CXX11 && !defined(__NVCC__) +#define PROTOBUF_CXX11 1 +#else +#define PROTOBUF_CXX11 0 +#endif + +#if PROTOBUF_CXX11 +#define PROTOBUF_FINAL final +#else +#define PROTOBUF_FINAL +#endif + namespace google { namespace protobuf { @@ -109,15 +139,15 @@ typedef unsigned __int16 uint16; typedef unsigned __int32 uint32; typedef unsigned __int64 uint64; #else -typedef signed char int8; -typedef short int16; -typedef int int32; -typedef long long int64; - -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned int uint32; -typedef unsigned long long uint64; +typedef int8_t int8; +typedef int16_t int16; +typedef int32_t int32; +typedef int64_t int64; + +typedef uint8_t uint8; +typedef uint16_t uint16; +typedef uint32_t uint32; +typedef uint64_t uint64; #endif // long long macros to be used because gcc and vc++ use different suffixes, @@ -131,8 +161,10 @@ typedef unsigned long long uint64; #define GOOGLE_ULONGLONG(x) x##UI64 #define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...) #else +// By long long, we actually mean int64. #define GOOGLE_LONGLONG(x) x##LL #define GOOGLE_ULONGLONG(x) x##ULL +// Used to format real long long integers. #define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also. #endif @@ -160,6 +192,8 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #endif #endif +#define GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE GOOGLE_ATTRIBUTE_ALWAYS_INLINE + #ifndef GOOGLE_ATTRIBUTE_NOINLINE #if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) // For functions we want to force not inline. @@ -174,15 +208,21 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #endif #endif -#ifndef GOOGLE_ATTRIBUTE_DEPRECATED -#ifdef __GNUC__ -// If the method/variable/type is used anywhere, produce a warning. -#define GOOGLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated)) +#define GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE + +#ifndef GOOGLE_ATTRIBUTE_FUNC_ALIGN +#if defined(__clang__) || \ + defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +// Function alignment attribute introduced in gcc 4.3 +#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes))) #else -#define GOOGLE_ATTRIBUTE_DEPRECATED +#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) #endif #endif +#define GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(bytes) \ + GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) + #ifndef GOOGLE_PREDICT_TRUE #ifdef __GNUC__ // Provided at least since GCC 3.0. @@ -201,6 +241,13 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #endif #endif +#ifndef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL +#ifdef __GNUC__ +#define GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL \ + __attribute__((returns_nonnull)) +#endif +#endif + // Delimits a block of code which may write to memory which is simultaneously // written by other threads, but which has been determined to be thread-safe // (e.g. because it is an idempotent write). @@ -211,24 +258,62 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #define GOOGLE_SAFE_CONCURRENT_WRITES_END() #endif -#if defined(__clang__) && defined(__has_cpp_attribute) \ - && !defined(GOOGLE_PROTOBUF_OS_APPLE) -# if defined(GOOGLE_PROTOBUF_OS_NACL) || defined(EMSCRIPTEN) || \ - __has_cpp_attribute(clang::fallthrough) -# define GOOGLE_FALLTHROUGH_INTENDED [[clang::fallthrough]] +#define GOOGLE_GUARDED_BY(x) +#define GOOGLE_ATTRIBUTE_COLD + +#ifdef GOOGLE_PROTOBUF_DONT_USE_UNALIGNED +# define GOOGLE_PROTOBUF_USE_UNALIGNED 0 +#else +# if defined(_M_X64) || defined(__x86_64__) || defined(_M_IX86) || defined(__i386__) +# define GOOGLE_PROTOBUF_USE_UNALIGNED 1 +# else +# define GOOGLE_PROTOBUF_USE_UNALIGNED 0 # endif #endif -#ifndef GOOGLE_FALLTHROUGH_INTENDED -# define GOOGLE_FALLTHROUGH_INTENDED -#endif +#define GOOGLE_PROTOBUF_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_COLD -#define GOOGLE_GUARDED_BY(x) -#define GOOGLE_ATTRIBUTE_COLD +#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) ||\ + defined(MEMORY_SANITIZER) + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus +uint16_t __sanitizer_unaligned_load16(const void *p); +uint32_t __sanitizer_unaligned_load32(const void *p); +uint64_t __sanitizer_unaligned_load64(const void *p); +void __sanitizer_unaligned_store16(void *p, uint16_t v); +void __sanitizer_unaligned_store32(void *p, uint32_t v); +void __sanitizer_unaligned_store64(void *p, uint64_t v); +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +inline uint16 GOOGLE_UNALIGNED_LOAD16(const void *p) { + return __sanitizer_unaligned_load16(p); +} -// x86 and x86-64 can perform unaligned loads/stores directly. -#if defined(_M_X64) || defined(__x86_64__) || \ - defined(_M_IX86) || defined(__i386__) +inline uint32 GOOGLE_UNALIGNED_LOAD32(const void *p) { + return __sanitizer_unaligned_load32(p); +} + +inline uint64 GOOGLE_UNALIGNED_LOAD64(const void *p) { + return __sanitizer_unaligned_load64(p); +} + +inline void GOOGLE_UNALIGNED_STORE16(void *p, uint16 v) { + __sanitizer_unaligned_store16(p, v); +} + +inline void GOOGLE_UNALIGNED_STORE32(void *p, uint32 v) { + __sanitizer_unaligned_store32(p, v); +} + +inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { + __sanitizer_unaligned_store64(p, v); +} + +#elif GOOGLE_PROTOBUF_USE_UNALIGNED #define GOOGLE_UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p)) #define GOOGLE_UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p)) @@ -270,16 +355,21 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { } #endif +#if defined(GOOGLE_PROTOBUF_OS_NACL) \ + || (defined(__ANDROID__) && defined(__clang__) \ + && (__clang_major__ == 3 && __clang_minor__ == 8) \ + && (__clang_patchlevel__ < 275480)) +# define GOOGLE_PROTOBUF_USE_PORTABLE_LOG2 +#endif + #if defined(_MSC_VER) #define GOOGLE_THREAD_LOCAL __declspec(thread) #else #define GOOGLE_THREAD_LOCAL __thread #endif -// The following guarantees declaration of the byte swap functions, and -// defines __BYTE_ORDER for MSVC +// The following guarantees declaration of the byte swap functions. #ifdef _MSC_VER -#define __BYTE_ORDER __LITTLE_ENDIAN #define bswap_16(x) _byteswap_ushort(x) #define bswap_32(x) _byteswap_ulong(x) #define bswap_64(x) _byteswap_uint64(x) @@ -290,7 +380,7 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) -#elif !defined(__GLIBC__) && !defined(__CYGWIN__) +#elif !defined(__GLIBC__) && !defined(__BIONIC__) && !defined(__CYGWIN__) static inline uint16 bswap_16(uint16 x) { return static_cast<uint16>(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8)); @@ -318,6 +408,69 @@ static inline uint64 bswap_64(uint64 x) { #endif // =================================================================== +// from google3/util/bits/bits.h + +class Bits { + public: + static uint32 Log2FloorNonZero(uint32 n) { +#if defined(__GNUC__) + return 31 ^ static_cast<uint32>(__builtin_clz(n)); +#elif defined(_MSC_VER) + unsigned long where; + _BitScanReverse(&where, n); + return where; +#else + return Log2FloorNonZero_Portable(n); +#endif + } + + static uint32 Log2FloorNonZero64(uint64 n) { + // Older versions of clang run into an instruction-selection failure when + // it encounters __builtin_clzll: + // https://bugs.chromium.org/p/nativeclient/issues/detail?id=4395 + // This includes arm-nacl-clang and clang in older Android NDK versions. + // To work around this, when we build with those we use the portable + // implementation instead. +#if defined(__GNUC__) && !defined(GOOGLE_PROTOBUF_USE_PORTABLE_LOG2) + return 63 ^ static_cast<uint32>(__builtin_clzll(n)); +#elif defined(_MSC_VER) && defined(_M_X64) + unsigned long where; + _BitScanReverse64(&where, n); + return where; +#else + return Log2FloorNonZero64_Portable(n); +#endif + } + private: + static int Log2FloorNonZero_Portable(uint32 n) { + if (n == 0) + return -1; + int log = 0; + uint32 value = n; + for (int i = 4; i >= 0; --i) { + int shift = (1 << i); + uint32 x = value >> shift; + if (x != 0) { + value = x; + log += shift; + } + } + assert(value == 1); + return log; + } + + static int Log2FloorNonZero64_Portable(uint64 n) { + const uint32 topbits = static_cast<uint32>(n >> 32); + if (topbits == 0) { + // Top bits are zero, so scan in bottom bits + return static_cast<int>(Log2FloorNonZero(static_cast<uint32>(n))); + } else { + return 32 + static_cast<int>(Log2FloorNonZero(topbits)); + } + } +}; + +// =================================================================== // from google3/util/endian/endian.h LIBPROTOBUF_EXPORT uint32 ghtonl(uint32 x); @@ -377,6 +530,11 @@ class BigEndian { } }; +#ifndef GOOGLE_ATTRIBUTE_SECTION_VARIABLE +#define GOOGLE_ATTRIBUTE_SECTION_VARIABLE(name) +#endif + +#define GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(name) } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/scoped_ptr.h b/src/google/protobuf/stubs/scoped_ptr.h deleted file mode 100644 index 4423c118..00000000 --- a/src/google/protobuf/stubs/scoped_ptr.h +++ /dev/null @@ -1,236 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_ -#define GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_ - -#include <google/protobuf/stubs/port.h> - -namespace google { -namespace protobuf { - -// =================================================================== -// from google3/base/scoped_ptr.h - -namespace internal { - -// This is an implementation designed to match the anticipated future TR2 -// implementation of the scoped_ptr class, and its closely-related brethren, -// scoped_array, scoped_ptr_malloc, and make_scoped_ptr. - -template <class C> class scoped_ptr; -template <class C> class scoped_array; - -// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T> -// automatically deletes the pointer it holds (if any). -// That is, scoped_ptr<T> owns the T object that it points to. -// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object. -// -// The size of a scoped_ptr is small: -// sizeof(scoped_ptr<C>) == sizeof(C*) -template <class C> -class scoped_ptr { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to initializing with NULL. - // There is no way to create an uninitialized scoped_ptr. - // The input parameter must be allocated with new. - explicit scoped_ptr(C* p = NULL) : ptr_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_ptr() { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != ptr_) { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - ptr_ = p; - } - } - - // Accessors to get the owned object. - // operator* and operator-> will assert() if there is no current object. - C& operator*() const { - assert(ptr_ != NULL); - return *ptr_; - } - C* operator->() const { - assert(ptr_ != NULL); - return ptr_; - } - C* get() const { return ptr_; } - - // Comparison operators. - // These return whether two scoped_ptr refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return ptr_ == p; } - bool operator!=(C* p) const { return ptr_ != p; } - - // Swap two scoped pointers. - void swap(scoped_ptr& p2) { - C* tmp = ptr_; - ptr_ = p2.ptr_; - p2.ptr_ = tmp; - } - - // Release a pointer. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = ptr_; - ptr_ = NULL; - return retVal; - } - - private: - C* ptr_; - - // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't - // make sense, and if C2 == C, it still doesn't make sense because you should - // never have the same object owned by two different scoped_ptrs. - template <class C2> bool operator==(scoped_ptr<C2> const& p2) const; - template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const; - - // Disallow evil constructors - scoped_ptr(const scoped_ptr&); - void operator=(const scoped_ptr&); -}; - -// scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate -// with new [] and the destructor deletes objects with delete []. -// -// As with scoped_ptr<C>, a scoped_array<C> either points to an object -// or is NULL. A scoped_array<C> owns the object that it points to. -// -// Size: sizeof(scoped_array<C>) == sizeof(C*) -template <class C> -class scoped_array { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to initializing with NULL. - // There is no way to create an uninitialized scoped_array. - // The input parameter must be allocated with new []. - explicit scoped_array(C* p = NULL) : array_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_array() { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != array_) { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - array_ = p; - } - } - - // Get one element of the current object. - // Will assert() if there is no current object, or index i is negative. - C& operator[](std::ptrdiff_t i) const { - assert(i >= 0); - assert(array_ != NULL); - return array_[i]; - } - - // Get a pointer to the zeroth element of the current object. - // If there is no current object, return NULL. - C* get() const { - return array_; - } - - // Comparison operators. - // These return whether two scoped_array refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return array_ == p; } - bool operator!=(C* p) const { return array_ != p; } - - // Swap two scoped arrays. - void swap(scoped_array& p2) { - C* tmp = array_; - array_ = p2.array_; - p2.array_ = tmp; - } - - // Release an array. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = array_; - array_ = NULL; - return retVal; - } - - private: - C* array_; - - // Forbid comparison of different scoped_array types. - template <class C2> bool operator==(scoped_array<C2> const& p2) const; - template <class C2> bool operator!=(scoped_array<C2> const& p2) const; - - // Disallow evil constructors - scoped_array(const scoped_array&); - void operator=(const scoped_array&); -}; - -} // namespace internal - -// We made these internal so that they would show up as such in the docs, -// but we don't want to stick "internal::" in front of them everywhere. -using internal::scoped_ptr; -using internal::scoped_array; - - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_SCOPED_PTR_H_ diff --git a/src/google/protobuf/stubs/shared_ptr.h b/src/google/protobuf/stubs/shared_ptr.h deleted file mode 100644 index d250bf4d..00000000 --- a/src/google/protobuf/stubs/shared_ptr.h +++ /dev/null @@ -1,470 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2014 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// from google3/util/gtl/shared_ptr.h - -#ifndef GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__ -#define GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__ - -#include <google/protobuf/stubs/atomicops.h> - -#include <algorithm> // for swap -#include <stddef.h> -#include <memory> - -namespace google { -namespace protobuf { -namespace internal { - -// Alias to std::shared_ptr for any C++11 platform, -// and for any supported MSVC compiler. -#if !defined(UTIL_GTL_USE_STD_SHARED_PTR) && \ - (defined(COMPILER_MSVC) || defined(LANG_CXX11)) -#define UTIL_GTL_USE_STD_SHARED_PTR 1 -#endif - -#if defined(UTIL_GTL_USE_STD_SHARED_PTR) && UTIL_GTL_USE_STD_SHARED_PTR - -// These are transitional. They will be going away soon. -// Please just #include <memory> and just type std::shared_ptr yourself, instead -// of relying on this file. -// -// Migration doc: http://go/std-shared-ptr-lsc -using std::enable_shared_from_this; -using std::shared_ptr; -using std::static_pointer_cast; -using std::weak_ptr; - -#else // below, UTIL_GTL_USE_STD_SHARED_PTR not set or set to 0. - -// For everything else there is the google3 implementation. -inline bool RefCountDec(volatile Atomic32 *ptr) { - return Barrier_AtomicIncrement(ptr, -1) != 0; -} - -inline void RefCountInc(volatile Atomic32 *ptr) { - NoBarrier_AtomicIncrement(ptr, 1); -} - -template <typename T> class shared_ptr; -template <typename T> class weak_ptr; - -// This class is an internal implementation detail for shared_ptr. If two -// shared_ptrs point to the same object, they also share a control block. -// An "empty" shared_pointer refers to NULL and also has a NULL control block. -// It contains all of the state that's needed for reference counting or any -// other kind of resource management. In this implementation the control block -// happens to consist of two atomic words, the reference count (the number -// of shared_ptrs that share ownership of the object) and the weak count -// (the number of weak_ptrs that observe the object, plus 1 if the -// refcount is nonzero). -// -// The "plus 1" is to prevent a race condition in the shared_ptr and -// weak_ptr destructors. We need to make sure the control block is -// only deleted once, so we need to make sure that at most one -// object sees the weak count decremented from 1 to 0. -class SharedPtrControlBlock { - template <typename T> friend class shared_ptr; - template <typename T> friend class weak_ptr; - private: - SharedPtrControlBlock() : refcount_(1), weak_count_(1) { } - Atomic32 refcount_; - Atomic32 weak_count_; -}; - -// Forward declaration. The class is defined below. -template <typename T> class enable_shared_from_this; - -template <typename T> -class shared_ptr { - template <typename U> friend class weak_ptr; - public: - typedef T element_type; - - shared_ptr() : ptr_(NULL), control_block_(NULL) {} - - explicit shared_ptr(T* ptr) - : ptr_(ptr), - control_block_(ptr != NULL ? new SharedPtrControlBlock : NULL) { - // If p is non-null and T inherits from enable_shared_from_this, we - // set up the data that shared_from_this needs. - MaybeSetupWeakThis(ptr); - } - - // Copy constructor: makes this object a copy of ptr, and increments - // the reference count. - template <typename U> - shared_ptr(const shared_ptr<U>& ptr) - : ptr_(NULL), - control_block_(NULL) { - Initialize(ptr); - } - // Need non-templated version to prevent the compiler-generated default - shared_ptr(const shared_ptr<T>& ptr) - : ptr_(NULL), - control_block_(NULL) { - Initialize(ptr); - } - - // Assignment operator. Replaces the existing shared_ptr with ptr. - // Increment ptr's reference count and decrement the one being replaced. - template <typename U> - shared_ptr<T>& operator=(const shared_ptr<U>& ptr) { - if (ptr_ != ptr.ptr_) { - shared_ptr<T> me(ptr); // will hold our previous state to be destroyed. - swap(me); - } - return *this; - } - - // Need non-templated version to prevent the compiler-generated default - shared_ptr<T>& operator=(const shared_ptr<T>& ptr) { - if (ptr_ != ptr.ptr_) { - shared_ptr<T> me(ptr); // will hold our previous state to be destroyed. - swap(me); - } - return *this; - } - - // TODO(austern): Consider providing this constructor. The draft C++ standard - // (20.8.10.2.1) includes it. However, it says that this constructor throws - // a bad_weak_ptr exception when ptr is expired. Is it better to provide this - // constructor and make it do something else, like fail with a CHECK, or to - // leave this constructor out entirely? - // - // template <typename U> - // shared_ptr(const weak_ptr<U>& ptr); - - ~shared_ptr() { - if (ptr_ != NULL) { - if (!RefCountDec(&control_block_->refcount_)) { - delete ptr_; - - // weak_count_ is defined as the number of weak_ptrs that observe - // ptr_, plus 1 if refcount_ is nonzero. - if (!RefCountDec(&control_block_->weak_count_)) { - delete control_block_; - } - } - } - } - - // Replaces underlying raw pointer with the one passed in. The reference - // count is set to one (or zero if the pointer is NULL) for the pointer - // being passed in and decremented for the one being replaced. - // - // If you have a compilation error with this code, make sure you aren't - // passing NULL, nullptr, or 0 to this function. Call reset without an - // argument to reset to a null ptr. - template <typename Y> - void reset(Y* p) { - if (p != ptr_) { - shared_ptr<T> tmp(p); - tmp.swap(*this); - } - } - - void reset() { - reset(static_cast<T*>(NULL)); - } - - // Exchanges the contents of this with the contents of r. This function - // supports more efficient swapping since it eliminates the need for a - // temporary shared_ptr object. - void swap(shared_ptr<T>& r) { - using std::swap; // http://go/using-std-swap - swap(ptr_, r.ptr_); - swap(control_block_, r.control_block_); - } - - // The following function is useful for gaining access to the underlying - // pointer when a shared_ptr remains in scope so the reference-count is - // known to be > 0 (e.g. for parameter passing). - T* get() const { - return ptr_; - } - - T& operator*() const { - return *ptr_; - } - - T* operator->() const { - return ptr_; - } - - long use_count() const { - return control_block_ ? control_block_->refcount_ : 1; - } - - bool unique() const { - return use_count() == 1; - } - - private: - // If r is non-empty, initialize *this to share ownership with r, - // increasing the underlying reference count. - // If r is empty, *this remains empty. - // Requires: this is empty, namely this->ptr_ == NULL. - template <typename U> - void Initialize(const shared_ptr<U>& r) { - // This performs a static_cast on r.ptr_ to U*, which is a no-op since it - // is already a U*. So initialization here requires that r.ptr_ is - // implicitly convertible to T*. - InitializeWithStaticCast<U>(r); - } - - // Initializes *this as described in Initialize, but additionally performs a - // static_cast from r.ptr_ (V*) to U*. - // NOTE(gfc): We'd need a more general form to support const_pointer_cast and - // dynamic_pointer_cast, but those operations are sufficiently discouraged - // that supporting static_pointer_cast is sufficient. - template <typename U, typename V> - void InitializeWithStaticCast(const shared_ptr<V>& r) { - if (r.control_block_ != NULL) { - RefCountInc(&r.control_block_->refcount_); - - ptr_ = static_cast<U*>(r.ptr_); - control_block_ = r.control_block_; - } - } - - // Helper function for the constructor that takes a raw pointer. If T - // doesn't inherit from enable_shared_from_this<T> then we have nothing to - // do, so this function is trivial and inline. The other version is declared - // out of line, after the class definition of enable_shared_from_this. - void MaybeSetupWeakThis(enable_shared_from_this<T>* ptr); - void MaybeSetupWeakThis(...) { } - - T* ptr_; - SharedPtrControlBlock* control_block_; - -#ifndef SWIG - template <typename U> - friend class shared_ptr; - - template <typename U, typename V> - friend shared_ptr<U> static_pointer_cast(const shared_ptr<V>& rhs); -#endif -}; - -// Matches the interface of std::swap as an aid to generic programming. -template <typename T> void swap(shared_ptr<T>& r, shared_ptr<T>& s) { - r.swap(s); -} - -template <typename T, typename U> -shared_ptr<T> static_pointer_cast(const shared_ptr<U>& rhs) { - shared_ptr<T> lhs; - lhs.template InitializeWithStaticCast<T>(rhs); - return lhs; -} - -// See comments at the top of the file for a description of why this -// class exists, and the draft C++ standard (as of July 2009 the -// latest draft is N2914) for the detailed specification. -template <typename T> -class weak_ptr { - template <typename U> friend class weak_ptr; - public: - typedef T element_type; - - // Create an empty (i.e. already expired) weak_ptr. - weak_ptr() : ptr_(NULL), control_block_(NULL) { } - - // Create a weak_ptr that observes the same object that ptr points - // to. Note that there is no race condition here: we know that the - // control block can't disappear while we're looking at it because - // it is owned by at least one shared_ptr, ptr. - template <typename U> weak_ptr(const shared_ptr<U>& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Copy a weak_ptr. The object it points to might disappear, but we - // don't care: we're only working with the control block, and it can't - // disappear while we're looking at because it's owned by at least one - // weak_ptr, ptr. - template <typename U> weak_ptr(const weak_ptr<U>& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Need non-templated version to prevent default copy constructor - weak_ptr(const weak_ptr& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Destroy the weak_ptr. If no shared_ptr owns the control block, and if - // we are the last weak_ptr to own it, then it can be deleted. Note that - // weak_count_ is defined as the number of weak_ptrs sharing this control - // block, plus 1 if there are any shared_ptrs. We therefore know that it's - // safe to delete the control block when weak_count_ reaches 0, without - // having to perform any additional tests. - ~weak_ptr() { - if (control_block_ != NULL && - !RefCountDec(&control_block_->weak_count_)) { - delete control_block_; - } - } - - weak_ptr& operator=(const weak_ptr& ptr) { - if (&ptr != this) { - weak_ptr tmp(ptr); - tmp.swap(*this); - } - return *this; - } - template <typename U> weak_ptr& operator=(const weak_ptr<U>& ptr) { - weak_ptr tmp(ptr); - tmp.swap(*this); - return *this; - } - template <typename U> weak_ptr& operator=(const shared_ptr<U>& ptr) { - weak_ptr tmp(ptr); - tmp.swap(*this); - return *this; - } - - void swap(weak_ptr& ptr) { - using std::swap; // http://go/using-std-swap - swap(ptr_, ptr.ptr_); - swap(control_block_, ptr.control_block_); - } - - void reset() { - weak_ptr tmp; - tmp.swap(*this); - } - - // Return the number of shared_ptrs that own the object we are observing. - // Note that this number can be 0 (if this pointer has expired). - long use_count() const { - return control_block_ != NULL ? control_block_->refcount_ : 0; - } - - bool expired() const { return use_count() == 0; } - - // Return a shared_ptr that owns the object we are observing. If we - // have expired, the shared_ptr will be empty. We have to be careful - // about concurrency, though, since some other thread might be - // destroying the last owning shared_ptr while we're in this - // function. We want to increment the refcount only if it's nonzero - // and get the new value, and we want that whole operation to be - // atomic. - shared_ptr<T> lock() const { - shared_ptr<T> result; - if (control_block_ != NULL) { - Atomic32 old_refcount; - do { - old_refcount = control_block_->refcount_; - if (old_refcount == 0) - break; - } while (old_refcount != - NoBarrier_CompareAndSwap( - &control_block_->refcount_, old_refcount, - old_refcount + 1)); - if (old_refcount > 0) { - result.ptr_ = ptr_; - result.control_block_ = control_block_; - } - } - - return result; - } - - private: - void CopyFrom(T* ptr, SharedPtrControlBlock* control_block) { - ptr_ = ptr; - control_block_ = control_block; - if (control_block_ != NULL) - RefCountInc(&control_block_->weak_count_); - } - - private: - element_type* ptr_; - SharedPtrControlBlock* control_block_; -}; - -template <typename T> void swap(weak_ptr<T>& r, weak_ptr<T>& s) { - r.swap(s); -} - -// See comments at the top of the file for a description of why this class -// exists, and section 20.8.10.5 of the draft C++ standard (as of July 2009 -// the latest draft is N2914) for the detailed specification. -template <typename T> -class enable_shared_from_this { - friend class shared_ptr<T>; - public: - // Precondition: there must be a shared_ptr that owns *this and that was - // created, directly or indirectly, from a raw pointer of type T*. (The - // latter part of the condition is technical but not quite redundant; it - // rules out some complicated uses involving inheritance hierarchies.) - shared_ptr<T> shared_from_this() { - // Behavior is undefined if the precondition isn't satisfied; we choose - // to die with a CHECK failure. - CHECK(!weak_this_.expired()) << "No shared_ptr owns this object"; - return weak_this_.lock(); - } - shared_ptr<const T> shared_from_this() const { - CHECK(!weak_this_.expired()) << "No shared_ptr owns this object"; - return weak_this_.lock(); - } - - protected: - enable_shared_from_this() { } - enable_shared_from_this(const enable_shared_from_this& other) { } - enable_shared_from_this& operator=(const enable_shared_from_this& other) { - return *this; - } - ~enable_shared_from_this() { } - - private: - weak_ptr<T> weak_this_; -}; - -// This is a helper function called by shared_ptr's constructor from a raw -// pointer. If T inherits from enable_shared_from_this<T>, it sets up -// weak_this_ so that shared_from_this works correctly. If T does not inherit -// from weak_this we get a different overload, defined inline, which does -// nothing. -template<typename T> -void shared_ptr<T>::MaybeSetupWeakThis(enable_shared_from_this<T>* ptr) { - if (ptr) { - CHECK(ptr->weak_this_.expired()) << "Object already owned by a shared_ptr"; - ptr->weak_this_ = *this; - } -} - -#endif // UTIL_GTL_USE_STD_SHARED_PTR - -} // internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_SHARED_PTR_H__ diff --git a/src/google/protobuf/stubs/singleton.h b/src/google/protobuf/stubs/singleton.h index 9301f549..2e6ccbdb 100644 --- a/src/google/protobuf/stubs/singleton.h +++ b/src/google/protobuf/stubs/singleton.h @@ -30,7 +30,6 @@ #ifndef GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ #define GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ -#include <google/protobuf/stubs/atomicops.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> diff --git a/src/google/protobuf/stubs/status.cc b/src/google/protobuf/stubs/status.cc index dd1bd614..2bfbe0b4 100644 --- a/src/google/protobuf/stubs/status.cc +++ b/src/google/protobuf/stubs/status.cc @@ -124,7 +124,7 @@ string Status::ToString() const { } } -ostream& operator<<(ostream& os, const Status& x) { +std::ostream& operator<<(std::ostream& os, const Status& x) { os << x.ToString(); return os; } diff --git a/src/google/protobuf/stubs/status.h b/src/google/protobuf/stubs/status.h index 614ab994..c5d38f0b 100644 --- a/src/google/protobuf/stubs/status.h +++ b/src/google/protobuf/stubs/status.h @@ -106,7 +106,7 @@ class LIBPROTOBUF_EXPORT Status { }; // Prints a human-readable representation of 'x' to 'os'. -LIBPROTOBUF_EXPORT ostream& operator<<(ostream& os, const Status& x); +LIBPROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x); #define EXPECT_OK(value) EXPECT_TRUE((value).ok()) diff --git a/src/google/protobuf/stubs/statusor.h b/src/google/protobuf/stubs/statusor.h index ad848701..29f869ad 100644 --- a/src/google/protobuf/stubs/statusor.h +++ b/src/google/protobuf/stubs/statusor.h @@ -224,7 +224,7 @@ inline StatusOr<T>& StatusOr<T>::operator=(const StatusOr<T>& other) { template<typename T> template<typename U> inline StatusOr<T>::StatusOr(const StatusOr<U>& other) - : status_(other.status_), value_(other.status_.ok() ? other.value_ : NULL) { + : status_(other.status_), value_(other.status_.ok() ? other.value_ : T()) { } template<typename T> diff --git a/src/google/protobuf/stubs/stringpiece.h b/src/google/protobuf/stubs/stringpiece.h index ec3ffd5b..563ff75d 100644 --- a/src/google/protobuf/stubs/stringpiece.h +++ b/src/google/protobuf/stubs/stringpiece.h @@ -222,14 +222,6 @@ class LIBPROTOBUF_EXPORT StringPiece { : ptr_(str.data()), length_(0) { length_ = CheckedSsizeTFromSizeT(str.size()); } -#if defined(HAS_GLOBAL_STRING) - template <class Allocator> - StringPiece( // NOLINT(runtime/explicit) - const basic_string<char, std::char_traits<char>, Allocator>& str) - : ptr_(str.data()), length_(0) { - length_ = CheckedSsizeTFromSizeT(str.size()); - } -#endif StringPiece(const char* offset, stringpiece_ssize_type len) : ptr_(offset), length_(len) { @@ -300,7 +292,7 @@ class LIBPROTOBUF_EXPORT StringPiece { int compare(StringPiece x) const { const stringpiece_ssize_type min_size = length_ < x.length_ ? length_ : x.length_; - int r = memcmp(ptr_, x.ptr_, min_size); + int r = memcmp(ptr_, x.ptr_, static_cast<size_t>(min_size)); if (r < 0) return -1; if (r > 0) return 1; if (length_ < x.length_) return -1; @@ -318,7 +310,7 @@ class LIBPROTOBUF_EXPORT StringPiece { // "as_string()" method defined here for existing code. string ToString() const { if (ptr_ == NULL) return string(); - return string(data(), size()); + return string(data(), static_cast<size_type>(size())); } operator string() const { @@ -329,12 +321,14 @@ class LIBPROTOBUF_EXPORT StringPiece { void AppendToString(string* target) const; bool starts_with(StringPiece x) const { - return (length_ >= x.length_) && (memcmp(ptr_, x.ptr_, x.length_) == 0); + return (length_ >= x.length_) && + (memcmp(ptr_, x.ptr_, static_cast<size_t>(x.length_)) == 0); } bool ends_with(StringPiece x) const { return ((length_ >= x.length_) && - (memcmp(ptr_ + (length_-x.length_), x.ptr_, x.length_) == 0)); + (memcmp(ptr_ + (length_-x.length_), x.ptr_, + static_cast<size_t>(x.length_)) == 0)); } // Checks whether StringPiece starts with x and if so advances the beginning @@ -406,7 +400,7 @@ inline bool operator==(StringPiece x, StringPiece y) { } return x.data() == y.data() || len <= 0 || - memcmp(x.data(), y.data(), len) == 0; + memcmp(x.data(), y.data(), static_cast<size_t>(len)) == 0; } inline bool operator!=(StringPiece x, StringPiece y) { @@ -416,7 +410,7 @@ inline bool operator!=(StringPiece x, StringPiece y) { inline bool operator<(StringPiece x, StringPiece y) { const stringpiece_ssize_type min_size = x.size() < y.size() ? x.size() : y.size(); - const int r = memcmp(x.data(), y.data(), min_size); + const int r = memcmp(x.data(), y.data(), static_cast<size_t>(min_size)); return (r < 0) || (r == 0 && x.size() < y.size()); } @@ -435,6 +429,46 @@ inline bool operator>=(StringPiece x, StringPiece y) { // allow StringPiece to be logged extern std::ostream& operator<<(std::ostream& o, StringPiece piece); +namespace internal { +// StringPiece is not a POD and can not be used in an union (pre C++11). We +// need a POD version of it. +struct StringPiecePod { + // Create from a StringPiece. + static StringPiecePod CreateFromStringPiece(StringPiece str) { + StringPiecePod pod; + pod.data_ = str.data(); + pod.size_ = str.size(); + return pod; + } + + // Cast to StringPiece. + operator StringPiece() const { return StringPiece(data_, size_); } + + bool operator==(const char* value) const { + return StringPiece(data_, size_) == StringPiece(value); + } + + char operator[](stringpiece_ssize_type i) const { + assert(0 <= i); + assert(i < size_); + return data_[i]; + } + + const char* data() const { return data_; } + + stringpiece_ssize_type size() const { + return size_; + } + + std::string ToString() const { + return std::string(data_, static_cast<size_t>(size_)); + } + private: + const char* data_; + stringpiece_ssize_type size_; +}; + +} // namespace internal } // namespace protobuf } // namespace google @@ -443,7 +477,7 @@ template<> struct hash<StringPiece> { size_t operator()(const StringPiece& s) const { size_t result = 0; for (const char *str = s.data(), *end = str + s.size(); str < end; str++) { - result = 5 * result + *str; + result = 5 * result + static_cast<size_t>(*str); } return result; } diff --git a/src/google/protobuf/stubs/stringpiece_unittest.cc b/src/google/protobuf/stubs/stringpiece_unittest.cc index a52d81f8..a6a87595 100644 --- a/src/google/protobuf/stubs/stringpiece_unittest.cc +++ b/src/google/protobuf/stubs/stringpiece_unittest.cc @@ -783,11 +783,13 @@ TEST(FindOneCharTest, EdgeCases) { EXPECT_EQ(StringPiece::npos, a.rfind('x')); } +#ifdef PROTOBUF_HAS_DEATH_TEST #ifndef NDEBUG TEST(NonNegativeLenTest, NonNegativeLen) { EXPECT_DEATH(StringPiece("xyz", -1), "len >= 0"); } #endif // ndef DEBUG +#endif // PROTOBUF_HAS_DEATH_TEST } // namespace } // namespace protobuf diff --git a/src/google/protobuf/stubs/stringprintf.cc b/src/google/protobuf/stubs/stringprintf.cc index 3272d8e3..d98b9b87 100644 --- a/src/google/protobuf/stubs/stringprintf.cc +++ b/src/google/protobuf/stubs/stringprintf.cc @@ -37,7 +37,6 @@ #include <stdio.h> // MSVC requires this for _vsnprintf #include <vector> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/testing/googletest.h> namespace google { namespace protobuf { @@ -138,7 +137,7 @@ const int kStringPrintfVectorMaxArgs = 32; // and we can fix the problem or protect against an attack. static const char string_printf_empty_block[256] = { '\0' }; -string StringPrintfVector(const char* format, const vector<string>& v) { +string StringPrintfVector(const char* format, const std::vector<string>& v) { GOOGLE_CHECK_LE(v.size(), kStringPrintfVectorMaxArgs) << "StringPrintfVector currently only supports up to " << kStringPrintfVectorMaxArgs << " arguments. " diff --git a/src/google/protobuf/stubs/stringprintf.h b/src/google/protobuf/stubs/stringprintf.h index ab1ab558..7183ec6a 100644 --- a/src/google/protobuf/stubs/stringprintf.h +++ b/src/google/protobuf/stubs/stringprintf.h @@ -68,7 +68,7 @@ LIBPROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs; // You can use this version when all your arguments are strings, but // you don't know how many arguments you'll have at compile time. // StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs -LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const vector<string>& v); +LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const std::vector<string>& v); } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/structurally_valid.cc b/src/google/protobuf/stubs/structurally_valid.cc index d79a6ee4..b2239682 100644 --- a/src/google/protobuf/stubs/structurally_valid.cc +++ b/src/google/protobuf/stubs/structurally_valid.cc @@ -1,4 +1,33 @@ -// Copyright 2005-2008 Google Inc. All Rights Reserved. +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // Author: jrm@google.com (Jim Meehan) #include <google/protobuf/stubs/common.h> diff --git a/src/google/protobuf/stubs/structurally_valid_unittest.cc b/src/google/protobuf/stubs/structurally_valid_unittest.cc index 90888885..eec07a87 100644 --- a/src/google/protobuf/stubs/structurally_valid_unittest.cc +++ b/src/google/protobuf/stubs/structurally_valid_unittest.cc @@ -1,3 +1,33 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // Copyright 2008 Google Inc. All Rights Reserved. // Author: xpeng@google.com (Peter Peng) diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc index 7ba92e8f..552d416f 100644 --- a/src/google/protobuf/stubs/strutil.cc +++ b/src/google/protobuf/stubs/strutil.cc @@ -93,6 +93,21 @@ void StripString(string* s, const char* remove, char replacewith) { } } +// ---------------------------------------------------------------------- +// ReplaceCharacters +// Replaces any occurrence of the character 'remove' (or the characters +// in 'remove') with the character 'replacewith'. +// ---------------------------------------------------------------------- +void ReplaceCharacters(string *s, const char *remove, char replacewith) { + const char *str_start = s->c_str(); + const char *str = str_start; + for (str = strpbrk(str, remove); + str != NULL; + str = strpbrk(str + 1, remove)) { + (*s)[str - str_start] = replacewith; + } +} + void StripWhitespace(string* str) { int str_length = str->length(); @@ -211,8 +226,8 @@ void SplitStringToIteratorUsing(const string& full, void SplitStringUsing(const string& full, const char* delim, - vector<string>* result) { - back_insert_iterator< vector<string> > it(*result); + std::vector<string>* result) { + std::back_insert_iterator< std::vector<string> > it(*result); SplitStringToIteratorUsing(full, delim, it); } @@ -249,8 +264,8 @@ void SplitStringToIteratorAllowEmpty(const StringType& full, } void SplitStringAllowEmpty(const string& full, const char* delim, - vector<string>* result) { - back_insert_iterator<vector<string> > it(*result); + std::vector<string>* result) { + std::back_insert_iterator<std::vector<string> > it(*result); SplitStringToIteratorAllowEmpty(full, delim, 0, it); } @@ -288,7 +303,7 @@ static void JoinStringsIterator(const ITERATOR& start, } } -void JoinStrings(const vector<string>& components, +void JoinStrings(const std::vector<string>& components, const char* delim, string * result) { JoinStringsIterator(components.begin(), components.end(), delim, result); @@ -317,7 +332,7 @@ int UnescapeCEscapeSequences(const char* source, char* dest) { } int UnescapeCEscapeSequences(const char* source, char* dest, - vector<string> *errors) { + std::vector<string> *errors) { GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented."; char* d = dest; @@ -453,8 +468,8 @@ int UnescapeCEscapeString(const string& src, string* dest) { } int UnescapeCEscapeString(const string& src, string* dest, - vector<string> *errors) { - scoped_array<char> unescaped(new char[src.size() + 1]); + std::vector<string> *errors) { + std::unique_ptr<char[]> unescaped(new char[src.size() + 1]); int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), errors); GOOGLE_CHECK(dest); dest->assign(unescaped.get(), len); @@ -462,7 +477,7 @@ int UnescapeCEscapeString(const string& src, string* dest, } string UnescapeCEscapeString(const string& src) { - scoped_array<char> unescaped(new char[src.size() + 1]); + std::unique_ptr<char[]> unescaped(new char[src.size() + 1]); int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL); return string(unescaped.get(), len); } @@ -605,7 +620,7 @@ namespace strings { string Utf8SafeCEscape(const string& src) { const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array<char> dest(new char[dest_length]); + std::unique_ptr<char[]> dest(new char[dest_length]); const int len = CEscapeInternal(src.data(), src.size(), dest.get(), dest_length, false, true); GOOGLE_DCHECK_GE(len, 0); @@ -614,7 +629,7 @@ string Utf8SafeCEscape(const string& src) { string CHexEscape(const string& src) { const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array<char> dest(new char[dest_length]); + std::unique_ptr<char[]> dest(new char[dest_length]); const int len = CEscapeInternal(src.data(), src.size(), dest.get(), dest_length, true, false); GOOGLE_DCHECK_GE(len, 0); @@ -966,7 +981,7 @@ static const char two_ASCII_digits[100][2] = { }; char* FastUInt32ToBufferLeft(uint32 u, char* buffer) { - int digits; + uint32 digits; const char *ASCII_digits = NULL; // The idea of this implementation is to trim the number of divides to as few // as possible by using multiplication and subtraction rather than mod (%), @@ -1247,10 +1262,10 @@ char* DoubleToBuffer(double value, char* buffer) { // this assert. GOOGLE_COMPILE_ASSERT(DBL_DIG < 20, DBL_DIG_is_too_big); - if (value == numeric_limits<double>::infinity()) { + if (value == std::numeric_limits<double>::infinity()) { strcpy(buffer, "inf"); return buffer; - } else if (value == -numeric_limits<double>::infinity()) { + } else if (value == -std::numeric_limits<double>::infinity()) { strcpy(buffer, "-inf"); return buffer; } else if (MathLimits<double>::IsNaN(value)) { @@ -1365,10 +1380,10 @@ char* FloatToBuffer(float value, char* buffer) { // this assert. GOOGLE_COMPILE_ASSERT(FLT_DIG < 10, FLT_DIG_is_too_big); - if (value == numeric_limits<double>::infinity()) { + if (value == std::numeric_limits<double>::infinity()) { strcpy(buffer, "inf"); return buffer; - } else if (value == -numeric_limits<double>::infinity()) { + } else if (value == -std::numeric_limits<double>::infinity()) { strcpy(buffer, "-inf"); return buffer; } else if (MathLimits<float>::IsNaN(value)) { @@ -1386,7 +1401,7 @@ char* FloatToBuffer(float value, char* buffer) { float parsed_value; if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) { int snprintf_result = - snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value); + snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+3, value); // Should never overflow; see above. GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize); diff --git a/src/google/protobuf/stubs/strutil.h b/src/google/protobuf/stubs/strutil.h index 27d47575..a839b8b3 100644 --- a/src/google/protobuf/stubs/strutil.h +++ b/src/google/protobuf/stubs/strutil.h @@ -147,7 +147,7 @@ inline string StripSuffixString(const string& str, const string& suffix) { } // ---------------------------------------------------------------------- -// StripString +// ReplaceCharacters // Replaces any occurrence of the character 'remove' (or the characters // in 'remove') with the character 'replacewith'. // Good for keeping html characters or protocol characters (\t) out @@ -155,6 +155,8 @@ inline string StripSuffixString(const string& str, const string& suffix) { // StripWhitespace // Removes whitespaces from both ends of the given string. // ---------------------------------------------------------------------- +LIBPROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove, + char replacewith); LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove, char replacewith); @@ -211,7 +213,7 @@ LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub, // over all of them. // ---------------------------------------------------------------------- LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, - vector<string>* res); + std::vector<string>* res); // Split a string using one or more byte delimiters, presented // as a nul-terminated c string. Append the components to 'result'. @@ -223,15 +225,15 @@ LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, // ---------------------------------------------------------------------- LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full, const char* delim, - vector<string>* result); + std::vector<string>* result); // ---------------------------------------------------------------------- // Split() // Split a string using a character delimiter. // ---------------------------------------------------------------------- -inline vector<string> Split( +inline std::vector<string> Split( const string& full, const char* delim, bool skip_empty = true) { - vector<string> result; + std::vector<string> result; if (skip_empty) { SplitStringUsing(full, delim, &result); } else { @@ -248,10 +250,10 @@ inline vector<string> Split( // another takes a pointer to the target string. In the latter case the // target string is cleared and overwritten. // ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void JoinStrings(const vector<string>& components, +LIBPROTOBUF_EXPORT void JoinStrings(const std::vector<string>& components, const char* delim, string* result); -inline string JoinStrings(const vector<string>& components, +inline string JoinStrings(const std::vector<string>& components, const char* delim) { string result; JoinStrings(components, delim, &result); @@ -283,15 +285,15 @@ inline string JoinStrings(const vector<string>& components, // // Errors: In the first form of the call, errors are reported with // LOG(ERROR). The same is true for the second form of the call if -// the pointer to the string vector is NULL; otherwise, error -// messages are stored in the vector. In either case, the effect on +// the pointer to the string std::vector is NULL; otherwise, error +// messages are stored in the std::vector. In either case, the effect on // the dest array is not defined, but rest of the source will be // processed. // ---------------------------------------------------------------------- LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest); LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, - vector<string> *errors); + std::vector<string> *errors); // ---------------------------------------------------------------------- // UnescapeCEscapeString() @@ -310,7 +312,7 @@ LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest); LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest, - vector<string> *errors); + std::vector<string> *errors); LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src); // ---------------------------------------------------------------------- @@ -648,6 +650,9 @@ struct LIBPROTOBUF_EXPORT AlphaNum { AlphaNum(StringPiece str) : piece_data_(str.data()), piece_size_(str.size()) {} + AlphaNum(internal::StringPiecePod str) + : piece_data_(str.data()), piece_size_(str.size()) {} + size_t size() const { return piece_size_; } const char *data() const { return piece_data_; } @@ -847,6 +852,11 @@ LIBPROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc, LIBPROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc, string* dest, bool do_padding); +inline bool IsValidCodePoint(uint32 code_point) { + return code_point < 0xD800 || + (code_point >= 0xE000 && code_point <= 0x10FFFF); +} + static const int UTFmax = 4; // ---------------------------------------------------------------------- // EncodeAsUTF8Char() diff --git a/src/google/protobuf/stubs/strutil_unittest.cc b/src/google/protobuf/stubs/strutil_unittest.cc index 5d62fc4a..6bf0f598 100644 --- a/src/google/protobuf/stubs/strutil_unittest.cc +++ b/src/google/protobuf/stubs/strutil_unittest.cc @@ -782,7 +782,7 @@ TEST(Base64, EscapeAndUnescape) { reinterpret_cast<const unsigned char*>(base64_strings[i].plaintext); int plain_length = strlen(base64_strings[i].plaintext); int cypher_length = strlen(base64_strings[i].cyphertext); - vector<char> buffer(cypher_length+1); + std::vector<char> buffer(cypher_length+1); int encode_length = WebSafeBase64Escape(unsigned_plaintext, plain_length, &buffer[0], diff --git a/src/google/protobuf/stubs/substitute.cc b/src/google/protobuf/stubs/substitute.cc index c9d95899..7194a5b1 100644 --- a/src/google/protobuf/stubs/substitute.cc +++ b/src/google/protobuf/stubs/substitute.cc @@ -113,7 +113,9 @@ void SubstituteAndAppend( for (int i = 0; format[i] != '\0'; i++) { if (format[i] == '$') { if (ascii_isdigit(format[i+1])) { - const SubstituteArg* src = args_array[format[i+1] - '0']; + unsigned int index = format[i+1] - '0'; + assert(index < 10); + const SubstituteArg* src = args_array[index]; memcpy(target, src->data(), src->size()); target += src->size(); ++i; // Skip next char. diff --git a/src/google/protobuf/stubs/time.cc b/src/google/protobuf/stubs/time.cc index 49c0412c..6def637e 100644 --- a/src/google/protobuf/stubs/time.cc +++ b/src/google/protobuf/stubs/time.cc @@ -80,9 +80,9 @@ bool ValidateDateTime(const DateTime& time) { return false; } if (time.month == 2 && IsLeapYear(time.year)) { - return time.month <= kDaysInMonth[time.month] + 1; + return time.day <= kDaysInMonth[time.month] + 1; } else { - return time.month <= kDaysInMonth[time.month]; + return time.day <= kDaysInMonth[time.month]; } } diff --git a/src/google/protobuf/stubs/time.h b/src/google/protobuf/stubs/time.h index 20a6b56d..45607ca9 100644 --- a/src/google/protobuf/stubs/time.h +++ b/src/google/protobuf/stubs/time.h @@ -66,7 +66,7 @@ void LIBPROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos); string LIBPROTOBUF_EXPORT FormatTime(int64 seconds, int32 nanos); // Parses a time string. This method accepts RFC3339 date/time string with UTC // offset. For example, "2015-05-20T13:29:35.120-08:00". -bool LIBPROTOBUF_EXPORT ParseTime(const string& vaule, int64* seconds, int32* nanos); +bool LIBPROTOBUF_EXPORT ParseTime(const string& value, int64* seconds, int32* nanos); } // namespace internal } // namespace protobuf diff --git a/src/google/protobuf/stubs/time_test.cc b/src/google/protobuf/stubs/time_test.cc index 59e9d1c7..53da9480 100644 --- a/src/google/protobuf/stubs/time_test.cc +++ b/src/google/protobuf/stubs/time_test.cc @@ -149,6 +149,59 @@ TEST(DateTimeTest, LeapYear) { CreateTimestamp(2400, 3, 1) - CreateTimestamp(2400, 2, 29)); } +TEST(DateTimeTest, WrongDays) { + int64 seconds; + DateTime time; + time.hour = 0; + time.minute = 0; + time.second = 0; + time.month = 2; + + // Non-leap year. + time.year = 2015; + time.day = 29; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + + // Leap year. + time.year = 2016; + time.day = 29; + ASSERT_TRUE(DateTimeToSeconds(time, &seconds)); + time.day = 30; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + + // Non-leap year. + time.year = 2100; + time.day = 29; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + + // Leap year. + time.year = 2400; + time.day = 29; + ASSERT_TRUE(DateTimeToSeconds(time, &seconds)); + time.day = 30; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + + // Non-february + time.year = 2015; + time.month = 1; + time.day = 0; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + time.day = 1; + ASSERT_TRUE(DateTimeToSeconds(time, &seconds)); + time.day = 31; + ASSERT_TRUE(DateTimeToSeconds(time, &seconds)); + time.day = 32; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + + // Bad month + time.year = 2015; + time.month = 0; + time.day = 1; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); + time.month = 13; + ASSERT_FALSE(DateTimeToSeconds(time, &seconds)); +} + TEST(DateTimeTest, StringFormat) { DateTime start, end; start.year = 1; diff --git a/src/google/protobuf/stubs/type_traits.h b/src/google/protobuf/stubs/type_traits.h deleted file mode 100644 index 0d8127e5..00000000 --- a/src/google/protobuf/stubs/type_traits.h +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// ---- -// Author: Matt Austern -// -// This code is compiled directly on many platforms, including client -// platforms like Windows, Mac, and embedded systems. Before making -// any changes here, make sure that you're not breaking any platforms. -// -// Define a small subset of tr1 type traits. The traits we define are: -// enable_if -// is_integral -// is_floating_point -// is_pointer -// is_enum -// is_reference -// is_pod -// has_trivial_constructor -// has_trivial_copy -// has_trivial_assign -// has_trivial_destructor -// remove_const -// remove_volatile -// remove_cv -// remove_reference -// add_reference -// remove_pointer -// is_same -// is_convertible -// We can add more type traits as required. - -#ifndef GOOGLE_PROTOBUF_TYPE_TRAITS_H_ -#define GOOGLE_PROTOBUF_TYPE_TRAITS_H_ - -#include <cstddef> // for NULL -#include <utility> // For pair - -#include <google/protobuf/stubs/template_util.h> // For true_type and false_type - -namespace google { -namespace protobuf { -namespace internal { - -template<typename B, typename D> -struct is_base_of { - typedef char (&yes)[1]; - typedef char (&no)[2]; - - // BEGIN GOOGLE LOCAL MODIFICATION -- check is a #define on Mac. - #undef check - // END GOOGLE LOCAL MODIFICATION - - static yes check(const B*); - static no check(const void*); - - enum { - value = sizeof(check(static_cast<const D*>(NULL))) == sizeof(yes), - }; -}; - -template <bool cond, class T = void> struct enable_if; -template <class T> struct is_integral; -template <class T> struct is_floating_point; -template <class T> struct is_pointer; -// MSVC can't compile this correctly, and neither can gcc 3.3.5 (at least) -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) -// is_enum uses is_convertible, which is not available on MSVC. -template <class T> struct is_enum; -#endif -template <class T> struct is_reference; -template <class T> struct is_pod; -template <class T> struct has_trivial_constructor; -template <class T> struct has_trivial_copy; -template <class T> struct has_trivial_assign; -template <class T> struct has_trivial_destructor; -template <class T> struct remove_const; -template <class T> struct remove_volatile; -template <class T> struct remove_cv; -template <class T> struct remove_reference; -template <class T> struct add_reference; -template <class T> struct remove_pointer; -template <class T, class U> struct is_same; -#if !(defined(__GNUC__) && __GNUC__ <= 3) -template <class From, class To> struct is_convertible; -#endif - -// enable_if, equivalent semantics to c++11 std::enable_if, specifically: -// "If B is true, the member typedef type shall equal T; otherwise, there -// shall be no member typedef type." -// Specified by 20.9.7.6 [Other transformations] - -template<bool cond, class T> struct enable_if { typedef T type; }; -template<class T> struct enable_if<false, T> {}; -// is_integral is false except for the built-in integer types. A -// cv-qualified type is integral if and only if the underlying type is. -template <class T> struct is_integral : false_type { }; -template<> struct is_integral<bool> : true_type { }; -template<> struct is_integral<char> : true_type { }; -template<> struct is_integral<unsigned char> : true_type { }; -template<> struct is_integral<signed char> : true_type { }; -#if defined(_MSC_VER) -// wchar_t is not by default a distinct type from unsigned short in -// Microsoft C. -// See http://msdn2.microsoft.com/en-us/library/dh8che7s(VS.80).aspx -template<> struct is_integral<__wchar_t> : true_type { }; -#else -template<> struct is_integral<wchar_t> : true_type { }; -#endif -template<> struct is_integral<short> : true_type { }; -template<> struct is_integral<unsigned short> : true_type { }; -template<> struct is_integral<int> : true_type { }; -template<> struct is_integral<unsigned int> : true_type { }; -template<> struct is_integral<long> : true_type { }; -template<> struct is_integral<unsigned long> : true_type { }; -#ifdef HAVE_LONG_LONG -template<> struct is_integral<long long> : true_type { }; -template<> struct is_integral<unsigned long long> : true_type { }; -#endif -template <class T> struct is_integral<const T> : is_integral<T> { }; -template <class T> struct is_integral<volatile T> : is_integral<T> { }; -template <class T> struct is_integral<const volatile T> : is_integral<T> { }; - -// is_floating_point is false except for the built-in floating-point types. -// A cv-qualified type is integral if and only if the underlying type is. -template <class T> struct is_floating_point : false_type { }; -template<> struct is_floating_point<float> : true_type { }; -template<> struct is_floating_point<double> : true_type { }; -template<> struct is_floating_point<long double> : true_type { }; -template <class T> struct is_floating_point<const T> - : is_floating_point<T> { }; -template <class T> struct is_floating_point<volatile T> - : is_floating_point<T> { }; -template <class T> struct is_floating_point<const volatile T> - : is_floating_point<T> { }; - -// is_pointer is false except for pointer types. A cv-qualified type (e.g. -// "int* const", as opposed to "int const*") is cv-qualified if and only if -// the underlying type is. -template <class T> struct is_pointer : false_type { }; -template <class T> struct is_pointer<T*> : true_type { }; -template <class T> struct is_pointer<const T> : is_pointer<T> { }; -template <class T> struct is_pointer<volatile T> : is_pointer<T> { }; -template <class T> struct is_pointer<const volatile T> : is_pointer<T> { }; - -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - -namespace type_traits_internal { - -template <class T> struct is_class_or_union { - template <class U> static small_ tester(void (U::*)()); - template <class U> static big_ tester(...); - static const bool value = sizeof(tester<T>(0)) == sizeof(small_); -}; - -// is_convertible chokes if the first argument is an array. That's why -// we use add_reference here. -template <bool NotUnum, class T> struct is_enum_impl - : is_convertible<typename add_reference<T>::type, int> { }; - -template <class T> struct is_enum_impl<true, T> : false_type { }; - -} // namespace type_traits_internal - -// Specified by TR1 [4.5.1] primary type categories. - -// Implementation note: -// -// Each type is either void, integral, floating point, array, pointer, -// reference, member object pointer, member function pointer, enum, -// union or class. Out of these, only integral, floating point, reference, -// class and enum types are potentially convertible to int. Therefore, -// if a type is not a reference, integral, floating point or class and -// is convertible to int, it's a enum. Adding cv-qualification to a type -// does not change whether it's an enum. -// -// Is-convertible-to-int check is done only if all other checks pass, -// because it can't be used with some types (e.g. void or classes with -// inaccessible conversion operators). -template <class T> struct is_enum - : type_traits_internal::is_enum_impl< - is_same<T, void>::value || - is_integral<T>::value || - is_floating_point<T>::value || - is_reference<T>::value || - type_traits_internal::is_class_or_union<T>::value, - T> { }; - -template <class T> struct is_enum<const T> : is_enum<T> { }; -template <class T> struct is_enum<volatile T> : is_enum<T> { }; -template <class T> struct is_enum<const volatile T> : is_enum<T> { }; - -#endif - -// is_reference is false except for reference types. -template<typename T> struct is_reference : false_type {}; -template<typename T> struct is_reference<T&> : true_type {}; - - -// We can't get is_pod right without compiler help, so fail conservatively. -// We will assume it's false except for arithmetic types, enumerations, -// pointers and cv-qualified versions thereof. Note that std::pair<T,U> -// is not a POD even if T and U are PODs. -template <class T> struct is_pod - : integral_constant<bool, (is_integral<T>::value || - is_floating_point<T>::value || -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - // is_enum is not available on MSVC. - is_enum<T>::value || -#endif - is_pointer<T>::value)> { }; -template <class T> struct is_pod<const T> : is_pod<T> { }; -template <class T> struct is_pod<volatile T> : is_pod<T> { }; -template <class T> struct is_pod<const volatile T> : is_pod<T> { }; - - -// We can't get has_trivial_constructor right without compiler help, so -// fail conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial -// constructors. (3) array of a type with a trivial constructor. -// (4) const versions thereof. -template <class T> struct has_trivial_constructor : is_pod<T> { }; -template <class T, class U> struct has_trivial_constructor<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_constructor<T>::value && - has_trivial_constructor<U>::value)> { }; -template <class A, int N> struct has_trivial_constructor<A[N]> - : has_trivial_constructor<A> { }; -template <class T> struct has_trivial_constructor<const T> - : has_trivial_constructor<T> { }; - -// We can't get has_trivial_copy right without compiler help, so fail -// conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial copy -// constructors. (3) array of a type with a trivial copy constructor. -// (4) const versions thereof. -template <class T> struct has_trivial_copy : is_pod<T> { }; -template <class T, class U> struct has_trivial_copy<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_copy<T>::value && - has_trivial_copy<U>::value)> { }; -template <class A, int N> struct has_trivial_copy<A[N]> - : has_trivial_copy<A> { }; -template <class T> struct has_trivial_copy<const T> : has_trivial_copy<T> { }; - -// We can't get has_trivial_assign right without compiler help, so fail -// conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial copy -// constructors. (3) array of a type with a trivial assign constructor. -template <class T> struct has_trivial_assign : is_pod<T> { }; -template <class T, class U> struct has_trivial_assign<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_assign<T>::value && - has_trivial_assign<U>::value)> { }; -template <class A, int N> struct has_trivial_assign<A[N]> - : has_trivial_assign<A> { }; - -// We can't get has_trivial_destructor right without compiler help, so -// fail conservatively. We will assume it's false except for: (1) types -// for which is_pod is true. (2) std::pair of types with trivial -// destructors. (3) array of a type with a trivial destructor. -// (4) const versions thereof. -template <class T> struct has_trivial_destructor : is_pod<T> { }; -template <class T, class U> struct has_trivial_destructor<std::pair<T, U> > - : integral_constant<bool, - (has_trivial_destructor<T>::value && - has_trivial_destructor<U>::value)> { }; -template <class A, int N> struct has_trivial_destructor<A[N]> - : has_trivial_destructor<A> { }; -template <class T> struct has_trivial_destructor<const T> - : has_trivial_destructor<T> { }; - -// Specified by TR1 [4.7.1] -template<typename T> struct remove_const { typedef T type; }; -template<typename T> struct remove_const<T const> { typedef T type; }; -template<typename T> struct remove_volatile { typedef T type; }; -template<typename T> struct remove_volatile<T volatile> { typedef T type; }; -template<typename T> struct remove_cv { - typedef typename remove_const<typename remove_volatile<T>::type>::type type; -}; - - -// Specified by TR1 [4.7.2] Reference modifications. -template<typename T> struct remove_reference { typedef T type; }; -template<typename T> struct remove_reference<T&> { typedef T type; }; - -template <typename T> struct add_reference { typedef T& type; }; -template <typename T> struct add_reference<T&> { typedef T& type; }; - -// Specified by TR1 [4.7.4] Pointer modifications. -template<typename T> struct remove_pointer { typedef T type; }; -template<typename T> struct remove_pointer<T*> { typedef T type; }; -template<typename T> struct remove_pointer<T* const> { typedef T type; }; -template<typename T> struct remove_pointer<T* volatile> { typedef T type; }; -template<typename T> struct remove_pointer<T* const volatile> { - typedef T type; }; - -// Specified by TR1 [4.6] Relationships between types -template<typename T, typename U> struct is_same : public false_type { }; -template<typename T> struct is_same<T, T> : public true_type { }; - -// Specified by TR1 [4.6] Relationships between types -#if !(defined(__GNUC__) && __GNUC__ <= 3) -namespace type_traits_internal { - -// This class is an implementation detail for is_convertible, and you -// don't need to know how it works to use is_convertible. For those -// who care: we declare two different functions, one whose argument is -// of type To and one with a variadic argument list. We give them -// return types of different size, so we can use sizeof to trick the -// compiler into telling us which function it would have chosen if we -// had called it with an argument of type From. See Alexandrescu's -// _Modern C++ Design_ for more details on this sort of trick. - -template <typename From, typename To> -struct ConvertHelper { - static small_ Test(To); - static big_ Test(...); - static From Create(); - enum { - value = sizeof(Test(Create())) == sizeof(small_) - }; -}; -} // namespace type_traits_internal - -// Inherits from true_type if From is convertible to To, false_type otherwise. -template <typename From, typename To> -struct is_convertible - : integral_constant<bool, - type_traits_internal::ConvertHelper<From, To>::value> { -}; -#endif - -} // namespace internal -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_TYPE_TRAITS_H_ diff --git a/src/google/protobuf/stubs/type_traits_unittest.cc b/src/google/protobuf/stubs/type_traits_unittest.cc deleted file mode 100644 index 49c10ace..00000000 --- a/src/google/protobuf/stubs/type_traits_unittest.cc +++ /dev/null @@ -1,631 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// ---- -// Author: Matt Austern - -#include <google/protobuf/stubs/type_traits.h> - -#include <stdlib.h> // for exit() -#include <stdio.h> -#include <string> -#include <vector> - -#include <google/protobuf/testing/googletest.h> -#include <gtest/gtest.h> - -typedef int int32; -// IBM AIX typedefs `int64` in `sys/inttypes.h`, included transitively above. -#ifndef _AIX -typedef long int64; -#endif - -using std::string; -using std::vector; -using std::pair; - - -// This assertion produces errors like "error: invalid use of -// incomplete type 'struct <unnamed>::AssertTypesEq<const int, int>'" -// when it fails. -template<typename T, typename U> struct AssertTypesEq; -template<typename T> struct AssertTypesEq<T, T> {}; -#define COMPILE_ASSERT_TYPES_EQ(T, U) static_cast<void>(AssertTypesEq<T, U>()) - -// A user-defined POD type. -struct A { - int n_; -}; - -// A user-defined non-POD type with a trivial copy constructor. -class B { - public: - explicit B(int n) : n_(n) { } - private: - int n_; -}; - -// Another user-defined non-POD type with a trivial copy constructor. -// We will explicitly declare C to have a trivial copy constructor -// by specializing has_trivial_copy. -class C { - public: - explicit C(int n) : n_(n) { } - private: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_copy<C> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -// Another user-defined non-POD type with a trivial assignment operator. -// We will explicitly declare C to have a trivial assignment operator -// by specializing has_trivial_assign. -class D { - public: - explicit D(int n) : n_(n) { } - private: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_assign<D> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -// Another user-defined non-POD type with a trivial constructor. -// We will explicitly declare E to have a trivial constructor -// by specializing has_trivial_constructor. -class E { - public: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_constructor<E> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -// Another user-defined non-POD type with a trivial destructor. -// We will explicitly declare E to have a trivial destructor -// by specializing has_trivial_destructor. -class F { - public: - explicit F(int n) : n_(n) { } - private: - int n_; -}; - -namespace google { -namespace protobuf { -namespace internal { -template<> struct has_trivial_destructor<F> : true_type { }; -} // namespace internal -} // namespace protobuf -} // namespace google - -enum G {}; - -union H {}; - -class I { - public: - operator int() const; -}; - -class J { - private: - operator int() const; -}; - -namespace google { -namespace protobuf { -namespace internal { -namespace { - -// A base class and a derived class that inherits from it, used for -// testing conversion type traits. -class Base { - public: - virtual ~Base() { } -}; - -class Derived : public Base { -}; - -TEST(TypeTraitsTest, TestIsInteger) { - // Verify that is_integral is true for all integer types. - EXPECT_TRUE(is_integral<bool>::value); - EXPECT_TRUE(is_integral<char>::value); - EXPECT_TRUE(is_integral<unsigned char>::value); - EXPECT_TRUE(is_integral<signed char>::value); - EXPECT_TRUE(is_integral<wchar_t>::value); - EXPECT_TRUE(is_integral<int>::value); - EXPECT_TRUE(is_integral<unsigned int>::value); - EXPECT_TRUE(is_integral<short>::value); - EXPECT_TRUE(is_integral<unsigned short>::value); - EXPECT_TRUE(is_integral<long>::value); - EXPECT_TRUE(is_integral<unsigned long>::value); - - // Verify that is_integral is false for a few non-integer types. - EXPECT_FALSE(is_integral<void>::value); - EXPECT_FALSE(is_integral<float>::value); - EXPECT_FALSE(is_integral<string>::value); - EXPECT_FALSE(is_integral<int*>::value); - EXPECT_FALSE(is_integral<A>::value); - EXPECT_FALSE((is_integral<pair<int, int> >::value)); - - // Verify that cv-qualified integral types are still integral, and - // cv-qualified non-integral types are still non-integral. - EXPECT_TRUE(is_integral<const char>::value); - EXPECT_TRUE(is_integral<volatile bool>::value); - EXPECT_TRUE(is_integral<const volatile unsigned int>::value); - EXPECT_FALSE(is_integral<const float>::value); - EXPECT_FALSE(is_integral<int* volatile>::value); - EXPECT_FALSE(is_integral<const volatile string>::value); -} - -TEST(TypeTraitsTest, TestIsFloating) { - // Verify that is_floating_point is true for all floating-point types. - EXPECT_TRUE(is_floating_point<float>::value); - EXPECT_TRUE(is_floating_point<double>::value); - EXPECT_TRUE(is_floating_point<long double>::value); - - // Verify that is_floating_point is false for a few non-float types. - EXPECT_FALSE(is_floating_point<void>::value); - EXPECT_FALSE(is_floating_point<long>::value); - EXPECT_FALSE(is_floating_point<string>::value); - EXPECT_FALSE(is_floating_point<float*>::value); - EXPECT_FALSE(is_floating_point<A>::value); - EXPECT_FALSE((is_floating_point<pair<int, int> >::value)); - - // Verify that cv-qualified floating point types are still floating, and - // cv-qualified non-floating types are still non-floating. - EXPECT_TRUE(is_floating_point<const float>::value); - EXPECT_TRUE(is_floating_point<volatile double>::value); - EXPECT_TRUE(is_floating_point<const volatile long double>::value); - EXPECT_FALSE(is_floating_point<const int>::value); - EXPECT_FALSE(is_floating_point<volatile string>::value); - EXPECT_FALSE(is_floating_point<const volatile char>::value); -} - -TEST(TypeTraitsTest, TestIsPointer) { - // Verify that is_pointer is true for some pointer types. - EXPECT_TRUE(is_pointer<int*>::value); - EXPECT_TRUE(is_pointer<void*>::value); - EXPECT_TRUE(is_pointer<string*>::value); - EXPECT_TRUE(is_pointer<const void*>::value); - EXPECT_TRUE(is_pointer<volatile float* const*>::value); - - // Verify that is_pointer is false for some non-pointer types. - EXPECT_FALSE(is_pointer<void>::value); - EXPECT_FALSE(is_pointer<float&>::value); - EXPECT_FALSE(is_pointer<long>::value); - EXPECT_FALSE(is_pointer<vector<int*> >::value); - EXPECT_FALSE(is_pointer<int[5]>::value); - - // A function pointer is a pointer, but a function type, or a function - // reference type, is not. - EXPECT_TRUE(is_pointer<int (*)(int x)>::value); - EXPECT_FALSE(is_pointer<void(char x)>::value); - EXPECT_FALSE(is_pointer<double (&)(string x)>::value); - - // Verify that is_pointer<T> is true for some cv-qualified pointer types, - // and false for some cv-qualified non-pointer types. - EXPECT_TRUE(is_pointer<int* const>::value); - EXPECT_TRUE(is_pointer<const void* volatile>::value); - EXPECT_TRUE(is_pointer<char** const volatile>::value); - EXPECT_FALSE(is_pointer<const int>::value); - EXPECT_FALSE(is_pointer<volatile vector<int*> >::value); - EXPECT_FALSE(is_pointer<const volatile double>::value); -} - -TEST(TypeTraitsTest, TestIsEnum) { -// is_enum isn't supported on MSVC or gcc 3.x -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - // Verify that is_enum is true for enum types. - EXPECT_TRUE(is_enum<G>::value); - EXPECT_TRUE(is_enum<const G>::value); - EXPECT_TRUE(is_enum<volatile G>::value); - EXPECT_TRUE(is_enum<const volatile G>::value); - - // Verify that is_enum is false for a few non-enum types. - EXPECT_FALSE(is_enum<void>::value); - EXPECT_FALSE(is_enum<G&>::value); - EXPECT_FALSE(is_enum<G[1]>::value); - EXPECT_FALSE(is_enum<const G[1]>::value); - EXPECT_FALSE(is_enum<G[]>::value); - EXPECT_FALSE(is_enum<int>::value); - EXPECT_FALSE(is_enum<float>::value); - EXPECT_FALSE(is_enum<A>::value); - EXPECT_FALSE(is_enum<A*>::value); - EXPECT_FALSE(is_enum<const A>::value); - EXPECT_FALSE(is_enum<H>::value); - EXPECT_FALSE(is_enum<I>::value); - EXPECT_FALSE(is_enum<J>::value); - EXPECT_FALSE(is_enum<void()>::value); - EXPECT_FALSE(is_enum<void(*)()>::value); - EXPECT_FALSE(is_enum<int A::*>::value); - EXPECT_FALSE(is_enum<void (A::*)()>::value); -#endif -} - -TEST(TypeTraitsTest, TestIsReference) { - // Verifies that is_reference is true for all reference types. - typedef float& RefFloat; - EXPECT_TRUE(is_reference<float&>::value); - EXPECT_TRUE(is_reference<const int&>::value); - EXPECT_TRUE(is_reference<const int*&>::value); - EXPECT_TRUE(is_reference<int (&)(bool)>::value); - EXPECT_TRUE(is_reference<RefFloat>::value); - EXPECT_TRUE(is_reference<const RefFloat>::value); - EXPECT_TRUE(is_reference<volatile RefFloat>::value); - EXPECT_TRUE(is_reference<const volatile RefFloat>::value); - - - // Verifies that is_reference is false for all non-reference types. - EXPECT_FALSE(is_reference<float>::value); - EXPECT_FALSE(is_reference<const float>::value); - EXPECT_FALSE(is_reference<volatile float>::value); - EXPECT_FALSE(is_reference<const volatile float>::value); - EXPECT_FALSE(is_reference<const int*>::value); - EXPECT_FALSE(is_reference<int()>::value); - EXPECT_FALSE(is_reference<void(*)(const char&)>::value); -} - -TEST(TypeTraitsTest, TestAddReference) { - COMPILE_ASSERT_TYPES_EQ(int&, add_reference<int>::type); - COMPILE_ASSERT_TYPES_EQ(const int&, add_reference<const int>::type); - COMPILE_ASSERT_TYPES_EQ(volatile int&, - add_reference<volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(const volatile int&, - add_reference<const volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(int&, add_reference<int&>::type); - COMPILE_ASSERT_TYPES_EQ(const int&, add_reference<const int&>::type); - COMPILE_ASSERT_TYPES_EQ(volatile int&, - add_reference<volatile int&>::type); - COMPILE_ASSERT_TYPES_EQ(const volatile int&, - add_reference<const volatile int&>::type); -} - -TEST(TypeTraitsTest, TestIsPod) { - // Verify that arithmetic types and pointers are marked as PODs. - EXPECT_TRUE(is_pod<bool>::value); - EXPECT_TRUE(is_pod<char>::value); - EXPECT_TRUE(is_pod<unsigned char>::value); - EXPECT_TRUE(is_pod<signed char>::value); - EXPECT_TRUE(is_pod<wchar_t>::value); - EXPECT_TRUE(is_pod<int>::value); - EXPECT_TRUE(is_pod<unsigned int>::value); - EXPECT_TRUE(is_pod<short>::value); - EXPECT_TRUE(is_pod<unsigned short>::value); - EXPECT_TRUE(is_pod<long>::value); - EXPECT_TRUE(is_pod<unsigned long>::value); - EXPECT_TRUE(is_pod<float>::value); - EXPECT_TRUE(is_pod<double>::value); - EXPECT_TRUE(is_pod<long double>::value); - EXPECT_TRUE(is_pod<string*>::value); - EXPECT_TRUE(is_pod<A*>::value); - EXPECT_TRUE(is_pod<const B*>::value); - EXPECT_TRUE(is_pod<C**>::value); - EXPECT_TRUE(is_pod<const int>::value); - EXPECT_TRUE(is_pod<char* volatile>::value); - EXPECT_TRUE(is_pod<const volatile double>::value); -#if !defined(_MSC_VER) && !(defined(__GNUC__) && __GNUC__ <= 3) - EXPECT_TRUE(is_pod<G>::value); - EXPECT_TRUE(is_pod<const G>::value); - EXPECT_TRUE(is_pod<volatile G>::value); - EXPECT_TRUE(is_pod<const volatile G>::value); -#endif - - // Verify that some non-POD types are not marked as PODs. - EXPECT_FALSE(is_pod<void>::value); - EXPECT_FALSE(is_pod<string>::value); - EXPECT_FALSE((is_pod<pair<int, int> >::value)); - EXPECT_FALSE(is_pod<A>::value); - EXPECT_FALSE(is_pod<B>::value); - EXPECT_FALSE(is_pod<C>::value); - EXPECT_FALSE(is_pod<const string>::value); - EXPECT_FALSE(is_pod<volatile A>::value); - EXPECT_FALSE(is_pod<const volatile B>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialConstructor) { - // Verify that arithmetic types and pointers have trivial constructors. - EXPECT_TRUE(has_trivial_constructor<bool>::value); - EXPECT_TRUE(has_trivial_constructor<char>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned char>::value); - EXPECT_TRUE(has_trivial_constructor<signed char>::value); - EXPECT_TRUE(has_trivial_constructor<wchar_t>::value); - EXPECT_TRUE(has_trivial_constructor<int>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned int>::value); - EXPECT_TRUE(has_trivial_constructor<short>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned short>::value); - EXPECT_TRUE(has_trivial_constructor<long>::value); - EXPECT_TRUE(has_trivial_constructor<unsigned long>::value); - EXPECT_TRUE(has_trivial_constructor<float>::value); - EXPECT_TRUE(has_trivial_constructor<double>::value); - EXPECT_TRUE(has_trivial_constructor<long double>::value); - EXPECT_TRUE(has_trivial_constructor<string*>::value); - EXPECT_TRUE(has_trivial_constructor<A*>::value); - EXPECT_TRUE(has_trivial_constructor<const B*>::value); - EXPECT_TRUE(has_trivial_constructor<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // constructors. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_constructor<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_constructor<int10>::value); - - // Verify that pairs of types without trivial constructors - // are not marked as trivial. - EXPECT_FALSE((has_trivial_constructor<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_constructor<pair<string, int> >::value)); - - // Verify that types without trivial constructors are - // correctly marked as such. - EXPECT_FALSE(has_trivial_constructor<string>::value); - EXPECT_FALSE(has_trivial_constructor<vector<int> >::value); - - // Verify that E, which we have declared to have a trivial - // constructor, is correctly marked as such. - EXPECT_TRUE(has_trivial_constructor<E>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialCopy) { - // Verify that arithmetic types and pointers have trivial copy - // constructors. - EXPECT_TRUE(has_trivial_copy<bool>::value); - EXPECT_TRUE(has_trivial_copy<char>::value); - EXPECT_TRUE(has_trivial_copy<unsigned char>::value); - EXPECT_TRUE(has_trivial_copy<signed char>::value); - EXPECT_TRUE(has_trivial_copy<wchar_t>::value); - EXPECT_TRUE(has_trivial_copy<int>::value); - EXPECT_TRUE(has_trivial_copy<unsigned int>::value); - EXPECT_TRUE(has_trivial_copy<short>::value); - EXPECT_TRUE(has_trivial_copy<unsigned short>::value); - EXPECT_TRUE(has_trivial_copy<long>::value); - EXPECT_TRUE(has_trivial_copy<unsigned long>::value); - EXPECT_TRUE(has_trivial_copy<float>::value); - EXPECT_TRUE(has_trivial_copy<double>::value); - EXPECT_TRUE(has_trivial_copy<long double>::value); - EXPECT_TRUE(has_trivial_copy<string*>::value); - EXPECT_TRUE(has_trivial_copy<A*>::value); - EXPECT_TRUE(has_trivial_copy<const B*>::value); - EXPECT_TRUE(has_trivial_copy<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // copy constructors. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_copy<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_copy<int10>::value); - - // Verify that pairs of types without trivial copy constructors - // are not marked as trivial. - EXPECT_FALSE((has_trivial_copy<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_copy<pair<string, int> >::value)); - - // Verify that types without trivial copy constructors are - // correctly marked as such. - EXPECT_FALSE(has_trivial_copy<string>::value); - EXPECT_FALSE(has_trivial_copy<vector<int> >::value); - - // Verify that C, which we have declared to have a trivial - // copy constructor, is correctly marked as such. - EXPECT_TRUE(has_trivial_copy<C>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialAssign) { - // Verify that arithmetic types and pointers have trivial assignment - // operators. - EXPECT_TRUE(has_trivial_assign<bool>::value); - EXPECT_TRUE(has_trivial_assign<char>::value); - EXPECT_TRUE(has_trivial_assign<unsigned char>::value); - EXPECT_TRUE(has_trivial_assign<signed char>::value); - EXPECT_TRUE(has_trivial_assign<wchar_t>::value); - EXPECT_TRUE(has_trivial_assign<int>::value); - EXPECT_TRUE(has_trivial_assign<unsigned int>::value); - EXPECT_TRUE(has_trivial_assign<short>::value); - EXPECT_TRUE(has_trivial_assign<unsigned short>::value); - EXPECT_TRUE(has_trivial_assign<long>::value); - EXPECT_TRUE(has_trivial_assign<unsigned long>::value); - EXPECT_TRUE(has_trivial_assign<float>::value); - EXPECT_TRUE(has_trivial_assign<double>::value); - EXPECT_TRUE(has_trivial_assign<long double>::value); - EXPECT_TRUE(has_trivial_assign<string*>::value); - EXPECT_TRUE(has_trivial_assign<A*>::value); - EXPECT_TRUE(has_trivial_assign<const B*>::value); - EXPECT_TRUE(has_trivial_assign<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // assignment operators. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_assign<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_assign<int10>::value); - - // Verify that pairs of types without trivial assignment operators - // are not marked as trivial. - EXPECT_FALSE((has_trivial_assign<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_assign<pair<string, int> >::value)); - - // Verify that types without trivial assignment operators are - // correctly marked as such. - EXPECT_FALSE(has_trivial_assign<string>::value); - EXPECT_FALSE(has_trivial_assign<vector<int> >::value); - - // Verify that D, which we have declared to have a trivial - // assignment operator, is correctly marked as such. - EXPECT_TRUE(has_trivial_assign<D>::value); -} - -TEST(TypeTraitsTest, TestHasTrivialDestructor) { - // Verify that arithmetic types and pointers have trivial destructors. - EXPECT_TRUE(has_trivial_destructor<bool>::value); - EXPECT_TRUE(has_trivial_destructor<char>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned char>::value); - EXPECT_TRUE(has_trivial_destructor<signed char>::value); - EXPECT_TRUE(has_trivial_destructor<wchar_t>::value); - EXPECT_TRUE(has_trivial_destructor<int>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned int>::value); - EXPECT_TRUE(has_trivial_destructor<short>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned short>::value); - EXPECT_TRUE(has_trivial_destructor<long>::value); - EXPECT_TRUE(has_trivial_destructor<unsigned long>::value); - EXPECT_TRUE(has_trivial_destructor<float>::value); - EXPECT_TRUE(has_trivial_destructor<double>::value); - EXPECT_TRUE(has_trivial_destructor<long double>::value); - EXPECT_TRUE(has_trivial_destructor<string*>::value); - EXPECT_TRUE(has_trivial_destructor<A*>::value); - EXPECT_TRUE(has_trivial_destructor<const B*>::value); - EXPECT_TRUE(has_trivial_destructor<C**>::value); - - // Verify that pairs and arrays of such types have trivial - // destructors. - typedef int int10[10]; - EXPECT_TRUE((has_trivial_destructor<pair<int, char*> >::value)); - EXPECT_TRUE(has_trivial_destructor<int10>::value); - - // Verify that pairs of types without trivial destructors - // are not marked as trivial. - EXPECT_FALSE((has_trivial_destructor<pair<int, string> >::value)); - EXPECT_FALSE((has_trivial_destructor<pair<string, int> >::value)); - - // Verify that types without trivial destructors are - // correctly marked as such. - EXPECT_FALSE(has_trivial_destructor<string>::value); - EXPECT_FALSE(has_trivial_destructor<vector<int> >::value); - - // Verify that F, which we have declared to have a trivial - // destructor, is correctly marked as such. - EXPECT_TRUE(has_trivial_destructor<F>::value); -} - -// Tests remove_pointer. -TEST(TypeTraitsTest, TestRemovePointer) { - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int*>::type); - COMPILE_ASSERT_TYPES_EQ(const int, remove_pointer<const int*>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int* const>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_pointer<int* volatile>::type); -} - -TEST(TypeTraitsTest, TestRemoveConst) { - COMPILE_ASSERT_TYPES_EQ(int, remove_const<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_const<const int>::type); - COMPILE_ASSERT_TYPES_EQ(int *, remove_const<int * const>::type); - // TR1 examples. - COMPILE_ASSERT_TYPES_EQ(const int *, remove_const<const int *>::type); - COMPILE_ASSERT_TYPES_EQ(volatile int, - remove_const<const volatile int>::type); -} - -TEST(TypeTraitsTest, TestRemoveVolatile) { - COMPILE_ASSERT_TYPES_EQ(int, remove_volatile<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_volatile<volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(int *, remove_volatile<int * volatile>::type); - // TR1 examples. - COMPILE_ASSERT_TYPES_EQ(volatile int *, - remove_volatile<volatile int *>::type); - COMPILE_ASSERT_TYPES_EQ(const int, - remove_volatile<const volatile int>::type); -} - -TEST(TypeTraitsTest, TestRemoveCV) { - COMPILE_ASSERT_TYPES_EQ(int, remove_cv<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_cv<volatile int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_cv<const int>::type); - COMPILE_ASSERT_TYPES_EQ(int *, remove_cv<int * const volatile>::type); - // TR1 examples. - COMPILE_ASSERT_TYPES_EQ(const volatile int *, - remove_cv<const volatile int *>::type); - COMPILE_ASSERT_TYPES_EQ(int, - remove_cv<const volatile int>::type); -} - -TEST(TypeTraitsTest, TestRemoveReference) { - COMPILE_ASSERT_TYPES_EQ(int, remove_reference<int>::type); - COMPILE_ASSERT_TYPES_EQ(int, remove_reference<int&>::type); - COMPILE_ASSERT_TYPES_EQ(const int, remove_reference<const int&>::type); - COMPILE_ASSERT_TYPES_EQ(int*, remove_reference<int * &>::type); -} - -TEST(TypeTraitsTest, TestIsSame) { - EXPECT_TRUE((is_same<int32, int32>::value)); - EXPECT_FALSE((is_same<int32, int64>::value)); - EXPECT_FALSE((is_same<int64, int32>::value)); - EXPECT_FALSE((is_same<int, const int>::value)); - - EXPECT_TRUE((is_same<void, void>::value)); - EXPECT_FALSE((is_same<void, int>::value)); - EXPECT_FALSE((is_same<int, void>::value)); - - EXPECT_TRUE((is_same<int*, int*>::value)); - EXPECT_TRUE((is_same<void*, void*>::value)); - EXPECT_FALSE((is_same<int*, void*>::value)); - EXPECT_FALSE((is_same<void*, int*>::value)); - EXPECT_FALSE((is_same<void*, const void*>::value)); - EXPECT_FALSE((is_same<void*, void* const>::value)); - - EXPECT_TRUE((is_same<Base*, Base*>::value)); - EXPECT_TRUE((is_same<Derived*, Derived*>::value)); - EXPECT_FALSE((is_same<Base*, Derived*>::value)); - EXPECT_FALSE((is_same<Derived*, Base*>::value)); -} - -TEST(TypeTraitsTest, TestConvertible) { -#if !(defined(__GNUC__) && __GNUC__ <= 3) - EXPECT_TRUE((is_convertible<int, int>::value)); - EXPECT_TRUE((is_convertible<int, long>::value)); - EXPECT_TRUE((is_convertible<long, int>::value)); - - EXPECT_TRUE((is_convertible<int*, void*>::value)); - EXPECT_FALSE((is_convertible<void*, int*>::value)); - - EXPECT_TRUE((is_convertible<Derived*, Base*>::value)); - EXPECT_FALSE((is_convertible<Base*, Derived*>::value)); - EXPECT_TRUE((is_convertible<Derived*, const Base*>::value)); - EXPECT_FALSE((is_convertible<const Derived*, Base*>::value)); -#endif -} - -} // anonymous namespace -} // namespace internal -} // namespace protobuf -} // namespace google |