diff options
Diffstat (limited to 'mojo/public/cpp/bindings/lib')
43 files changed, 0 insertions, 3918 deletions
diff --git a/mojo/public/cpp/bindings/lib/DEPS b/mojo/public/cpp/bindings/lib/DEPS deleted file mode 100644 index b809b58..0000000 --- a/mojo/public/cpp/bindings/lib/DEPS +++ /dev/null @@ -1,5 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/bindings", - "+mojo/public/cpp/environment", - "+mojo/public/cpp/system", -] diff --git a/mojo/public/cpp/bindings/lib/TODO b/mojo/public/cpp/bindings/lib/TODO deleted file mode 100644 index 21bcb6f..0000000 --- a/mojo/public/cpp/bindings/lib/TODO +++ /dev/null @@ -1,6 +0,0 @@ -TODOs: - - Ensure validation checks are solid - - Add tests of validation logic - - Optimize Buffer classes? - - Add compile-time asserts to verify object packing and padding. - - Investigate making arrays of objects not be arrays of pointers. diff --git a/mojo/public/cpp/bindings/lib/array_internal.cc b/mojo/public/cpp/bindings/lib/array_internal.cc deleted file mode 100644 index 61e4b0d..0000000 --- a/mojo/public/cpp/bindings/lib/array_internal.cc +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/array_internal.h" - -#include <sstream> - -namespace mojo { -namespace internal { - -std::string MakeMessageWithArrayIndex(const char* message, - size_t size, - size_t index) { - std::ostringstream stream; - stream << message << ": array size - " << size << "; index - " << index; - return stream.str(); -} - -std::string MakeMessageWithExpectedArraySize(const char* message, - size_t size, - size_t expected_size) { - std::ostringstream stream; - stream << message << ": array size - " << size << "; expected size - " - << expected_size; - return stream.str(); -} - -ArrayDataTraits<bool>::BitRef::~BitRef() { -} - -ArrayDataTraits<bool>::BitRef::BitRef(uint8_t* storage, uint8_t mask) - : storage_(storage), mask_(mask) { -} - -ArrayDataTraits<bool>::BitRef& ArrayDataTraits<bool>::BitRef::operator=( - bool value) { - if (value) { - *storage_ |= mask_; - } else { - *storage_ &= ~mask_; - } - return *this; -} - -ArrayDataTraits<bool>::BitRef& ArrayDataTraits<bool>::BitRef::operator=( - const BitRef& value) { - return (*this) = static_cast<bool>(value); -} - -ArrayDataTraits<bool>::BitRef::operator bool() const { - return (*storage_ & mask_) != 0; -} - -// static -void ArraySerializationHelper<Handle, true>::EncodePointersAndHandles( - const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) { - for (uint32_t i = 0; i < header->num_elements; ++i) - EncodeHandle(&elements[i], handles); -} - -// static -void ArraySerializationHelper<Handle, true>::DecodePointersAndHandles( - const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) { - for (uint32_t i = 0; i < header->num_elements; ++i) - DecodeHandle(&elements[i], handles); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/array_internal.h b/mojo/public/cpp/bindings/lib/array_internal.h deleted file mode 100644 index eb25e35..0000000 --- a/mojo/public/cpp/bindings/lib/array_internal.h +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_ARRAY_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_ARRAY_INTERNAL_H_ - -#include <new> -#include <vector> - -#include "mojo/public/c/system/macros.h" -#include "mojo/public/cpp/bindings/lib/bindings_internal.h" -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/bindings/lib/bounds_checker.h" -#include "mojo/public/cpp/bindings/lib/buffer.h" -#include "mojo/public/cpp/bindings/lib/map_data_internal.h" -#include "mojo/public/cpp/bindings/lib/template_util.h" -#include "mojo/public/cpp/bindings/lib/validate_params.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -template <typename T> -class Array; -class String; - -namespace internal { - -// std::numeric_limits<uint32_t>::max() is not a compile-time constant (until -// C++11). -const uint32_t kMaxUint32 = 0xFFFFFFFF; - -std::string MakeMessageWithArrayIndex(const char* message, - size_t size, - size_t index); - -std::string MakeMessageWithExpectedArraySize(const char* message, - size_t size, - size_t expected_size); - -template <typename T> -struct ArrayDataTraits { - typedef T StorageType; - typedef T& Ref; - typedef T const& ConstRef; - - static const uint32_t kMaxNumElements = - (kMaxUint32 - sizeof(ArrayHeader)) / sizeof(StorageType); - - static uint32_t GetStorageSize(uint32_t num_elements) { - MOJO_DCHECK(num_elements <= kMaxNumElements); - return sizeof(ArrayHeader) + sizeof(StorageType) * num_elements; - } - static Ref ToRef(StorageType* storage, size_t offset) { - return storage[offset]; - } - static ConstRef ToConstRef(const StorageType* storage, size_t offset) { - return storage[offset]; - } -}; - -template <typename P> -struct ArrayDataTraits<P*> { - typedef StructPointer<P> StorageType; - typedef P*& Ref; - typedef P* const& ConstRef; - - static const uint32_t kMaxNumElements = - (kMaxUint32 - sizeof(ArrayHeader)) / sizeof(StorageType); - - static uint32_t GetStorageSize(uint32_t num_elements) { - MOJO_DCHECK(num_elements <= kMaxNumElements); - return sizeof(ArrayHeader) + sizeof(StorageType) * num_elements; - } - static Ref ToRef(StorageType* storage, size_t offset) { - return storage[offset].ptr; - } - static ConstRef ToConstRef(const StorageType* storage, size_t offset) { - return storage[offset].ptr; - } -}; - -template <typename T> -struct ArrayDataTraits<Array_Data<T>*> { - typedef ArrayPointer<T> StorageType; - typedef Array_Data<T>*& Ref; - typedef Array_Data<T>* const& ConstRef; - - static const uint32_t kMaxNumElements = - (kMaxUint32 - sizeof(ArrayHeader)) / sizeof(StorageType); - - static uint32_t GetStorageSize(uint32_t num_elements) { - MOJO_DCHECK(num_elements <= kMaxNumElements); - return sizeof(ArrayHeader) + sizeof(StorageType) * num_elements; - } - static Ref ToRef(StorageType* storage, size_t offset) { - return storage[offset].ptr; - } - static ConstRef ToConstRef(const StorageType* storage, size_t offset) { - return storage[offset].ptr; - } -}; - -// Specialization of Arrays for bools, optimized for space. It has the -// following differences from a generalized Array: -// * Each element takes up a single bit of memory. -// * Accessing a non-const single element uses a helper class |BitRef|, which -// emulates a reference to a bool. -template <> -struct ArrayDataTraits<bool> { - // Helper class to emulate a reference to a bool, used for direct element - // access. - class BitRef { - public: - ~BitRef(); - BitRef& operator=(bool value); - BitRef& operator=(const BitRef& value); - operator bool() const; - - private: - friend struct ArrayDataTraits<bool>; - BitRef(uint8_t* storage, uint8_t mask); - BitRef(); - uint8_t* storage_; - uint8_t mask_; - }; - - // Because each element consumes only 1/8 byte. - static const uint32_t kMaxNumElements = kMaxUint32; - - typedef uint8_t StorageType; - typedef BitRef Ref; - typedef bool ConstRef; - - static uint32_t GetStorageSize(uint32_t num_elements) { - return sizeof(ArrayHeader) + ((num_elements + 7) / 8); - } - static BitRef ToRef(StorageType* storage, size_t offset) { - return BitRef(&storage[offset / 8], 1 << (offset % 8)); - } - static bool ToConstRef(const StorageType* storage, size_t offset) { - return (storage[offset / 8] & (1 << (offset % 8))) != 0; - } -}; - -// What follows is code to support the serialization of Array_Data<T>. There -// are two interesting cases: arrays of primitives and arrays of objects. -// Arrays of objects are represented as arrays of pointers to objects. - -template <typename T, bool is_handle> -struct ArraySerializationHelper; - -template <typename T> -struct ArraySerializationHelper<T, false> { - typedef typename ArrayDataTraits<T>::StorageType ElementType; - - static void EncodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) {} - - static void DecodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) {} - - template <bool element_is_nullable, typename ElementValidateParams> - static bool ValidateElements(const ArrayHeader* header, - const ElementType* elements, - BoundsChecker* bounds_checker) { - static_assert(!element_is_nullable, - "Primitive type should be non-nullable"); - static_assert((IsSame<ElementValidateParams, NoValidateParams>::value), - "Primitive type should not have array validate params"); - return true; - } -}; - -template <> -struct ArraySerializationHelper<Handle, true> { - typedef ArrayDataTraits<Handle>::StorageType ElementType; - - static void EncodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles); - - static void DecodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles); - - template <bool element_is_nullable, typename ElementValidateParams> - static bool ValidateElements(const ArrayHeader* header, - const ElementType* elements, - BoundsChecker* bounds_checker) { - static_assert((IsSame<ElementValidateParams, NoValidateParams>::value), - "Handle type should not have array validate params"); - - for (uint32_t i = 0; i < header->num_elements; ++i) { - if (!element_is_nullable && - elements[i].value() == kEncodedInvalidHandleValue) { - ReportValidationError( - VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, - MakeMessageWithArrayIndex( - "invalid handle in array expecting valid handles", - header->num_elements, - i).c_str()); - return false; - } - if (!bounds_checker->ClaimHandle(elements[i])) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_HANDLE); - return false; - } - } - return true; - } -}; - -template <typename H> -struct ArraySerializationHelper<H, true> { - typedef typename ArrayDataTraits<H>::StorageType ElementType; - - static void EncodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) { - ArraySerializationHelper<Handle, true>::EncodePointersAndHandles( - header, elements, handles); - } - - static void DecodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) { - ArraySerializationHelper<Handle, true>::DecodePointersAndHandles( - header, elements, handles); - } - - template <bool element_is_nullable, typename ElementValidateParams> - static bool ValidateElements(const ArrayHeader* header, - const ElementType* elements, - BoundsChecker* bounds_checker) { - return ArraySerializationHelper<Handle, true>::ValidateElements< - element_is_nullable, - ElementValidateParams>(header, elements, bounds_checker); - } -}; - -template <typename P> -struct ArraySerializationHelper<P*, false> { - typedef typename ArrayDataTraits<P*>::StorageType ElementType; - - static void EncodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) { - for (uint32_t i = 0; i < header->num_elements; ++i) - Encode(&elements[i], handles); - } - - static void DecodePointersAndHandles(const ArrayHeader* header, - ElementType* elements, - std::vector<Handle>* handles) { - for (uint32_t i = 0; i < header->num_elements; ++i) - Decode(&elements[i], handles); - } - - template <bool element_is_nullable, typename ElementValidateParams> - static bool ValidateElements(const ArrayHeader* header, - const ElementType* elements, - BoundsChecker* bounds_checker) { - for (uint32_t i = 0; i < header->num_elements; ++i) { - if (!element_is_nullable && !elements[i].offset) { - ReportValidationError( - VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - MakeMessageWithArrayIndex("null in array expecting valid pointers", - header->num_elements, - i).c_str()); - return false; - } - if (!ValidateEncodedPointer(&elements[i].offset)) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_POINTER); - return false; - } - if (!ValidateCaller<P, ElementValidateParams>::Run( - DecodePointerRaw(&elements[i].offset), bounds_checker)) { - return false; - } - } - return true; - } - - private: - template <typename T, typename Params> - struct ValidateCaller { - static bool Run(const void* data, BoundsChecker* bounds_checker) { - static_assert((IsSame<Params, NoValidateParams>::value), - "Struct type should not have array validate params"); - - return T::Validate(data, bounds_checker); - } - }; - - template <typename Key, typename Value, typename Params> - struct ValidateCaller<Map_Data<Key, Value>, Params> { - static bool Run(const void* data, BoundsChecker* bounds_checker) { - return Map_Data<Key, Value>::template Validate<Params>(data, - bounds_checker); - } - }; - - template <typename T, typename Params> - struct ValidateCaller<Array_Data<T>, Params> { - static bool Run(const void* data, BoundsChecker* bounds_checker) { - return Array_Data<T>::template Validate<Params>(data, bounds_checker); - } - }; -}; - -template <typename T> -class Array_Data { - public: - typedef ArrayDataTraits<T> Traits; - typedef typename Traits::StorageType StorageType; - typedef typename Traits::Ref Ref; - typedef typename Traits::ConstRef ConstRef; - typedef ArraySerializationHelper<T, IsHandle<T>::value> Helper; - - // Returns null if |num_elements| or the corresponding storage size cannot be - // stored in uint32_t. - static Array_Data<T>* New(size_t num_elements, Buffer* buf) { - if (num_elements > Traits::kMaxNumElements) - return nullptr; - - uint32_t num_bytes = - Traits::GetStorageSize(static_cast<uint32_t>(num_elements)); - return new (buf->Allocate(num_bytes)) - Array_Data<T>(num_bytes, static_cast<uint32_t>(num_elements)); - } - - template <typename Params> - static bool Validate(const void* data, BoundsChecker* bounds_checker) { - if (!data) - return true; - if (!IsAligned(data)) { - ReportValidationError(VALIDATION_ERROR_MISALIGNED_OBJECT); - return false; - } - if (!bounds_checker->IsValidRange(data, sizeof(ArrayHeader))) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); - return false; - } - const ArrayHeader* header = static_cast<const ArrayHeader*>(data); - if (header->num_elements > Traits::kMaxNumElements || - header->num_bytes < Traits::GetStorageSize(header->num_elements)) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER); - return false; - } - if (Params::expected_num_elements != 0 && - header->num_elements != Params::expected_num_elements) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER, - MakeMessageWithExpectedArraySize( - "fixed-size array has wrong number of elements", - header->num_elements, - Params::expected_num_elements).c_str()); - return false; - } - if (!bounds_checker->ClaimMemory(data, header->num_bytes)) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); - return false; - } - - const Array_Data<T>* object = static_cast<const Array_Data<T>*>(data); - return Helper::template ValidateElements< - Params::element_is_nullable, - typename Params::ElementValidateParams>( - &object->header_, object->storage(), bounds_checker); - } - - size_t size() const { return header_.num_elements; } - - Ref at(size_t offset) { - MOJO_DCHECK(offset < static_cast<size_t>(header_.num_elements)); - return Traits::ToRef(storage(), offset); - } - - ConstRef at(size_t offset) const { - MOJO_DCHECK(offset < static_cast<size_t>(header_.num_elements)); - return Traits::ToConstRef(storage(), offset); - } - - StorageType* storage() { - return reinterpret_cast<StorageType*>(reinterpret_cast<char*>(this) + - sizeof(*this)); - } - - const StorageType* storage() const { - return reinterpret_cast<const StorageType*>( - reinterpret_cast<const char*>(this) + sizeof(*this)); - } - - void EncodePointersAndHandles(std::vector<Handle>* handles) { - Helper::EncodePointersAndHandles(&header_, storage(), handles); - } - - void DecodePointersAndHandles(std::vector<Handle>* handles) { - Helper::DecodePointersAndHandles(&header_, storage(), handles); - } - - private: - Array_Data(uint32_t num_bytes, uint32_t num_elements) { - header_.num_bytes = num_bytes; - header_.num_elements = num_elements; - } - ~Array_Data() = delete; - - internal::ArrayHeader header_; - - // Elements of type internal::ArrayDataTraits<T>::StorageType follow. -}; -static_assert(sizeof(Array_Data<char>) == 8, "Bad sizeof(Array_Data)"); - -// UTF-8 encoded -typedef Array_Data<char> String_Data; - -template <typename T, bool kIsMoveOnlyType> -struct ArrayTraits {}; - -template <typename T> -struct ArrayTraits<T, false> { - typedef T StorageType; - typedef typename std::vector<T>::reference RefType; - typedef typename std::vector<T>::const_reference ConstRefType; - typedef ConstRefType ForwardType; - static inline void Initialize(std::vector<T>* vec) {} - static inline void Finalize(std::vector<T>* vec) {} - static inline ConstRefType at(const std::vector<T>* vec, size_t offset) { - return vec->at(offset); - } - static inline RefType at(std::vector<T>* vec, size_t offset) { - return vec->at(offset); - } - static inline void Resize(std::vector<T>* vec, size_t size) { - vec->resize(size); - } - static inline void PushBack(std::vector<T>* vec, ForwardType value) { - vec->push_back(value); - } - static inline void Clone(const std::vector<T>& src_vec, - std::vector<T>* dest_vec) { - dest_vec->assign(src_vec.begin(), src_vec.end()); - } -}; - -template <typename T> -struct ArrayTraits<T, true> { - struct StorageType { - char buf[sizeof(T) + (8 - (sizeof(T) % 8)) % 8]; // Make 8-byte aligned. - }; - typedef T& RefType; - typedef const T& ConstRefType; - typedef T ForwardType; - static inline void Initialize(std::vector<StorageType>* vec) { - for (size_t i = 0; i < vec->size(); ++i) - new (vec->at(i).buf) T(); - } - static inline void Finalize(std::vector<StorageType>* vec) { - for (size_t i = 0; i < vec->size(); ++i) - reinterpret_cast<T*>(vec->at(i).buf)->~T(); - } - static inline ConstRefType at(const std::vector<StorageType>* vec, - size_t offset) { - return *reinterpret_cast<const T*>(vec->at(offset).buf); - } - static inline RefType at(std::vector<StorageType>* vec, size_t offset) { - return *reinterpret_cast<T*>(vec->at(offset).buf); - } - static inline void Resize(std::vector<StorageType>* vec, size_t size) { - size_t old_size = vec->size(); - for (size_t i = size; i < old_size; i++) - reinterpret_cast<T*>(vec->at(i).buf)->~T(); - ResizeStorage(vec, size); - for (size_t i = old_size; i < vec->size(); i++) - new (vec->at(i).buf) T(); - } - static inline void PushBack(std::vector<StorageType>* vec, RefType value) { - size_t old_size = vec->size(); - ResizeStorage(vec, old_size + 1); - new (vec->at(old_size).buf) T(value.Pass()); - } - static inline void ResizeStorage(std::vector<StorageType>* vec, size_t size) { - if (size <= vec->capacity()) { - vec->resize(size); - return; - } - std::vector<StorageType> new_storage(size); - for (size_t i = 0; i < vec->size(); i++) - new (new_storage.at(i).buf) T(at(vec, i).Pass()); - vec->swap(new_storage); - Finalize(&new_storage); - } - static inline void Clone(const std::vector<StorageType>& src_vec, - std::vector<StorageType>* dest_vec) { - Resize(dest_vec, src_vec.size()); - for (size_t i = 0; i < src_vec.size(); ++i) - at(dest_vec, i) = at(&src_vec, i).Clone(); - } -}; - -template <> -struct WrapperTraits<String, false> { - typedef String_Data* DataType; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_ARRAY_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/array_serialization.h b/mojo/public/cpp/bindings/lib/array_serialization.h deleted file mode 100644 index eacf298..0000000 --- a/mojo/public/cpp/bindings/lib/array_serialization.h +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_ARRAY_SERIALIZATION_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_ARRAY_SERIALIZATION_H_ - -#include <string.h> // For |memcpy()|. - -#include <vector> - -#include "mojo/public/c/system/macros.h" -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/lib/map_serialization.h" -#include "mojo/public/cpp/bindings/lib/string_serialization.h" -#include "mojo/public/cpp/bindings/lib/template_util.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" - -namespace mojo { - -template <typename E> -inline size_t GetSerializedSize_(const Array<E>& input); - -// Because ValidateParams requires explicit argument specification, the -// argument-dependent loopup technique used to omit namespace when calling -// Serialize_() doesn't seem to work. Therefore, this function is named -// differently from those Serialize_() overloads. -template <typename ValidateParams, typename E, typename F> -inline void SerializeArray_(Array<E> input, - internal::Buffer* buf, - internal::Array_Data<F>** output); - -template <typename ValueValidateParams, - typename KeyWrapperType, - typename ValueWrapperType, - typename KeySerializationType, - typename ValueSerializationType> -inline void SerializeMap_( - Map<KeyWrapperType, ValueWrapperType> input, - internal::Buffer* buf, - internal::Map_Data<KeySerializationType, ValueSerializationType>** output); - -template <typename E, typename F> -inline void Deserialize_(internal::Array_Data<F>* data, Array<E>* output); - -namespace internal { - -template <typename E, typename F, bool move_only = IsMoveOnlyType<E>::value> -struct ArraySerializer; - -template <typename E, typename F> -struct ArraySerializer<E, F, false> { - static_assert(sizeof(E) == sizeof(F), "Incorrect array serializer"); - static size_t GetSerializedSize(const Array<E>& input) { - return sizeof(Array_Data<F>) + Align(input.size() * sizeof(E)); - } - template <bool element_is_nullable, typename ElementValidateParams> - static void SerializeElements(Array<E> input, - Buffer* buf, - Array_Data<F>* output) { - static_assert(!element_is_nullable, - "Primitive type should be non-nullable"); - static_assert((IsSame<ElementValidateParams, NoValidateParams>::value), - "Primitive type should not have array validate params"); - - if (input.size()) - memcpy(output->storage(), &input.storage()[0], input.size() * sizeof(E)); - } - static void DeserializeElements(Array_Data<F>* input, Array<E>* output) { - std::vector<E> result(input->size()); - if (input->size()) - memcpy(&result[0], input->storage(), input->size() * sizeof(E)); - output->Swap(&result); - } -}; - -template <> -struct ArraySerializer<bool, bool, false> { - static size_t GetSerializedSize(const Array<bool>& input) { - return sizeof(Array_Data<bool>) + Align((input.size() + 7) / 8); - } - template <bool element_is_nullable, typename ElementValidateParams> - static void SerializeElements(Array<bool> input, - Buffer* buf, - Array_Data<bool>* output) { - static_assert(!element_is_nullable, - "Primitive type should be non-nullable"); - static_assert((IsSame<ElementValidateParams, NoValidateParams>::value), - "Primitive type should not have array validate params"); - - // TODO(darin): Can this be a memcpy somehow instead of a bit-by-bit copy? - for (size_t i = 0; i < input.size(); ++i) - output->at(i) = input[i]; - } - static void DeserializeElements(Array_Data<bool>* input, - Array<bool>* output) { - Array<bool> result(input->size()); - // TODO(darin): Can this be a memcpy somehow instead of a bit-by-bit copy? - for (size_t i = 0; i < input->size(); ++i) - result.at(i) = input->at(i); - output->Swap(&result); - } -}; - -template <typename H> -struct ArraySerializer<ScopedHandleBase<H>, H, true> { - static size_t GetSerializedSize(const Array<ScopedHandleBase<H>>& input) { - return sizeof(Array_Data<H>) + Align(input.size() * sizeof(H)); - } - template <bool element_is_nullable, typename ElementValidateParams> - static void SerializeElements(Array<ScopedHandleBase<H>> input, - Buffer* buf, - Array_Data<H>* output) { - static_assert((IsSame<ElementValidateParams, NoValidateParams>::value), - "Handle type should not have array validate params"); - - for (size_t i = 0; i < input.size(); ++i) { - output->at(i) = input[i].release(); // Transfer ownership of the handle. - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !element_is_nullable && !output->at(i).is_valid(), - VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, - MakeMessageWithArrayIndex( - "invalid handle in array expecting valid handles", - input.size(), - i)); - } - } - static void DeserializeElements(Array_Data<H>* input, - Array<ScopedHandleBase<H>>* output) { - Array<ScopedHandleBase<H>> result(input->size()); - for (size_t i = 0; i < input->size(); ++i) - result.at(i) = MakeScopedHandle(FetchAndReset(&input->at(i))); - output->Swap(&result); - } -}; - -// This template must only apply to pointer mojo entity (structs and arrays). -// This is done by ensuring that WrapperTraits<S>::DataType is a pointer. -template <typename S> -struct ArraySerializer<S, - typename internal::EnableIf< - internal::IsPointer<typename internal::WrapperTraits< - S>::DataType>::value, - typename internal::WrapperTraits<S>::DataType>::type, - true> { - typedef typename internal::RemovePointer< - typename internal::WrapperTraits<S>::DataType>::type S_Data; - static size_t GetSerializedSize(const Array<S>& input) { - size_t size = sizeof(Array_Data<S_Data*>) + - input.size() * sizeof(internal::StructPointer<S_Data>); - for (size_t i = 0; i < input.size(); ++i) - size += GetSerializedSize_(input[i]); - return size; - } - template <bool element_is_nullable, typename ElementValidateParams> - static void SerializeElements(Array<S> input, - Buffer* buf, - Array_Data<S_Data*>* output) { - for (size_t i = 0; i < input.size(); ++i) { - S_Data* element; - SerializeCaller<S, ElementValidateParams>::Run( - input[i].Pass(), buf, &element); - output->at(i) = element; - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !element_is_nullable && !element, - VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - MakeMessageWithArrayIndex( - "null in array expecting valid pointers", input.size(), i)); - } - } - static void DeserializeElements(Array_Data<S_Data*>* input, - Array<S>* output) { - Array<S> result(input->size()); - for (size_t i = 0; i < input->size(); ++i) { - S element; - Deserialize_(input->at(i), &element); - result[i] = element.Pass(); - } - output->Swap(&result); - } - - private: - template <typename T, typename Params> - struct SerializeCaller { - static void Run(T input, - Buffer* buf, - typename internal::WrapperTraits<T>::DataType* output) { - static_assert((IsSame<Params, NoValidateParams>::value), - "Struct type should not have array validate params"); - - Serialize_(input.Pass(), buf, output); - } - }; - - template <typename T, typename Params> - struct SerializeCaller<Array<T>, Params> { - static void Run(Array<T> input, - Buffer* buf, - typename Array<T>::Data_** output) { - SerializeArray_<Params>(input.Pass(), buf, output); - } - }; - - template <typename T, typename U, typename Params> - struct SerializeCaller<Map<T, U>, Params> { - static void Run(Map<T, U> input, - Buffer* buf, - typename Map<T, U>::Data_** output) { - SerializeMap_<Params>(input.Pass(), buf, output); - } - }; -}; - -template <> -struct ArraySerializer<String, String_Data*, false> { - static size_t GetSerializedSize(const Array<String>& input) { - size_t size = sizeof(Array_Data<String_Data*>) + - input.size() * sizeof(internal::StringPointer); - for (size_t i = 0; i < input.size(); ++i) - size += GetSerializedSize_(input[i]); - return size; - } - template <bool element_is_nullable, typename ElementValidateParams> - static void SerializeElements(Array<String> input, - Buffer* buf, - Array_Data<String_Data*>* output) { - static_assert( - (IsSame<ElementValidateParams, - ArrayValidateParams<0, false, NoValidateParams>>::value), - "String type has unexpected array validate params"); - - for (size_t i = 0; i < input.size(); ++i) { - String_Data* element; - Serialize_(input[i], buf, &element); - output->at(i) = element; - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - !element_is_nullable && !element, - VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - MakeMessageWithArrayIndex( - "null in array expecting valid strings", input.size(), i)); - } - } - static void DeserializeElements(Array_Data<String_Data*>* input, - Array<String>* output) { - Array<String> result(input->size()); - for (size_t i = 0; i < input->size(); ++i) - Deserialize_(input->at(i), &result[i]); - output->Swap(&result); - } -}; - -} // namespace internal - -template <typename E> -inline size_t GetSerializedSize_(const Array<E>& input) { - if (!input) - return 0; - typedef typename internal::WrapperTraits<E>::DataType F; - return internal::ArraySerializer<E, F>::GetSerializedSize(input); -} - -template <typename ValidateParams, typename E, typename F> -inline void SerializeArray_(Array<E> input, - internal::Buffer* buf, - internal::Array_Data<F>** output) { - if (input) { - MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( - ValidateParams::expected_num_elements != 0 && - input.size() != ValidateParams::expected_num_elements, - internal::VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER, - internal::MakeMessageWithExpectedArraySize( - "fixed-size array has wrong number of elements", - input.size(), - ValidateParams::expected_num_elements)); - - internal::Array_Data<F>* result = - internal::Array_Data<F>::New(input.size(), buf); - if (result) { - internal::ArraySerializer<E, F>::template SerializeElements< - ValidateParams::element_is_nullable, - typename ValidateParams::ElementValidateParams>( - internal::Forward(input), buf, result); - } - *output = result; - } else { - *output = nullptr; - } -} - -template <typename E, typename F> -inline void Deserialize_(internal::Array_Data<F>* input, Array<E>* output) { - if (input) { - internal::ArraySerializer<E, F>::DeserializeElements(input, output); - } else { - output->reset(); - } -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_ARRAY_SERIALIZATION_H_ diff --git a/mojo/public/cpp/bindings/lib/bindings_internal.h b/mojo/public/cpp/bindings/lib/bindings_internal.h deleted file mode 100644 index ec70d37..0000000 --- a/mojo/public/cpp/bindings/lib/bindings_internal.h +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_INTERNAL_H_ - -#include "mojo/public/cpp/bindings/lib/template_util.h" -#include "mojo/public/cpp/bindings/struct_ptr.h" -#include "mojo/public/cpp/system/core.h" - -namespace mojo { -class String; - -template <typename T> -class Array; - -template <typename K, typename V> -class Map; - -namespace internal { -template <typename T> -class Array_Data; - -#pragma pack(push, 1) - -struct StructHeader { - uint32_t num_bytes; - uint32_t num_fields; -}; -static_assert(sizeof(StructHeader) == 8, "Bad sizeof(StructHeader)"); - -struct ArrayHeader { - uint32_t num_bytes; - uint32_t num_elements; -}; -static_assert(sizeof(ArrayHeader) == 8, "Bad_sizeof(ArrayHeader)"); - -template <typename T> -union StructPointer { - uint64_t offset; - T* ptr; -}; -static_assert(sizeof(StructPointer<char>) == 8, "Bad_sizeof(StructPointer)"); - -template <typename T> -union ArrayPointer { - uint64_t offset; - Array_Data<T>* ptr; -}; -static_assert(sizeof(ArrayPointer<char>) == 8, "Bad_sizeof(ArrayPointer)"); - -union StringPointer { - uint64_t offset; - Array_Data<char>* ptr; -}; -static_assert(sizeof(StringPointer) == 8, "Bad_sizeof(StringPointer)"); - -#pragma pack(pop) - -template <typename T> -void ResetIfNonNull(T* ptr) { - if (ptr) - *ptr = T(); -} - -template <typename T> -T FetchAndReset(T* ptr) { - T temp = *ptr; - *ptr = T(); - return temp; -} - -template <typename H> -struct IsHandle { - enum { value = IsBaseOf<Handle, H>::value }; -}; - -template <typename T, bool move_only = IsMoveOnlyType<T>::value> -struct WrapperTraits; - -template <typename T> -struct WrapperTraits<T, false> { - typedef T DataType; -}; -template <typename H> -struct WrapperTraits<ScopedHandleBase<H>, true> { - typedef H DataType; -}; -template <typename S> -struct WrapperTraits<StructPtr<S>, true> { - typedef typename S::Data_* DataType; -}; -template <typename S> -struct WrapperTraits<InlinedStructPtr<S>, true> { - typedef typename S::Data_* DataType; -}; -template <typename S> -struct WrapperTraits<S, true> { - typedef typename S::Data_* DataType; -}; - -template <typename T, typename Enable = void> -struct ValueTraits { - static bool Equals(const T& a, const T& b) { return a == b; } -}; - -template <typename T> -struct ValueTraits< - T, - typename EnableIf<IsSpecializationOf<Array, T>::value || - IsSpecializationOf<Map, T>::value || - IsSpecializationOf<StructPtr, T>::value || - IsSpecializationOf<InlinedStructPtr, T>::value>::type> { - static bool Equals(const T& a, const T& b) { return a.Equals(b); } -}; - -template <typename T> -struct ValueTraits<ScopedHandleBase<T>> { - static bool Equals(const ScopedHandleBase<T>& a, - const ScopedHandleBase<T>& b) { - return a.get().value() == b.get().value(); - } -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/bindings_serialization.cc b/mojo/public/cpp/bindings/lib/bindings_serialization.cc deleted file mode 100644 index 936d0ca..0000000 --- a/mojo/public/cpp/bindings/lib/bindings_serialization.cc +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" - -#include "mojo/public/cpp/bindings/lib/bindings_internal.h" -#include "mojo/public/cpp/bindings/lib/bounds_checker.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { - -namespace { - -const size_t kAlignment = 8; - -template <typename T> -T AlignImpl(T t) { - return t + (kAlignment - (t % kAlignment)) % kAlignment; -} - -} // namespace - -size_t Align(size_t size) { - return AlignImpl(size); -} - -char* AlignPointer(char* ptr) { - return reinterpret_cast<char*>(AlignImpl(reinterpret_cast<uintptr_t>(ptr))); -} - -bool IsAligned(const void* ptr) { - return !(reinterpret_cast<uintptr_t>(ptr) % kAlignment); -} - -void EncodePointer(const void* ptr, uint64_t* offset) { - if (!ptr) { - *offset = 0; - return; - } - - const char* p_obj = reinterpret_cast<const char*>(ptr); - const char* p_slot = reinterpret_cast<const char*>(offset); - MOJO_DCHECK(p_obj > p_slot); - - *offset = static_cast<uint64_t>(p_obj - p_slot); -} - -const void* DecodePointerRaw(const uint64_t* offset) { - if (!*offset) - return nullptr; - return reinterpret_cast<const char*>(offset) + *offset; -} - -bool ValidateEncodedPointer(const uint64_t* offset) { - // Cast to uintptr_t so overflow behavior is well defined. - return reinterpret_cast<uintptr_t>(offset) + *offset >= - reinterpret_cast<uintptr_t>(offset); -} - -void EncodeHandle(Handle* handle, std::vector<Handle>* handles) { - if (handle->is_valid()) { - handles->push_back(*handle); - handle->set_value(static_cast<MojoHandle>(handles->size() - 1)); - } else { - handle->set_value(kEncodedInvalidHandleValue); - } -} - -void DecodeHandle(Handle* handle, std::vector<Handle>* handles) { - if (handle->value() == kEncodedInvalidHandleValue) { - *handle = Handle(); - return; - } - MOJO_DCHECK(handle->value() < handles->size()); - // Just leave holes in the vector so we don't screw up other indices. - *handle = FetchAndReset(&handles->at(handle->value())); -} - -bool ValidateStructHeader(const void* data, - uint32_t min_num_bytes, - uint32_t min_num_fields, - BoundsChecker* bounds_checker) { - MOJO_DCHECK(min_num_bytes >= sizeof(StructHeader)); - - if (!IsAligned(data)) { - ReportValidationError(VALIDATION_ERROR_MISALIGNED_OBJECT); - return false; - } - if (!bounds_checker->IsValidRange(data, sizeof(StructHeader))) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); - return false; - } - - const StructHeader* header = static_cast<const StructHeader*>(data); - - // TODO(yzshen): Currently our binding code cannot handle structs of smaller - // size or with fewer fields than the version that it sees. That needs to be - // changed in order to provide backward compatibility. - if (header->num_bytes < min_num_bytes || - header->num_fields < min_num_fields) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); - return false; - } - - if (!bounds_checker->ClaimMemory(data, header->num_bytes)) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE); - return false; - } - - return true; -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/bindings_serialization.h b/mojo/public/cpp/bindings/lib/bindings_serialization.h deleted file mode 100644 index 6bebf90..0000000 --- a/mojo/public/cpp/bindings/lib/bindings_serialization.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_ - -#include <vector> - -#include "mojo/public/cpp/system/core.h" - -namespace mojo { -namespace internal { - -class BoundsChecker; - -// Please note that this is a different value than |mojo::kInvalidHandleValue|, -// which is the "decoded" invalid handle. -const MojoHandle kEncodedInvalidHandleValue = static_cast<MojoHandle>(-1); - -size_t Align(size_t size); -char* AlignPointer(char* ptr); - -bool IsAligned(const void* ptr); - -// Pointers are encoded as relative offsets. The offsets are relative to the -// address of where the offset value is stored, such that the pointer may be -// recovered with the expression: -// -// ptr = reinterpret_cast<char*>(offset) + *offset -// -// A null pointer is encoded as an offset value of 0. -// -void EncodePointer(const void* ptr, uint64_t* offset); -// Note: This function doesn't validate the encoded pointer value. -const void* DecodePointerRaw(const uint64_t* offset); - -// Note: This function doesn't validate the encoded pointer value. -template <typename T> -inline void DecodePointer(const uint64_t* offset, T** ptr) { - *ptr = reinterpret_cast<T*>(const_cast<void*>(DecodePointerRaw(offset))); -} - -// Checks whether decoding the pointer will overflow and produce a pointer -// smaller than |offset|. -bool ValidateEncodedPointer(const uint64_t* offset); - -// Handles are encoded as indices into a vector of handles. These functions -// manipulate the value of |handle|, mapping it to and from an index. -void EncodeHandle(Handle* handle, std::vector<Handle>* handles); -// Note: This function doesn't validate the encoded handle value. -void DecodeHandle(Handle* handle, std::vector<Handle>* handles); - -// The following 2 functions are used to encode/decode all objects (structs and -// arrays) in a consistent manner. - -template <typename T> -inline void Encode(T* obj, std::vector<Handle>* handles) { - if (obj->ptr) - obj->ptr->EncodePointersAndHandles(handles); - EncodePointer(obj->ptr, &obj->offset); -} - -// Note: This function doesn't validate the encoded pointer and handle values. -template <typename T> -inline void Decode(T* obj, std::vector<Handle>* handles) { - DecodePointer(&obj->offset, &obj->ptr); - if (obj->ptr) - obj->ptr->DecodePointersAndHandles(handles); -} - -// If returns true, this function also claims the memory range of the size -// specified in the struct header, starting from |data|. -// Note: |min_num_bytes| must be no less than sizeof(StructHeader). -bool ValidateStructHeader(const void* data, - uint32_t min_num_bytes, - uint32_t min_num_fields, - BoundsChecker* bounds_checker); - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BINDINGS_SERIALIZATION_H_ diff --git a/mojo/public/cpp/bindings/lib/bounds_checker.cc b/mojo/public/cpp/bindings/lib/bounds_checker.cc deleted file mode 100644 index 5b96b2d..0000000 --- a/mojo/public/cpp/bindings/lib/bounds_checker.cc +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/bounds_checker.h" - -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/environment/logging.h" -#include "mojo/public/cpp/system/handle.h" - -namespace mojo { -namespace internal { - -BoundsChecker::BoundsChecker(const void* data, - uint32_t data_num_bytes, - size_t num_handles) - : data_begin_(reinterpret_cast<uintptr_t>(data)), - data_end_(data_begin_ + data_num_bytes), - handle_begin_(0), - handle_end_(static_cast<uint32_t>(num_handles)) { - if (data_end_ < data_begin_) { - // The calculation of |data_end_| overflowed. - // It shouldn't happen but if it does, set the range to empty so - // IsValidRange() and ClaimMemory() always fail. - MOJO_DCHECK(false) << "Not reached"; - data_end_ = data_begin_; - } - if (handle_end_ < num_handles) { - // Assigning |num_handles| to |handle_end_| overflowed. - // It shouldn't happen but if it does, set the handle index range to empty. - MOJO_DCHECK(false) << "Not reached"; - handle_end_ = 0; - } -} - -BoundsChecker::~BoundsChecker() { -} - -bool BoundsChecker::ClaimMemory(const void* position, uint32_t num_bytes) { - uintptr_t begin = reinterpret_cast<uintptr_t>(position); - uintptr_t end = begin + num_bytes; - - if (!InternalIsValidRange(begin, end)) - return false; - - data_begin_ = end; - return true; -} - -bool BoundsChecker::ClaimHandle(const Handle& encoded_handle) { - uint32_t index = encoded_handle.value(); - if (index == kEncodedInvalidHandleValue) - return true; - - if (index < handle_begin_ || index >= handle_end_) - return false; - - // |index| + 1 shouldn't overflow, because |index| is not the max value of - // uint32_t (it is less than |handle_end_|). - handle_begin_ = index + 1; - return true; -} - -bool BoundsChecker::IsValidRange(const void* position, - uint32_t num_bytes) const { - uintptr_t begin = reinterpret_cast<uintptr_t>(position); - uintptr_t end = begin + num_bytes; - - return InternalIsValidRange(begin, end); -} - -bool BoundsChecker::InternalIsValidRange(uintptr_t begin, uintptr_t end) const { - return end > begin && begin >= data_begin_ && end <= data_end_; -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/bounds_checker.h b/mojo/public/cpp/bindings/lib/bounds_checker.h deleted file mode 100644 index f0520be..0000000 --- a/mojo/public/cpp/bindings/lib/bounds_checker.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BOUNDS_CHECKER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_BOUNDS_CHECKER_H_ - -#include <stdint.h> - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -class Handle; - -namespace internal { - -// BoundsChecker is used to validate object sizes, pointers and handle indices -// for payload of incoming messages. -class BoundsChecker { - public: - // [data, data + data_num_bytes) specifies the initial valid memory range. - // [0, num_handles) specifies the initial valid range of handle indices. - BoundsChecker(const void* data, uint32_t data_num_bytes, size_t num_handles); - - ~BoundsChecker(); - - // Claims the specified memory range. - // The method succeeds if the range is valid to claim. (Please see - // the comments for IsValidRange().) - // On success, the valid memory range is shrinked to begin right after the end - // of the claimed range. - bool ClaimMemory(const void* position, uint32_t num_bytes); - - // Claims the specified encoded handle (which is basically a handle index). - // The method succeeds if: - // - |encoded_handle|'s value is |kEncodedInvalidHandleValue|. - // - the handle is contained inside the valid range of handle indices. In this - // case, the valid range is shinked to begin right after the claimed handle. - bool ClaimHandle(const Handle& encoded_handle); - - // Returns true if the specified range is not empty, and the range is - // contained inside the valid memory range. - bool IsValidRange(const void* position, uint32_t num_bytes) const; - - private: - bool InternalIsValidRange(uintptr_t begin, uintptr_t end) const; - - // [data_begin_, data_end_) is the valid memory range. - uintptr_t data_begin_; - uintptr_t data_end_; - - // [handle_begin_, handle_end_) is the valid handle index range. - uint32_t handle_begin_; - uint32_t handle_end_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(BoundsChecker); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BOUNDS_CHECKER_H_ diff --git a/mojo/public/cpp/bindings/lib/buffer.h b/mojo/public/cpp/bindings/lib/buffer.h deleted file mode 100644 index c3b570e..0000000 --- a/mojo/public/cpp/bindings/lib/buffer.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ - -#include <stddef.h> - -namespace mojo { -namespace internal { - -// Buffer provides a way to allocate memory. Allocations are 8-byte aligned and -// zero-initialized. Allocations remain valid for the lifetime of the Buffer. -class Buffer { - public: - virtual ~Buffer() {} - virtual void* Allocate(size_t num_bytes) = 0; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_BUFFER_H_ diff --git a/mojo/public/cpp/bindings/lib/callback_internal.h b/mojo/public/cpp/bindings/lib/callback_internal.h deleted file mode 100644 index f76ebef..0000000 --- a/mojo/public/cpp/bindings/lib/callback_internal.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_CALLBACK_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_CALLBACK_INTERNAL_H_ - -namespace mojo { -class String; - -namespace internal { - -template <typename T> -struct Callback_ParamTraits { - typedef T ForwardType; -}; - -template <> -struct Callback_ParamTraits<String> { - typedef const String& ForwardType; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_CALLBACK_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/connector.cc b/mojo/public/cpp/bindings/lib/connector.cc deleted file mode 100644 index 4f965ee2..0000000 --- a/mojo/public/cpp/bindings/lib/connector.cc +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/connector.h" - -#include "mojo/public/cpp/bindings/error_handler.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { - -// ---------------------------------------------------------------------------- - -Connector::Connector(ScopedMessagePipeHandle message_pipe, - const MojoAsyncWaiter* waiter) - : error_handler_(nullptr), - waiter_(waiter), - message_pipe_(message_pipe.Pass()), - incoming_receiver_(nullptr), - async_wait_id_(0), - error_(false), - drop_writes_(false), - enforce_errors_from_incoming_receiver_(true), - destroyed_flag_(nullptr) { - // Even though we don't have an incoming receiver, we still want to monitor - // the message pipe to know if is closed or encounters an error. - WaitToReadMore(); -} - -Connector::~Connector() { - if (destroyed_flag_) - *destroyed_flag_ = true; - - CancelWait(); -} - -void Connector::CloseMessagePipe() { - CancelWait(); - Close(message_pipe_.Pass()); -} - -ScopedMessagePipeHandle Connector::PassMessagePipe() { - CancelWait(); - return message_pipe_.Pass(); -} - -bool Connector::WaitForIncomingMessage() { - if (error_) - return false; - - MojoResult rv = Wait(message_pipe_.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, - nullptr); - if (rv != MOJO_RESULT_OK) { - NotifyError(); - return false; - } - mojo_ignore_result(ReadSingleMessage(&rv)); - return (rv == MOJO_RESULT_OK); -} - -bool Connector::Accept(Message* message) { - MOJO_CHECK(message_pipe_.is_valid()); - - if (error_) - return false; - - if (drop_writes_) - return true; - - MojoResult rv = - WriteMessageRaw(message_pipe_.get(), - message->data(), - message->data_num_bytes(), - message->mutable_handles()->empty() - ? nullptr - : reinterpret_cast<const MojoHandle*>( - &message->mutable_handles()->front()), - static_cast<uint32_t>(message->mutable_handles()->size()), - MOJO_WRITE_MESSAGE_FLAG_NONE); - - switch (rv) { - case MOJO_RESULT_OK: - // The handles were successfully transferred, so we don't need the message - // to track their lifetime any longer. - message->mutable_handles()->clear(); - break; - case MOJO_RESULT_FAILED_PRECONDITION: - // There's no point in continuing to write to this pipe since the other - // end is gone. Avoid writing any future messages. Hide write failures - // from the caller since we'd like them to continue consuming any backlog - // of incoming messages before regarding the message pipe as closed. - drop_writes_ = true; - break; - case MOJO_RESULT_BUSY: - // We'd get a "busy" result if one of the message's handles is: - // - |message_pipe_|'s own handle; - // - simultaneously being used on another thread; or - // - in a "busy" state that prohibits it from being transferred (e.g., - // a data pipe handle in the middle of a two-phase read/write, - // regardless of which thread that two-phase read/write is happening - // on). - // TODO(vtl): I wonder if this should be a |MOJO_DCHECK()|. (But, until - // crbug.com/389666, etc. are resolved, this will make tests fail quickly - // rather than hanging.) - MOJO_CHECK(false) << "Race condition or other bug detected"; - return false; - default: - // This particular write was rejected, presumably because of bad input. - // The pipe is not necessarily in a bad state. - return false; - } - return true; -} - -// static -void Connector::CallOnHandleReady(void* closure, MojoResult result) { - Connector* self = static_cast<Connector*>(closure); - self->OnHandleReady(result); -} - -void Connector::OnHandleReady(MojoResult result) { - MOJO_CHECK(async_wait_id_ != 0); - async_wait_id_ = 0; - if (result != MOJO_RESULT_OK) { - NotifyError(); - return; - } - ReadAllAvailableMessages(); - // At this point, this object might have been deleted. Return. -} - -void Connector::WaitToReadMore() { - MOJO_CHECK(!async_wait_id_); - async_wait_id_ = waiter_->AsyncWait(message_pipe_.get().value(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, - &Connector::CallOnHandleReady, - this); -} - -bool Connector::ReadSingleMessage(MojoResult* read_result) { - bool receiver_result = false; - - // Detect if |this| was destroyed during message dispatch. Allow for the - // possibility of re-entering ReadMore() through message dispatch. - bool was_destroyed_during_dispatch = false; - bool* previous_destroyed_flag = destroyed_flag_; - destroyed_flag_ = &was_destroyed_during_dispatch; - - MojoResult rv = ReadAndDispatchMessage( - message_pipe_.get(), incoming_receiver_, &receiver_result); - if (read_result) - *read_result = rv; - - if (was_destroyed_during_dispatch) { - if (previous_destroyed_flag) - *previous_destroyed_flag = true; // Propagate flag. - return false; - } - destroyed_flag_ = previous_destroyed_flag; - - if (rv == MOJO_RESULT_SHOULD_WAIT) - return true; - - if (rv != MOJO_RESULT_OK || - (enforce_errors_from_incoming_receiver_ && !receiver_result)) { - NotifyError(); - return false; - } - return true; -} - -void Connector::ReadAllAvailableMessages() { - while (!error_) { - MojoResult rv; - - // Return immediately if |this| was destroyed. Do not touch any members! - if (!ReadSingleMessage(&rv)) - return; - - if (rv == MOJO_RESULT_SHOULD_WAIT) { - WaitToReadMore(); - break; - } - } -} - -void Connector::CancelWait() { - if (!async_wait_id_) - return; - - waiter_->CancelWait(async_wait_id_); - async_wait_id_ = 0; -} - -void Connector::NotifyError() { - error_ = true; - CancelWait(); - if (error_handler_) - error_handler_->OnConnectionError(); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/connector.h b/mojo/public/cpp/bindings/lib/connector.h deleted file mode 100644 index 7c1d445..0000000 --- a/mojo/public/cpp/bindings/lib/connector.h +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_CONNECTOR_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_CONNECTOR_H_ - -#include "mojo/public/c/environment/async_waiter.h" -#include "mojo/public/cpp/bindings/lib/message_queue.h" -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/core.h" - -namespace mojo { -class ErrorHandler; - -namespace internal { - -// The Connector class is responsible for performing read/write operations on a -// MessagePipe. It writes messages it receives through the MessageReceiver -// interface that it subclasses, and it forwards messages it reads through the -// MessageReceiver interface assigned as its incoming receiver. -// -// NOTE: MessagePipe I/O is non-blocking. -// -class Connector : public MessageReceiver { - public: - // The Connector takes ownership of |message_pipe|. - explicit Connector( - ScopedMessagePipeHandle message_pipe, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()); - ~Connector() override; - - // Sets the receiver to handle messages read from the message pipe. The - // Connector will read messages from the pipe regardless of whether or not an - // incoming receiver has been set. - void set_incoming_receiver(MessageReceiver* receiver) { - incoming_receiver_ = receiver; - } - - // Errors from incoming receivers will force the connector into an error - // state, where no more messages will be processed. This method is used - // during testing to prevent that from happening. - void set_enforce_errors_from_incoming_receiver(bool enforce) { - enforce_errors_from_incoming_receiver_ = enforce; - } - - // Sets the error handler to receive notifications when an error is - // encountered while reading from the pipe or waiting to read from the pipe. - void set_error_handler(ErrorHandler* error_handler) { - error_handler_ = error_handler; - } - - // Returns true if an error was encountered while reading from the pipe or - // waiting to read from the pipe. - bool encountered_error() const { return error_; } - - // Closes the pipe, triggering the error state. Connector is put into a - // quiescent state. - void CloseMessagePipe(); - - // Releases the pipe, not triggering the error state. Connector is put into - // a quiescent state. - ScopedMessagePipeHandle PassMessagePipe(); - - // Waits for the next message on the pipe, blocking until one arrives or an - // error happens. Returns |true| if a message has been delivered, |false| - // otherwise. - bool WaitForIncomingMessage(); - - // MessageReceiver implementation: - bool Accept(Message* message) override; - - private: - static void CallOnHandleReady(void* closure, MojoResult result); - void OnHandleReady(MojoResult result); - - void WaitToReadMore(); - - // Returns false if |this| was destroyed during message dispatch. - MOJO_WARN_UNUSED_RESULT bool ReadSingleMessage(MojoResult* read_result); - - // |this| can be destroyed during message dispatch. - void ReadAllAvailableMessages(); - - void NotifyError(); - - // Cancels any calls made to |waiter_|. - void CancelWait(); - - ErrorHandler* error_handler_; - const MojoAsyncWaiter* waiter_; - - ScopedMessagePipeHandle message_pipe_; - MessageReceiver* incoming_receiver_; - - MojoAsyncWaitID async_wait_id_; - bool error_; - bool drop_writes_; - bool enforce_errors_from_incoming_receiver_; - - // If non-null, this will be set to true when the Connector is destroyed. We - // use this flag to allow for the Connector to be destroyed as a side-effect - // of dispatching an incoming message. - bool* destroyed_flag_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(Connector); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_CONNECTOR_H_ diff --git a/mojo/public/cpp/bindings/lib/filter_chain.cc b/mojo/public/cpp/bindings/lib/filter_chain.cc deleted file mode 100644 index d32eb78..0000000 --- a/mojo/public/cpp/bindings/lib/filter_chain.cc +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/filter_chain.h" - -#include <algorithm> - -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { - -FilterChain::FilterChain(MessageReceiver* sink) : sink_(sink) { -} - -FilterChain::FilterChain(FilterChain&& other) : sink_(other.sink_) { - other.sink_ = nullptr; - filters_.swap(other.filters_); -} - -FilterChain& FilterChain::operator=(FilterChain&& other) { - std::swap(sink_, other.sink_); - filters_.swap(other.filters_); - return *this; -} - -FilterChain::~FilterChain() { - for (std::vector<MessageFilter*>::iterator iter = filters_.begin(); - iter != filters_.end(); - ++iter) { - delete *iter; - } -} - -void FilterChain::SetSink(MessageReceiver* sink) { - MOJO_DCHECK(!sink_); - sink_ = sink; - if (!filters_.empty()) - filters_.back()->set_sink(sink); -} - -MessageReceiver* FilterChain::GetHead() { - MOJO_DCHECK(sink_); - return filters_.empty() ? sink_ : filters_.front(); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/filter_chain.h b/mojo/public/cpp/bindings/lib/filter_chain.h deleted file mode 100644 index bd7f9f5..0000000 --- a/mojo/public/cpp/bindings/lib/filter_chain.h +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_FILTER_CHAIN_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_FILTER_CHAIN_H_ - -#include <vector> - -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/bindings/message_filter.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -namespace internal { - -class FilterChain { - MOJO_MOVE_ONLY_TYPE(FilterChain) - - public: - // Doesn't take ownership of |sink|. Therefore |sink| has to stay alive while - // this object is alive. - explicit FilterChain(MessageReceiver* sink = nullptr); - - FilterChain(FilterChain&& other); - FilterChain& operator=(FilterChain&& other); - ~FilterChain(); - - template <typename FilterType> - inline void Append(); - - // Doesn't take ownership of |sink|. Therefore |sink| has to stay alive while - // this object is alive. - void SetSink(MessageReceiver* sink); - - // Returns a receiver to accept messages. Messages flow through all filters in - // the same order as they were appended to the chain. If all filters allow a - // message to pass, it will be forwarded to |sink_|. - // The returned value is invalidated when this object goes away. - MessageReceiver* GetHead(); - - private: - // Owned by this object. - std::vector<MessageFilter*> filters_; - - MessageReceiver* sink_; -}; - -template <typename FilterType> -inline void FilterChain::Append() { - FilterType* filter = new FilterType(sink_); - if (!filters_.empty()) - filters_.back()->set_sink(filter); - filters_.push_back(filter); -} - -template <> -inline void FilterChain::Append<PassThroughFilter>() { -} - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_FILTER_CHAIN_H_ diff --git a/mojo/public/cpp/bindings/lib/fixed_buffer.cc b/mojo/public/cpp/bindings/lib/fixed_buffer.cc deleted file mode 100644 index 980abc3..0000000 --- a/mojo/public/cpp/bindings/lib/fixed_buffer.cc +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/fixed_buffer.h" - -#include <stdlib.h> - -#include <algorithm> - -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { - -FixedBuffer::FixedBuffer(size_t size) - : ptr_(nullptr), cursor_(0), size_(internal::Align(size)) { - // calloc() required to zero memory and thus avoid info leaks. - ptr_ = static_cast<char*>(calloc(size_, 1)); -} - -FixedBuffer::~FixedBuffer() { - free(ptr_); -} - -void* FixedBuffer::Allocate(size_t delta) { - delta = internal::Align(delta); - - if (delta == 0 || delta > size_ - cursor_) { - MOJO_DCHECK(false) << "Not reached"; - return nullptr; - } - - char* result = ptr_ + cursor_; - cursor_ += delta; - - return result; -} - -void* FixedBuffer::Leak() { - char* ptr = ptr_; - ptr_ = nullptr; - cursor_ = 0; - size_ = 0; - return ptr; -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/fixed_buffer.h b/mojo/public/cpp/bindings/lib/fixed_buffer.h deleted file mode 100644 index c6cf34e..0000000 --- a/mojo/public/cpp/bindings/lib/fixed_buffer.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_FIXED_BUFFER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_FIXED_BUFFER_H_ - -#include "mojo/public/cpp/bindings/lib/buffer.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -namespace internal { - -// FixedBuffer provides a simple way to allocate objects within a fixed chunk -// of memory. Objects are allocated by calling the |Allocate| method, which -// extends the buffer accordingly. Objects allocated in this way are not freed -// explicitly. Instead, they remain valid so long as the FixedBuffer remains -// valid. The Leak method may be used to steal the underlying memory from the -// FixedBuffer. -// -// Typical usage: -// -// { -// FixedBuffer buf(8 + 8); -// -// int* a = static_cast<int*>(buf->Allocate(sizeof(int))); -// *a = 2; -// -// double* b = static_cast<double*>(buf->Allocate(sizeof(double))); -// *b = 3.14f; -// -// void* data = buf.Leak(); -// Process(data); -// -// free(data); -// } -// -class FixedBuffer : public Buffer { - public: - explicit FixedBuffer(size_t size); - ~FixedBuffer() override; - - // Grows the buffer by |num_bytes| and returns a pointer to the start of the - // addition. The resulting address is 8-byte aligned, and the content of the - // memory is zero-filled. - void* Allocate(size_t num_bytes) override; - - size_t size() const { return size_; } - - // Returns the internal memory owned by the Buffer to the caller. The Buffer - // relinquishes its pointer, effectively resetting the state of the Buffer - // and leaving the caller responsible for freeing the returned memory address - // when no longer needed. - void* Leak(); - - private: - char* ptr_; - size_t cursor_; - size_t size_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(FixedBuffer); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_FIXED_BUFFER_H_ diff --git a/mojo/public/cpp/bindings/lib/interface_ptr_internal.h b/mojo/public/cpp/bindings/lib/interface_ptr_internal.h deleted file mode 100644 index a38baf7..0000000 --- a/mojo/public/cpp/bindings/lib/interface_ptr_internal.h +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_INTERFACE_PTR_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_INTERFACE_PTR_INTERNAL_H_ - -#include <algorithm> // For |std::swap()|. - -#include "mojo/public/cpp/bindings/lib/filter_chain.h" -#include "mojo/public/cpp/bindings/lib/message_header_validator.h" -#include "mojo/public/cpp/bindings/lib/router.h" -#include "mojo/public/cpp/environment/logging.h" - -struct MojoAsyncWaiter; - -namespace mojo { -namespace internal { - -template <typename Interface> -class InterfacePtrState { - public: - InterfacePtrState() : proxy_(nullptr), router_(nullptr), waiter_(nullptr) {} - - ~InterfacePtrState() { - // Destruction order matters here. We delete |proxy_| first, even though - // |router_| may have a reference to it, so that |~Interface| may have a - // shot at generating new outbound messages (ie, invoking client methods). - delete proxy_; - delete router_; - } - - Interface* instance() { - ConfigureProxyIfNecessary(); - - // This will be null if the object is not bound. - return proxy_; - } - - void Swap(InterfacePtrState* other) { - std::swap(other->proxy_, proxy_); - std::swap(other->router_, router_); - handle_.swap(other->handle_); - std::swap(other->waiter_, waiter_); - } - - void Bind(ScopedMessagePipeHandle handle, const MojoAsyncWaiter* waiter) { - MOJO_DCHECK(!proxy_); - MOJO_DCHECK(!router_); - MOJO_DCHECK(!handle_.is_valid()); - MOJO_DCHECK(!waiter_); - - handle_ = handle.Pass(); - waiter_ = waiter; - } - - bool WaitForIncomingMethodCall() { - ConfigureProxyIfNecessary(); - - MOJO_DCHECK(router_); - return router_->WaitForIncomingMessage(); - } - - ScopedMessagePipeHandle PassMessagePipe() { - if (router_) - return router_->PassMessagePipe(); - - waiter_ = nullptr; - return handle_.Pass(); - } - - bool is_bound() const { return handle_.is_valid() || router_; } - - void set_client(typename Interface::Client* client) { - ConfigureProxyIfNecessary(); - - MOJO_DCHECK(proxy_); - proxy_->stub.set_sink(client); - } - - bool encountered_error() const { - return router_ ? router_->encountered_error() : false; - } - - void set_error_handler(ErrorHandler* error_handler) { - ConfigureProxyIfNecessary(); - - MOJO_DCHECK(router_); - router_->set_error_handler(error_handler); - } - - Router* router_for_testing() { - ConfigureProxyIfNecessary(); - return router_; - } - - private: - class ProxyWithStub : public Interface::Proxy_ { - public: - explicit ProxyWithStub(MessageReceiverWithResponder* receiver) - : Interface::Proxy_(receiver) {} - typename Interface::Client::Stub_ stub; - - private: - MOJO_DISALLOW_COPY_AND_ASSIGN(ProxyWithStub); - }; - - void ConfigureProxyIfNecessary() { - // The proxy has been configured. - if (proxy_) { - MOJO_DCHECK(router_); - return; - } - // The object hasn't been bound. - if (!waiter_) { - MOJO_DCHECK(!handle_.is_valid()); - return; - } - - FilterChain filters; - filters.Append<MessageHeaderValidator>(); - filters.Append<typename Interface::Client::RequestValidator_>(); - filters.Append<typename Interface::ResponseValidator_>(); - - router_ = new Router(handle_.Pass(), filters.Pass(), waiter_); - waiter_ = nullptr; - - ProxyWithStub* proxy = new ProxyWithStub(router_); - router_->set_incoming_receiver(&proxy->stub); - - proxy_ = proxy; - } - - ProxyWithStub* proxy_; - Router* router_; - - // |proxy_| and |router_| are not initialized until read/write with the - // message pipe handle is needed. Before that, |handle_| and |waiter_| store - // the arguments of Bind(). - ScopedMessagePipeHandle handle_; - const MojoAsyncWaiter* waiter_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(InterfacePtrState); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_INTERFACE_PTR_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/map_data_internal.h b/mojo/public/cpp/bindings/lib/map_data_internal.h deleted file mode 100644 index 7787714..0000000 --- a/mojo/public/cpp/bindings/lib/map_data_internal.h +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_DATA_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_DATA_INTERNAL_H_ - -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/lib/validate_params.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" - -namespace mojo { -namespace internal { - -// Data types for keys. -template <typename MapKey> -struct MapKeyValidateParams { - public: - typedef NoValidateParams ElementValidateParams; - static const uint32_t expected_num_elements = 0; - static const bool element_is_nullable = false; -}; - -// For non-nullable strings only. (Which is OK; map keys can't be null.) -template <> -struct MapKeyValidateParams<mojo::internal::Array_Data<char>*> { - public: - typedef ArrayValidateParams<0, false, NoValidateParams> ElementValidateParams; - static const uint32_t expected_num_elements = 0; - static const bool element_is_nullable = false; -}; - -// Map serializes into a struct which has two arrays as struct fields, the keys -// and the values. -template <typename Key, typename Value> -class Map_Data { - public: - static Map_Data* New(Buffer* buf) { - return new (buf->Allocate(sizeof(Map_Data))) Map_Data(); - } - - template <typename ValueParams> - static bool Validate(const void* data, BoundsChecker* bounds_checker) { - if (!data) - return true; - - if (!ValidateStructHeader(data, sizeof(Map_Data), 2, bounds_checker)) - return false; - - const Map_Data* object = static_cast<const Map_Data*>(data); - if (!ValidateEncodedPointer(&object->keys.offset)) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_POINTER); - return false; - } - if (!object->keys.offset) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - "null key array in map struct"); - return false; - } - if (!Array_Data<Key>::template Validate<MapKeyValidateParams<Key>>( - DecodePointerRaw(&object->keys.offset), bounds_checker)) { - return false; - } - - if (!ValidateEncodedPointer(&object->values.offset)) { - ReportValidationError(VALIDATION_ERROR_ILLEGAL_POINTER); - return false; - } - if (!object->values.offset) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - "null value array in map struct"); - return false; - } - if (!Array_Data<Value>::template Validate<ValueParams>( - DecodePointerRaw(&object->values.offset), bounds_checker)) { - return false; - } - - const ArrayHeader* key_header = - static_cast<const ArrayHeader*>(DecodePointerRaw(&object->keys.offset)); - const ArrayHeader* value_header = static_cast<const ArrayHeader*>( - DecodePointerRaw(&object->values.offset)); - if (key_header->num_elements != value_header->num_elements) { - ReportValidationError(VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP); - return false; - } - - return true; - } - - StructHeader header_; - - ArrayPointer<Key> keys; - ArrayPointer<Value> values; - - void EncodePointersAndHandles(std::vector<mojo::Handle>* handles) { - Encode(&keys, handles); - Encode(&values, handles); - } - - void DecodePointersAndHandles(std::vector<mojo::Handle>* handles) { - Decode(&keys, handles); - Decode(&values, handles); - } - - private: - Map_Data() { - header_.num_bytes = sizeof(*this); - header_.num_fields = 2; - } - ~Map_Data() = delete; -}; -static_assert(sizeof(Map_Data<char, char>) == 24, "Bad sizeof(Map_Data)"); - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_DATA_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/map_internal.h b/mojo/public/cpp/bindings/lib/map_internal.h deleted file mode 100644 index f006cd0..0000000 --- a/mojo/public/cpp/bindings/lib/map_internal.h +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_INTERNAL_H_ - -#include <map> - -#include "mojo/public/cpp/bindings/array.h" -#include "mojo/public/cpp/bindings/lib/template_util.h" - -namespace mojo { -namespace internal { - -template <typename Key, typename Value, bool kValueIsMoveOnlyType> -struct MapTraits {}; - -template <typename Key, typename Value> -struct MapTraits<Key, Value, false> { - // Map keys can't be move only types. - static_assert(!internal::IsMoveOnlyType<Key>::value, - "Map keys can not be move only types."); - - typedef Key KeyStorageType; - typedef Key& KeyRefType; - typedef const Key& KeyConstRefType; - typedef KeyConstRefType KeyForwardType; - - typedef Value ValueStorageType; - typedef Value& ValueRefType; - typedef const Value& ValueConstRefType; - typedef ValueConstRefType ValueForwardType; - - static inline void InitializeFrom( - std::map<KeyStorageType, ValueStorageType>* m, - mojo::Array<Key> keys, - mojo::Array<Value> values) { - for (size_t i = 0; i < keys.size(); ++i) - Insert(m, keys[i], values[i]); - } - static inline void Decompose(std::map<KeyStorageType, ValueStorageType>* m, - mojo::Array<Key>* keys, - mojo::Array<Value>* values) { - keys->resize(m->size()); - values->resize(m->size()); - int i = 0; - for (typename std::map<KeyStorageType, ValueStorageType>::iterator - it = m->begin(); - it != m->end(); - ++it, ++i) { - (*keys)[i] = it->first; - (*values)[i] = it->second; - } - } - static inline void Finalize(std::map<KeyStorageType, ValueStorageType>* m) {} - static inline ValueRefType at(std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key) { - // We don't have C++11 library support yet, so we have to emulate the crash - // on a non-existent key. - auto it = m->find(key); - MOJO_CHECK(it != m->end()); - return it->second; - } - static inline ValueConstRefType at( - const std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key) { - // We don't have C++11 library support yet, so we have to emulate the crash - // on a non-existent key. - auto it = m->find(key); - MOJO_CHECK(it != m->end()); - return it->second; - } - static inline ValueRefType GetOrInsert( - std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key) { - // This is the backing for the index operator (operator[]). - return (*m)[key]; - } - static inline void Insert(std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key, - ValueForwardType value) { - m->insert(std::make_pair(key, value)); - } - static inline KeyConstRefType GetKey( - const typename std::map<KeyStorageType, ValueStorageType>::const_iterator& - it) { - return it->first; - } - static inline ValueConstRefType GetValue( - const typename std::map<KeyStorageType, ValueStorageType>::const_iterator& - it) { - return it->second; - } - static inline ValueRefType GetValue( - const typename std::map<KeyStorageType, ValueStorageType>::iterator& it) { - return it->second; - } - static inline void Clone( - const std::map<KeyStorageType, ValueStorageType>& src, - std::map<KeyStorageType, ValueStorageType>* dst) { - dst->clear(); - for (auto it = src.begin(); it != src.end(); ++it) - dst->insert(*it); - } -}; - -template <typename Key, typename Value> -struct MapTraits<Key, Value, true> { - // Map keys can't be move only types. - static_assert(!internal::IsMoveOnlyType<Key>::value, - "Map keys can not be move only types."); - - typedef Key KeyStorageType; - typedef Key& KeyRefType; - typedef const Key& KeyConstRefType; - typedef KeyConstRefType KeyForwardType; - - struct ValueStorageType { - // Make 8-byte aligned. - char buf[sizeof(Value) + (8 - (sizeof(Value) % 8)) % 8]; - }; - typedef Value& ValueRefType; - typedef const Value& ValueConstRefType; - typedef Value ValueForwardType; - - static inline void InitializeFrom( - std::map<KeyStorageType, ValueStorageType>* m, - mojo::Array<Key> keys, - mojo::Array<Value> values) { - for (size_t i = 0; i < keys.size(); ++i) - Insert(m, keys[i], values[i]); - } - static inline void Decompose(std::map<KeyStorageType, ValueStorageType>* m, - mojo::Array<Key>* keys, - mojo::Array<Value>* values) { - keys->resize(m->size()); - values->resize(m->size()); - int i = 0; - for (typename std::map<KeyStorageType, ValueStorageType>::iterator - it = m->begin(); - it != m->end(); - ++it, ++i) { - (*keys)[i] = it->first; - (*values)[i] = GetValue(it).Pass(); - } - } - static inline void Finalize(std::map<KeyStorageType, ValueStorageType>* m) { - for (auto& pair : *m) - reinterpret_cast<Value*>(pair.second.buf)->~Value(); - } - static inline ValueRefType at(std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key) { - // We don't have C++11 library support yet, so we have to emulate the crash - // on a non-existent key. - auto it = m->find(key); - MOJO_CHECK(it != m->end()); - return GetValue(it); - } - static inline ValueConstRefType at( - const std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key) { - // We don't have C++11 library support yet, so we have to emulate the crash - // on a non-existent key. - auto it = m->find(key); - MOJO_CHECK(it != m->end()); - return GetValue(it); - } - static inline ValueRefType GetOrInsert( - std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key) { - // This is the backing for the index operator (operator[]). - auto it = m->find(key); - if (it == m->end()) { - it = m->insert(std::make_pair(key, ValueStorageType())).first; - new (it->second.buf) Value(); - } - - return GetValue(it); - } - static inline void Insert(std::map<KeyStorageType, ValueStorageType>* m, - KeyForwardType key, - ValueRefType value) { - // STL insert() doesn't insert |value| if |key| is already part of |m|. We - // have to use operator[] to initialize into the storage buffer, but we - // have to do a manual check so that we don't overwrite an existing object. - auto it = m->find(key); - if (it == m->end()) - new ((*m)[key].buf) Value(value.Pass()); - } - static inline KeyConstRefType GetKey( - const typename std::map<KeyStorageType, ValueStorageType>::const_iterator& - it) { - return it->first; - } - static inline ValueConstRefType GetValue( - const typename std::map<KeyStorageType, ValueStorageType>::const_iterator& - it) { - return *reinterpret_cast<const Value*>(it->second.buf); - } - static inline ValueRefType GetValue( - const typename std::map<KeyStorageType, ValueStorageType>::iterator& it) { - return *reinterpret_cast<Value*>(it->second.buf); - } - static inline void Clone( - const std::map<KeyStorageType, ValueStorageType>& src, - std::map<KeyStorageType, ValueStorageType>* dst) { - Finalize(dst); - dst->clear(); - for (auto it = src.begin(); it != src.end(); ++it) - new ((*dst)[it->first].buf) Value(GetValue(it).Clone()); - } -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/map_serialization.h b/mojo/public/cpp/bindings/lib/map_serialization.h deleted file mode 100644 index fba8165..0000000 --- a/mojo/public/cpp/bindings/lib/map_serialization.h +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_SERIALIZATION_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_SERIALIZATION_H_ - -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/lib/map_data_internal.h" -#include "mojo/public/cpp/bindings/lib/map_internal.h" -#include "mojo/public/cpp/bindings/lib/string_serialization.h" -#include "mojo/public/cpp/bindings/map.h" - -namespace mojo { - -template <typename Key, typename Value> -inline size_t GetSerializedSize_(const Map<Key, Value>& input); - -template <typename ValidateParams, typename E, typename F> -inline void SerializeArray_(Array<E> input, - internal::Buffer* buf, - internal::Array_Data<F>** output); - -namespace internal { - -template <typename MapType, - typename DataType, - bool kValueIsMoveOnlyType = IsMoveOnlyType<MapType>::value> -struct MapSerializer; - -template <typename MapType, typename DataType> -struct MapSerializer<MapType, DataType, false> { - static size_t GetBaseArraySize(size_t count) { - return Align(count * sizeof(DataType)); - } - static size_t GetItemSize(const MapType& item) { return 0; } -}; - -template <> -struct MapSerializer<bool, bool, false> { - static size_t GetBaseArraySize(size_t count) { - return Align((count + 7) / 8); - } - static size_t GetItemSize(bool item) { return 0; } -}; - -template <typename H> -struct MapSerializer<ScopedHandleBase<H>, H, true> { - static size_t GetBaseArraySize(size_t count) { - return Align(count * sizeof(H)); - } - static size_t GetItemSize(const H& item) { return 0; } -}; - -// This template must only apply to pointer mojo entity (structs and arrays). -// This is done by ensuring that WrapperTraits<S>::DataType is a pointer. -template <typename S> -struct MapSerializer< - S, - typename EnableIf<IsPointer<typename WrapperTraits<S>::DataType>::value, - typename WrapperTraits<S>::DataType>::type, - true> { - typedef - typename RemovePointer<typename WrapperTraits<S>::DataType>::type S_Data; - static size_t GetBaseArraySize(size_t count) { - return count * sizeof(StructPointer<S_Data>); - } - static size_t GetItemSize(const S& item) { return GetSerializedSize_(item); } -}; - -template <> -struct MapSerializer<String, String_Data*, false> { - static size_t GetBaseArraySize(size_t count) { - return count * sizeof(StringPointer); - } - static size_t GetItemSize(const String& item) { - return GetSerializedSize_(item); - } -}; - -} // namespace internal - -// TODO(erg): This can't go away yet. We still need to calculate out the size -// of a struct header, and two arrays. -template <typename MapKey, typename MapValue> -inline size_t GetSerializedSize_(const Map<MapKey, MapValue>& input) { - if (!input) - return 0; - typedef typename internal::WrapperTraits<MapKey>::DataType DataKey; - typedef typename internal::WrapperTraits<MapValue>::DataType DataValue; - - size_t count = input.size(); - size_t struct_overhead = sizeof(mojo::internal::Map_Data<DataKey, DataValue>); - size_t key_base_size = - sizeof(internal::ArrayHeader) + - internal::MapSerializer<MapKey, DataKey>::GetBaseArraySize(count); - size_t value_base_size = - sizeof(internal::ArrayHeader) + - internal::MapSerializer<MapValue, DataValue>::GetBaseArraySize(count); - - size_t key_data_size = 0; - size_t value_data_size = 0; - for (auto it = input.begin(); it != input.end(); ++it) { - key_data_size += - internal::MapSerializer<MapKey, DataKey>::GetItemSize(it.GetKey()); - value_data_size += - internal::MapSerializer<MapValue, DataValue>::GetItemSize( - it.GetValue()); - } - - return struct_overhead + key_base_size + key_data_size + value_base_size + - value_data_size; -} - -// We don't need a KeyValidateParams, because we konw exactly what params are -// needed. (Keys are primitive types or non-nullable strings.) -template <typename ValueValidateParams, - typename MapKey, - typename MapValue, - typename DataKey, - typename DataValue> -inline void SerializeMap_(Map<MapKey, MapValue> input, - internal::Buffer* buf, - internal::Map_Data<DataKey, DataValue>** output) { - if (input) { - internal::Map_Data<DataKey, DataValue>* result = - internal::Map_Data<DataKey, DataValue>::New(buf); - if (result) { - Array<MapKey> keys; - Array<MapValue> values; - input.DecomposeMapTo(&keys, &values); - SerializeArray_<internal::MapKeyValidateParams<DataKey>>( - keys.Pass(), buf, &result->keys.ptr); - SerializeArray_<ValueValidateParams>( - values.Pass(), buf, &result->values.ptr); - } - *output = result; - } else { - *output = nullptr; - } -} - -template <typename MapKey, - typename MapValue, - typename DataKey, - typename DataValue> -inline void Deserialize_(internal::Map_Data<DataKey, DataValue>* input, - Map<MapKey, MapValue>* output) { - if (input) { - Array<MapKey> keys; - Array<MapValue> values; - - Deserialize_(input->keys.ptr, &keys); - Deserialize_(input->values.ptr, &values); - - *output = Map<MapKey, MapValue>(keys.Pass(), values.Pass()); - } else { - output->reset(); - } -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MAP_SERIALIZATION_H_ diff --git a/mojo/public/cpp/bindings/lib/message.cc b/mojo/public/cpp/bindings/lib/message.cc deleted file mode 100644 index 2723bcb..0000000 --- a/mojo/public/cpp/bindings/lib/message.cc +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/message.h" - -#include <stdlib.h> - -#include <algorithm> - -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { - -Message::Message() : data_num_bytes_(0), data_(nullptr) { -} - -Message::~Message() { - free(data_); - - for (std::vector<Handle>::iterator it = handles_.begin(); - it != handles_.end(); - ++it) { - if (it->is_valid()) - CloseRaw(*it); - } -} - -void Message::AllocUninitializedData(uint32_t num_bytes) { - MOJO_DCHECK(!data_); - data_num_bytes_ = num_bytes; - data_ = static_cast<internal::MessageData*>(malloc(num_bytes)); -} - -void Message::AdoptData(uint32_t num_bytes, internal::MessageData* data) { - MOJO_DCHECK(!data_); - data_num_bytes_ = num_bytes; - data_ = data; -} - -void Message::Swap(Message* other) { - std::swap(data_num_bytes_, other->data_num_bytes_); - std::swap(data_, other->data_); - std::swap(handles_, other->handles_); -} - -MojoResult ReadAndDispatchMessage(MessagePipeHandle handle, - MessageReceiver* receiver, - bool* receiver_result) { - MojoResult rv; - - uint32_t num_bytes = 0, num_handles = 0; - rv = ReadMessageRaw(handle, - nullptr, - &num_bytes, - nullptr, - &num_handles, - MOJO_READ_MESSAGE_FLAG_NONE); - if (rv != MOJO_RESULT_RESOURCE_EXHAUSTED) - return rv; - - Message message; - message.AllocUninitializedData(num_bytes); - message.mutable_handles()->resize(num_handles); - - rv = ReadMessageRaw( - handle, - message.mutable_data(), - &num_bytes, - message.mutable_handles()->empty() - ? nullptr - : reinterpret_cast<MojoHandle*>(&message.mutable_handles()->front()), - &num_handles, - MOJO_READ_MESSAGE_FLAG_NONE); - if (receiver && rv == MOJO_RESULT_OK) - *receiver_result = receiver->Accept(&message); - - return rv; -} - -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/message_builder.cc b/mojo/public/cpp/bindings/lib/message_builder.cc deleted file mode 100644 index cc914e8..0000000 --- a/mojo/public/cpp/bindings/lib/message_builder.cc +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/message_builder.h" - -#include "mojo/public/cpp/bindings/message.h" - -namespace mojo { -namespace internal { - -template <typename Header> -void Allocate(Buffer* buf, Header** header) { - *header = static_cast<Header*>(buf->Allocate(sizeof(Header))); - (*header)->num_bytes = sizeof(Header); -} - -MessageBuilder::MessageBuilder(uint32_t name, size_t payload_size) - : buf_(sizeof(MessageHeader) + payload_size) { - MessageHeader* header; - Allocate(&buf_, &header); - header->num_fields = 2; - header->name = name; -} - -MessageBuilder::~MessageBuilder() { -} - -void MessageBuilder::Finish(Message* message) { - uint32_t num_bytes = static_cast<uint32_t>(buf_.size()); - message->AdoptData(num_bytes, static_cast<MessageData*>(buf_.Leak())); -} - -MessageBuilder::MessageBuilder(size_t size) : buf_(size) { -} - -MessageWithRequestIDBuilder::MessageWithRequestIDBuilder(uint32_t name, - size_t payload_size, - uint32_t flags, - uint64_t request_id) - : MessageBuilder(sizeof(MessageHeaderWithRequestID) + payload_size) { - MessageHeaderWithRequestID* header; - Allocate(&buf_, &header); - header->num_fields = 3; - header->name = name; - header->flags = flags; - header->request_id = request_id; -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/message_builder.h b/mojo/public/cpp/bindings/lib/message_builder.h deleted file mode 100644 index a10940c..0000000 --- a/mojo/public/cpp/bindings/lib/message_builder.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_BUILDER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_BUILDER_H_ - -#include <stdint.h> - -#include "mojo/public/cpp/bindings/lib/fixed_buffer.h" -#include "mojo/public/cpp/bindings/lib/message_internal.h" - -namespace mojo { -class Message; - -namespace internal { - -class MessageBuilder { - public: - MessageBuilder(uint32_t name, size_t payload_size); - ~MessageBuilder(); - - Buffer* buffer() { return &buf_; } - - // Call Finish when done making allocations in |buffer()|. Upon return, - // |message| will contain the message data, and |buffer()| will no longer be - // valid to reference. - void Finish(Message* message); - - protected: - explicit MessageBuilder(size_t size); - FixedBuffer buf_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(MessageBuilder); -}; - -class MessageWithRequestIDBuilder : public MessageBuilder { - public: - MessageWithRequestIDBuilder(uint32_t name, - size_t payload_size, - uint32_t flags, - uint64_t request_id); -}; - -class RequestMessageBuilder : public MessageWithRequestIDBuilder { - public: - RequestMessageBuilder(uint32_t name, size_t payload_size) - : MessageWithRequestIDBuilder(name, - payload_size, - kMessageExpectsResponse, - 0) {} -}; - -class ResponseMessageBuilder : public MessageWithRequestIDBuilder { - public: - ResponseMessageBuilder(uint32_t name, - size_t payload_size, - uint64_t request_id) - : MessageWithRequestIDBuilder(name, - payload_size, - kMessageIsResponse, - request_id) {} -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_BUILDER_H_ diff --git a/mojo/public/cpp/bindings/lib/message_filter.cc b/mojo/public/cpp/bindings/lib/message_filter.cc deleted file mode 100644 index b09f40d..0000000 --- a/mojo/public/cpp/bindings/lib/message_filter.cc +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/message_filter.h" - -namespace mojo { - -MessageFilter::MessageFilter(MessageReceiver* sink) : sink_(sink) { -} - -MessageFilter::~MessageFilter() { -} - -PassThroughFilter::PassThroughFilter(MessageReceiver* sink) - : MessageFilter(sink) { -} - -bool PassThroughFilter::Accept(Message* message) { - return sink_->Accept(message); -} - -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/message_header_validator.cc b/mojo/public/cpp/bindings/lib/message_header_validator.cc deleted file mode 100644 index 9d28ecc..0000000 --- a/mojo/public/cpp/bindings/lib/message_header_validator.cc +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/message_header_validator.h" - -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/bindings/lib/bounds_checker.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" - -namespace mojo { -namespace internal { -namespace { - -bool IsValidMessageHeader(const MessageHeader* header) { - // NOTE: Our goal is to preserve support for future extension of the message - // header. If we encounter fields we do not understand, we must ignore them. - - // Extra validation of the struct header: - if (header->num_fields == 2) { - if (header->num_bytes != sizeof(MessageHeader)) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); - return false; - } - } else if (header->num_fields == 3) { - if (header->num_bytes != sizeof(MessageHeaderWithRequestID)) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); - return false; - } - } else if (header->num_fields > 3) { - if (header->num_bytes < sizeof(MessageHeaderWithRequestID)) { - ReportValidationError(VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); - return false; - } - } - - // Validate flags (allow unknown bits): - - // These flags require a RequestID. - if (header->num_fields < 3 && ((header->flags & kMessageExpectsResponse) || - (header->flags & kMessageIsResponse))) { - ReportValidationError(VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID); - return false; - } - - // These flags are mutually exclusive. - if ((header->flags & kMessageExpectsResponse) && - (header->flags & kMessageIsResponse)) { - ReportValidationError( - VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAG_COMBINATION); - return false; - } - - return true; -} - -} // namespace - -MessageHeaderValidator::MessageHeaderValidator(MessageReceiver* sink) - : MessageFilter(sink) { -} - -bool MessageHeaderValidator::Accept(Message* message) { - // Pass 0 as number of handles because we don't expect any in the header, even - // if |message| contains handles. - BoundsChecker bounds_checker(message->data(), message->data_num_bytes(), 0); - - if (!ValidateStructHeader( - message->data(), sizeof(MessageHeader), 2, &bounds_checker)) { - return false; - } - - if (!IsValidMessageHeader(message->header())) - return false; - - return sink_->Accept(message); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/message_header_validator.h b/mojo/public/cpp/bindings/lib/message_header_validator.h deleted file mode 100644 index bccef1f..0000000 --- a/mojo/public/cpp/bindings/lib/message_header_validator.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_HEADER_VALIDATOR_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_HEADER_VALIDATOR_H_ - -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/bindings/message_filter.h" - -namespace mojo { -namespace internal { - -class MessageHeaderValidator : public MessageFilter { - public: - explicit MessageHeaderValidator(MessageReceiver* sink = nullptr); - - bool Accept(Message* message) override; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_HEADER_VALIDATOR_H_ diff --git a/mojo/public/cpp/bindings/lib/message_internal.h b/mojo/public/cpp/bindings/lib/message_internal.h deleted file mode 100644 index cdecf91..0000000 --- a/mojo/public/cpp/bindings/lib/message_internal.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_INTERNAL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_INTERNAL_H_ - -#include "mojo/public/cpp/bindings/lib/bindings_internal.h" - -namespace mojo { -namespace internal { - -#pragma pack(push, 1) - -enum { kMessageExpectsResponse = 1 << 0, kMessageIsResponse = 1 << 1 }; - -struct MessageHeader : internal::StructHeader { - uint32_t name; - uint32_t flags; -}; -static_assert(sizeof(MessageHeader) == 16, "Bad sizeof(MessageHeader)"); - -struct MessageHeaderWithRequestID : MessageHeader { - uint64_t request_id; -}; -static_assert(sizeof(MessageHeaderWithRequestID) == 24, - "Bad sizeof(MessageHeaderWithRequestID)"); - -struct MessageData { - MessageHeader header; -}; - -static_assert(sizeof(MessageData) == sizeof(MessageHeader), - "Bad sizeof(MessageData)"); - -#pragma pack(pop) - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_INTERNAL_H_ diff --git a/mojo/public/cpp/bindings/lib/message_queue.cc b/mojo/public/cpp/bindings/lib/message_queue.cc deleted file mode 100644 index fd701e97..0000000 --- a/mojo/public/cpp/bindings/lib/message_queue.cc +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/message_queue.h" - -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { - -MessageQueue::MessageQueue() { -} - -MessageQueue::~MessageQueue() { - while (!queue_.empty()) - Pop(); -} - -bool MessageQueue::IsEmpty() const { - return queue_.empty(); -} - -Message* MessageQueue::Peek() { - MOJO_DCHECK(!queue_.empty()); - return queue_.front(); -} - -void MessageQueue::Push(Message* message) { - queue_.push(new Message()); - queue_.back()->Swap(message); -} - -void MessageQueue::Pop(Message* message) { - MOJO_DCHECK(!queue_.empty()); - queue_.front()->Swap(message); - Pop(); -} - -void MessageQueue::Pop() { - MOJO_DCHECK(!queue_.empty()); - delete queue_.front(); - queue_.pop(); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/message_queue.h b/mojo/public/cpp/bindings/lib/message_queue.h deleted file mode 100644 index 4e46b54..0000000 --- a/mojo/public/cpp/bindings/lib/message_queue.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_QUEUE_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_QUEUE_H_ - -#include <queue> - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -class Message; - -namespace internal { - -// A queue for Message objects. -class MessageQueue { - public: - MessageQueue(); - ~MessageQueue(); - - bool IsEmpty() const; - Message* Peek(); - - // This method transfers ownership of |message->data| and |message->handles| - // to the message queue, resetting |message| in the process. - void Push(Message* message); - - // Removes the next message from the queue, transferring ownership of its - // data and handles to the given |message|. - void Pop(Message* message); - - // Removes the next message from the queue, discarding its data and handles. - // This is meant to be used in conjunction with |Peek|. - void Pop(); - - private: - std::queue<Message*> queue_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(MessageQueue); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_QUEUE_H_ diff --git a/mojo/public/cpp/bindings/lib/no_interface.cc b/mojo/public/cpp/bindings/lib/no_interface.cc deleted file mode 100644 index 9e0945c..0000000 --- a/mojo/public/cpp/bindings/lib/no_interface.cc +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/no_interface.h" - -namespace mojo { - -const char* NoInterface::Name_ = "mojo::NoInterface"; - -bool NoInterfaceStub::Accept(Message* message) { - return false; -} - -bool NoInterfaceStub::AcceptWithResponder(Message* message, - MessageReceiver* responder) { - return false; -} - -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/router.cc b/mojo/public/cpp/bindings/lib/router.cc deleted file mode 100644 index bb29e47..0000000 --- a/mojo/public/cpp/bindings/lib/router.cc +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/router.h" - -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { - -// ---------------------------------------------------------------------------- - -class ResponderThunk : public MessageReceiver { - public: - explicit ResponderThunk(const SharedData<Router*>& router) - : router_(router) {} - ~ResponderThunk() override {} - - // MessageReceiver implementation: - bool Accept(Message* message) override { - MOJO_DCHECK(message->has_flag(kMessageIsResponse)); - - bool result = false; - - Router* router = router_.value(); - if (router) - result = router->Accept(message); - - return result; - } - - private: - SharedData<Router*> router_; -}; - -// ---------------------------------------------------------------------------- - -Router::HandleIncomingMessageThunk::HandleIncomingMessageThunk(Router* router) - : router_(router) { -} - -Router::HandleIncomingMessageThunk::~HandleIncomingMessageThunk() { -} - -bool Router::HandleIncomingMessageThunk::Accept(Message* message) { - return router_->HandleIncomingMessage(message); -} - -// ---------------------------------------------------------------------------- - -Router::Router(ScopedMessagePipeHandle message_pipe, - FilterChain filters, - const MojoAsyncWaiter* waiter) - : thunk_(this), - filters_(filters.Pass()), - connector_(message_pipe.Pass(), waiter), - weak_self_(this), - incoming_receiver_(nullptr), - next_request_id_(0), - testing_mode_(false) { - filters_.SetSink(&thunk_); - connector_.set_incoming_receiver(filters_.GetHead()); -} - -Router::~Router() { - weak_self_.set_value(nullptr); - - for (ResponderMap::const_iterator i = responders_.begin(); - i != responders_.end(); - ++i) { - delete i->second; - } -} - -bool Router::Accept(Message* message) { - MOJO_DCHECK(!message->has_flag(kMessageExpectsResponse)); - return connector_.Accept(message); -} - -bool Router::AcceptWithResponder(Message* message, MessageReceiver* responder) { - MOJO_DCHECK(message->has_flag(kMessageExpectsResponse)); - - // Reserve 0 in case we want it to convey special meaning in the future. - uint64_t request_id = next_request_id_++; - if (request_id == 0) - request_id = next_request_id_++; - - message->set_request_id(request_id); - if (!connector_.Accept(message)) - return false; - - // We assume ownership of |responder|. - responders_[request_id] = responder; - return true; -} - -void Router::EnableTestingMode() { - testing_mode_ = true; - connector_.set_enforce_errors_from_incoming_receiver(false); -} - -bool Router::HandleIncomingMessage(Message* message) { - if (message->has_flag(kMessageExpectsResponse)) { - if (incoming_receiver_) { - MessageReceiver* responder = new ResponderThunk(weak_self_); - bool ok = incoming_receiver_->AcceptWithResponder(message, responder); - if (!ok) - delete responder; - return ok; - } - - // If we receive a request expecting a response when the client is not - // listening, then we have no choice but to tear down the pipe. - connector_.CloseMessagePipe(); - } else if (message->has_flag(kMessageIsResponse)) { - uint64_t request_id = message->request_id(); - ResponderMap::iterator it = responders_.find(request_id); - if (it == responders_.end()) { - MOJO_DCHECK(testing_mode_); - return false; - } - MessageReceiver* responder = it->second; - responders_.erase(it); - bool ok = responder->Accept(message); - delete responder; - return ok; - } else { - if (incoming_receiver_) - return incoming_receiver_->Accept(message); - // OK to drop message on the floor. - } - - return false; -} - -// ---------------------------------------------------------------------------- - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/router.h b/mojo/public/cpp/bindings/lib/router.h deleted file mode 100644 index 8254bab..0000000 --- a/mojo/public/cpp/bindings/lib/router.h +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_ROUTER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_ROUTER_H_ - -#include <map> - -#include "mojo/public/cpp/bindings/lib/connector.h" -#include "mojo/public/cpp/bindings/lib/filter_chain.h" -#include "mojo/public/cpp/bindings/lib/shared_data.h" -#include "mojo/public/cpp/environment/environment.h" - -namespace mojo { -namespace internal { - -class Router : public MessageReceiverWithResponder { - public: - Router(ScopedMessagePipeHandle message_pipe, - FilterChain filters, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()); - ~Router() override; - - // Sets the receiver to handle messages read from the message pipe that do - // not have the kMessageIsResponse flag set. - void set_incoming_receiver(MessageReceiverWithResponder* receiver) { - incoming_receiver_ = receiver; - } - - // Sets the error handler to receive notifications when an error is - // encountered while reading from the pipe or waiting to read from the pipe. - void set_error_handler(ErrorHandler* error_handler) { - connector_.set_error_handler(error_handler); - } - - // Returns true if an error was encountered while reading from the pipe or - // waiting to read from the pipe. - bool encountered_error() const { return connector_.encountered_error(); } - - void CloseMessagePipe() { connector_.CloseMessagePipe(); } - - ScopedMessagePipeHandle PassMessagePipe() { - return connector_.PassMessagePipe(); - } - - // MessageReceiver implementation: - bool Accept(Message* message) override; - bool AcceptWithResponder(Message* message, - MessageReceiver* responder) override; - - // Blocks the current thread for the first incoming method call, i.e., either - // a call to a client method or a callback method. - bool WaitForIncomingMessage() { return connector_.WaitForIncomingMessage(); } - - // Sets this object to testing mode. - // In testing mode: - // - the object is more tolerant of unrecognized response messages; - // - the connector continues working after seeing errors from its incoming - // receiver. - void EnableTestingMode(); - - private: - typedef std::map<uint64_t, MessageReceiver*> ResponderMap; - - class HandleIncomingMessageThunk : public MessageReceiver { - public: - HandleIncomingMessageThunk(Router* router); - ~HandleIncomingMessageThunk() override; - - // MessageReceiver implementation: - bool Accept(Message* message) override; - - private: - Router* router_; - }; - - bool HandleIncomingMessage(Message* message); - - HandleIncomingMessageThunk thunk_; - FilterChain filters_; - Connector connector_; - SharedData<Router*> weak_self_; - MessageReceiverWithResponder* incoming_receiver_; - ResponderMap responders_; - uint64_t next_request_id_; - bool testing_mode_; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_ROUTER_H_ diff --git a/mojo/public/cpp/bindings/lib/shared_data.h b/mojo/public/cpp/bindings/lib/shared_data.h deleted file mode 100644 index 54c9346..0000000 --- a/mojo/public/cpp/bindings/lib/shared_data.h +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_DATA_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_DATA_H_ - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -namespace internal { - -// Used to allocate an instance of T that can be shared via reference counting. -template <typename T> -class SharedData { - public: - ~SharedData() { holder_->Release(); } - - SharedData() : holder_(new Holder()) {} - - explicit SharedData(const T& value) : holder_(new Holder(value)) {} - - SharedData(const SharedData<T>& other) : holder_(other.holder_) { - holder_->Retain(); - } - - SharedData<T>& operator=(const SharedData<T>& other) { - if (other.holder_ == holder_) - return *this; - holder_->Release(); - holder_ = other.holder_; - holder_->Retain(); - return *this; - } - - void reset() { - holder_->Release(); - holder_ = new Holder(); - } - - void reset(const T& value) { - holder_->Release(); - holder_ = new Holder(value); - } - - void set_value(const T& value) { holder_->value = value; } - T* mutable_value() { return &holder_->value; } - const T& value() const { return holder_->value; } - - private: - class Holder { - public: - Holder() : value(), ref_count_(1) {} - Holder(const T& value) : value(value), ref_count_(1) {} - - void Retain() { ++ref_count_; } - void Release() { - if (--ref_count_ == 0) - delete this; - } - - T value; - - private: - int ref_count_; - MOJO_DISALLOW_COPY_AND_ASSIGN(Holder); - }; - - Holder* holder_; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_DATA_H_ diff --git a/mojo/public/cpp/bindings/lib/shared_ptr.h b/mojo/public/cpp/bindings/lib/shared_ptr.h deleted file mode 100644 index 37c8735..0000000 --- a/mojo/public/cpp/bindings/lib/shared_ptr.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_PTR_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_PTR_H_ - -#include "mojo/public/cpp/bindings/lib/shared_data.h" - -namespace mojo { -namespace internal { - -// Used to manage a heap-allocated instance of P that can be shared via -// reference counting. When the last reference is dropped, the instance is -// deleted. -template <typename P> -class SharedPtr { - public: - SharedPtr() {} - - explicit SharedPtr(P* ptr) { impl_.mutable_value()->ptr = ptr; } - - // Default copy-constructor and assignment operator are OK. - - P* get() { return impl_.value().ptr; } - const P* get() const { return impl_.value().ptr; } - - void reset() { impl_.reset(); } - - P* operator->() { return get(); } - const P* operator->() const { return get(); } - - private: - class Impl { - public: - ~Impl() { - if (ptr) - delete ptr; - } - - Impl() : ptr(nullptr) {} - - Impl(P* ptr) : ptr(ptr) {} - - P* ptr; - - private: - MOJO_DISALLOW_COPY_AND_ASSIGN(Impl); - }; - - SharedData<Impl> impl_; -}; - -} // namespace mojo -} // namespace internal - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_SHARED_PTR_H_ diff --git a/mojo/public/cpp/bindings/lib/string_serialization.cc b/mojo/public/cpp/bindings/lib/string_serialization.cc deleted file mode 100644 index e29d6f8..0000000 --- a/mojo/public/cpp/bindings/lib/string_serialization.cc +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/string_serialization.h" - -#include <string.h> - -namespace mojo { - -size_t GetSerializedSize_(const String& input) { - if (!input) - return 0; - return internal::Align(sizeof(internal::String_Data) + input.size()); -} - -void Serialize_(const String& input, - internal::Buffer* buf, - internal::String_Data** output) { - if (input) { - internal::String_Data* result = - internal::String_Data::New(input.size(), buf); - if (result) - memcpy(result->storage(), input.data(), input.size()); - *output = result; - } else { - *output = nullptr; - } -} - -void Deserialize_(internal::String_Data* input, String* output) { - if (input) { - String result(input->storage(), input->size()); - result.Swap(output); - } else { - output->reset(); - } -} - -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/string_serialization.h b/mojo/public/cpp/bindings/lib/string_serialization.h deleted file mode 100644 index 0118742..0000000 --- a/mojo/public/cpp/bindings/lib/string_serialization.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ - -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/string.h" - -namespace mojo { - -size_t GetSerializedSize_(const String& input); -void Serialize_(const String& input, - internal::Buffer* buffer, - internal::String_Data** output); -void Deserialize_(internal::String_Data* input, String* output); - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_ diff --git a/mojo/public/cpp/bindings/lib/template_util.h b/mojo/public/cpp/bindings/lib/template_util.h deleted file mode 100644 index c221a54..0000000 --- a/mojo/public/cpp/bindings/lib/template_util.h +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_TEMPLATE_UTIL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_TEMPLATE_UTIL_H_ - -namespace mojo { -namespace internal { - -template <class T, T v> -struct IntegralConstant { - static const T value = v; -}; - -template <class T, T v> -const T IntegralConstant<T, v>::value; - -typedef IntegralConstant<bool, true> TrueType; -typedef IntegralConstant<bool, false> FalseType; - -template <class T> -struct IsConst : FalseType {}; -template <class T> -struct IsConst<const T> : TrueType {}; - -template <class T> -struct IsPointer : FalseType {}; -template <class T> -struct IsPointer<T*> : TrueType {}; - -template <bool B, typename T = void> -struct EnableIf {}; - -template <typename T> -struct EnableIf<true, T> { - typedef T type; -}; - -// Types YesType and NoType are guaranteed such that sizeof(YesType) < -// sizeof(NoType). -typedef char YesType; - -struct NoType { - YesType dummy[2]; -}; - -// A helper template to determine if given type is non-const move-only-type, -// i.e. if a value of the given type should be passed via .Pass() in a -// destructive way. -template <typename T> -struct IsMoveOnlyType { - template <typename U> - static YesType Test(const typename U::MoveOnlyTypeForCPP03*); - - template <typename U> - static NoType Test(...); - - static const bool value = - sizeof(Test<T>(0)) == sizeof(YesType) && !IsConst<T>::value; -}; - -template <typename T> -typename EnableIf<!IsMoveOnlyType<T>::value, T>::type& Forward(T& t) { - return t; -} - -template <typename T> -typename EnableIf<IsMoveOnlyType<T>::value, T>::type Forward(T& t) { - return t.Pass(); -} - -// This goop is a trick used to implement a template that can be used to -// determine if a given class is the base class of another given class. -template <typename, typename> -struct IsSame { - static bool const value = false; -}; -template <typename A> -struct IsSame<A, A> { - static bool const value = true; -}; -template <typename Base, typename Derived> -struct IsBaseOf { - private: - // This class doesn't work correctly with forward declarations. - // Because sizeof cannot be applied to incomplete types, this line prevents us - // from passing in forward declarations. - typedef char (*EnsureTypesAreComplete)[sizeof(Base) + sizeof(Derived)]; - - static Derived* CreateDerived(); - static char(&Check(Base*))[1]; - static char(&Check(...))[2]; - - public: - static bool const value = sizeof Check(CreateDerived()) == 1 && - !IsSame<Base const, void const>::value; -}; - -template <class T> -struct RemovePointer {}; -template <class T> -struct RemovePointer<T*> { - typedef T type; -}; - -template <template <typename...> class Template, typename T> -struct IsSpecializationOf : FalseType {}; - -template <template <typename...> class Template, typename... Args> -struct IsSpecializationOf<Template, Template<Args...>> : TrueType {}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_TEMPLATE_UTIL_H_ diff --git a/mojo/public/cpp/bindings/lib/union_accessor.h b/mojo/public/cpp/bindings/lib/union_accessor.h deleted file mode 100644 index 821aede..0000000 --- a/mojo/public/cpp/bindings/lib/union_accessor.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_UNION_ACCESSOR_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_UNION_ACCESSOR_H_ - -namespace mojo { -namespace internal { - -// When serializing and deserializing Unions, it is necessary to access -// the private fields and methods of the Union. This allows us to do that -// without leaking those same fields and methods in the Union interface. -// All Union wrappers are friends of this class allowing such access. -template <typename U> -class UnionAccessor { - public: - explicit UnionAccessor(U* u) : u_(u) {} - - typename U::Union_* data() { return &(u_->data_); } - - typename U::Tag* tag() { return &(u_->tag_); } - - void SwitchActive(typename U::Tag new_tag) { u_->SwitchActive(new_tag); } - - private: - U* u_; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_UNION_ACCESSOR_H_ diff --git a/mojo/public/cpp/bindings/lib/validate_params.h b/mojo/public/cpp/bindings/lib/validate_params.h deleted file mode 100644 index 25bd98c..0000000 --- a/mojo/public/cpp/bindings/lib/validate_params.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_VALIDATE_PARAMS_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_VALIDATE_PARAMS_H_ - -namespace mojo { -namespace internal { - -// Array type information needed for valdiation. -template <uint32_t in_expected_num_elements, - bool in_element_is_nullable, - typename InElementValidateParams> -class ArrayValidateParams { - public: - // Validation information for elements. It is either another specialization - // of ArrayValidateParams (if elements are arrays or maps), or - // NoValidateParams. In the case of maps, this is used to validate the value - // array. - typedef InElementValidateParams ElementValidateParams; - - // If |expected_num_elements| is not 0, the array is expected to have exactly - // that number of elements. - static const uint32_t expected_num_elements = in_expected_num_elements; - // Whether the elements are nullable. - static const bool element_is_nullable = in_element_is_nullable; -}; - -// NoValidateParams is used to indicate the end of an ArrayValidateParams chain. -class NoValidateParams {}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_VALIDATE_PARAMS_H_ diff --git a/mojo/public/cpp/bindings/lib/validation_errors.cc b/mojo/public/cpp/bindings/lib/validation_errors.cc deleted file mode 100644 index b065d90..0000000 --- a/mojo/public/cpp/bindings/lib/validation_errors.cc +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/public/cpp/bindings/lib/validation_errors.h" - -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { -namespace internal { -namespace { - -ValidationErrorObserverForTesting* g_validation_error_observer = nullptr; -SerializationWarningObserverForTesting* g_serialization_warning_observer = - nullptr; - -} // namespace - -const char* ValidationErrorToString(ValidationError error) { - switch (error) { - case VALIDATION_ERROR_NONE: - return "VALIDATION_ERROR_NONE"; - case VALIDATION_ERROR_MISALIGNED_OBJECT: - return "VALIDATION_ERROR_MISALIGNED_OBJECT"; - case VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE: - return "VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE"; - case VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER: - return "VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER"; - case VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER: - return "VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER"; - case VALIDATION_ERROR_ILLEGAL_HANDLE: - return "VALIDATION_ERROR_ILLEGAL_HANDLE"; - case VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE: - return "VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE"; - case VALIDATION_ERROR_ILLEGAL_POINTER: - return "VALIDATION_ERROR_ILLEGAL_POINTER"; - case VALIDATION_ERROR_UNEXPECTED_NULL_POINTER: - return "VALIDATION_ERROR_UNEXPECTED_NULL_POINTER"; - case VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAG_COMBINATION: - return "VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAG_COMBINATION"; - case VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID: - return "VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID"; - case VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP: - return "VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP"; - } - - return "Unknown error"; -} - -void ReportValidationError(ValidationError error, const char* description) { - if (g_validation_error_observer) { - g_validation_error_observer->set_last_error(error); - } else if (description) { - MOJO_LOG(ERROR) << "Invalid message: " << ValidationErrorToString(error) - << " (" << description << ")"; - } else { - MOJO_LOG(ERROR) << "Invalid message: " << ValidationErrorToString(error); - } -} - -ValidationErrorObserverForTesting::ValidationErrorObserverForTesting() - : last_error_(VALIDATION_ERROR_NONE) { - MOJO_DCHECK(!g_validation_error_observer); - g_validation_error_observer = this; -} - -ValidationErrorObserverForTesting::~ValidationErrorObserverForTesting() { - MOJO_DCHECK(g_validation_error_observer == this); - g_validation_error_observer = nullptr; -} - -bool ReportSerializationWarning(ValidationError error) { - if (g_serialization_warning_observer) { - g_serialization_warning_observer->set_last_warning(error); - return true; - } - - return false; -} - -SerializationWarningObserverForTesting::SerializationWarningObserverForTesting() - : last_warning_(VALIDATION_ERROR_NONE) { - MOJO_DCHECK(!g_serialization_warning_observer); - g_serialization_warning_observer = this; -} - -SerializationWarningObserverForTesting:: - ~SerializationWarningObserverForTesting() { - MOJO_DCHECK(g_serialization_warning_observer == this); - g_serialization_warning_observer = nullptr; -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/lib/validation_errors.h b/mojo/public/cpp/bindings/lib/validation_errors.h deleted file mode 100644 index 2abb1b7..0000000 --- a/mojo/public/cpp/bindings/lib/validation_errors.h +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_VALIDATION_ERRORS_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_LIB_VALIDATION_ERRORS_H_ - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -namespace internal { - -enum ValidationError { - // There is no validation error. - VALIDATION_ERROR_NONE, - // An object (struct or array) is not 8-byte aligned. - VALIDATION_ERROR_MISALIGNED_OBJECT, - // An object is not contained inside the message data, or it overlaps other - // objects. - VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE, - // A struct header doesn't make sense, for example: - // - |num_bytes| is smaller than the size of the oldest version that we - // support. - // - |num_fields| is smaller than the field number of the oldest version that - // we support. - // - |num_bytes| and |num_fields| don't match. - VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER, - // An array header doesn't make sense, for example: - // - |num_bytes| is smaller than the size of the header plus the size required - // to store |num_elements| elements. - // - For fixed-size arrays, |num_elements| is different than the specified - // size. - VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER, - // An encoded handle is illegal. - VALIDATION_ERROR_ILLEGAL_HANDLE, - // A non-nullable handle field is set to invalid handle. - VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, - // An encoded pointer is illegal. - VALIDATION_ERROR_ILLEGAL_POINTER, - // A non-nullable pointer field is set to null. - VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, - // |flags| in the message header is an invalid flag combination. - VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAG_COMBINATION, - // |flags| in the message header indicates that a request ID is required but - // there isn't one. - VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID, - // Two parallel arrays which are supposed to represent a map have different - // lengths. - VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP -}; - -const char* ValidationErrorToString(ValidationError error); - -void ReportValidationError(ValidationError error, - const char* description = nullptr); - -// Only used by validation tests and when there is only one thread doing message -// validation. -class ValidationErrorObserverForTesting { - public: - ValidationErrorObserverForTesting(); - ~ValidationErrorObserverForTesting(); - - ValidationError last_error() const { return last_error_; } - void set_last_error(ValidationError error) { last_error_ = error; } - - private: - ValidationError last_error_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ValidationErrorObserverForTesting); -}; - -// Used only by MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING. Don't use it directly. -// -// The function returns true if the error is recorded (by a -// SerializationWarningObserverForTesting object), false otherwise. -bool ReportSerializationWarning(ValidationError error); - -// Only used by serialization tests and when there is only one thread doing -// message serialization. -class SerializationWarningObserverForTesting { - public: - SerializationWarningObserverForTesting(); - ~SerializationWarningObserverForTesting(); - - ValidationError last_warning() const { return last_warning_; } - void set_last_warning(ValidationError error) { last_warning_ = error; } - - private: - ValidationError last_warning_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(SerializationWarningObserverForTesting); -}; - -} // namespace internal -} // namespace mojo - -// In debug build, logs a serialization warning if |condition| evaluates to -// true: -// - if there is a SerializationWarningObserverForTesting object alive, -// records |error| in it; -// - otherwise, logs a fatal-level message. -// |error| is the validation error that will be triggered by the receiver -// of the serialzation result. -// -// In non-debug build, does nothing (not even compiling |condition|). -#define MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( \ - condition, error, description) \ - MOJO_DLOG_IF(FATAL, (condition) && !ReportSerializationWarning(error)) \ - << "The outgoing message will trigger " \ - << ValidationErrorToString(error) << " at the receiving side (" \ - << description << ")."; - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_VALIDATION_ERRORS_H_ |