diff options
author | blundell <blundell@chromium.org> | 2015-01-19 09:18:33 -0800 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2015-01-19 17:19:27 +0000 |
commit | 70fb54767b472a5edfb859e489beeeec7abdb0e4 (patch) | |
tree | 28e534ec774391a9f6571a1770e12a0d63ebf833 /mojo/public/cpp | |
parent | ba5f0233fa38f949e24f6274ba891fa652eab640 (diff) | |
download | chromium_src-70fb54767b472a5edfb859e489beeeec7abdb0e4.zip chromium_src-70fb54767b472a5edfb859e489beeeec7abdb0e4.tar.gz chromium_src-70fb54767b472a5edfb859e489beeeec7abdb0e4.tar.bz2 |
Move //mojo/{public, edk} underneath //third_party
This CL move //mojo/public and //mojo/edk to live in the following locations:
- //third_party/mojo/src/mojo/public
- //third_party/mojo/src/mojo/edk
It moves the related gypfiles from //mojo to //third_party/mojo and updates
them as necessary to account for the file moves. It also updates clients of the
mojo SDK and EDK targets in both GYP and GN. (Note that for GN, the mojo SDK
and EDK build systems are maintained in the Mojo repo and designed to be
flexible wrt the location of the SDK/EDK in a client repo, so no changes are
needed.
This CL does not update include paths to the code being moved to limit the
number of moving parts, instead relying on the include_dirs that the SDK and
EDK targets supply to their direct dependents to ensure that include paths
continue to resolve correctly.
NOPRESUBMIT=true
Review URL: https://codereview.chromium.org/814543006
Cr-Commit-Position: refs/heads/master@{#312129}
Diffstat (limited to 'mojo/public/cpp')
164 files changed, 0 insertions, 17179 deletions
diff --git a/mojo/public/cpp/DEPS b/mojo/public/cpp/DEPS deleted file mode 100644 index 74acd7c..0000000 --- a/mojo/public/cpp/DEPS +++ /dev/null @@ -1,18 +0,0 @@ -include_rules = [ - # Require explicit dependencies in each directory. - "-mojo/public", - # But everyone can depend on the C and C++ system headers. - "+mojo/public/c/system", - "+mojo/public/cpp/system", - # Ditto for the C environment headers (but not the C++ environment, since it - # has dependencies of its own). - "+mojo/public/c/environment", -] - -specific_include_rules = { - r".*_(unit|perf)test\.cc": [ - "+testing", - "+mojo/public/cpp/test_support", - "+mojo/public/cpp/utility", - ], -} diff --git a/mojo/public/cpp/README.md b/mojo/public/cpp/README.md deleted file mode 100644 index 8f03d98..0000000 --- a/mojo/public/cpp/README.md +++ /dev/null @@ -1,71 +0,0 @@ -Mojo Public C++ API -=================== - -This directory contains C++ language bindings for the Mojo Public API. - -A number of subdirectories provide wrappers for the lower-level C APIs (in -subdirectories of the same name, under mojo/public/c/). Typically, these -wrappers provide increased convenience and/or type-safety. - -Other subdirectories provide support (static) libraries of various sorts. In -this case, the organization is to have the public interface for the library in -defined in header files in the subdirectory itself and the implementation of the -library at a lower level, under a lib (sub)subdirectory. A developer should be -able to substitute their own implementation of any such support library, and -expect other support libraries, which may depend on that library, to work -properly. - -Bindings --------- - -The bindings/ subdirectory contains a support (static) library needed by the -code generated by the bindings generator tool (in mojo/public/tools/bindings/), -which translates Mojo IDL (.mojom) files into idiomatic C++ (among other -languages). - -This library depends on the Environment library. - -Environment ------------ - -The environment/ subdirectory contains a support (static) library that -represents shared state needed to support the Bindings and GLES2 libraries. - -This library depends on the Utility library. - - -GLES2 ------ - -The gles2/ subdirectory contains C++ wrappers (and some additional helpers) of -the API defined in mojo/public/c/gles2/ (which provides access to GLES2). - -These wrappers depend on the Environment library. - -Shell ------ - -The shell/ subdirectory contains a support (static) library that aids in writing -Mojo applications and interacting with the Shell service. - -System ------- - -The system/ subdirectory contains C++ wrappers (and some additional helpers) of -the API defined in mojo/public/c/system/, which defines the basic, "core" API, -especially used to communicate with Mojo services. - -Test Support ------------- - -The test_support/ subdirectory contains C++ wrappers of the test-only API -defined in mojo/public/c/test_support/. It is not meant for general use by Mojo -applications. - -Utility -------- - -The utility/ subdirectory contains a support (static) library that provides -various basic functionality. Most notably, it provides an implementation of a -RunLoop based on MojoWaitMany() that applications may use as the basis for -asynchronous message processing. diff --git a/mojo/public/cpp/application/BUILD.gn b/mojo/public/cpp/application/BUILD.gn deleted file mode 100644 index 1c8842d..0000000 --- a/mojo/public/cpp/application/BUILD.gn +++ /dev/null @@ -1,91 +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. - -import("../../mojo_sdk.gni") - -# GYP version: mojo/public/mojo_public.gyp:mojo_application_base -mojo_sdk_source_set("application") { - sources = [ - "application_connection.h", - "application_delegate.h", - "application_impl.h", - "connect.h", - "service_provider_impl.h", - "interface_factory.h", - "interface_factory_impl.h", - "lib/application_connection.cc", - "lib/application_delegate.cc", - "lib/application_impl.cc", - "lib/service_provider_impl.cc", - "lib/service_connector.cc", - "lib/service_connector.h", - "lib/service_registry.cc", - "lib/service_registry.h", - "lib/weak_service_provider.cc", - "lib/weak_service_provider.h", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/bindings", - "mojo/public/cpp/environment", - "mojo/public/cpp/system", - "mojo/public/interfaces/application", - ] -} - -# GYP version: mojo/public/mojo_public.gyp:mojo_application_standalone -mojo_sdk_source_set("standalone") { - sources = [ - "lib/application_runner.cc", - ] - - public_deps = [ - ":application", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/environment:standalone", - "mojo/public/cpp/utility", - ] -} - -mojo_sdk_source_set("test_support") { - testonly = true - sources = [ - "application_test_base.h", - "lib/application_test_base.cc", - ] - - deps = [ - ":application", - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/bindings", - "mojo/public/cpp/environment", - "mojo/public/cpp/system", - ] -} - -mojo_sdk_source_set("test_support_standalone") { - testonly = true - sources = [ - "lib/application_test_main.cc", - ] - - public_deps = [ - ":test_support", - ] - - deps = [ - ":application", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/environment:standalone", - "mojo/public/cpp/system", - "mojo/public/cpp/utility", - ] -} diff --git a/mojo/public/cpp/application/DEPS b/mojo/public/cpp/application/DEPS deleted file mode 100644 index 503eebc..0000000 --- a/mojo/public/cpp/application/DEPS +++ /dev/null @@ -1,11 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/bindings", - "+mojo/public/cpp/environment", - "+mojo/public/interfaces/application", - "+mojo/public/interfaces/service_provider", -] -specific_include_rules = { - r"application_test_base\.h": [ - "+testing/gtest/include/gtest", - ], -}
\ No newline at end of file diff --git a/mojo/public/cpp/application/application_connection.h b/mojo/public/cpp/application/application_connection.h deleted file mode 100644 index d5d6dde..0000000 --- a/mojo/public/cpp/application/application_connection.h +++ /dev/null @@ -1,82 +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_APPLICATION_APPLICATION_CONNECTION_H_ -#define MOJO_PUBLIC_APPLICATION_APPLICATION_CONNECTION_H_ - -#include <string> - -#include "mojo/public/cpp/application/lib/service_connector.h" -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { - -// An instance of this class is passed to -// ApplicationDelegate's ConfigureIncomingConnection() method each time a -// connection is made to this app, and to ApplicationDelegate's -// ConfigureOutgoingConnection() method when the app connects to -// another. -// -// To use define a class that implements your specific service api, e.g. FooImpl -// to implement a service named Foo. -// That class must subclass an InterfaceImpl specialization. -// -// Then implement an InterfaceFactory<Foo> that binds instances of FooImpl to -// InterfaceRequest<Foo>s and register that on the connection. -// -// connection->AddService(&factory); -// -// Or if you have multiple factories implemented by the same type, explicitly -// specify the interface to register the factory for: -// -// connection->AddService<Foo>(&my_foo_and_bar_factory_); -// connection->AddService<Bar>(&my_foo_and_bar_factory_); -// -// The InterfaceFactory must outlive the ApplicationConnection. -class ApplicationConnection { - public: - virtual ~ApplicationConnection(); - - template <typename Interface> - void AddService(InterfaceFactory<Interface>* factory) { - AddServiceConnector( - new internal::InterfaceFactoryConnector<Interface>(factory)); - } - - // Connect to the service implementing |Interface|. - template <typename Interface> - void ConnectToService(InterfacePtr<Interface>* ptr) { - MessagePipe pipe; - ptr->Bind(pipe.handle0.Pass()); - GetServiceProvider()->ConnectToService(Interface::Name_, - pipe.handle1.Pass()); - } - - // The url identifying the application on the other end of this connection. - virtual const std::string& GetRemoteApplicationURL() = 0; - - // Establishes a new connection to an application. - // TODO(davemoore): Would it be better to expose the ApplicationImpl? - virtual ApplicationConnection* ConnectToApplication( - const std::string& url) = 0; - - // Connect to application identified by |application_url| and connect to - // the service implementation of the interface identified by |Interface|. - template <typename Interface> - void ConnectToService(const std::string& application_url, - InterfacePtr<Interface>* ptr) { - ConnectToApplication(application_url)->ConnectToService(ptr); - } - - // Raw ServiceProvider interface to remote application. - virtual ServiceProvider* GetServiceProvider() = 0; - - private: - virtual void AddServiceConnector( - internal::ServiceConnectorBase* service_connector) = 0; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_APPLICATION_APPLICATION_CONNECTION_H_ diff --git a/mojo/public/cpp/application/application_delegate.h b/mojo/public/cpp/application/application_delegate.h deleted file mode 100644 index b0f2916..0000000 --- a/mojo/public/cpp/application/application_delegate.h +++ /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. - -#ifndef MOJO_PUBLIC_APPLICATION_APPLICATION_DELEGATE_H_ -#define MOJO_PUBLIC_APPLICATION_APPLICATION_DELEGATE_H_ - -#include <string> - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -class ApplicationConnection; -class ApplicationImpl; - -class ApplicationDelegate { - public: - ApplicationDelegate(); - virtual ~ApplicationDelegate(); - - virtual void Initialize(ApplicationImpl* app); - - // Override this method to configure what services a connection supports when - // being connected to from an app. - // return false to reject the connection entirely. - virtual bool ConfigureIncomingConnection(ApplicationConnection* connection); - - // Override this method to configure what services a connection supports when - // connecting to another app. - // return false to reject the connection entirely. - virtual bool ConfigureOutgoingConnection(ApplicationConnection* connection); - - private: - MOJO_DISALLOW_COPY_AND_ASSIGN(ApplicationDelegate); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_APPLICATION_APPLICATION_DELEGATE_H_ diff --git a/mojo/public/cpp/application/application_impl.h b/mojo/public/cpp/application/application_impl.h deleted file mode 100644 index 0ea22c9..0000000 --- a/mojo/public/cpp/application/application_impl.h +++ /dev/null @@ -1,119 +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_APPLICATION_APPLICATION_IMPL_H_ -#define MOJO_PUBLIC_APPLICATION_APPLICATION_IMPL_H_ -#include <vector> - -#include "mojo/public/cpp/application/application_connection.h" -#include "mojo/public/cpp/application/lib/service_connector.h" -#include "mojo/public/cpp/application/lib/service_registry.h" -#include "mojo/public/cpp/system/core.h" -#include "mojo/public/interfaces/application/application.mojom.h" -#include "mojo/public/interfaces/application/shell.mojom.h" - -namespace mojo { - -class ApplicationDelegate; - -// Utility class for communicating with the Shell, and providing Services -// to clients. -// -// To use define a class that implements your specific server api, e.g. FooImpl -// to implement a service named Foo. -// That class must subclass an InterfaceImpl specialization. -// -// If there is context that is to be shared amongst all instances, define a -// constructor with that class as its only argument, otherwise define an empty -// constructor. -// -// class FooImpl : public InterfaceImpl<Foo> { -// public: -// FooImpl(ApplicationContext* app_context) {} -// }; -// -// or -// -// class BarImpl : public InterfaceImpl<Bar> { -// public: -// // contexts will remain valid for the lifetime of BarImpl. -// BarImpl(ApplicationContext* app_context, BarContext* service_context) -// : app_context_(app_context), servicecontext_(context) {} -// -// Create an ApplicationImpl instance that collects any service implementations. -// -// ApplicationImpl app(service_provider_handle); -// app.AddService<FooImpl>(); -// -// BarContext context; -// app.AddService<BarImpl>(&context); -// -// -class ApplicationImpl : public InterfaceImpl<Application> { - public: - ApplicationImpl(ApplicationDelegate* delegate, - ScopedMessagePipeHandle shell_handle); - ApplicationImpl(ApplicationDelegate* delegate, MojoHandle shell_handle); - ~ApplicationImpl() override; - - Shell* shell() const { return shell_.get(); } - - // Returns any initial configuration arguments, passed by the Shell. - const std::vector<std::string>& args() const { return args_; } - bool HasArg(const std::string& arg) const; - - // Establishes a new connection to an application. Caller does not own. - ApplicationConnection* ConnectToApplication(const String& application_url); - - // Connect to application identified by |application_url| and connect to the - // service implementation of the interface identified by |Interface|. - template <typename Interface> - void ConnectToService(const std::string& application_url, - InterfacePtr<Interface>* ptr) { - ConnectToApplication(application_url)->ConnectToService(ptr); - } - - // Wait for the ShellPtr's Initialize message. - bool WaitForInitialize(); - - // Unbind the shell from this application and return its handle. - ScopedMessagePipeHandle UnbindShell(); - - // Application implementation. - void Initialize(Array<String> args) override; - - // Quits the main run loop for this application. - static void Terminate(); - - private: - class ShellPtrWatcher; - - void BindShell(ScopedMessagePipeHandle shell_handle); - void ClearConnections(); - void OnShellError() { - ClearConnections(); - Terminate(); - } - - // Application implementation. - void AcceptConnection(const String& requestor_url, - InterfaceRequest<ServiceProvider> services, - ServiceProviderPtr exposed_services) override; - - typedef std::vector<internal::ServiceRegistry*> ServiceRegistryList; - - bool initialized_; - ServiceRegistryList incoming_service_registries_; - ServiceRegistryList outgoing_service_registries_; - ApplicationDelegate* delegate_; - ShellPtr shell_; - ShellPtrWatcher* shell_watch_; - std::vector<std::string> args_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ApplicationImpl); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_APPLICATION_APPLICATION_IMPL_H_ diff --git a/mojo/public/cpp/application/application_runner.h b/mojo/public/cpp/application/application_runner.h deleted file mode 100644 index b88ec8e..0000000 --- a/mojo/public/cpp/application/application_runner.h +++ /dev/null @@ -1,44 +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_APPLICATION_APPLICATION_RUNNER_H_ -#define MOJO_PUBLIC_APPLICATION_APPLICATION_RUNNER_H_ - -#include "mojo/public/cpp/system/core.h" - -namespace mojo { - -class ApplicationDelegate; - -// A utility for running an Application. The typical use case is to use -// when writing your MojoMain: -// -// MojoResult MojoMain(MojoHandle shell_handle) { -// mojo::ApplicationRunner runner(new MyApplicationDelegate()); -// return runner.Run(shell_handle); -// } -// -// ApplicationRunner takes care of mojo environment initialization and -// shutdown, and starting a RunLoop from which your application can run and -// ultimately Quit(). -class ApplicationRunner { - public: - // Takes ownership of |delegate|. - explicit ApplicationRunner(ApplicationDelegate* delegate); - ~ApplicationRunner(); - - // Once the various parameters have been set above, use Run to initialize an - // ApplicationImpl wired to the provided delegate, and run a RunLoop until - // the application exits. - MojoResult Run(MojoHandle shell_handle); - - private: - ApplicationDelegate* delegate_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ApplicationRunner); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_APPLICATION_APPLICATION_RUNNER_H_ diff --git a/mojo/public/cpp/application/application_test_base.h b/mojo/public/cpp/application/application_test_base.h deleted file mode 100644 index bdf2f8b..0000000 --- a/mojo/public/cpp/application/application_test_base.h +++ /dev/null @@ -1,65 +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_APPLICATION_APPLICATION_TEST_BASE_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_APPLICATION_TEST_BASE_H_ - -#include "mojo/public/cpp/application/application_delegate.h" -#include "mojo/public/cpp/bindings/array.h" -#include "mojo/public/cpp/bindings/string.h" -#include "mojo/public/cpp/system/macros.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { - -class ApplicationImpl; - -namespace test { - -// Access the command line arguments passed to the application test. -const Array<String>& Args(); - -// Run all application tests. This must be called after the environment is -// initialized, to support construction of a default run loop. -MojoResult RunAllTests(MojoHandle shell_handle); - -// A GTEST base class for application testing executed in mojo_shell. -class ApplicationTestBase : public testing::Test { - public: - ApplicationTestBase(); - ~ApplicationTestBase() override; - - protected: - ApplicationImpl* application_impl() { return application_impl_; } - - // Get the ApplicationDelegate for the application to be tested. - virtual ApplicationDelegate* GetApplicationDelegate(); - - // A testing::Test::SetUp helper to override the application command - // line arguments. - void SetUpWithArgs(const Array<String>& args); - - // testing::Test: - void SetUp() override; - void TearDown() override; - - // True by default, which indicates a MessageLoop will automatically be - // created for the application. Tests may override this function to prevent - // a default loop from being created. - virtual bool ShouldCreateDefaultRunLoop(); - - private: - // The application implementation instance, reconstructed for each test. - ApplicationImpl* application_impl_; - // The application delegate used if GetApplicationDelegate is not overridden. - ApplicationDelegate default_application_delegate_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ApplicationTestBase); -}; - -} // namespace test - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_APPLICATION_TEST_BASE_H_ diff --git a/mojo/public/cpp/application/connect.h b/mojo/public/cpp/application/connect.h deleted file mode 100644 index a41c028..0000000 --- a/mojo/public/cpp/application/connect.h +++ /dev/null @@ -1,22 +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_APPLICATION_CONNECT_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_CONNECT_H_ - -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { - -template <typename Interface> -inline void ConnectToService(ServiceProvider* service_provider, - InterfacePtr<Interface>* ptr) { - MessagePipe pipe; - ptr->Bind(pipe.handle0.Pass()); - service_provider->ConnectToService(Interface::Name_, pipe.handle1.Pass()); -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_CONNECT_H_ diff --git a/mojo/public/cpp/application/interface_factory.h b/mojo/public/cpp/application/interface_factory.h deleted file mode 100644 index 8840fcb..0000000 --- a/mojo/public/cpp/application/interface_factory.h +++ /dev/null @@ -1,31 +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_APPLICATION_INTERFACE_FACTORY_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_INTERFACE_FACTORY_H_ - -#include "mojo/public/cpp/bindings/interface_impl.h" -#include "mojo/public/cpp/bindings/interface_request.h" - -namespace mojo { - -class ApplicationConnection; -template <typename Interface> -class InterfaceRequest; - -// Implement this class to provide implementations of a given interface and -// bind them to incoming requests. The implementation of this class is -// responsible for managing the lifetime of the implementations of the -// interface. -template <typename Interface> -class InterfaceFactory { - public: - virtual ~InterfaceFactory() {} - virtual void Create(ApplicationConnection* connection, - InterfaceRequest<Interface> request) = 0; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_INTERFACE_FACTORY_H_ diff --git a/mojo/public/cpp/application/interface_factory_impl.h b/mojo/public/cpp/application/interface_factory_impl.h deleted file mode 100644 index 72d3254..0000000 --- a/mojo/public/cpp/application/interface_factory_impl.h +++ /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. - -#ifndef MOJO_PUBLIC_CPP_APPLICATION_INTERFACE_FACTORY_IMPL_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_INTERFACE_FACTORY_IMPL_H_ - -#include "mojo/public/cpp/application/interface_factory.h" - -namespace mojo { - -// Use this class to allocate and bind instances of Impl to interface requests. -// The lifetime of the constructed Impl is bound to the pipe. -template <typename Impl, - typename Interface = typename Impl::ImplementedInterface> -class InterfaceFactoryImpl : public InterfaceFactory<Interface> { - public: - virtual ~InterfaceFactoryImpl() {} - - virtual void Create(ApplicationConnection* connection, - InterfaceRequest<Interface> request) override { - BindToRequest(new Impl(), &request); - } -}; - -// Use this class to allocate and bind instances of Impl constructed with a -// context parameter to interface requests. The lifetime of the constructed -// Impl is bound to the pipe. -template <typename Impl, - typename Context, - typename Interface = typename Impl::ImplementedInterface> -class InterfaceFactoryImplWithContext : public InterfaceFactory<Interface> { - public: - explicit InterfaceFactoryImplWithContext(Context* context) - : context_(context) {} - virtual ~InterfaceFactoryImplWithContext() {} - - virtual void Create(ApplicationConnection* connection, - InterfaceRequest<Interface> request) override { - BindToRequest(new Impl(context_), &request); - } - - private: - Context* context_; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_INTERFACE_FACTORY_IMPL_H_ diff --git a/mojo/public/cpp/application/lazy_interface_ptr.h b/mojo/public/cpp/application/lazy_interface_ptr.h deleted file mode 100644 index a9b57db..0000000 --- a/mojo/public/cpp/application/lazy_interface_ptr.h +++ /dev/null @@ -1,44 +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_APPLICATION_LAZY_INTERFACE_PTR_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_LAZY_INTERFACE_PTR_H_ - -#include "mojo/public/cpp/application/connect.h" -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { - -template <typename Interface> -class LazyInterfacePtr : public InterfacePtr<Interface> { - public: - LazyInterfacePtr() : service_provider_(nullptr) {} - - LazyInterfacePtr(ServiceProvider* service_provider) - : service_provider_(service_provider) {} - - void set_service_provider(ServiceProvider* service_provider) { - if (service_provider != service_provider_) { - InterfacePtr<Interface>::reset(); - } - service_provider_ = service_provider; - } - - Interface* get() const { - if (!InterfacePtr<Interface>::get() && service_provider_) { - mojo::ConnectToService<Interface>( - service_provider_, const_cast<LazyInterfacePtr<Interface>*>(this)); - } - return InterfacePtr<Interface>::get(); - } - Interface* operator->() const { return get(); } - Interface& operator*() const { return *get(); } - - private: - ServiceProvider* service_provider_; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_LAZY_INTERFACE_PTR_H_ diff --git a/mojo/public/cpp/application/lib/DEPS b/mojo/public/cpp/application/lib/DEPS deleted file mode 100644 index a04ed0f..0000000 --- a/mojo/public/cpp/application/lib/DEPS +++ /dev/null @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/utility", -] diff --git a/mojo/public/cpp/application/lib/application_connection.cc b/mojo/public/cpp/application/lib/application_connection.cc deleted file mode 100644 index d557817..0000000 --- a/mojo/public/cpp/application/lib/application_connection.cc +++ /dev/null @@ -1,12 +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/application/application_connection.h" - -namespace mojo { - -ApplicationConnection::~ApplicationConnection() { -} - -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/application_delegate.cc b/mojo/public/cpp/application/lib/application_delegate.cc deleted file mode 100644 index bd6aebd..0000000 --- a/mojo/public/cpp/application/lib/application_delegate.cc +++ /dev/null @@ -1,27 +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/application/application_delegate.h" - -namespace mojo { - -ApplicationDelegate::ApplicationDelegate() { -} -ApplicationDelegate::~ApplicationDelegate() { -} - -void ApplicationDelegate::Initialize(ApplicationImpl* app) { -} - -bool ApplicationDelegate::ConfigureIncomingConnection( - ApplicationConnection* connection) { - return true; -} - -bool ApplicationDelegate::ConfigureOutgoingConnection( - ApplicationConnection* connection) { - return true; -} - -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/application_impl.cc b/mojo/public/cpp/application/lib/application_impl.cc deleted file mode 100644 index 6677003..0000000 --- a/mojo/public/cpp/application/lib/application_impl.cc +++ /dev/null @@ -1,117 +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/application/application_impl.h" - -#include "mojo/public/cpp/application/application_delegate.h" -#include "mojo/public/cpp/application/lib/service_registry.h" -#include "mojo/public/cpp/bindings/interface_ptr.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { - -class ApplicationImpl::ShellPtrWatcher : public ErrorHandler { - public: - ShellPtrWatcher(ApplicationImpl* impl) : impl_(impl) {} - - ~ShellPtrWatcher() override {} - - void OnConnectionError() override { impl_->OnShellError(); } - - private: - ApplicationImpl* impl_; - MOJO_DISALLOW_COPY_AND_ASSIGN(ShellPtrWatcher); -}; - -ApplicationImpl::ApplicationImpl(ApplicationDelegate* delegate, - ScopedMessagePipeHandle shell_handle) - : initialized_(false), delegate_(delegate), shell_watch_(nullptr) { - BindShell(shell_handle.Pass()); -} - -ApplicationImpl::ApplicationImpl(ApplicationDelegate* delegate, - MojoHandle shell_handle) - : initialized_(false), delegate_(delegate), shell_watch_(nullptr) { - BindShell(MakeScopedHandle(MessagePipeHandle(shell_handle))); -} - -bool ApplicationImpl::HasArg(const std::string& arg) const { - return std::find(args_.begin(), args_.end(), arg) != args_.end(); -} - -void ApplicationImpl::ClearConnections() { - for (ServiceRegistryList::iterator i(incoming_service_registries_.begin()); - i != incoming_service_registries_.end(); - ++i) - delete *i; - for (ServiceRegistryList::iterator i(outgoing_service_registries_.begin()); - i != outgoing_service_registries_.end(); - ++i) - delete *i; - incoming_service_registries_.clear(); - outgoing_service_registries_.clear(); -} - -ApplicationImpl::~ApplicationImpl() { - ClearConnections(); - delete shell_watch_; -} - -ApplicationConnection* ApplicationImpl::ConnectToApplication( - const String& application_url) { - MOJO_CHECK(initialized_); - ServiceProviderPtr local_services; - InterfaceRequest<ServiceProvider> local_request = GetProxy(&local_services); - ServiceProviderPtr remote_services; - shell_->ConnectToApplication(application_url, GetProxy(&remote_services), - local_services.Pass()); - internal::ServiceRegistry* registry = new internal::ServiceRegistry( - this, application_url, remote_services.Pass(), local_request.Pass()); - if (!delegate_->ConfigureOutgoingConnection(registry)) { - delete registry; - return nullptr; - } - outgoing_service_registries_.push_back(registry); - return registry; -} - -bool ApplicationImpl::WaitForInitialize() { - MOJO_CHECK(!initialized_); - bool result = shell_.WaitForIncomingMethodCall(); - MOJO_CHECK(initialized_ || !result); - return result; -} - -ScopedMessagePipeHandle ApplicationImpl::UnbindShell() { - return shell_.PassMessagePipe(); -} - -void ApplicationImpl::Initialize(Array<String> args) { - MOJO_CHECK(!initialized_); - initialized_ = true; - args_ = args.To<std::vector<std::string>>(); - delegate_->Initialize(this); -} - -void ApplicationImpl::BindShell(ScopedMessagePipeHandle shell_handle) { - shell_watch_ = new ShellPtrWatcher(this); - shell_.Bind(shell_handle.Pass()); - shell_.set_client(this); - shell_.set_error_handler(shell_watch_); -} - -void ApplicationImpl::AcceptConnection( - const String& requestor_url, - InterfaceRequest<ServiceProvider> services, - ServiceProviderPtr exposed_services) { - internal::ServiceRegistry* registry = new internal::ServiceRegistry( - this, requestor_url, exposed_services.Pass(), services.Pass()); - if (!delegate_->ConfigureIncomingConnection(registry)) { - delete registry; - return; - } - incoming_service_registries_.push_back(registry); -} - -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/application_runner.cc b/mojo/public/cpp/application/lib/application_runner.cc deleted file mode 100644 index dec74489..0000000 --- a/mojo/public/cpp/application/lib/application_runner.cc +++ /dev/null @@ -1,39 +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/application/application_runner.h" - -#include "mojo/public/cpp/application/application_delegate.h" -#include "mojo/public/cpp/application/application_impl.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/utility/run_loop.h" - -namespace mojo { - -// static -void ApplicationImpl::Terminate() { - RunLoop::current()->Quit(); -} - -ApplicationRunner::ApplicationRunner(ApplicationDelegate* delegate) - : delegate_(delegate) { -} -ApplicationRunner::~ApplicationRunner() { - assert(!delegate_); -} - -MojoResult ApplicationRunner::Run(MojoHandle shell_handle) { - Environment env; - { - RunLoop loop; - ApplicationImpl app(delegate_, shell_handle); - loop.Run(); - } - - delete delegate_; - delegate_ = nullptr; - return MOJO_RESULT_OK; -} - -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/application_test_base.cc b/mojo/public/cpp/application/lib/application_test_base.cc deleted file mode 100644 index 20a60a1..0000000 --- a/mojo/public/cpp/application/lib/application_test_base.cc +++ /dev/null @@ -1,129 +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/application/application_test_base.h" - -#include "mojo/public/cpp/application/application_delegate.h" -#include "mojo/public/cpp/application/application_impl.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/message_pipe.h" - -namespace mojo { -namespace test { - -namespace { - -// This shell handle is shared by multiple test application instances. -MessagePipeHandle g_shell_handle; -// Share the application command-line arguments with multiple application tests. -Array<String> g_args; - -ScopedMessagePipeHandle PassShellHandle() { - MOJO_CHECK(g_shell_handle.is_valid()); - ScopedMessagePipeHandle scoped_handle(g_shell_handle); - g_shell_handle = MessagePipeHandle(); - return scoped_handle.Pass(); -} - -void SetShellHandle(ScopedMessagePipeHandle handle) { - MOJO_CHECK(handle.is_valid()); - MOJO_CHECK(!g_shell_handle.is_valid()); - g_shell_handle = handle.release(); -} - -void InitializeArgs(int argc, std::vector<const char*> argv) { - MOJO_CHECK(g_args.is_null()); - for (const char* arg : argv) { - if (arg) - g_args.push_back(arg); - } -} - -} // namespace - -const Array<String>& Args() { - return g_args; -} - -MojoResult RunAllTests(MojoHandle shell_handle) { - { - // This loop is used for init, and then destroyed before running tests. - Environment::InstantiateDefaultRunLoop(); - - // Construct an ApplicationImpl just for the GTEST commandline arguments. - // GTEST command line arguments are supported amid application arguments: - // $ mojo_shell mojo:example_apptests - // --args-for='mojo:example_apptests arg1 --gtest_filter=foo arg2' - mojo::ApplicationDelegate dummy_application_delegate; - mojo::ApplicationImpl app(&dummy_application_delegate, shell_handle); - MOJO_CHECK(app.WaitForInitialize()); - - // InitGoogleTest expects (argc + 1) elements, including a terminating null. - // It also removes GTEST arguments from |argv| and updates the |argc| count. - const std::vector<std::string>& args = app.args(); - MOJO_CHECK(args.size() < - static_cast<size_t>(std::numeric_limits<int>::max())); - int argc = static_cast<int>(args.size()); - std::vector<const char*> argv(argc + 1); - for (int i = 0; i < argc; ++i) - argv[i] = args[i].c_str(); - argv[argc] = nullptr; - - testing::InitGoogleTest(&argc, const_cast<char**>(&(argv[0]))); - SetShellHandle(app.UnbindShell()); - InitializeArgs(argc, argv); - - Environment::DestroyDefaultRunLoop(); - } - - int result = RUN_ALL_TESTS(); - - shell_handle = mojo::test::PassShellHandle().release().value(); - MojoResult close_result = MojoClose(shell_handle); - MOJO_CHECK(close_result == MOJO_RESULT_OK); - - return (result == 0) ? MOJO_RESULT_OK : MOJO_RESULT_UNKNOWN; -} - -ApplicationTestBase::ApplicationTestBase() : application_impl_(nullptr) { -} - -ApplicationTestBase::~ApplicationTestBase() { -} - -ApplicationDelegate* ApplicationTestBase::GetApplicationDelegate() { - return &default_application_delegate_; -} - -void ApplicationTestBase::SetUpWithArgs(const Array<String>& args) { - // A run loop is recommended for ApplicationImpl initialization and - // communication. - if (ShouldCreateDefaultRunLoop()) - Environment::InstantiateDefaultRunLoop(); - - // New applications are constructed for each test to avoid persisting state. - application_impl_ = new ApplicationImpl(GetApplicationDelegate(), - PassShellHandle()); - - // Fake application initialization with the given command line arguments. - application_impl_->Initialize(args.Clone()); -} - -void ApplicationTestBase::SetUp() { - SetUpWithArgs(Args()); -} - -void ApplicationTestBase::TearDown() { - SetShellHandle(application_impl_->UnbindShell()); - delete application_impl_; - if (ShouldCreateDefaultRunLoop()) - Environment::DestroyDefaultRunLoop(); -} - -bool ApplicationTestBase::ShouldCreateDefaultRunLoop() { - return true; -} - -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/application_test_main.cc b/mojo/public/cpp/application/lib/application_test_main.cc deleted file mode 100644 index 47f36e9..0000000 --- a/mojo/public/cpp/application/lib/application_test_main.cc +++ /dev/null @@ -1,14 +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/c/system/main.h" -#include "mojo/public/cpp/application/application_test_base.h" -#include "mojo/public/cpp/environment/environment.h" - -MojoResult MojoMain(MojoHandle shell_handle) { - // An Environment instance is needed to construct run loops. - mojo::Environment environment; - - return mojo::test::RunAllTests(shell_handle); -} diff --git a/mojo/public/cpp/application/lib/service_connector.cc b/mojo/public/cpp/application/lib/service_connector.cc deleted file mode 100644 index ada5d9c..0000000 --- a/mojo/public/cpp/application/lib/service_connector.cc +++ /dev/null @@ -1,18 +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/application/lib/service_connector.h" - -namespace mojo { -namespace internal { - -ServiceConnectorBase::ServiceConnectorBase(const std::string& name) - : name_(name), application_connection_(nullptr) { -} - -ServiceConnectorBase::~ServiceConnectorBase() { -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/service_connector.h b/mojo/public/cpp/application/lib/service_connector.h deleted file mode 100644 index 70c1380..0000000 --- a/mojo/public/cpp/application/lib/service_connector.h +++ /dev/null @@ -1,55 +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_APPLICATION_LIB_SERVICE_CONNECTOR_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_LIB_SERVICE_CONNECTOR_H_ - -#include "mojo/public/cpp/application/interface_factory.h" -#include "mojo/public/cpp/bindings/interface_request.h" - -namespace mojo { -class ApplicationConnection; - -namespace internal { - -class ServiceConnectorBase { - public: - ServiceConnectorBase(const std::string& name); - virtual ~ServiceConnectorBase(); - virtual void ConnectToService(const std::string& name, - ScopedMessagePipeHandle client_handle) = 0; - std::string name() const { return name_; } - void set_application_connection(ApplicationConnection* connection) { - application_connection_ = connection; - } - - protected: - std::string name_; - ApplicationConnection* application_connection_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ServiceConnectorBase); -}; - -template <typename Interface> -class InterfaceFactoryConnector : public ServiceConnectorBase { - public: - explicit InterfaceFactoryConnector(InterfaceFactory<Interface>* factory) - : ServiceConnectorBase(Interface::Name_), factory_(factory) {} - virtual ~InterfaceFactoryConnector() {} - - virtual void ConnectToService(const std::string& name, - ScopedMessagePipeHandle client_handle) { - factory_->Create(application_connection_, - MakeRequest<Interface>(client_handle.Pass())); - } - - private: - InterfaceFactory<Interface>* factory_; - MOJO_DISALLOW_COPY_AND_ASSIGN(InterfaceFactoryConnector); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_LIB_SERVICE_CONNECTOR_H_ diff --git a/mojo/public/cpp/application/lib/service_provider_impl.cc b/mojo/public/cpp/application/lib/service_provider_impl.cc deleted file mode 100644 index 08a0648..0000000 --- a/mojo/public/cpp/application/lib/service_provider_impl.cc +++ /dev/null @@ -1,69 +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/application/service_provider_impl.h" - -#include "mojo/public/cpp/application/lib/service_connector.h" -#include "mojo/public/cpp/application/lib/weak_service_provider.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { - -ServiceProviderImpl::ServiceProviderImpl() : remote_(nullptr) { -} - -ServiceProviderImpl::~ServiceProviderImpl() { -} - -ServiceProvider* ServiceProviderImpl::CreateRemoteServiceProvider() { - // TODO(beng): it sure would be nice if this method could return a scoped_ptr. - MOJO_DCHECK(!remote_); - remote_ = new internal::WeakServiceProvider(this, client()); - return remote_; -} - -void ServiceProviderImpl::ConnectToService( - const String& service_name, - ScopedMessagePipeHandle client_handle) { - if (service_connectors_.find(service_name) == service_connectors_.end()) { - client_handle.reset(); - return; - } - - internal::ServiceConnectorBase* service_connector = - service_connectors_[service_name]; - return service_connector->ConnectToService(service_name, - client_handle.Pass()); -} - -void ServiceProviderImpl::OnConnectionError() { - ClearRemote(); -} - -void ServiceProviderImpl::AddServiceConnector( - internal::ServiceConnectorBase* service_connector) { - RemoveServiceConnector(service_connector); - service_connectors_[service_connector->name()] = service_connector; - // TODO(beng): perhaps take app connection thru ctor?? - service_connector->set_application_connection(nullptr); -} - -void ServiceProviderImpl::RemoveServiceConnector( - internal::ServiceConnectorBase* service_connector) { - NameToServiceConnectorMap::iterator it = - service_connectors_.find(service_connector->name()); - if (it == service_connectors_.end()) - return; - delete it->second; - service_connectors_.erase(it); -} - -void ServiceProviderImpl::ClearRemote() { - if (remote_) { - remote_->Clear(); - remote_ = nullptr; - } -} - -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/service_registry.cc b/mojo/public/cpp/application/lib/service_registry.cc deleted file mode 100644 index d934a16..0000000 --- a/mojo/public/cpp/application/lib/service_registry.cc +++ /dev/null @@ -1,91 +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/application/lib/service_registry.h" - -#include "mojo/public/cpp/application/application_connection.h" -#include "mojo/public/cpp/application/application_impl.h" -#include "mojo/public/cpp/application/lib/service_connector.h" - -namespace mojo { -namespace internal { - -ServiceRegistry::ServiceRegistry( - ApplicationImpl* application_impl, - const std::string& url, - ServiceProviderPtr remote_services, - InterfaceRequest<ServiceProvider> local_services) - : application_impl_(application_impl), - url_(url), - local_binding_(this, local_services.Pass()), - remote_service_provider_(remote_services.Pass()) { -} - -ServiceRegistry::ServiceRegistry() - : application_impl_(nullptr), local_binding_(this) { -} - -ServiceRegistry::~ServiceRegistry() { - for (NameToServiceConnectorMap::iterator i = - name_to_service_connector_.begin(); - i != name_to_service_connector_.end(); - ++i) { - delete i->second; - } - name_to_service_connector_.clear(); -} - -void ServiceRegistry::AddServiceConnector( - ServiceConnectorBase* service_connector) { - RemoveServiceConnectorInternal(service_connector); - name_to_service_connector_[service_connector->name()] = service_connector; - service_connector->set_application_connection(this); -} - -void ServiceRegistry::RemoveServiceConnector( - ServiceConnectorBase* service_connector) { - RemoveServiceConnectorInternal(service_connector); - if (name_to_service_connector_.empty()) - remote_service_provider_.reset(); -} - -bool ServiceRegistry::RemoveServiceConnectorInternal( - ServiceConnectorBase* service_connector) { - NameToServiceConnectorMap::iterator it = - name_to_service_connector_.find(service_connector->name()); - if (it == name_to_service_connector_.end()) - return false; - delete it->second; - name_to_service_connector_.erase(it); - return true; -} - -const std::string& ServiceRegistry::GetRemoteApplicationURL() { - return url_; -} - -ServiceProvider* ServiceRegistry::GetServiceProvider() { - return remote_service_provider_.get(); -} - -ApplicationConnection* ServiceRegistry::ConnectToApplication( - const std::string& url) { - return application_impl_->ConnectToApplication(url); -} - -void ServiceRegistry::ConnectToService(const mojo::String& service_name, - ScopedMessagePipeHandle client_handle) { - if (name_to_service_connector_.find(service_name) == - name_to_service_connector_.end()) { - client_handle.reset(); - return; - } - internal::ServiceConnectorBase* service_connector = - name_to_service_connector_[service_name]; - return service_connector->ConnectToService(service_name, - client_handle.Pass()); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/service_registry.h b/mojo/public/cpp/application/lib/service_registry.h deleted file mode 100644 index af1613b..0000000 --- a/mojo/public/cpp/application/lib/service_registry.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_APPLICATION_LIB_SERVICE_REGISTRY_H_ -#define MOJO_PUBLIC_CPP_APPLICATION_LIB_SERVICE_REGISTRY_H_ - -#include "mojo/public/cpp/application/application_connection.h" -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { - -class Application; -class ApplicationImpl; - -namespace internal { - -class ServiceConnectorBase; - -// A ServiceRegistry represents each half of a connection between two -// applications, allowing customization of which services are published to the -// other. -class ServiceRegistry : public ServiceProvider, public ApplicationConnection { - public: - ServiceRegistry(); - ServiceRegistry(ApplicationImpl* application_impl, - const std::string& url, - ServiceProviderPtr remote_services, - InterfaceRequest<ServiceProvider> local_services); - ~ServiceRegistry() override; - - // ApplicationConnection overrides. - void AddServiceConnector(ServiceConnectorBase* service_connector) override; - const std::string& GetRemoteApplicationURL() override; - ApplicationConnection* ConnectToApplication(const std::string& url) override; - ServiceProvider* GetServiceProvider() override; - - virtual void RemoveServiceConnector(ServiceConnectorBase* service_connector); - - private: - // ServiceProvider method. - void ConnectToService(const mojo::String& service_name, - ScopedMessagePipeHandle client_handle) override; - - ApplicationImpl* application_impl_; - const std::string url_; - - private: - bool RemoveServiceConnectorInternal(ServiceConnectorBase* service_connector); - - Application* application_; - typedef std::map<std::string, ServiceConnectorBase*> - NameToServiceConnectorMap; - NameToServiceConnectorMap name_to_service_connector_; - Binding<ServiceProvider> local_binding_; - ServiceProviderPtr remote_service_provider_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ServiceRegistry); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_APPLICATION_LIB_SERVICE_REGISTRY_H_ diff --git a/mojo/public/cpp/application/lib/weak_service_provider.cc b/mojo/public/cpp/application/lib/weak_service_provider.cc deleted file mode 100644 index de0cb6c..0000000 --- a/mojo/public/cpp/application/lib/weak_service_provider.cc +++ /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. - -#include "mojo/public/cpp/application/lib/weak_service_provider.h" - -#include "mojo/public/cpp/application/service_provider_impl.h" -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { -namespace internal { - -WeakServiceProvider::WeakServiceProvider(ServiceProviderImpl* creator, - ServiceProvider* service_provider) - : creator_(creator), service_provider_(service_provider) { -} - -WeakServiceProvider::~WeakServiceProvider() { - if (creator_) - creator_->ClearRemote(); -} - -void WeakServiceProvider::Clear() { - creator_ = nullptr; - service_provider_ = nullptr; -} - -void WeakServiceProvider::ConnectToService( - const String& service_name, - ScopedMessagePipeHandle client_handle) { - if (service_provider_) - service_provider_->ConnectToService(service_name, client_handle.Pass()); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/application/lib/weak_service_provider.h b/mojo/public/cpp/application/lib/weak_service_provider.h deleted file mode 100644 index 3d959d1..0000000 --- a/mojo/public/cpp/application/lib/weak_service_provider.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_APPLICATION_LIB_WEAK_SERVICE_PROVIDER_H_ -#define MOJO_PUBLIC_APPLICATION_LIB_WEAK_SERVICE_PROVIDER_H_ - -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { -class ServiceProviderImpl; -namespace internal { -class ServiceConnectorBase; - -// Implements a weak pointer to a ServiceProvider. Necessary as the lifetime of -// the ServiceProviderImpl is bound to that of its pipe, but code may continue -// to reference a remote service provider beyond the lifetime of said pipe. -// Calls to ConnectToService() are silently dropped when the pipe is closed. -class WeakServiceProvider : public ServiceProvider { - public: - WeakServiceProvider(ServiceProviderImpl* creator, - ServiceProvider* service_provider); - ~WeakServiceProvider() override; - - void Clear(); - - private: - // Overridden from ServiceProvider: - void ConnectToService(const String& service_name, - ScopedMessagePipeHandle client_handle) override; - - ServiceProviderImpl* creator_; - ServiceProvider* service_provider_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(WeakServiceProvider); -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_APPLICATION_LIB_WEAK_SERVICE_PROVIDER_H_ diff --git a/mojo/public/cpp/application/service_provider_impl.h b/mojo/public/cpp/application/service_provider_impl.h deleted file mode 100644 index 45ad7b8..0000000 --- a/mojo/public/cpp/application/service_provider_impl.h +++ /dev/null @@ -1,66 +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_APPLICATION_SERVICE_PROVIDER_IMPL_H_ -#define MOJO_PUBLIC_APPLICATION_SERVICE_PROVIDER_IMPL_H_ - -#include "mojo/public/cpp/application/lib/service_connector.h" -#include "mojo/public/interfaces/application/service_provider.mojom.h" - -namespace mojo { -namespace internal { -class WeakServiceProvider; -class ServiceConnectorBase; -} - -// Implements a registry that can be used to expose services to another app. -class ServiceProviderImpl : public InterfaceImpl<ServiceProvider> { - public: - ServiceProviderImpl(); - ~ServiceProviderImpl() override; - - template <typename Interface> - void AddService(InterfaceFactory<Interface>* factory) { - AddServiceConnector( - new internal::InterfaceFactoryConnector<Interface>(factory)); - } - - // Returns an instance of a ServiceProvider that weakly wraps this impl's - // connection to some other app. Whereas the lifetime of an instance of - // ServiceProviderImpl is bound to the lifetime of the pipe it - // encapsulates, the lifetime of the ServiceProvider instance returned by this - // method is assumed by the caller. After the pipe is closed - // ConnectToService() calls on this object will be silently dropped. - // This method must only be called once per ServiceProviderImpl. - ServiceProvider* CreateRemoteServiceProvider(); - - private: - typedef std::map<std::string, internal::ServiceConnectorBase*> - NameToServiceConnectorMap; - - friend class internal::WeakServiceProvider; - - // Overridden from ServiceProvider: - void ConnectToService(const String& service_name, - ScopedMessagePipeHandle client_handle) override; - - // Overridden from InterfaceImpl: - void OnConnectionError() override; - - void AddServiceConnector(internal::ServiceConnectorBase* service_connector); - void RemoveServiceConnector( - internal::ServiceConnectorBase* service_connector); - - void ClearRemote(); - - NameToServiceConnectorMap service_connectors_; - - internal::WeakServiceProvider* remote_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ServiceProviderImpl); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_APPLICATION_SERVICE_PROVIDER_IMPL_H_ diff --git a/mojo/public/cpp/application/tests/BUILD.gn b/mojo/public/cpp/application/tests/BUILD.gn deleted file mode 100644 index 7766a7d..0000000 --- a/mojo/public/cpp/application/tests/BUILD.gn +++ /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. - -import("../../../mojo_sdk.gni") - -mojo_sdk_source_set("tests") { - testonly = true - - sources = [ - "service_registry_unittest.cc", - ] - - deps = [ - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/application:standalone", - "mojo/public/cpp/environment:standalone", - "mojo/public/cpp/utility", - ] -} diff --git a/mojo/public/cpp/application/tests/service_registry_unittest.cc b/mojo/public/cpp/application/tests/service_registry_unittest.cc deleted file mode 100644 index 283bf14..0000000 --- a/mojo/public/cpp/application/tests/service_registry_unittest.cc +++ /dev/null @@ -1,65 +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/application/lib/service_registry.h" - -#include "mojo/public/cpp/application/lib/service_connector.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace internal { -namespace { - -class TestConnector : public ServiceConnectorBase { - public: - TestConnector(const std::string& name, int* delete_count) - : ServiceConnectorBase(name), delete_count_(delete_count) {} - ~TestConnector() override { (*delete_count_)++; } - void ConnectToService(const std::string& name, - ScopedMessagePipeHandle client_handle) override {} - - private: - int* delete_count_; -}; - -TEST(ServiceRegistryTest, Ownership) { - int delete_count = 0; - - // Destruction. - { - ServiceRegistry registry; - registry.AddServiceConnector(new TestConnector("TC1", &delete_count)); - } - EXPECT_EQ(1, delete_count); - - // Removal. - { - ServiceRegistry registry; - ServiceConnectorBase* c = new TestConnector("TC1", &delete_count); - registry.AddServiceConnector(c); - registry.RemoveServiceConnector(c); - EXPECT_EQ(2, delete_count); - } - - // Multiple. - { - ServiceRegistry registry; - registry.AddServiceConnector(new TestConnector("TC1", &delete_count)); - registry.AddServiceConnector(new TestConnector("TC2", &delete_count)); - } - EXPECT_EQ(4, delete_count); - - // Re-addition. - { - ServiceRegistry registry; - registry.AddServiceConnector(new TestConnector("TC1", &delete_count)); - registry.AddServiceConnector(new TestConnector("TC1", &delete_count)); - EXPECT_EQ(5, delete_count); - } - EXPECT_EQ(6, delete_count); -} - -} // namespace -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/bindings/BUILD.gn b/mojo/public/cpp/bindings/BUILD.gn deleted file mode 100644 index 515c3e1..0000000 --- a/mojo/public/cpp/bindings/BUILD.gn +++ /dev/null @@ -1,79 +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. - -import("../../mojo_sdk.gni") - -mojo_sdk_source_set("bindings") { - sources = [ - "array.h", - "binding.h", - "error_handler.h", - "interface_ptr.h", - "map.h", - "message.h", - "message_filter.h", - "no_interface.h", - "strong_binding.h", - "string.h", - "struct_ptr.h", - "type_converter.h", - "lib/array_internal.cc", - "lib/array_internal.h", - "lib/array_serialization.h", - "lib/bindings_internal.h", - "lib/bindings_serialization.cc", - "lib/bindings_serialization.h", - "lib/bounds_checker.cc", - "lib/bounds_checker.h", - "lib/buffer.h", - "lib/connector.cc", - "lib/connector.h", - "lib/filter_chain.cc", - "lib/filter_chain.h", - "lib/fixed_buffer.cc", - "lib/fixed_buffer.h", - "lib/map_data_internal.h", - "lib/map_internal.h", - "lib/map_serialization.h", - "lib/message.cc", - "lib/message_builder.cc", - "lib/message_builder.h", - "lib/message_filter.cc", - "lib/message_header_validator.cc", - "lib/message_header_validator.h", - "lib/message_internal.h", - "lib/message_queue.cc", - "lib/message_queue.h", - "lib/no_interface.cc", - "lib/router.cc", - "lib/router.h", - "lib/string_serialization.cc", - "lib/string_serialization.h", - "lib/union_accessor.h", - "lib/validate_params.h", - "lib/validation_errors.cc", - "lib/validation_errors.h", - ] - - deps = [ - ":callback", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/environment", - "mojo/public/cpp/system", - ] -} - -mojo_sdk_source_set("callback") { - sources = [ - "callback.h", - "lib/callback_internal.h", - "lib/template_util.h", - "lib/shared_data.h", - "lib/shared_ptr.h", - ] - - mojo_sdk_deps = [ "mojo/public/cpp/system" ] -} diff --git a/mojo/public/cpp/bindings/DEPS b/mojo/public/cpp/bindings/DEPS deleted file mode 100644 index 2a0496e..0000000 --- a/mojo/public/cpp/bindings/DEPS +++ /dev/null @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/environment", -] diff --git a/mojo/public/cpp/bindings/array.h b/mojo/public/cpp/bindings/array.h deleted file mode 100644 index ca4e9cc..0000000 --- a/mojo/public/cpp/bindings/array.h +++ /dev/null @@ -1,164 +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_ARRAY_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_ARRAY_H_ - -#include <string.h> - -#include <algorithm> -#include <string> -#include <vector> - -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/lib/bindings_internal.h" -#include "mojo/public/cpp/bindings/lib/template_util.h" -#include "mojo/public/cpp/bindings/type_converter.h" - -namespace mojo { - -template <typename T> -class Array { - MOJO_MOVE_ONLY_TYPE(Array) - public: - typedef internal::ArrayTraits<T, internal::IsMoveOnlyType<T>::value> Traits; - typedef typename Traits::ConstRefType ConstRefType; - typedef typename Traits::RefType RefType; - typedef typename Traits::StorageType StorageType; - typedef typename Traits::ForwardType ForwardType; - - typedef internal::Array_Data<typename internal::WrapperTraits<T>::DataType> - Data_; - - Array() : is_null_(true) {} - explicit Array(size_t size) : vec_(size), is_null_(false) { - Traits::Initialize(&vec_); - } - ~Array() { Traits::Finalize(&vec_); } - - Array(Array&& other) : is_null_(true) { Take(&other); } - Array& operator=(Array&& other) { - Take(&other); - return *this; - } - - static Array New(size_t size) { return Array(size).Pass(); } - - template <typename U> - static Array From(const U& other) { - return TypeConverter<Array, U>::Convert(other); - } - - template <typename U> - U To() const { - return TypeConverter<U, Array>::Convert(*this); - } - - void reset() { - if (!vec_.empty()) { - Traits::Finalize(&vec_); - vec_.clear(); - } - is_null_ = true; - } - - bool is_null() const { return is_null_; } - - ConstRefType front() const { return vec_.front(); } - RefType front() { return vec_.front(); } - - size_t size() const { return vec_.size(); } - - ConstRefType at(size_t offset) const { return Traits::at(&vec_, offset); } - ConstRefType operator[](size_t offset) const { return at(offset); } - - RefType at(size_t offset) { return Traits::at(&vec_, offset); } - RefType operator[](size_t offset) { return at(offset); } - - void push_back(ForwardType value) { - is_null_ = false; - Traits::PushBack(&vec_, value); - } - - void resize(size_t size) { - is_null_ = false; - Traits::Resize(&vec_, size); - } - - const std::vector<StorageType>& storage() const { return vec_; } - operator const std::vector<StorageType>&() const { return vec_; } - - void Swap(Array* other) { - std::swap(is_null_, other->is_null_); - vec_.swap(other->vec_); - } - void Swap(std::vector<StorageType>* other) { - is_null_ = false; - vec_.swap(*other); - } - - // Please note that calling this method will fail compilation if the element - // type cannot be cloned (which usually means that it is a Mojo handle type or - // a type contains Mojo handles). - Array Clone() const { - Array result; - result.is_null_ = is_null_; - Traits::Clone(vec_, &result.vec_); - return result.Pass(); - } - - bool Equals(const Array& other) const { - if (is_null() != other.is_null()) - return false; - if (size() != other.size()) - return false; - for (size_t i = 0; i < size(); ++i) { - if (!internal::ValueTraits<T>::Equals(at(i), other.at(i))) - return false; - } - return true; - } - - private: - typedef std::vector<StorageType> Array::*Testable; - - public: - operator Testable() const { return is_null_ ? 0 : &Array::vec_; } - - private: - void Take(Array* other) { - reset(); - Swap(other); - } - - std::vector<StorageType> vec_; - bool is_null_; -}; - -template <typename T, typename E> -struct TypeConverter<Array<T>, std::vector<E>> { - static Array<T> Convert(const std::vector<E>& input) { - Array<T> result(input.size()); - for (size_t i = 0; i < input.size(); ++i) - result[i] = TypeConverter<T, E>::Convert(input[i]); - return result.Pass(); - } -}; - -template <typename E, typename T> -struct TypeConverter<std::vector<E>, Array<T>> { - static std::vector<E> Convert(const Array<T>& input) { - std::vector<E> result; - if (!input.is_null()) { - result.resize(input.size()); - for (size_t i = 0; i < input.size(); ++i) - result[i] = TypeConverter<E, T>::Convert(input[i]); - } - return result; - } -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_ARRAY_H_ diff --git a/mojo/public/cpp/bindings/binding.h b/mojo/public/cpp/bindings/binding.h deleted file mode 100644 index 4ecc6a8..0000000 --- a/mojo/public/cpp/bindings/binding.h +++ /dev/null @@ -1,152 +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_BINDING_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_BINDING_H_ - -#include "mojo/public/c/environment/async_waiter.h" -#include "mojo/public/cpp/bindings/error_handler.h" -#include "mojo/public/cpp/bindings/interface_ptr.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#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" -#include "mojo/public/cpp/system/core.h" - -namespace mojo { - -// This binds an interface implementation a pipe. Deleting the binding closes -// the pipe. -// -// Example: -// -// #include "foo.mojom.h" -// -// class FooImpl : public Foo { -// public: -// explicit FooImpl(InterfaceRequest<Foo> request) -// : binding_(this, request.Pass()) {} -// -// // Foo implementation here. -// -// private: -// Binding<Foo> binding_; -// }; -// -// class MyFooFactory : public InterfaceFactory<Foo> { -// public: -// void Create(..., InterfaceRequest<Foo> request) override { -// auto f = new FooImpl(request.Pass()); -// // Do something to manage the lifetime of |f|. Use StrongBinding<> to -// // delete FooImpl on connection errors. -// } -// }; -template <typename Interface> -class Binding : public ErrorHandler { - public: - using Client = typename Interface::Client; - - explicit Binding(Interface* impl) : impl_(impl) { stub_.set_sink(impl_); } - - Binding(Interface* impl, - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) - : Binding(impl) { - Bind(handle.Pass(), waiter); - } - - Binding(Interface* impl, - InterfacePtr<Interface>* ptr, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) - : Binding(impl) { - Bind(ptr, waiter); - } - - Binding(Interface* impl, - InterfaceRequest<Interface> request, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) - : Binding(impl) { - Bind(request.PassMessagePipe(), waiter); - } - - ~Binding() override { - delete proxy_; - if (internal_router_) { - internal_router_->set_error_handler(nullptr); - delete internal_router_; - } - } - - void Bind( - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - internal::FilterChain filters; - filters.Append<internal::MessageHeaderValidator>(); - filters.Append<typename Interface::RequestValidator_>(); - filters.Append<typename Client::ResponseValidator_>(); - - internal_router_ = - new internal::Router(handle.Pass(), filters.Pass(), waiter); - internal_router_->set_incoming_receiver(&stub_); - internal_router_->set_error_handler(this); - - proxy_ = new typename Client::Proxy_(internal_router_); - } - - void Bind( - InterfacePtr<Interface>* ptr, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - MessagePipe pipe; - ptr->Bind(pipe.handle0.Pass(), waiter); - Bind(pipe.handle1.Pass(), waiter); - } - - void Bind( - InterfaceRequest<Interface> request, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - Bind(request.PassMessagePipe(), waiter); - } - - bool WaitForIncomingMethodCall() { - MOJO_DCHECK(internal_router_); - return internal_router_->WaitForIncomingMessage(); - } - - void Close() { - MOJO_DCHECK(internal_router_); - internal_router_->CloseMessagePipe(); - } - - void set_error_handler(ErrorHandler* error_handler) { - error_handler_ = error_handler; - } - - // ErrorHandler implementation - void OnConnectionError() override { - if (error_handler_) - error_handler_->OnConnectionError(); - } - - Interface* impl() { return impl_; } - Client* client() { return proxy_; } - - bool is_bound() const { return !!internal_router_; } - - // Exposed for testing, should not generally be used. - internal::Router* internal_router() { return internal_router_; } - - private: - internal::Router* internal_router_ = nullptr; - typename Client::Proxy_* proxy_ = nullptr; - typename Interface::Stub_ stub_; - Interface* impl_; - ErrorHandler* error_handler_ = nullptr; - - MOJO_DISALLOW_COPY_AND_ASSIGN(Binding); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_BINDING_H_ diff --git a/mojo/public/cpp/bindings/callback.h b/mojo/public/cpp/bindings/callback.h deleted file mode 100644 index d7bab16..0000000 --- a/mojo/public/cpp/bindings/callback.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_CALLBACK_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_CALLBACK_H_ - -#include "mojo/public/cpp/bindings/lib/callback_internal.h" -#include "mojo/public/cpp/bindings/lib/shared_ptr.h" -#include "mojo/public/cpp/bindings/lib/template_util.h" - -namespace mojo { - -template <typename Sig> -class Callback; - -template <typename... Args> -class Callback<void(Args...)> { - public: - struct Runnable { - virtual ~Runnable() {} - virtual void Run( - typename internal::Callback_ParamTraits<Args>::ForwardType...) - const = 0; - }; - - Callback() {} - - // The Callback assumes ownership of |runnable|. - explicit Callback(Runnable* runnable) : sink_(runnable) {} - - // Any class that is copy-constructable and has a compatible Run method may - // be adapted to a Callback using this constructor. - template <typename Sink> - Callback(const Sink& sink) - : sink_(new Adapter<Sink>(sink)) {} - - void Run(typename internal::Callback_ParamTraits<Args>::ForwardType... args) - const { - if (sink_.get()) - sink_->Run(internal::Forward(args)...); - } - - bool is_null() const { return !sink_.get(); } - - void reset() { sink_.reset(); } - - private: - template <typename Sink> - struct Adapter : public Runnable { - explicit Adapter(const Sink& sink) : sink(sink) {} - virtual void Run( - typename internal::Callback_ParamTraits<Args>::ForwardType... args) - const override { - sink.Run(internal::Forward(args)...); - } - Sink sink; - }; - - internal::SharedPtr<Runnable> sink_; -}; - -typedef Callback<void()> Closure; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_CALLBACK_H_ diff --git a/mojo/public/cpp/bindings/error_handler.h b/mojo/public/cpp/bindings/error_handler.h deleted file mode 100644 index 8ce1af2..0000000 --- a/mojo/public/cpp/bindings/error_handler.h +++ /dev/null @@ -1,19 +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_ERROR_HANDLER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_ERROR_HANDLER_H_ - -namespace mojo { - -// This interface is used to report connection errors. -class ErrorHandler { - public: - virtual ~ErrorHandler() {} - virtual void OnConnectionError() = 0; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_ERROR_HANDLER_H_ diff --git a/mojo/public/cpp/bindings/interface_impl.h b/mojo/public/cpp/bindings/interface_impl.h deleted file mode 100644 index 5663cc3..0000000 --- a/mojo/public/cpp/bindings/interface_impl.h +++ /dev/null @@ -1,184 +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_INTERFACE_IMPL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_IMPL_H_ - -#include "mojo/public/cpp/bindings/binding.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// DEPRECATED! Please use mojo::Binding instead of InterfaceImpl<> in new code. -// -// InterfaceImpl<..> is designed to be the base class of an interface -// implementation. It may be bound to a pipe or a proxy, see BindToPipe and -// BindToProxy. -template <typename Interface> -class InterfaceImpl : public Interface, public ErrorHandler { - public: - using ImplementedInterface = Interface; - using Client = typename Interface::Client; - - InterfaceImpl() : binding_(this), error_handler_impl_(this) { - binding_.set_error_handler(&error_handler_impl_); - } - virtual ~InterfaceImpl() {} - - void BindToHandle( - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - binding_.Bind(handle.Pass(), waiter); - } - - bool WaitForIncomingMethodCall() { - return binding_.WaitForIncomingMethodCall(); - } - - Client* client() { return binding_.client(); } - internal::Router* internal_router() { return binding_.internal_router(); } - - // Implements ErrorHandler. - // - // Called when the client is no longer connected to this instance. NOTE: The - // client() method continues to return a non-null pointer after this method - // is called. After this method is called, any method calls made on client() - // will be silently ignored. - void OnConnectionError() override {} - - void set_delete_on_error(bool delete_on_error) { - error_handler_impl_.set_delete_on_error(delete_on_error); - } - - private: - class ErrorHandlerImpl : public ErrorHandler { - public: - explicit ErrorHandlerImpl(InterfaceImpl* impl) : impl_(impl) {} - ~ErrorHandlerImpl() override {} - - // ErrorHandler implementation: - void OnConnectionError() override { - // If the the instance is not bound to the pipe, the instance might choose - // to delete the binding in the OnConnectionError handler, which would in - // turn delete |this|. Save the error behavior before invoking the error - // handler so we can correctly decide what to do. - bool delete_on_error = delete_on_error_; - impl_->OnConnectionError(); - if (delete_on_error) - delete impl_; - } - - void set_delete_on_error(bool delete_on_error) { - delete_on_error_ = delete_on_error; - } - - private: - InterfaceImpl* impl_; - bool delete_on_error_ = false; - - MOJO_DISALLOW_COPY_AND_ASSIGN(ErrorHandlerImpl); - }; - - Binding<Interface> binding_; - ErrorHandlerImpl error_handler_impl_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(InterfaceImpl); -}; - -// Takes an instance of an InterfaceImpl<..> subclass and binds it to the given -// MessagePipe. The instance is returned for convenience in member initializer -// lists, etc. -// -// If the pipe is closed, the instance's OnConnectionError method will be called -// and then the instance will be deleted. -// -// The instance is also bound to the current thread. Its methods will only be -// called on the current thread, and if the current thread exits, then the end -// point of the pipe will be closed and the error handler's OnConnectionError -// method will be called. -template <typename Impl> -Impl* BindToPipe( - Impl* instance, - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - instance->set_delete_on_error(true); - instance->BindToHandle(handle.Pass(), waiter); - return instance; -} - -// Like BindToPipe but does not delete the instance after a channel error. -template <typename Impl> -Impl* WeakBindToPipe( - Impl* instance, - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - instance->BindToHandle(handle.Pass(), waiter); - return instance; -} - -// Takes an instance of an InterfaceImpl<..> subclass and binds it to the given -// InterfacePtr<..>. The instance is returned for convenience in member -// initializer lists, etc. If the pipe is closed, the instance's -// OnConnectionError method will be called and then the instance will be -// deleted. -// -// The instance is also bound to the current thread. Its methods will only be -// called on the current thread, and if the current thread exits, then it will -// also be deleted, and along with it, its end point of the pipe will be closed. -template <typename Impl, typename Interface> -Impl* BindToProxy( - Impl* instance, - InterfacePtr<Interface>* ptr, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - instance->set_delete_on_error(true); - WeakBindToProxy(instance, ptr, waiter); - return instance; -} - -// Like BindToProxy but does not delete the instance after a channel error. -template <typename Impl, typename Interface> -Impl* WeakBindToProxy( - Impl* instance, - InterfacePtr<Interface>* ptr, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - MessagePipe pipe; - ptr->Bind(pipe.handle0.Pass(), waiter); - instance->BindToHandle(pipe.handle1.Pass(), waiter); - return instance; -} - -// Takes an instance of an InterfaceImpl<..> subclass and binds it to the given -// InterfaceRequest<..>. The instance is returned for convenience in member -// initializer lists, etc. If the pipe is closed, the instance's -// OnConnectionError method will be called and then the instance will be -// deleted. -// -// The instance is also bound to the current thread. Its methods will only be -// called on the current thread, and if the current thread exits, then it will -// also be deleted, and along with it, its end point of the pipe will be closed. -// -// Before returning, the instance will receive a SetClient call, providing it -// with a proxy to the client on the other end of the pipe. -template <typename Impl, typename Interface> -Impl* BindToRequest( - Impl* instance, - InterfaceRequest<Interface>* request, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - return BindToPipe(instance, request->PassMessagePipe(), waiter); -} - -// Like BindToRequest but does not delete the instance after a channel error. -template <typename Impl, typename Interface> -Impl* WeakBindToRequest( - Impl* instance, - InterfaceRequest<Interface>* request, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - return WeakBindToPipe(instance, request->PassMessagePipe(), waiter); -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_IMPL_H_ diff --git a/mojo/public/cpp/bindings/interface_ptr.h b/mojo/public/cpp/bindings/interface_ptr.h deleted file mode 100644 index a2ede4d..0000000 --- a/mojo/public/cpp/bindings/interface_ptr.h +++ /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. - -#ifndef MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_PTR_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_PTR_H_ - -#include <algorithm> - -#include "mojo/public/cpp/bindings/error_handler.h" -#include "mojo/public/cpp/bindings/lib/interface_ptr_internal.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -class ErrorHandler; - -// InterfacePtr represents a proxy to a remote instance of an interface. -template <typename Interface> -class InterfacePtr { - MOJO_MOVE_ONLY_TYPE(InterfacePtr) - public: - InterfacePtr() {} - InterfacePtr(decltype(nullptr)) {} - - InterfacePtr(InterfacePtr&& other) { - internal_state_.Swap(&other.internal_state_); - } - InterfacePtr& operator=(InterfacePtr&& other) { - reset(); - internal_state_.Swap(&other.internal_state_); - return *this; - } - - InterfacePtr& operator=(decltype(nullptr)) { - reset(); - return *this; - } - - ~InterfacePtr() {} - - Interface* get() const { return internal_state_.instance(); } - Interface* operator->() const { return get(); } - Interface& operator*() const { return *get(); } - - void reset() { - State doomed; - internal_state_.Swap(&doomed); - } - - // Blocks the current thread for the first incoming method call, i.e., either - // a call to a client method or a callback method. Returns |true| if a method - // has been called, |false| in case of error. It must only be called on a - // bound object. - bool WaitForIncomingMethodCall() { - return internal_state_.WaitForIncomingMethodCall(); - } - - // This method configures the InterfacePtr<..> to be a proxy to a remote - // object on the other end of the given pipe. - // - // The proxy is bound to the current thread, which means its methods may - // only be called on the current thread. - // - // To move a bound InterfacePtr<..> to another thread, call PassMessagePipe(). - // Then create a new InterfacePtr<..> on another thread, and bind the new - // InterfacePtr<..> to the message pipe on that thread. - void Bind( - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - reset(); - internal_state_.Bind(handle.Pass(), waiter); - } - - // The client interface may only be set after this InterfacePtr<..> is bound. - void set_client(typename Interface::Client* client) { - internal_state_.set_client(client); - } - - // This method may be called to query if the underlying pipe has encountered - // an error. If true, this means method calls made on this interface will be - // dropped (and may have already been dropped) on the floor. - bool encountered_error() const { return internal_state_.encountered_error(); } - - // This method may be called to register an ErrorHandler to observe a - // connection error on the underlying pipe. It must only be called on a bound - // object. - // The callback runs asynchronously from the current message loop. - void set_error_handler(ErrorHandler* error_handler) { - internal_state_.set_error_handler(error_handler); - } - - // Returns the underlying message pipe handle (if any) and resets the - // InterfacePtr<..> to its uninitialized state. This method is helpful if you - // need to move a proxy to another thread. See related notes for Bind. - ScopedMessagePipeHandle PassMessagePipe() { - State state; - internal_state_.Swap(&state); - return state.PassMessagePipe(); - } - - // DO NOT USE. Exposed only for internal use and for testing. - internal::InterfacePtrState<Interface>* internal_state() { - return &internal_state_; - } - - // Allow InterfacePtr<> to be used in boolean expressions, but not - // implicitly convertible to a real bool (which is dangerous). - private: - typedef internal::InterfacePtrState<Interface> InterfacePtr::*Testable; - - public: - operator Testable() const { - return internal_state_.is_bound() ? &InterfacePtr::internal_state_ - : nullptr; - } - - private: - typedef internal::InterfacePtrState<Interface> State; - mutable State internal_state_; -}; - -// Takes a handle to the proxy end-point of a pipe. On the other end is -// presumed to be an interface implementation of type |Interface|. Returns a -// generated proxy to that interface, which may be used on the current thread. -// It is valid to call set_client on the returned InterfacePtr<..> to set an -// instance of Interface::Client. -template <typename Interface> -InterfacePtr<Interface> MakeProxy( - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - InterfacePtr<Interface> ptr; - if (handle.is_valid()) - ptr.Bind(handle.Pass(), waiter); - return ptr.Pass(); -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_PTR_H_ diff --git a/mojo/public/cpp/bindings/interface_request.h b/mojo/public/cpp/bindings/interface_request.h deleted file mode 100644 index 1723330..0000000 --- a/mojo/public/cpp/bindings/interface_request.h +++ /dev/null @@ -1,70 +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_INTERFACE_REQUEST_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_REQUEST_H_ - -#include "mojo/public/cpp/bindings/interface_ptr.h" - -namespace mojo { - -// Used in methods that return instances of remote objects. -template <typename Interface> -class InterfaceRequest { - MOJO_MOVE_ONLY_TYPE(InterfaceRequest) - public: - InterfaceRequest() {} - - InterfaceRequest(InterfaceRequest&& other) { handle_ = other.handle_.Pass(); } - InterfaceRequest& operator=(InterfaceRequest&& other) { - handle_ = other.handle_.Pass(); - return *this; - } - - // Returns true if the request has yet to be completed. - bool is_pending() const { return handle_.is_valid(); } - - void Bind(ScopedMessagePipeHandle handle) { handle_ = handle.Pass(); } - - ScopedMessagePipeHandle PassMessagePipe() { return handle_.Pass(); } - - private: - ScopedMessagePipeHandle handle_; -}; - -template <typename Interface> -InterfaceRequest<Interface> MakeRequest(ScopedMessagePipeHandle handle) { - InterfaceRequest<Interface> request; - request.Bind(handle.Pass()); - return request.Pass(); -} - -// Used to construct a request that synchronously binds an InterfacePtr<..>, -// making it immediately usable upon return. The resulting request object may -// then be later bound to an InterfaceImpl<..> via BindToRequest. -// -// Given the following interface: -// -// interface Foo { -// CreateBar(Bar& bar); -// } -// -// The caller of CreateBar would have code similar to the following: -// -// InterfacePtr<Foo> foo = ...; -// InterfacePtr<Bar> bar; -// foo->CreateBar(GetProxy(&bar)); -// -// Upon return from CreateBar, |bar| is ready to have methods called on it. -// -template <typename Interface> -InterfaceRequest<Interface> GetProxy(InterfacePtr<Interface>* ptr) { - MessagePipe pipe; - ptr->Bind(pipe.handle0.Pass()); - return MakeRequest<Interface>(pipe.handle1.Pass()); -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_INTERFACE_REQUEST_H_ 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_ diff --git a/mojo/public/cpp/bindings/map.h b/mojo/public/cpp/bindings/map.h deleted file mode 100644 index 5149bb0..0000000 --- a/mojo/public/cpp/bindings/map.h +++ /dev/null @@ -1,231 +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_MAP_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_MAP_H_ - -#include <map> - -#include "mojo/public/cpp/bindings/lib/map_internal.h" - -namespace mojo { - -template <typename Key, typename Value> -class Map { - MOJO_MOVE_ONLY_TYPE(Map) - - public: - // Map keys can not be move only classes. - static_assert(!internal::IsMoveOnlyType<Key>::value, - "Map keys can not be move only types."); - - typedef internal::MapTraits<Key, - Value, - internal::IsMoveOnlyType<Value>::value> Traits; - typedef typename Traits::KeyStorageType KeyStorageType; - typedef typename Traits::KeyRefType KeyRefType; - typedef typename Traits::KeyConstRefType KeyConstRefType; - typedef typename Traits::KeyForwardType KeyForwardType; - - typedef typename Traits::ValueStorageType ValueStorageType; - typedef typename Traits::ValueRefType ValueRefType; - typedef typename Traits::ValueConstRefType ValueConstRefType; - typedef typename Traits::ValueForwardType ValueForwardType; - - typedef internal::Map_Data<typename internal::WrapperTraits<Key>::DataType, - typename internal::WrapperTraits<Value>::DataType> - Data_; - - Map() : is_null_(true) {} - - Map(mojo::Array<Key> keys, mojo::Array<Value> values) : is_null_(false) { - MOJO_DCHECK(keys.size() == values.size()); - Traits::InitializeFrom(&map_, keys.Pass(), values.Pass()); - } - - ~Map() { Traits::Finalize(&map_); } - - Map(Map&& other) : is_null_(true) { Take(&other); } - Map& operator=(Map&& other) { - Take(&other); - return *this; - } - - template <typename U> - static Map From(const U& other) { - return TypeConverter<Map, U>::Convert(other); - } - - template <typename U> - U To() const { - return TypeConverter<U, Map>::Convert(*this); - } - - void reset() { - if (!map_.empty()) { - Traits::Finalize(&map_); - map_.clear(); - } - is_null_ = true; - } - - bool is_null() const { return is_null_; } - - size_t size() const { return map_.size(); } - - // Used to mark an empty map as non-null for serialization purposes. - void mark_non_null() { is_null_ = false; } - - // Inserts a key-value pair into the map. Like std::map, this does not insert - // |value| if |key| is already a member of the map. - void insert(KeyForwardType key, ValueForwardType value) { - is_null_ = false; - Traits::Insert(&map_, key, value); - } - - ValueRefType at(KeyForwardType key) { return Traits::at(&map_, key); } - ValueConstRefType at(KeyForwardType key) const { - return Traits::at(&map_, key); - } - - ValueRefType operator[](KeyForwardType key) { - is_null_ = false; - return Traits::GetOrInsert(&map_, key); - } - - void Swap(Map<Key, Value>* other) { - std::swap(is_null_, other->is_null_); - map_.swap(other->map_); - } - void Swap(std::map<Key, Value>* other) { - is_null_ = false; - map_.swap(*other); - } - - // This moves all values in the map to a set of parallel arrays. This action - // is destructive because we can have move-only objects as values; therefore - // we can't have copy semantics here. - void DecomposeMapTo(mojo::Array<Key>* keys, mojo::Array<Value>* values) { - Traits::Decompose(&map_, keys, values); - Traits::Finalize(&map_); - map_.clear(); - is_null_ = true; - } - - // Please note that calling this method will fail compilation if the value - // type cannot be cloned (which usually means that it is a Mojo handle type or - // a type contains Mojo handles). - Map Clone() const { - Map result; - result.is_null_ = is_null_; - Traits::Clone(map_, &result.map_); - return result.Pass(); - } - - bool Equals(const Map& other) const { - if (is_null() != other.is_null()) - return false; - if (size() != other.size()) - return false; - auto i = begin(); - auto j = other.begin(); - while (i != end()) { - if (i.GetKey() != j.GetKey()) - return false; - if (!internal::ValueTraits<Value>::Equals(i.GetValue(), j.GetValue())) - return false; - ++i; - ++j; - } - return true; - } - - class ConstMapIterator { - public: - ConstMapIterator( - const typename std::map<KeyStorageType, - ValueStorageType>::const_iterator& it) - : it_(it) {} - - KeyConstRefType GetKey() { return Traits::GetKey(it_); } - ValueConstRefType GetValue() { return Traits::GetValue(it_); } - - ConstMapIterator& operator++() { - it_++; - return *this; - } - bool operator!=(const ConstMapIterator& rhs) const { - return it_ != rhs.it_; - } - bool operator==(const ConstMapIterator& rhs) const { - return it_ == rhs.it_; - } - - private: - typename std::map<KeyStorageType, ValueStorageType>::const_iterator it_; - }; - - // Provide read-only iteration over map members. - ConstMapIterator begin() const { return ConstMapIterator(map_.begin()); } - ConstMapIterator end() const { return ConstMapIterator(map_.end()); } - - ConstMapIterator find(KeyForwardType key) const { - return ConstMapIterator(map_.find(key)); - } - - private: - typedef std::map<KeyStorageType, ValueStorageType> Map::*Testable; - - public: - operator Testable() const { return is_null_ ? 0 : &Map::map_; } - - private: - void Take(Map* other) { - reset(); - Swap(other); - } - - std::map<KeyStorageType, ValueStorageType> map_; - bool is_null_; -}; - -template <typename MojoKey, - typename MojoValue, - typename STLKey, - typename STLValue> -struct TypeConverter<Map<MojoKey, MojoValue>, std::map<STLKey, STLValue>> { - static Map<MojoKey, MojoValue> Convert( - const std::map<STLKey, STLValue>& input) { - Map<MojoKey, MojoValue> result; - result.mark_non_null(); - for (auto& pair : input) { - result.insert(TypeConverter<MojoKey, STLKey>::Convert(pair.first), - TypeConverter<MojoValue, STLValue>::Convert(pair.second)); - } - return result.Pass(); - } -}; - -template <typename MojoKey, - typename MojoValue, - typename STLKey, - typename STLValue> -struct TypeConverter<std::map<STLKey, STLValue>, Map<MojoKey, MojoValue>> { - static std::map<STLKey, STLValue> Convert( - const Map<MojoKey, MojoValue>& input) { - std::map<STLKey, STLValue> result; - if (!input.is_null()) { - for (auto it = input.begin(); it != input.end(); ++it) { - result.insert(std::make_pair( - TypeConverter<STLKey, MojoKey>::Convert(it.GetKey()), - TypeConverter<STLValue, MojoValue>::Convert(it.GetValue()))); - } - } - return result; - } -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_MAP_H_ diff --git a/mojo/public/cpp/bindings/message.h b/mojo/public/cpp/bindings/message.h deleted file mode 100644 index 5cab4ea..0000000 --- a/mojo/public/cpp/bindings/message.h +++ /dev/null @@ -1,122 +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_MESSAGE_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_MESSAGE_H_ - -#include <vector> - -#include "mojo/public/cpp/bindings/lib/message_internal.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { - -// Message is a holder for the data and handles to be sent over a MessagePipe. -// Message owns its data and handles, but a consumer of Message is free to -// mutate the data and handles. The message's data is comprised of a header -// followed by payload. -class Message { - public: - Message(); - ~Message(); - - // These may only be called on a newly created Message object. - void AllocUninitializedData(uint32_t num_bytes); - void AdoptData(uint32_t num_bytes, internal::MessageData* data); - - // Swaps data and handles between this Message and another. - void Swap(Message* other); - - uint32_t data_num_bytes() const { return data_num_bytes_; } - - // Access the raw bytes of the message. - const uint8_t* data() const { - return reinterpret_cast<const uint8_t*>(data_); - } - uint8_t* mutable_data() { return reinterpret_cast<uint8_t*>(data_); } - - // Access the header. - const internal::MessageHeader* header() const { return &data_->header; } - - uint32_t name() const { return data_->header.name; } - bool has_flag(uint32_t flag) const { return !!(data_->header.flags & flag); } - - // Access the request_id field (if present). - bool has_request_id() const { return data_->header.num_fields >= 3; } - uint64_t request_id() const { - MOJO_DCHECK(has_request_id()); - return static_cast<const internal::MessageHeaderWithRequestID*>( - &data_->header)->request_id; - } - void set_request_id(uint64_t request_id) { - MOJO_DCHECK(has_request_id()); - static_cast<internal::MessageHeaderWithRequestID*>(&data_->header) - ->request_id = request_id; - } - - // Access the payload. - const uint8_t* payload() const { - return reinterpret_cast<const uint8_t*>(data_) + data_->header.num_bytes; - } - uint8_t* mutable_payload() { - return reinterpret_cast<uint8_t*>(data_) + data_->header.num_bytes; - } - uint32_t payload_num_bytes() const { - MOJO_DCHECK(data_num_bytes_ >= data_->header.num_bytes); - return data_num_bytes_ - data_->header.num_bytes; - } - - // Access the handles. - const std::vector<Handle>* handles() const { return &handles_; } - std::vector<Handle>* mutable_handles() { return &handles_; } - - private: - uint32_t data_num_bytes_; - internal::MessageData* data_; // Heap-allocated using malloc. - std::vector<Handle> handles_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(Message); -}; - -class MessageReceiver { - public: - virtual ~MessageReceiver() {} - - // The receiver may mutate the given message. Returns true if the message - // was accepted and false otherwise, indicating that the message was invalid - // or malformed. - virtual bool Accept(Message* message) MOJO_WARN_UNUSED_RESULT = 0; -}; - -class MessageReceiverWithResponder : public MessageReceiver { - public: - ~MessageReceiverWithResponder() override {} - - // A variant on Accept that registers a MessageReceiver (known as the - // responder) to handle the response message generated from the given - // message. The responder's Accept method may be called during - // AcceptWithResponder or some time after its return. - // - // NOTE: Upon returning true, AcceptWithResponder assumes ownership of - // |responder| and will delete it after calling |responder->Accept| or upon - // its own destruction. - // - virtual bool AcceptWithResponder(Message* message, MessageReceiver* responder) - MOJO_WARN_UNUSED_RESULT = 0; -}; - -// Read a single message from the pipe and dispatch to the given receiver. The -// receiver may be null, in which case the message is simply discarded. -// Returns MOJO_RESULT_SHOULD_WAIT if the caller should wait on the handle to -// become readable. Returns MOJO_RESULT_OK if a message was dispatched and -// otherwise returns an error code if something went wrong. -// -// NOTE: The message hasn't been validated and may be malformed! -MojoResult ReadAndDispatchMessage(MessagePipeHandle handle, - MessageReceiver* receiver, - bool* receiver_result); - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_MESSAGE_H_ diff --git a/mojo/public/cpp/bindings/message_filter.h b/mojo/public/cpp/bindings/message_filter.h deleted file mode 100644 index 12885b0..0000000 --- a/mojo/public/cpp/bindings/message_filter.h +++ /dev/null @@ -1,39 +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_MESSAGE_FILTER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_MESSAGE_FILTER_H_ - -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// This class is the base class for message filters. Subclasses should -// implement the pure virtual method Accept() inherited from MessageReceiver to -// process messages and/or forward them to |sink_|. -class MessageFilter : public MessageReceiver { - public: - // Doesn't take ownership of |sink|. Therefore |sink| has to stay alive while - // this object is alive. - explicit MessageFilter(MessageReceiver* sink = nullptr); - ~MessageFilter() override; - - void set_sink(MessageReceiver* sink) { sink_ = sink; } - - protected: - MessageReceiver* sink_; -}; - -// A trivial filter that simply forwards every message it receives to |sink_|. -class PassThroughFilter : public MessageFilter { - public: - explicit PassThroughFilter(MessageReceiver* sink = nullptr); - - bool Accept(Message* message) override; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_MESSAGE_FILTER_H_ diff --git a/mojo/public/cpp/bindings/no_interface.h b/mojo/public/cpp/bindings/no_interface.h deleted file mode 100644 index 4c35789..0000000 --- a/mojo/public/cpp/bindings/no_interface.h +++ /dev/null @@ -1,53 +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_NO_INTERFACE_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_NO_INTERFACE_H_ - -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/bindings/message_filter.h" -#include "mojo/public/cpp/system/core.h" - -namespace mojo { - -// NoInterface is for use in cases when a non-existent or empty interface is -// needed (e.g., when the Mojom "Peer" attribute is not present). - -class NoInterfaceProxy; -class NoInterfaceStub; - -class NoInterface { - public: - static const char* Name_; - typedef NoInterfaceProxy Proxy_; - typedef NoInterfaceStub Stub_; - typedef PassThroughFilter RequestValidator_; - typedef PassThroughFilter ResponseValidator_; - typedef NoInterface Client; - virtual ~NoInterface() {} -}; - -class NoInterfaceProxy : public NoInterface { - public: - explicit NoInterfaceProxy(MessageReceiver* receiver) {} -}; - -class NoInterfaceStub : public MessageReceiverWithResponder { - public: - NoInterfaceStub() {} - void set_sink(NoInterface* sink) {} - NoInterface* sink() { return nullptr; } - bool Accept(Message* message) override; - bool AcceptWithResponder(Message* message, - MessageReceiver* responder) override; -}; - -// AnyInterface is for use in cases where any interface would do (e.g., see the -// Shell::Connect method). - -typedef NoInterface AnyInterface; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_NO_INTERFACE_H_ diff --git a/mojo/public/cpp/bindings/string.h b/mojo/public/cpp/bindings/string.h deleted file mode 100644 index ba0d8fa8..0000000 --- a/mojo/public/cpp/bindings/string.h +++ /dev/null @@ -1,172 +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_STRING_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_STRING_H_ - -#include <string> - -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/type_converter.h" -#include "mojo/public/cpp/environment/logging.h" - -namespace mojo { - -class String { - public: - typedef internal::String_Data Data_; - - String() : is_null_(true) {} - String(const std::string& str) : value_(str), is_null_(false) {} - String(const char* chars) : is_null_(!chars) { - if (chars) - value_ = chars; - } - String(const char* chars, size_t num_chars) - : value_(chars, num_chars), is_null_(false) {} - String(const mojo::String& str) - : value_(str.value_), is_null_(str.is_null_) {} - - template <size_t N> - String(const char chars[N]) - : value_(chars, N - 1), is_null_(false) {} - - template <typename U> - static String From(const U& other) { - return TypeConverter<String, U>::Convert(other); - } - - template <typename U> - U To() const { - return TypeConverter<U, String>::Convert(*this); - } - - String& operator=(const mojo::String& str) { - value_ = str.value_; - is_null_ = str.is_null_; - return *this; - } - String& operator=(const std::string& str) { - value_ = str; - is_null_ = false; - return *this; - } - String& operator=(const char* chars) { - is_null_ = !chars; - if (chars) { - value_ = chars; - } else { - value_.clear(); - } - return *this; - } - - void reset() { - value_.clear(); - is_null_ = true; - } - - bool is_null() const { return is_null_; } - - size_t size() const { return value_.size(); } - - const char* data() const { return value_.data(); } - - const char& at(size_t offset) const { return value_.at(offset); } - const char& operator[](size_t offset) const { return value_[offset]; } - - const std::string& get() const { return value_; } - operator const std::string&() const { return value_; } - - void Swap(String* other) { - std::swap(is_null_, other->is_null_); - value_.swap(other->value_); - } - - void Swap(std::string* other) { - is_null_ = false; - value_.swap(*other); - } - - private: - typedef std::string String::*Testable; - - public: - operator Testable() const { return is_null_ ? 0 : &String::value_; } - - private: - std::string value_; - bool is_null_; -}; - -inline bool operator==(const String& a, const String& b) { - return a.is_null() == b.is_null() && a.get() == b.get(); -} -inline bool operator==(const char* a, const String& b) { - return !b.is_null() && a == b.get(); -} -inline bool operator==(const String& a, const char* b) { - return !a.is_null() && a.get() == b; -} -inline bool operator!=(const String& a, const String& b) { - return !(a == b); -} -inline bool operator!=(const char* a, const String& b) { - return !(a == b); -} -inline bool operator!=(const String& a, const char* b) { - return !(a == b); -} - -inline std::ostream& operator<<(std::ostream& out, const String& s) { - return out << s.get(); -} - -inline bool operator<(const String& a, const String& b) { - if (a.is_null()) - return !b.is_null(); - if (b.is_null()) - return false; - - return a.get() < b.get(); -} - -// TODO(darin): Add similar variants of operator<,<=,>,>= - -template <> -struct TypeConverter<String, std::string> { - static String Convert(const std::string& input) { return String(input); } -}; - -template <> -struct TypeConverter<std::string, String> { - static std::string Convert(const String& input) { return input; } -}; - -template <size_t N> -struct TypeConverter<String, char[N]> { - static String Convert(const char input[N]) { - MOJO_DCHECK(input); - return String(input, N - 1); - } -}; - -// Appease MSVC. -template <size_t N> -struct TypeConverter<String, const char[N]> { - static String Convert(const char input[N]) { - MOJO_DCHECK(input); - return String(input, N - 1); - } -}; - -template <> -struct TypeConverter<String, const char*> { - // |input| may be null, in which case a null String will be returned. - static String Convert(const char* input) { return String(input); } -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_STRING_H_ diff --git a/mojo/public/cpp/bindings/strong_binding.h b/mojo/public/cpp/bindings/strong_binding.h deleted file mode 100644 index 0cd4f03..0000000 --- a/mojo/public/cpp/bindings/strong_binding.h +++ /dev/null @@ -1,127 +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_STRONG_BINDING_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_STRONG_BINDING_H_ - -#include <assert.h> - -#include "mojo/public/c/environment/async_waiter.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "mojo/public/cpp/bindings/error_handler.h" -#include "mojo/public/cpp/bindings/interface_ptr.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#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/system/core.h" - -namespace mojo { - -// This connects an interface implementation strongly to a pipe. When a -// connection error is detected the implementation is deleted. Deleting the -// connector also closes the pipe. -// -// Example of an implementation that is always bound strongly to a pipe -// -// class StronglyBound : public Foo { -// public: -// explicit StronglyBound(InterfaceRequest<Foo> request) -// : binding_(this, request.Pass()) {} -// -// // Foo implementation here -// -// private: -// StrongBinding<Foo> binding_; -// }; -// -// class MyFooFactory : public InterfaceFactory<Foo> { -// public: -// void Create(..., InterfaceRequest<Foo> request) override { -// new StronglyBound(request.Pass()); // The binding now owns the -// // instance of StronglyBound. -// } -// }; -template <typename Interface> -class StrongBinding : public ErrorHandler { - public: - explicit StrongBinding(Interface* impl) : binding_(impl) { - binding_.set_error_handler(this); - } - - StrongBinding( - Interface* impl, - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) - : StrongBinding(impl) { - binding_.Bind(handle.Pass(), waiter); - } - - StrongBinding( - Interface* impl, - InterfacePtr<Interface>* ptr, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) - : StrongBinding(impl) { - binding_.Bind(ptr, waiter); - } - - StrongBinding( - Interface* impl, - InterfaceRequest<Interface> request, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) - : StrongBinding(impl) { - binding_.Bind(request.Pass(), waiter); - } - - ~StrongBinding() override {} - - void Bind( - ScopedMessagePipeHandle handle, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - assert(!binding_.is_bound()); - binding_.Bind(handle.Pass(), waiter); - } - - void Bind( - InterfacePtr<Interface>* ptr, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - assert(!binding_.is_bound()); - binding_.Bind(ptr, waiter); - } - - void Bind( - InterfaceRequest<Interface> request, - const MojoAsyncWaiter* waiter = Environment::GetDefaultAsyncWaiter()) { - assert(!binding_.is_bound()); - binding_.Bind(request.Pass(), waiter); - } - - bool WaitForIncomingMethodCall() { - return binding_.WaitForIncomingMethodCall(); - } - - void set_error_handler(ErrorHandler* error_handler) { - error_handler_ = error_handler; - } - - Interface* impl() { return binding_.impl(); } - typename Interface::Client* client() { return binding_.client(); } - // Exposed for testing, should not generally be used. - internal::Router* internal_router() { return binding_.internal_router(); } - - // ErrorHandler implementation - void OnConnectionError() override { - if (error_handler_) - error_handler_->OnConnectionError(); - delete binding_.impl(); - } - - private: - ErrorHandler* error_handler_ = nullptr; - Binding<Interface> binding_; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_STRONG_BINDING_H_ diff --git a/mojo/public/cpp/bindings/struct_ptr.h b/mojo/public/cpp/bindings/struct_ptr.h deleted file mode 100644 index a420fa5..0000000 --- a/mojo/public/cpp/bindings/struct_ptr.h +++ /dev/null @@ -1,189 +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_STRUCT_PTR_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_STRUCT_PTR_H_ - -#include <new> - -#include "mojo/public/cpp/bindings/type_converter.h" -#include "mojo/public/cpp/environment/logging.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -namespace internal { - -template <typename Struct> -class StructHelper { - public: - template <typename Ptr> - static void Initialize(Ptr* ptr) { - ptr->Initialize(); - } -}; - -} // namespace internal - -template <typename Struct> -class StructPtr { - MOJO_MOVE_ONLY_TYPE(StructPtr) - - public: - - StructPtr() : ptr_(nullptr) {} - StructPtr(decltype(nullptr)) : ptr_(nullptr) {} - - ~StructPtr() { delete ptr_; } - - StructPtr& operator=(decltype(nullptr)) { - reset(); - return *this; - } - - StructPtr(StructPtr&& other) : ptr_(nullptr) { Take(&other); } - StructPtr& operator=(StructPtr&& other) { - Take(&other); - return *this; - } - - template <typename U> - U To() const { - return TypeConverter<U, StructPtr>::Convert(*this); - } - - void reset() { - if (ptr_) { - delete ptr_; - ptr_ = nullptr; - } - } - - bool is_null() const { return ptr_ == nullptr; } - - Struct& operator*() const { - MOJO_DCHECK(ptr_); - return *ptr_; - } - Struct* operator->() const { - MOJO_DCHECK(ptr_); - return ptr_; - } - Struct* get() const { return ptr_; } - - void Swap(StructPtr* other) { std::swap(ptr_, other->ptr_); } - - // Please note that calling this method will fail compilation if the value - // type |Struct| doesn't have a Clone() method defined (which usually means - // that it contains Mojo handles). - StructPtr Clone() const { return is_null() ? StructPtr() : ptr_->Clone(); } - - bool Equals(const StructPtr& other) const { - if (is_null() || other.is_null()) - return is_null() && other.is_null(); - return ptr_->Equals(*other.ptr_); - } - - private: - typedef Struct* StructPtr::*Testable; - - public: - operator Testable() const { return ptr_ ? &StructPtr::ptr_ : 0; } - - private: - friend class internal::StructHelper<Struct>; - void Initialize() { - MOJO_DCHECK(!ptr_); - ptr_ = new Struct(); - } - - void Take(StructPtr* other) { - reset(); - Swap(other); - } - - Struct* ptr_; -}; - -// Designed to be used when Struct is small and copyable. -template <typename Struct> -class InlinedStructPtr { - MOJO_MOVE_ONLY_TYPE(InlinedStructPtr); - - public: - - InlinedStructPtr() : is_null_(true) {} - InlinedStructPtr(decltype(nullptr)) : is_null_(true) {} - - ~InlinedStructPtr() {} - - InlinedStructPtr& operator=(decltype(nullptr)) { - reset(); - return *this; - } - - InlinedStructPtr(InlinedStructPtr&& other) : is_null_(true) { Take(&other); } - InlinedStructPtr& operator=(InlinedStructPtr&& other) { - Take(&other); - return *this; - } - - template <typename U> - U To() const { - return TypeConverter<U, InlinedStructPtr>::Convert(*this); - } - - void reset() { - is_null_ = true; - value_. ~Struct(); - new (&value_) Struct(); - } - - bool is_null() const { return is_null_; } - - Struct& operator*() const { - MOJO_DCHECK(!is_null_); - return value_; - } - Struct* operator->() const { - MOJO_DCHECK(!is_null_); - return &value_; - } - Struct* get() const { return &value_; } - - void Swap(InlinedStructPtr* other) { - std::swap(value_, other->value_); - std::swap(is_null_, other->is_null_); - } - - InlinedStructPtr Clone() const { - return is_null() ? InlinedStructPtr() : value_.Clone(); - } - bool Equals(const InlinedStructPtr& other) const { - if (is_null() || other.is_null()) - return is_null() && other.is_null(); - return value_.Equals(other.value_); - } - - private: - typedef Struct InlinedStructPtr::*Testable; - - public: - operator Testable() const { return is_null_ ? 0 : &InlinedStructPtr::value_; } - - private: - friend class internal::StructHelper<Struct>; - void Initialize() { is_null_ = false; } - - void Take(InlinedStructPtr* other) { - reset(); - Swap(other); - } - - mutable Struct value_; - bool is_null_; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_STRUCT_PTR_H_ diff --git a/mojo/public/cpp/bindings/tests/BUILD.gn b/mojo/public/cpp/bindings/tests/BUILD.gn deleted file mode 100644 index 0051270..0000000 --- a/mojo/public/cpp/bindings/tests/BUILD.gn +++ /dev/null @@ -1,52 +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. - -import("../../../mojo_sdk.gni") - -mojo_sdk_source_set("tests") { - testonly = true - - sources = [ - "array_unittest.cc", - "bounds_checker_unittest.cc", - "buffer_unittest.cc", - "connector_unittest.cc", - "container_test_util.cc", - "equals_unittest.cc", - "handle_passing_unittest.cc", - "interface_ptr_unittest.cc", - "map_unittest.cc", - "request_response_unittest.cc", - "router_unittest.cc", - "sample_service_unittest.cc", - "serialization_warning_unittest.cc", - "string_unittest.cc", - "struct_unittest.cc", - "type_conversion_unittest.cc", - "validation_unittest.cc", - ] - - deps = [ - ":mojo_public_bindings_test_utils", - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/bindings", - "mojo/public/cpp/environment:standalone", - "mojo/public/cpp/system", - "mojo/public/cpp/test_support:test_utils", - "mojo/public/cpp/utility", - "mojo/public/interfaces/bindings/tests:test_interfaces", - ] -} - -mojo_sdk_source_set("mojo_public_bindings_test_utils") { - sources = [ - "validation_test_input_parser.cc", - "validation_test_input_parser.h", - ] - - mojo_sdk_deps = [ "mojo/public/c/system" ] -} diff --git a/mojo/public/cpp/bindings/tests/DEPS b/mojo/public/cpp/bindings/tests/DEPS deleted file mode 100644 index b99d520..0000000 --- a/mojo/public/cpp/bindings/tests/DEPS +++ /dev/null @@ -1,4 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/environment", - "+mojo/public/interfaces/bindings/tests", -] diff --git a/mojo/public/cpp/bindings/tests/array_unittest.cc b/mojo/public/cpp/bindings/tests/array_unittest.cc deleted file mode 100644 index ed9a647..0000000 --- a/mojo/public/cpp/bindings/tests/array_unittest.cc +++ /dev/null @@ -1,450 +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/array.h" -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/lib/array_serialization.h" -#include "mojo/public/cpp/bindings/lib/fixed_buffer.h" -#include "mojo/public/cpp/bindings/tests/container_test_util.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/interfaces/bindings/tests/test_structs.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -using mojo::internal::Array_Data; -using mojo::internal::ArrayValidateParams; -using mojo::internal::FixedBuffer; -using mojo::internal::NoValidateParams; -using mojo::internal::String_Data; - -class ArrayTest : public testing::Test { - public: - ~ArrayTest() override {} - - private: - Environment env_; -}; - -// Tests that basic Array operations work. -TEST_F(ArrayTest, Basic) { - Array<char> array(8); - for (size_t i = 0; i < array.size(); ++i) { - char val = static_cast<char>(i * 2); - array[i] = val; - EXPECT_EQ(val, array.at(i)); - } -} - -// Tests that basic Array<bool> operations work. -TEST_F(ArrayTest, Bool) { - Array<bool> array(64); - for (size_t i = 0; i < array.size(); ++i) { - bool val = i % 3 == 0; - array[i] = val; - EXPECT_EQ(val, array.at(i)); - } -} - -// Tests that Array<ScopedMessagePipeHandle> supports transferring handles. -TEST_F(ArrayTest, Handle) { - MessagePipe pipe; - Array<ScopedMessagePipeHandle> handles(2); - handles[0] = pipe.handle0.Pass(); - handles[1].reset(pipe.handle1.release()); - - EXPECT_FALSE(pipe.handle0.is_valid()); - EXPECT_FALSE(pipe.handle1.is_valid()); - - Array<ScopedMessagePipeHandle> handles2 = handles.Pass(); - EXPECT_TRUE(handles2[0].is_valid()); - EXPECT_TRUE(handles2[1].is_valid()); - - ScopedMessagePipeHandle pipe_handle = handles2[0].Pass(); - EXPECT_TRUE(pipe_handle.is_valid()); - EXPECT_FALSE(handles2[0].is_valid()); -} - -// Tests that Array<ScopedMessagePipeHandle> supports closing handles. -TEST_F(ArrayTest, HandlesAreClosed) { - MessagePipe pipe; - MojoHandle pipe0_value = pipe.handle0.get().value(); - MojoHandle pipe1_value = pipe.handle0.get().value(); - - { - Array<ScopedMessagePipeHandle> handles(2); - handles[0] = pipe.handle0.Pass(); - handles[1].reset(pipe.handle0.release()); - } - - // We expect the pipes to have been closed. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(pipe0_value)); - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(pipe1_value)); -} - -TEST_F(ArrayTest, Clone) { - { - // Test POD. - Array<int32_t> array(3); - for (size_t i = 0; i < array.size(); ++i) - array[i] = static_cast<int32_t>(i); - - Array<int32_t> clone_array = array.Clone(); - EXPECT_EQ(array.size(), clone_array.size()); - for (size_t i = 0; i < array.size(); ++i) - EXPECT_EQ(array[i], clone_array[i]); - } - - { - // Test copyable object. - Array<String> array(2); - array[0] = "hello"; - array[1] = "world"; - - Array<String> clone_array = array.Clone(); - EXPECT_EQ(array.size(), clone_array.size()); - for (size_t i = 0; i < array.size(); ++i) - EXPECT_EQ(array[i], clone_array[i]); - } - - { - // Test struct. - Array<RectPtr> array(2); - array[1] = Rect::New(); - array[1]->x = 1; - array[1]->y = 2; - array[1]->width = 3; - array[1]->height = 4; - - Array<RectPtr> clone_array = array.Clone(); - EXPECT_EQ(array.size(), clone_array.size()); - EXPECT_TRUE(clone_array[0].is_null()); - EXPECT_EQ(array[1]->x, clone_array[1]->x); - EXPECT_EQ(array[1]->y, clone_array[1]->y); - EXPECT_EQ(array[1]->width, clone_array[1]->width); - EXPECT_EQ(array[1]->height, clone_array[1]->height); - } - - { - // Test array of array. - Array<Array<int8_t>> array(2); - array[1] = Array<int8_t>(2); - array[1][0] = 0; - array[1][1] = 1; - - Array<Array<int8_t>> clone_array = array.Clone(); - EXPECT_EQ(array.size(), clone_array.size()); - EXPECT_TRUE(clone_array[0].is_null()); - EXPECT_EQ(array[1].size(), clone_array[1].size()); - EXPECT_EQ(array[1][0], clone_array[1][0]); - EXPECT_EQ(array[1][1], clone_array[1][1]); - } - - { - // Test that array of handles still works although Clone() is not available. - Array<ScopedMessagePipeHandle> array(10); - EXPECT_FALSE(array[0].is_valid()); - } -} - -TEST_F(ArrayTest, Serialization_ArrayOfPOD) { - Array<int32_t> array(4); - for (size_t i = 0; i < array.size(); ++i) - array[i] = static_cast<int32_t>(i); - - size_t size = GetSerializedSize_(array); - EXPECT_EQ(8U + 4 * 4U, size); - - FixedBuffer buf(size); - Array_Data<int32_t>* data; - SerializeArray_<ArrayValidateParams<0, false, NoValidateParams>>( - array.Pass(), &buf, &data); - - Array<int32_t> array2; - Deserialize_(data, &array2); - - EXPECT_EQ(4U, array2.size()); - for (size_t i = 0; i < array2.size(); ++i) - EXPECT_EQ(static_cast<int32_t>(i), array2[i]); -} - -TEST_F(ArrayTest, Serialization_EmptyArrayOfPOD) { - Array<int32_t> array(0); - size_t size = GetSerializedSize_(array); - EXPECT_EQ(8U, size); - - FixedBuffer buf(size); - Array_Data<int32_t>* data; - SerializeArray_<ArrayValidateParams<0, false, NoValidateParams>>( - array.Pass(), &buf, &data); - - Array<int32_t> array2; - Deserialize_(data, &array2); - EXPECT_EQ(0U, array2.size()); -} - -TEST_F(ArrayTest, Serialization_ArrayOfArrayOfPOD) { - Array<Array<int32_t>> array(2); - for (size_t j = 0; j < array.size(); ++j) { - Array<int32_t> inner(4); - for (size_t i = 0; i < inner.size(); ++i) - inner[i] = static_cast<int32_t>(i + (j * 10)); - array[j] = inner.Pass(); - } - - size_t size = GetSerializedSize_(array); - EXPECT_EQ(8U + 2 * 8U + 2 * (8U + 4 * 4U), size); - - FixedBuffer buf(size); - Array_Data<Array_Data<int32_t>*>* data; - SerializeArray_< - ArrayValidateParams<0, - false, - ArrayValidateParams<0, false, NoValidateParams>>>( - array.Pass(), &buf, &data); - - Array<Array<int32_t>> array2; - Deserialize_(data, &array2); - - EXPECT_EQ(2U, array2.size()); - for (size_t j = 0; j < array2.size(); ++j) { - const Array<int32_t>& inner = array2[j]; - EXPECT_EQ(4U, inner.size()); - for (size_t i = 0; i < inner.size(); ++i) - EXPECT_EQ(static_cast<int32_t>(i + (j * 10)), inner[i]); - } -} - -TEST_F(ArrayTest, Serialization_ArrayOfBool) { - Array<bool> array(10); - for (size_t i = 0; i < array.size(); ++i) - array[i] = i % 2 ? true : false; - - size_t size = GetSerializedSize_(array); - EXPECT_EQ(8U + 8U, size); - - FixedBuffer buf(size); - Array_Data<bool>* data; - SerializeArray_<ArrayValidateParams<0, false, NoValidateParams>>( - array.Pass(), &buf, &data); - - Array<bool> array2; - Deserialize_(data, &array2); - - EXPECT_EQ(10U, array2.size()); - for (size_t i = 0; i < array2.size(); ++i) - EXPECT_EQ(i % 2 ? true : false, array2[i]); -} - -TEST_F(ArrayTest, Serialization_ArrayOfString) { - Array<String> array(10); - for (size_t i = 0; i < array.size(); ++i) { - char c = 'A' + static_cast<char>(i); - array[i] = String(&c, 1); - } - - size_t size = GetSerializedSize_(array); - EXPECT_EQ(8U + // array header - 10 * 8U + // array payload (10 pointers) - 10 * (8U + // string header - 8U), // string length of 1 padded to 8 - size); - - FixedBuffer buf(size); - Array_Data<String_Data*>* data; - SerializeArray_< - ArrayValidateParams<0, - false, - ArrayValidateParams<0, false, NoValidateParams>>>( - array.Pass(), &buf, &data); - - Array<String> array2; - Deserialize_(data, &array2); - - EXPECT_EQ(10U, array2.size()); - for (size_t i = 0; i < array2.size(); ++i) { - char c = 'A' + static_cast<char>(i); - EXPECT_EQ(String(&c, 1), array2[i]); - } -} - -TEST_F(ArrayTest, Resize_Copyable) { - ASSERT_EQ(0u, CopyableType::num_instances()); - mojo::Array<CopyableType> array(3); - std::vector<CopyableType*> value_ptrs; - value_ptrs.push_back(array[0].ptr()); - value_ptrs.push_back(array[1].ptr()); - - for (size_t i = 0; i < array.size(); i++) - array[i].ResetCopied(); - - array.resize(2); - ASSERT_EQ(2u, array.size()); - EXPECT_EQ(array.size(), CopyableType::num_instances()); - for (size_t i = 0; i < array.size(); i++) { - EXPECT_FALSE(array[i].copied()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - } - - array.resize(3); - array[2].ResetCopied(); - ASSERT_EQ(3u, array.size()); - EXPECT_EQ(array.size(), CopyableType::num_instances()); - for (size_t i = 0; i < array.size(); i++) - EXPECT_FALSE(array[i].copied()); - value_ptrs.push_back(array[2].ptr()); - - size_t capacity = array.storage().capacity(); - array.resize(capacity); - ASSERT_EQ(capacity, array.size()); - EXPECT_EQ(array.size(), CopyableType::num_instances()); - for (size_t i = 0; i < 3; i++) - EXPECT_FALSE(array[i].copied()); - for (size_t i = 3; i < array.size(); i++) { - array[i].ResetCopied(); - value_ptrs.push_back(array[i].ptr()); - } - - array.resize(capacity + 2); - ASSERT_EQ(capacity + 2, array.size()); - EXPECT_EQ(array.size(), CopyableType::num_instances()); - for (size_t i = 0; i < capacity; i++) { - EXPECT_TRUE(array[i].copied()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - } - array.reset(); - EXPECT_EQ(0u, CopyableType::num_instances()); - EXPECT_FALSE(array); - array.resize(0); - EXPECT_EQ(0u, CopyableType::num_instances()); - EXPECT_TRUE(array); -} - -TEST_F(ArrayTest, Resize_MoveOnly) { - ASSERT_EQ(0u, MoveOnlyType::num_instances()); - mojo::Array<MoveOnlyType> array(3); - std::vector<MoveOnlyType*> value_ptrs; - value_ptrs.push_back(array[0].ptr()); - value_ptrs.push_back(array[1].ptr()); - - for (size_t i = 0; i < array.size(); i++) - EXPECT_FALSE(array[i].moved()); - - array.resize(2); - ASSERT_EQ(2u, array.size()); - EXPECT_EQ(array.size(), MoveOnlyType::num_instances()); - for (size_t i = 0; i < array.size(); i++) { - EXPECT_FALSE(array[i].moved()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - } - - array.resize(3); - ASSERT_EQ(3u, array.size()); - EXPECT_EQ(array.size(), MoveOnlyType::num_instances()); - for (size_t i = 0; i < array.size(); i++) - EXPECT_FALSE(array[i].moved()); - value_ptrs.push_back(array[2].ptr()); - - size_t capacity = array.storage().capacity(); - array.resize(capacity); - ASSERT_EQ(capacity, array.size()); - EXPECT_EQ(array.size(), MoveOnlyType::num_instances()); - for (size_t i = 0; i < array.size(); i++) - EXPECT_FALSE(array[i].moved()); - for (size_t i = 3; i < array.size(); i++) - value_ptrs.push_back(array[i].ptr()); - - array.resize(capacity + 2); - ASSERT_EQ(capacity + 2, array.size()); - EXPECT_EQ(array.size(), MoveOnlyType::num_instances()); - for (size_t i = 0; i < capacity; i++) { - EXPECT_TRUE(array[i].moved()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - } - for (size_t i = capacity; i < array.size(); i++) - EXPECT_FALSE(array[i].moved()); - - array.reset(); - EXPECT_EQ(0u, MoveOnlyType::num_instances()); - EXPECT_FALSE(array); - array.resize(0); - EXPECT_EQ(0u, MoveOnlyType::num_instances()); - EXPECT_TRUE(array); -} - -TEST_F(ArrayTest, PushBack_Copyable) { - ASSERT_EQ(0u, CopyableType::num_instances()); - mojo::Array<CopyableType> array(2); - array.reset(); - std::vector<CopyableType*> value_ptrs; - size_t capacity = array.storage().capacity(); - for (size_t i = 0; i < capacity; i++) { - CopyableType value; - value_ptrs.push_back(value.ptr()); - array.push_back(value); - ASSERT_EQ(i + 1, array.size()); - ASSERT_EQ(i + 1, value_ptrs.size()); - EXPECT_EQ(array.size() + 1, CopyableType::num_instances()); - EXPECT_TRUE(array[i].copied()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - array[i].ResetCopied(); - EXPECT_TRUE(array); - } - { - CopyableType value; - value_ptrs.push_back(value.ptr()); - array.push_back(value); - EXPECT_EQ(array.size() + 1, CopyableType::num_instances()); - } - ASSERT_EQ(capacity + 1, array.size()); - EXPECT_EQ(array.size(), CopyableType::num_instances()); - - for (size_t i = 0; i < array.size(); i++) { - EXPECT_TRUE(array[i].copied()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - } - array.reset(); - EXPECT_EQ(0u, CopyableType::num_instances()); -} - -TEST_F(ArrayTest, PushBack_MoveOnly) { - ASSERT_EQ(0u, MoveOnlyType::num_instances()); - mojo::Array<MoveOnlyType> array(2); - array.reset(); - std::vector<MoveOnlyType*> value_ptrs; - size_t capacity = array.storage().capacity(); - for (size_t i = 0; i < capacity; i++) { - MoveOnlyType value; - value_ptrs.push_back(value.ptr()); - array.push_back(value.Pass()); - ASSERT_EQ(i + 1, array.size()); - ASSERT_EQ(i + 1, value_ptrs.size()); - EXPECT_EQ(array.size() + 1, MoveOnlyType::num_instances()); - EXPECT_TRUE(array[i].moved()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - array[i].ResetMoved(); - EXPECT_TRUE(array); - } - { - MoveOnlyType value; - value_ptrs.push_back(value.ptr()); - array.push_back(value.Pass()); - EXPECT_EQ(array.size() + 1, MoveOnlyType::num_instances()); - } - ASSERT_EQ(capacity + 1, array.size()); - EXPECT_EQ(array.size(), MoveOnlyType::num_instances()); - - for (size_t i = 0; i < array.size(); i++) { - EXPECT_TRUE(array[i].moved()); - EXPECT_EQ(value_ptrs[i], array[i].ptr()); - } - array.reset(); - EXPECT_EQ(0u, MoveOnlyType::num_instances()); -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/bounds_checker_unittest.cc b/mojo/public/cpp/bindings/tests/bounds_checker_unittest.cc deleted file mode 100644 index 1cd9618..0000000 --- a/mojo/public/cpp/bindings/tests/bounds_checker_unittest.cc +++ /dev/null @@ -1,209 +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 <limits> - -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/bindings/lib/bounds_checker.h" -#include "mojo/public/cpp/system/core.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -const void* ToPtr(uintptr_t ptr) { - return reinterpret_cast<const void*>(ptr); -} - -#ifdef NDEBUG -TEST(BoundsCheckerTest, ConstructorRangeOverflow) { - { - // Test memory range overflow. - internal::BoundsChecker checker( - ToPtr(std::numeric_limits<uintptr_t>::max() - 3000), 5000, 0); - - EXPECT_FALSE(checker.IsValidRange( - ToPtr(std::numeric_limits<uintptr_t>::max() - 3000), 1)); - EXPECT_FALSE(checker.ClaimMemory( - ToPtr(std::numeric_limits<uintptr_t>::max() - 3000), 1)); - } - - if (sizeof(size_t) > sizeof(uint32_t)) { - // Test handle index range overflow. - size_t num_handles = - static_cast<size_t>(std::numeric_limits<uint32_t>::max()) + 5; - internal::BoundsChecker checker(ToPtr(0), 0, num_handles); - - EXPECT_FALSE(checker.ClaimHandle(Handle(0))); - EXPECT_FALSE( - checker.ClaimHandle(Handle(std::numeric_limits<uint32_t>::max() - 1))); - - EXPECT_TRUE( - checker.ClaimHandle(Handle(internal::kEncodedInvalidHandleValue))); - } -} -#endif - -TEST(BoundsCheckerTest, IsValidRange) { - { - internal::BoundsChecker checker(ToPtr(1234), 100, 0); - - // Basics. - EXPECT_FALSE(checker.IsValidRange(ToPtr(100), 5)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1230), 50)); - EXPECT_TRUE(checker.IsValidRange(ToPtr(1234), 5)); - EXPECT_TRUE(checker.IsValidRange(ToPtr(1240), 50)); - EXPECT_TRUE(checker.IsValidRange(ToPtr(1234), 100)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 101)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1240), 100)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1333), 5)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(2234), 5)); - - // ClaimMemory() updates the valid range. - EXPECT_TRUE(checker.ClaimMemory(ToPtr(1254), 10)); - - EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 1)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1254), 10)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1263), 1)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1263), 10)); - EXPECT_TRUE(checker.IsValidRange(ToPtr(1264), 10)); - EXPECT_TRUE(checker.IsValidRange(ToPtr(1264), 70)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1264), 71)); - } - - { - internal::BoundsChecker checker(ToPtr(1234), 100, 0); - // Should return false for empty ranges. - EXPECT_FALSE(checker.IsValidRange(ToPtr(0), 0)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1200), 0)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 0)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1240), 0)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(2234), 0)); - } - - { - // The valid memory range is empty. - internal::BoundsChecker checker(ToPtr(1234), 0, 0); - - EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 1)); - EXPECT_FALSE(checker.IsValidRange(ToPtr(1234), 0)); - } - - { - internal::BoundsChecker checker( - ToPtr(std::numeric_limits<uintptr_t>::max() - 2000), 1000, 0); - - // Test overflow. - EXPECT_FALSE(checker.IsValidRange( - ToPtr(std::numeric_limits<uintptr_t>::max() - 1500), 4000)); - EXPECT_FALSE(checker.IsValidRange( - ToPtr(std::numeric_limits<uintptr_t>::max() - 1500), - std::numeric_limits<uint32_t>::max())); - - // This should be fine. - EXPECT_TRUE(checker.IsValidRange( - ToPtr(std::numeric_limits<uintptr_t>::max() - 1500), 200)); - } -} - -TEST(BoundsCheckerTest, ClaimHandle) { - { - internal::BoundsChecker checker(ToPtr(0), 0, 10); - - // Basics. - EXPECT_TRUE(checker.ClaimHandle(Handle(0))); - EXPECT_FALSE(checker.ClaimHandle(Handle(0))); - - EXPECT_TRUE(checker.ClaimHandle(Handle(9))); - EXPECT_FALSE(checker.ClaimHandle(Handle(10))); - - // Should fail because it is smaller than the max index that has been - // claimed. - EXPECT_FALSE(checker.ClaimHandle(Handle(8))); - - // Should return true for invalid handle. - EXPECT_TRUE( - checker.ClaimHandle(Handle(internal::kEncodedInvalidHandleValue))); - EXPECT_TRUE( - checker.ClaimHandle(Handle(internal::kEncodedInvalidHandleValue))); - } - - { - // No handle to claim. - internal::BoundsChecker checker(ToPtr(0), 0, 0); - - EXPECT_FALSE(checker.ClaimHandle(Handle(0))); - - // Should still return true for invalid handle. - EXPECT_TRUE( - checker.ClaimHandle(Handle(internal::kEncodedInvalidHandleValue))); - } - - { - // Test the case that |num_handles| is the same value as - // |internal::kEncodedInvalidHandleValue|. - EXPECT_EQ(internal::kEncodedInvalidHandleValue, - std::numeric_limits<uint32_t>::max()); - internal::BoundsChecker checker( - ToPtr(0), 0, std::numeric_limits<uint32_t>::max()); - - EXPECT_TRUE( - checker.ClaimHandle(Handle(std::numeric_limits<uint32_t>::max() - 1))); - EXPECT_FALSE( - checker.ClaimHandle(Handle(std::numeric_limits<uint32_t>::max() - 1))); - EXPECT_FALSE(checker.ClaimHandle(Handle(0))); - - // Should still return true for invalid handle. - EXPECT_TRUE( - checker.ClaimHandle(Handle(internal::kEncodedInvalidHandleValue))); - } -} - -TEST(BoundsCheckerTest, ClaimMemory) { - { - internal::BoundsChecker checker(ToPtr(1000), 2000, 0); - - // Basics. - EXPECT_FALSE(checker.ClaimMemory(ToPtr(500), 100)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(800), 300)); - EXPECT_TRUE(checker.ClaimMemory(ToPtr(1000), 100)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(1099), 100)); - EXPECT_TRUE(checker.ClaimMemory(ToPtr(1100), 200)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(2000), 1001)); - EXPECT_TRUE(checker.ClaimMemory(ToPtr(2000), 500)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(2000), 500)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(1400), 100)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(3000), 1)); - EXPECT_TRUE(checker.ClaimMemory(ToPtr(2500), 500)); - } - - { - // No memory to claim. - internal::BoundsChecker checker(ToPtr(10000), 0, 0); - - EXPECT_FALSE(checker.ClaimMemory(ToPtr(10000), 1)); - EXPECT_FALSE(checker.ClaimMemory(ToPtr(10000), 0)); - } - - { - internal::BoundsChecker checker( - ToPtr(std::numeric_limits<uintptr_t>::max() - 1000), 500, 0); - - // Test overflow. - EXPECT_FALSE(checker.ClaimMemory( - ToPtr(std::numeric_limits<uintptr_t>::max() - 750), 4000)); - EXPECT_FALSE( - checker.ClaimMemory(ToPtr(std::numeric_limits<uintptr_t>::max() - 750), - std::numeric_limits<uint32_t>::max())); - - // This should be fine. - EXPECT_TRUE(checker.ClaimMemory( - ToPtr(std::numeric_limits<uintptr_t>::max() - 750), 200)); - } -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/buffer_unittest.cc b/mojo/public/cpp/bindings/tests/buffer_unittest.cc deleted file mode 100644 index 61424c05..0000000 --- a/mojo/public/cpp/bindings/tests/buffer_unittest.cc +++ /dev/null @@ -1,91 +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 <limits> - -#include "mojo/public/cpp/bindings/lib/bindings_serialization.h" -#include "mojo/public/cpp/bindings/lib/fixed_buffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -bool IsZero(void* p_buf, size_t size) { - char* buf = reinterpret_cast<char*>(p_buf); - for (size_t i = 0; i < size; ++i) { - if (buf[i] != 0) - return false; - } - return true; -} - -// Tests that FixedBuffer allocates memory aligned to 8 byte boundaries. -TEST(FixedBufferTest, Alignment) { - internal::FixedBuffer buf(internal::Align(10) * 2); - ASSERT_EQ(buf.size(), 16u * 2); - - void* a = buf.Allocate(10); - ASSERT_TRUE(a); - EXPECT_TRUE(IsZero(a, 10)); - EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(a) % 8); - - void* b = buf.Allocate(10); - ASSERT_TRUE(b); - EXPECT_TRUE(IsZero(b, 10)); - EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(b) % 8); - - // Any more allocations would result in an assert, but we can't test that. -} - -// Tests that FixedBuffer::Leak passes ownership to the caller. -TEST(FixedBufferTest, Leak) { - void* ptr = nullptr; - void* buf_ptr = nullptr; - { - internal::FixedBuffer buf(8); - ASSERT_EQ(8u, buf.size()); - - ptr = buf.Allocate(8); - ASSERT_TRUE(ptr); - buf_ptr = buf.Leak(); - - // The buffer should point to the first element allocated. - // TODO(mpcomplete): Is this a reasonable expectation? - EXPECT_EQ(ptr, buf_ptr); - - // The FixedBuffer should be empty now. - EXPECT_EQ(0u, buf.size()); - EXPECT_FALSE(buf.Leak()); - } - - // Since we called Leak, ptr is still writable after FixedBuffer went out of - // scope. - memset(ptr, 1, 8); - free(buf_ptr); -} - -#ifdef NDEBUG -TEST(FixedBufferTest, TooBig) { - internal::FixedBuffer buf(24); - - // A little bit too large. - EXPECT_EQ(reinterpret_cast<void*>(0), buf.Allocate(32)); - - // Move the cursor forward. - EXPECT_NE(reinterpret_cast<void*>(0), buf.Allocate(16)); - - // A lot too large. - EXPECT_EQ(reinterpret_cast<void*>(0), - buf.Allocate(std::numeric_limits<size_t>::max() - 1024u)); - - // A lot too large, leading to possible integer overflow. - EXPECT_EQ(reinterpret_cast<void*>(0), - buf.Allocate(std::numeric_limits<size_t>::max() - 8u)); -} -#endif - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/connector_unittest.cc b/mojo/public/cpp/bindings/tests/connector_unittest.cc deleted file mode 100644 index 3e00a67..0000000 --- a/mojo/public/cpp/bindings/tests/connector_unittest.cc +++ /dev/null @@ -1,394 +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 <stdlib.h> -#include <string.h> - -#include "mojo/public/cpp/bindings/lib/connector.h" -#include "mojo/public/cpp/bindings/lib/message_builder.h" -#include "mojo/public/cpp/bindings/lib/message_queue.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/macros.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -class MessageAccumulator : public MessageReceiver { - public: - MessageAccumulator() {} - - bool Accept(Message* message) override { - queue_.Push(message); - return true; - } - - bool IsEmpty() const { return queue_.IsEmpty(); } - - void Pop(Message* message) { queue_.Pop(message); } - - private: - internal::MessageQueue queue_; -}; - -class ConnectorDeletingMessageAccumulator : public MessageAccumulator { - public: - ConnectorDeletingMessageAccumulator(internal::Connector** connector) - : connector_(connector) {} - - bool Accept(Message* message) override { - delete *connector_; - *connector_ = 0; - return MessageAccumulator::Accept(message); - } - - private: - internal::Connector** connector_; -}; - -class ReentrantMessageAccumulator : public MessageAccumulator { - public: - ReentrantMessageAccumulator(internal::Connector* connector) - : connector_(connector), number_of_calls_(0) {} - - bool Accept(Message* message) override { - if (!MessageAccumulator::Accept(message)) - return false; - number_of_calls_++; - if (number_of_calls_ == 1) { - return connector_->WaitForIncomingMessage(); - } - return true; - } - - int number_of_calls() { return number_of_calls_; } - - private: - internal::Connector* connector_; - int number_of_calls_; -}; - -class ConnectorTest : public testing::Test { - public: - ConnectorTest() {} - - void SetUp() override { - CreateMessagePipe(nullptr, &handle0_, &handle1_); - } - - void TearDown() override {} - - void AllocMessage(const char* text, Message* message) { - size_t payload_size = strlen(text) + 1; // Plus null terminator. - internal::MessageBuilder builder(1, payload_size); - memcpy(builder.buffer()->Allocate(payload_size), text, payload_size); - builder.Finish(message); - } - - void PumpMessages() { loop_.RunUntilIdle(); } - - protected: - ScopedMessagePipeHandle handle0_; - ScopedMessagePipeHandle handle1_; - - private: - Environment env_; - RunLoop loop_; -}; - -TEST_F(ConnectorTest, Basic) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - const char kText[] = "hello world"; - - Message message; - AllocMessage(kText, &message); - - connector0.Accept(&message); - - MessageAccumulator accumulator; - connector1.set_incoming_receiver(&accumulator); - - PumpMessages(); - - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText), - std::string(reinterpret_cast<const char*>(message_received.payload()))); -} - -TEST_F(ConnectorTest, Basic_Synchronous) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - const char kText[] = "hello world"; - - Message message; - AllocMessage(kText, &message); - - connector0.Accept(&message); - - MessageAccumulator accumulator; - connector1.set_incoming_receiver(&accumulator); - - connector1.WaitForIncomingMessage(); - - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText), - std::string(reinterpret_cast<const char*>(message_received.payload()))); -} - -TEST_F(ConnectorTest, Basic_EarlyIncomingReceiver) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - MessageAccumulator accumulator; - connector1.set_incoming_receiver(&accumulator); - - const char kText[] = "hello world"; - - Message message; - AllocMessage(kText, &message); - - connector0.Accept(&message); - - PumpMessages(); - - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText), - std::string(reinterpret_cast<const char*>(message_received.payload()))); -} - -TEST_F(ConnectorTest, Basic_TwoMessages) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - const char* kText[] = {"hello", "world"}; - - for (size_t i = 0; i < MOJO_ARRAYSIZE(kText); ++i) { - Message message; - AllocMessage(kText[i], &message); - - connector0.Accept(&message); - } - - MessageAccumulator accumulator; - connector1.set_incoming_receiver(&accumulator); - - PumpMessages(); - - for (size_t i = 0; i < MOJO_ARRAYSIZE(kText); ++i) { - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText[i]), - std::string(reinterpret_cast<const char*>(message_received.payload()))); - } -} - -TEST_F(ConnectorTest, Basic_TwoMessages_Synchronous) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - const char* kText[] = {"hello", "world"}; - - for (size_t i = 0; i < MOJO_ARRAYSIZE(kText); ++i) { - Message message; - AllocMessage(kText[i], &message); - - connector0.Accept(&message); - } - - MessageAccumulator accumulator; - connector1.set_incoming_receiver(&accumulator); - - connector1.WaitForIncomingMessage(); - - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText[0]), - std::string(reinterpret_cast<const char*>(message_received.payload()))); - - ASSERT_TRUE(accumulator.IsEmpty()); -} - -TEST_F(ConnectorTest, WriteToClosedPipe) { - internal::Connector connector0(handle0_.Pass()); - - const char kText[] = "hello world"; - - Message message; - AllocMessage(kText, &message); - - // Close the other end of the pipe. - handle1_.reset(); - - // Not observed yet because we haven't spun the RunLoop yet. - EXPECT_FALSE(connector0.encountered_error()); - - // Write failures are not reported. - bool ok = connector0.Accept(&message); - EXPECT_TRUE(ok); - - // Still not observed. - EXPECT_FALSE(connector0.encountered_error()); - - // Spin the RunLoop, and then we should start observing the closed pipe. - PumpMessages(); - - EXPECT_TRUE(connector0.encountered_error()); -} - -TEST_F(ConnectorTest, MessageWithHandles) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - const char kText[] = "hello world"; - - Message message1; - AllocMessage(kText, &message1); - - MessagePipe pipe; - message1.mutable_handles()->push_back(pipe.handle0.release()); - - connector0.Accept(&message1); - - // The message should have been transferred, releasing the handles. - EXPECT_TRUE(message1.handles()->empty()); - - MessageAccumulator accumulator; - connector1.set_incoming_receiver(&accumulator); - - PumpMessages(); - - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText), - std::string(reinterpret_cast<const char*>(message_received.payload()))); - ASSERT_EQ(1U, message_received.handles()->size()); - - // Now send a message to the transferred handle and confirm it's sent through - // to the orginal pipe. - // TODO(vtl): Do we need a better way of "downcasting" the handle types? - ScopedMessagePipeHandle smph; - smph.reset(MessagePipeHandle(message_received.handles()->front().value())); - message_received.mutable_handles()->front() = Handle(); - // |smph| now owns this handle. - - internal::Connector connector_received(smph.Pass()); - internal::Connector connector_original(pipe.handle1.Pass()); - - Message message2; - AllocMessage(kText, &message2); - - connector_received.Accept(&message2); - connector_original.set_incoming_receiver(&accumulator); - PumpMessages(); - - ASSERT_FALSE(accumulator.IsEmpty()); - - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText), - std::string(reinterpret_cast<const char*>(message_received.payload()))); -} - -TEST_F(ConnectorTest, WaitForIncomingMessageWithError) { - internal::Connector connector0(handle0_.Pass()); - // Close the other end of the pipe. - handle1_.reset(); - ASSERT_FALSE(connector0.WaitForIncomingMessage()); -} - -TEST_F(ConnectorTest, WaitForIncomingMessageWithDeletion) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector* connector1 = new internal::Connector(handle1_.Pass()); - - const char kText[] = "hello world"; - - Message message; - AllocMessage(kText, &message); - - connector0.Accept(&message); - - ConnectorDeletingMessageAccumulator accumulator(&connector1); - connector1->set_incoming_receiver(&accumulator); - - connector1->WaitForIncomingMessage(); - - ASSERT_FALSE(connector1); - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText), - std::string(reinterpret_cast<const char*>(message_received.payload()))); -} - -TEST_F(ConnectorTest, WaitForIncomingMessageWithReentrancy) { - internal::Connector connector0(handle0_.Pass()); - internal::Connector connector1(handle1_.Pass()); - - const char* kText[] = {"hello", "world"}; - - for (size_t i = 0; i < MOJO_ARRAYSIZE(kText); ++i) { - Message message; - AllocMessage(kText[i], &message); - - connector0.Accept(&message); - } - - ReentrantMessageAccumulator accumulator(&connector1); - connector1.set_incoming_receiver(&accumulator); - - PumpMessages(); - - for (size_t i = 0; i < MOJO_ARRAYSIZE(kText); ++i) { - ASSERT_FALSE(accumulator.IsEmpty()); - - Message message_received; - accumulator.Pop(&message_received); - - EXPECT_EQ( - std::string(kText[i]), - std::string(reinterpret_cast<const char*>(message_received.payload()))); - } - - ASSERT_EQ(2, accumulator.number_of_calls()); -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/container_test_util.cc b/mojo/public/cpp/bindings/tests/container_test_util.cc deleted file mode 100644 index e8377c4..0000000 --- a/mojo/public/cpp/bindings/tests/container_test_util.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/tests/container_test_util.h" - -namespace mojo { - -size_t CopyableType::num_instances_ = 0; -size_t MoveOnlyType::num_instances_ = 0; - -CopyableType::CopyableType() : copied_(false), ptr_(this) { - num_instances_++; -} - -CopyableType::CopyableType(const CopyableType& other) - : copied_(true), ptr_(other.ptr()) { - num_instances_++; -} - -CopyableType& CopyableType::operator=(const CopyableType& other) { - copied_ = true; - ptr_ = other.ptr(); - return *this; -} - -CopyableType::~CopyableType() { - num_instances_--; -} - -MoveOnlyType::MoveOnlyType() : moved_(false), ptr_(this) { - num_instances_++; -} - -MoveOnlyType::MoveOnlyType(MoveOnlyType&& other) - : moved_(true), ptr_(other.ptr()) { - num_instances_++; -} - -MoveOnlyType& MoveOnlyType::operator=(MoveOnlyType&& other) { - moved_ = true; - ptr_ = other.ptr(); - return *this; -} - -MoveOnlyType::~MoveOnlyType() { - num_instances_--; -} - -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/container_test_util.h b/mojo/public/cpp/bindings/tests/container_test_util.h deleted file mode 100644 index 1e29d22..0000000 --- a/mojo/public/cpp/bindings/tests/container_test_util.h +++ /dev/null @@ -1,52 +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_TESTS_CONTAINER_TEST_UTIL_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_TESTS_CONTAINER_TEST_UTIL_H_ - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -class CopyableType { - public: - CopyableType(); - CopyableType(const CopyableType& other); - CopyableType& operator=(const CopyableType& other); - ~CopyableType(); - - bool copied() const { return copied_; } - static size_t num_instances() { return num_instances_; } - CopyableType* ptr() const { return ptr_; } - void ResetCopied() { copied_ = false; } - - private: - bool copied_; - static size_t num_instances_; - CopyableType* ptr_; -}; - -class MoveOnlyType { - MOJO_MOVE_ONLY_TYPE(MoveOnlyType) - public: - typedef MoveOnlyType Data_; - MoveOnlyType(); - MoveOnlyType(MoveOnlyType&& other); - MoveOnlyType& operator=(MoveOnlyType&& other); - ~MoveOnlyType(); - - bool moved() const { return moved_; } - static size_t num_instances() { return num_instances_; } - MoveOnlyType* ptr() const { return ptr_; } - void ResetMoved() { moved_ = false; } - - private: - bool moved_; - static size_t num_instances_; - MoveOnlyType* ptr_; -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_TESTS_CONTAINER_TEST_UTIL_H_ diff --git a/mojo/public/cpp/bindings/tests/equals_unittest.cc b/mojo/public/cpp/bindings/tests/equals_unittest.cc deleted file mode 100644 index 9196d86..0000000 --- a/mojo/public/cpp/bindings/tests/equals_unittest.cc +++ /dev/null @@ -1,120 +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/environment/environment.h" -#include "mojo/public/interfaces/bindings/tests/test_structs.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { - -namespace { - -RectPtr CreateRect() { - RectPtr r = Rect::New(); - r->x = 1; - r->y = 2; - r->width = 3; - r->height = 4; - return r.Pass(); -} - -class EqualsTest : public testing::Test { - public: - ~EqualsTest() override {} - - private: - Environment env_; -}; -} - -TEST_F(EqualsTest, Null) { - RectPtr r1; - RectPtr r2; - EXPECT_TRUE(r1.Equals(r2)); - EXPECT_TRUE(r2.Equals(r1)); - - r1 = CreateRect(); - EXPECT_FALSE(r1.Equals(r2)); - EXPECT_FALSE(r2.Equals(r1)); -} - -TEST_F(EqualsTest, EqualsStruct) { - RectPtr r1(CreateRect()); - RectPtr r2(r1.Clone()); - EXPECT_TRUE(r1.Equals(r2)); - r2->y = 1; - EXPECT_FALSE(r1.Equals(r2)); - r2.reset(); - EXPECT_FALSE(r1.Equals(r2)); -} - -TEST_F(EqualsTest, EqualsStructNested) { - RectPairPtr p1(RectPair::New()); - p1->first = CreateRect(); - p1->second = CreateRect(); - RectPairPtr p2(p1.Clone()); - EXPECT_TRUE(p1.Equals(p2)); - p2->second->width = 0; - EXPECT_FALSE(p1.Equals(p2)); - p2->second.reset(); - EXPECT_FALSE(p1.Equals(p2)); -} - -TEST_F(EqualsTest, EqualsArray) { - NamedRegionPtr n1(NamedRegion::New()); - n1->name = "n1"; - n1->rects.push_back(CreateRect()); - NamedRegionPtr n2(n1.Clone()); - EXPECT_TRUE(n1.Equals(n2)); - - n2->rects.reset(); - EXPECT_FALSE(n1.Equals(n2)); - n2->rects.resize(0); - EXPECT_FALSE(n1.Equals(n2)); - - n2->rects.push_back(CreateRect()); - n2->rects.push_back(CreateRect()); - EXPECT_FALSE(n1.Equals(n2)); - - n2->rects.resize(1); - n2->rects[0]->width = 0; - EXPECT_FALSE(n1.Equals(n2)); - - n2->rects[0] = CreateRect(); - EXPECT_TRUE(n1.Equals(n2)); -} - -TEST_F(EqualsTest, EqualsMap) { - auto n1(NamedRegion::New()); - n1->name = "foo"; - n1->rects.push_back(CreateRect()); - - Map<std::string, NamedRegionPtr> m1; - m1.insert("foo", n1.Pass()); - - decltype(m1) m2; - EXPECT_FALSE(m1.Equals(m2)); - - m2.insert("bar", m1.at("foo").Clone()); - EXPECT_FALSE(m1.Equals(m2)); - - m2 = m1.Clone(); - m2.at("foo")->name = "monkey"; - EXPECT_FALSE(m1.Equals(m2)); - - m2 = m1.Clone(); - m2.at("foo")->rects.push_back(Rect::New()); - EXPECT_FALSE(m1.Equals(m2)); - - m2.at("foo")->rects.resize(1); - m2.at("foo")->rects[0]->width = 1; - EXPECT_FALSE(m1.Equals(m2)); - - m2 = m1.Clone(); - EXPECT_TRUE(m1.Equals(m2)); -} - -} // test -} // mojo diff --git a/mojo/public/cpp/bindings/tests/handle_passing_unittest.cc b/mojo/public/cpp/bindings/tests/handle_passing_unittest.cc deleted file mode 100644 index 5667f64..0000000 --- a/mojo/public/cpp/bindings/tests/handle_passing_unittest.cc +++ /dev/null @@ -1,342 +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/environment/environment.h" -#include "mojo/public/cpp/test_support/test_utils.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "mojo/public/interfaces/bindings/tests/sample_factory.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -const char kText1[] = "hello"; -const char kText2[] = "world"; - -class StringRecorder { - public: - explicit StringRecorder(std::string* buf) : buf_(buf) {} - void Run(const String& a) const { *buf_ = a.To<std::string>(); } - - private: - std::string* buf_; -}; - -class ImportedInterfaceImpl - : public InterfaceImpl<imported::ImportedInterface> { - public: - void DoSomething() override { do_something_count_++; } - - static int do_something_count() { return do_something_count_; } - - private: - static int do_something_count_; -}; -int ImportedInterfaceImpl::do_something_count_ = 0; - -class SampleNamedObjectImpl : public InterfaceImpl<sample::NamedObject> { - public: - void SetName(const mojo::String& name) override { name_ = name; } - - void GetName(const mojo::Callback<void(mojo::String)>& callback) override { - callback.Run(name_); - } - - private: - std::string name_; -}; - -class SampleFactoryImpl : public InterfaceImpl<sample::Factory> { - public: - void DoStuff(sample::RequestPtr request, - ScopedMessagePipeHandle pipe) override { - std::string text1; - if (pipe.is_valid()) - EXPECT_TRUE(ReadTextMessage(pipe.get(), &text1)); - - std::string text2; - if (request->pipe.is_valid()) { - EXPECT_TRUE(ReadTextMessage(request->pipe.get(), &text2)); - - // Ensure that simply accessing request->pipe does not close it. - EXPECT_TRUE(request->pipe.is_valid()); - } - - ScopedMessagePipeHandle pipe0; - if (!text2.empty()) { - CreateMessagePipe(nullptr, &pipe0, &pipe1_); - EXPECT_TRUE(WriteTextMessage(pipe1_.get(), text2)); - } - - sample::ResponsePtr response(sample::Response::New()); - response->x = 2; - response->pipe = pipe0.Pass(); - client()->DidStuff(response.Pass(), text1); - - if (request->obj) - request->obj->DoSomething(); - } - - void DoStuff2(ScopedDataPipeConsumerHandle pipe) override { - // Read the data from the pipe, writing the response (as a string) to - // DidStuff2(). - ASSERT_TRUE(pipe.is_valid()); - uint32_t data_size = 0; - ASSERT_EQ(MOJO_RESULT_OK, - ReadDataRaw( - pipe.get(), nullptr, &data_size, MOJO_READ_DATA_FLAG_QUERY)); - ASSERT_NE(0, static_cast<int>(data_size)); - char data[64]; - ASSERT_LT(static_cast<int>(data_size), 64); - ASSERT_EQ( - MOJO_RESULT_OK, - ReadDataRaw( - pipe.get(), data, &data_size, MOJO_READ_DATA_FLAG_ALL_OR_NONE)); - - client()->DidStuff2(data); - } - - void CreateNamedObject( - InterfaceRequest<sample::NamedObject> object_request) override { - EXPECT_TRUE(object_request.is_pending()); - BindToRequest(new SampleNamedObjectImpl(), &object_request); - } - - // These aren't called or implemented, but exist here to test that the - // methods are generated with the correct argument types for imported - // interfaces. - void RequestImportedInterface( - InterfaceRequest<imported::ImportedInterface> imported, - const mojo::Callback<void(InterfaceRequest<imported::ImportedInterface>)>& - callback) override {} - void TakeImportedInterface( - imported::ImportedInterfacePtr imported, - const mojo::Callback<void(imported::ImportedInterfacePtr)>& callback) - override {} - - private: - ScopedMessagePipeHandle pipe1_; -}; - -class SampleFactoryClientImpl : public sample::FactoryClient { - public: - SampleFactoryClientImpl() : got_response_(false) {} - - void set_expected_text_reply(const std::string& expected_text_reply) { - expected_text_reply_ = expected_text_reply; - } - - bool got_response() const { return got_response_; } - - void DidStuff(sample::ResponsePtr response, - const String& text_reply) override { - EXPECT_EQ(expected_text_reply_, text_reply); - - if (response->pipe.is_valid()) { - std::string text2; - EXPECT_TRUE(ReadTextMessage(response->pipe.get(), &text2)); - - // Ensure that simply accessing response.pipe does not close it. - EXPECT_TRUE(response->pipe.is_valid()); - - EXPECT_EQ(std::string(kText2), text2); - - // Do some more tests of handle passing: - ScopedMessagePipeHandle p = response->pipe.Pass(); - EXPECT_TRUE(p.is_valid()); - EXPECT_FALSE(response->pipe.is_valid()); - } - - got_response_ = true; - } - - void DidStuff2(const String& text_reply) override { - got_response_ = true; - EXPECT_EQ(expected_text_reply_, text_reply); - } - - private: - ScopedMessagePipeHandle pipe1_; - ScopedMessagePipeHandle pipe3_; - std::string expected_text_reply_; - bool got_response_; -}; - -class HandlePassingTest : public testing::Test { - public: - void TearDown() override { PumpMessages(); } - - void PumpMessages() { loop_.RunUntilIdle(); } - - private: - Environment env_; - RunLoop loop_; -}; - -TEST_F(HandlePassingTest, Basic) { - sample::FactoryPtr factory; - BindToProxy(new SampleFactoryImpl(), &factory); - - SampleFactoryClientImpl factory_client; - factory_client.set_expected_text_reply(kText1); - - factory.set_client(&factory_client); - - MessagePipe pipe0; - EXPECT_TRUE(WriteTextMessage(pipe0.handle1.get(), kText1)); - - MessagePipe pipe1; - EXPECT_TRUE(WriteTextMessage(pipe1.handle1.get(), kText2)); - - imported::ImportedInterfacePtr imported; - BindToProxy(new ImportedInterfaceImpl(), &imported); - - sample::RequestPtr request(sample::Request::New()); - request->x = 1; - request->pipe = pipe1.handle0.Pass(); - request->obj = imported.Pass(); - factory->DoStuff(request.Pass(), pipe0.handle0.Pass()); - - EXPECT_FALSE(factory_client.got_response()); - int count_before = ImportedInterfaceImpl::do_something_count(); - - PumpMessages(); - - EXPECT_TRUE(factory_client.got_response()); - EXPECT_EQ(1, ImportedInterfaceImpl::do_something_count() - count_before); -} - -TEST_F(HandlePassingTest, PassInvalid) { - sample::FactoryPtr factory; - BindToProxy(new SampleFactoryImpl(), &factory); - - SampleFactoryClientImpl factory_client; - factory.set_client(&factory_client); - - sample::RequestPtr request(sample::Request::New()); - request->x = 1; - factory->DoStuff(request.Pass(), ScopedMessagePipeHandle().Pass()); - - EXPECT_FALSE(factory_client.got_response()); - - PumpMessages(); - - EXPECT_TRUE(factory_client.got_response()); -} - -// Verifies DataPipeConsumer can be passed and read from. -TEST_F(HandlePassingTest, DataPipe) { - sample::FactoryPtr factory; - BindToProxy(new SampleFactoryImpl(), &factory); - - SampleFactoryClientImpl factory_client; - factory.set_client(&factory_client); - - // Writes a string to a data pipe and passes the data pipe (consumer) to the - // factory. - ScopedDataPipeProducerHandle producer_handle; - ScopedDataPipeConsumerHandle consumer_handle; - MojoCreateDataPipeOptions options = {sizeof(MojoCreateDataPipeOptions), - MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE, - 1, - 1024}; - ASSERT_EQ(MOJO_RESULT_OK, - CreateDataPipe(&options, &producer_handle, &consumer_handle)); - std::string expected_text_reply = "got it"; - factory_client.set_expected_text_reply(expected_text_reply); - // +1 for \0. - uint32_t data_size = static_cast<uint32_t>(expected_text_reply.size() + 1); - ASSERT_EQ(MOJO_RESULT_OK, - WriteDataRaw(producer_handle.get(), - expected_text_reply.c_str(), - &data_size, - MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); - - factory->DoStuff2(consumer_handle.Pass()); - - EXPECT_FALSE(factory_client.got_response()); - - PumpMessages(); - - EXPECT_TRUE(factory_client.got_response()); -} - -TEST_F(HandlePassingTest, PipesAreClosed) { - sample::FactoryPtr factory; - BindToProxy(new SampleFactoryImpl(), &factory); - - SampleFactoryClientImpl factory_client; - factory.set_client(&factory_client); - - MessagePipe extra_pipe; - - MojoHandle handle0_value = extra_pipe.handle0.get().value(); - MojoHandle handle1_value = extra_pipe.handle1.get().value(); - - { - Array<ScopedMessagePipeHandle> pipes(2); - pipes[0] = extra_pipe.handle0.Pass(); - pipes[1] = extra_pipe.handle1.Pass(); - - sample::RequestPtr request(sample::Request::New()); - request->more_pipes = pipes.Pass(); - - factory->DoStuff(request.Pass(), ScopedMessagePipeHandle()); - } - - // We expect the pipes to have been closed. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(handle0_value)); - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(handle1_value)); -} - -TEST_F(HandlePassingTest, IsHandle) { - // Validate that mojo::internal::IsHandle<> works as expected since this. - // template is key to ensuring that we don't leak handles. - EXPECT_TRUE(internal::IsHandle<Handle>::value); - EXPECT_TRUE(internal::IsHandle<MessagePipeHandle>::value); - EXPECT_TRUE(internal::IsHandle<DataPipeConsumerHandle>::value); - EXPECT_TRUE(internal::IsHandle<DataPipeProducerHandle>::value); - EXPECT_TRUE(internal::IsHandle<SharedBufferHandle>::value); - - // Basic sanity checks... - EXPECT_FALSE(internal::IsHandle<int>::value); - EXPECT_FALSE(internal::IsHandle<sample::FactoryPtr>::value); - EXPECT_FALSE(internal::IsHandle<String>::value); -} - -TEST_F(HandlePassingTest, CreateNamedObject) { - sample::FactoryPtr factory; - BindToProxy(new SampleFactoryImpl(), &factory); - - sample::NamedObjectPtr object1; - EXPECT_FALSE(object1); - - InterfaceRequest<sample::NamedObject> object1_request = GetProxy(&object1); - EXPECT_TRUE(object1_request.is_pending()); - factory->CreateNamedObject(object1_request.Pass()); - EXPECT_FALSE(object1_request.is_pending()); // We've passed the request. - - ASSERT_TRUE(object1); - object1->SetName("object1"); - - sample::NamedObjectPtr object2; - factory->CreateNamedObject(GetProxy(&object2)); - object2->SetName("object2"); - - std::string name1; - object1->GetName(StringRecorder(&name1)); - - std::string name2; - object2->GetName(StringRecorder(&name2)); - - PumpMessages(); // Yield for results. - - EXPECT_EQ(std::string("object1"), name1); - EXPECT_EQ(std::string("object2"), name2); -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc b/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc deleted file mode 100644 index f90dc3d..0000000 --- a/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc +++ /dev/null @@ -1,482 +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/binding.h" -#include "mojo/public/cpp/bindings/error_handler.h" -#include "mojo/public/cpp/bindings/strong_binding.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "mojo/public/interfaces/bindings/tests/math_calculator.mojom.h" -#include "mojo/public/interfaces/bindings/tests/sample_service.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -class ErrorObserver : public ErrorHandler { - public: - ErrorObserver() : encountered_error_(false) {} - - bool encountered_error() const { return encountered_error_; } - - void OnConnectionError() override { encountered_error_ = true; } - - private: - bool encountered_error_; -}; - -class MathCalculatorImpl : public InterfaceImpl<math::Calculator> { - public: - ~MathCalculatorImpl() override {} - - MathCalculatorImpl() : total_(0.0) {} - - void Clear() override { client()->Output(total_); } - - void Add(double value) override { - total_ += value; - client()->Output(total_); - } - - void Multiply(double value) override { - total_ *= value; - client()->Output(total_); - } - - private: - double total_; -}; - -class MathCalculatorUIImpl : public math::CalculatorUI { - public: - explicit MathCalculatorUIImpl(math::CalculatorPtr calculator) - : calculator_(calculator.Pass()), output_(0.0) { - calculator_.set_client(this); - } - - bool WaitForIncomingMethodCall() { - return calculator_.WaitForIncomingMethodCall(); - } - - bool encountered_error() const { return calculator_.encountered_error(); } - - void Add(double value) { calculator_->Add(value); } - - void Subtract(double value) { calculator_->Add(-value); } - - void Multiply(double value) { calculator_->Multiply(value); } - - void Divide(double value) { calculator_->Multiply(1.0 / value); } - - double GetOutput() const { return output_; } - - private: - // math::CalculatorUI implementation: - void Output(double value) override { output_ = value; } - - math::CalculatorPtr calculator_; - double output_; -}; - -class SelfDestructingMathCalculatorUIImpl : public math::CalculatorUI { - public: - explicit SelfDestructingMathCalculatorUIImpl(math::CalculatorPtr calculator) - : calculator_(calculator.Pass()), nesting_level_(0) { - ++num_instances_; - calculator_.set_client(this); - } - - void BeginTest(bool nested) { - nesting_level_ = nested ? 2 : 1; - calculator_->Add(1.0); - } - - static int num_instances() { return num_instances_; } - - private: - ~SelfDestructingMathCalculatorUIImpl() override { --num_instances_; } - - void Output(double value) override { - if (--nesting_level_ > 0) { - // Add some more and wait for re-entrant call to Output! - calculator_->Add(1.0); - RunLoop::current()->RunUntilIdle(); - } else { - delete this; - } - } - - math::CalculatorPtr calculator_; - int nesting_level_; - static int num_instances_; -}; - -// static -int SelfDestructingMathCalculatorUIImpl::num_instances_ = 0; - -class ReentrantServiceImpl : public InterfaceImpl<sample::Service> { - public: - ~ReentrantServiceImpl() override {} - - ReentrantServiceImpl() : call_depth_(0), max_call_depth_(0) {} - - int max_call_depth() { return max_call_depth_; } - - void Frobinate(sample::FooPtr foo, - sample::Service::BazOptions baz, - sample::PortPtr port) override { - max_call_depth_ = std::max(++call_depth_, max_call_depth_); - if (call_depth_ == 1) { - EXPECT_TRUE(WaitForIncomingMethodCall()); - } - call_depth_--; - } - - void GetPort(mojo::InterfaceRequest<sample::Port> port) override {} - - private: - int call_depth_; - int max_call_depth_; -}; - -class InterfacePtrTest : public testing::Test { - public: - ~InterfacePtrTest() override { loop_.RunUntilIdle(); } - - void PumpMessages() { loop_.RunUntilIdle(); } - - private: - Environment env_; - RunLoop loop_; -}; - -TEST_F(InterfacePtrTest, EndToEnd) { - math::CalculatorPtr calc; - BindToProxy(new MathCalculatorImpl(), &calc); - - // Suppose this is instantiated in a process that has pipe1_. - MathCalculatorUIImpl calculator_ui(calc.Pass()); - - calculator_ui.Add(2.0); - calculator_ui.Multiply(5.0); - - PumpMessages(); - - EXPECT_EQ(10.0, calculator_ui.GetOutput()); -} - -TEST_F(InterfacePtrTest, EndToEnd_Synchronous) { - math::CalculatorPtr calc; - MathCalculatorImpl* impl = BindToProxy(new MathCalculatorImpl(), &calc); - - // Suppose this is instantiated in a process that has pipe1_. - MathCalculatorUIImpl calculator_ui(calc.Pass()); - - EXPECT_EQ(0.0, calculator_ui.GetOutput()); - - calculator_ui.Add(2.0); - EXPECT_EQ(0.0, calculator_ui.GetOutput()); - impl->WaitForIncomingMethodCall(); - calculator_ui.WaitForIncomingMethodCall(); - EXPECT_EQ(2.0, calculator_ui.GetOutput()); - - calculator_ui.Multiply(5.0); - EXPECT_EQ(2.0, calculator_ui.GetOutput()); - impl->WaitForIncomingMethodCall(); - calculator_ui.WaitForIncomingMethodCall(); - EXPECT_EQ(10.0, calculator_ui.GetOutput()); -} - -TEST_F(InterfacePtrTest, Movable) { - math::CalculatorPtr a; - math::CalculatorPtr b; - BindToProxy(new MathCalculatorImpl(), &b); - - EXPECT_TRUE(!a); - EXPECT_FALSE(!b); - - a = b.Pass(); - - EXPECT_FALSE(!a); - EXPECT_TRUE(!b); -} - -TEST_F(InterfacePtrTest, Resettable) { - math::CalculatorPtr a; - - EXPECT_TRUE(!a); - - MessagePipe pipe; - - // Save this so we can test it later. - Handle handle = pipe.handle0.get(); - - a = MakeProxy<math::Calculator>(pipe.handle0.Pass()); - - EXPECT_FALSE(!a); - - a.reset(); - - EXPECT_TRUE(!a); - EXPECT_FALSE(a.internal_state()->router_for_testing()); - - // Test that handle was closed. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, CloseRaw(handle)); -} - -TEST_F(InterfacePtrTest, EncounteredError) { - math::CalculatorPtr proxy; - MathCalculatorImpl* server = BindToProxy(new MathCalculatorImpl(), &proxy); - - MathCalculatorUIImpl calculator_ui(proxy.Pass()); - - calculator_ui.Add(2.0); - PumpMessages(); - EXPECT_EQ(2.0, calculator_ui.GetOutput()); - EXPECT_FALSE(calculator_ui.encountered_error()); - - calculator_ui.Multiply(5.0); - EXPECT_FALSE(calculator_ui.encountered_error()); - - // Close the server. - server->internal_router()->CloseMessagePipe(); - - // The state change isn't picked up locally yet. - EXPECT_FALSE(calculator_ui.encountered_error()); - - PumpMessages(); - - // OK, now we see the error. - EXPECT_TRUE(calculator_ui.encountered_error()); -} - -TEST_F(InterfacePtrTest, EncounteredErrorCallback) { - math::CalculatorPtr proxy; - MathCalculatorImpl* server = BindToProxy(new MathCalculatorImpl(), &proxy); - - ErrorObserver error_observer; - proxy.set_error_handler(&error_observer); - - MathCalculatorUIImpl calculator_ui(proxy.Pass()); - - calculator_ui.Add(2.0); - PumpMessages(); - EXPECT_EQ(2.0, calculator_ui.GetOutput()); - EXPECT_FALSE(calculator_ui.encountered_error()); - - calculator_ui.Multiply(5.0); - EXPECT_FALSE(calculator_ui.encountered_error()); - - // Close the server. - server->internal_router()->CloseMessagePipe(); - - // The state change isn't picked up locally yet. - EXPECT_FALSE(calculator_ui.encountered_error()); - - PumpMessages(); - - // OK, now we see the error. - EXPECT_TRUE(calculator_ui.encountered_error()); - - // We should have also been able to observe the error through the - // ErrorHandler interface. - EXPECT_TRUE(error_observer.encountered_error()); -} - -TEST_F(InterfacePtrTest, NoClientAttribute) { - // This is a test to ensure the following compiles. The sample::Port interface - // does not have an explicit Client attribute. - sample::PortPtr port; - MessagePipe pipe; - port.Bind(pipe.handle0.Pass()); -} - -TEST_F(InterfacePtrTest, DestroyInterfacePtrOnClientMethod) { - math::CalculatorPtr proxy; - BindToProxy(new MathCalculatorImpl(), &proxy); - - EXPECT_EQ(0, SelfDestructingMathCalculatorUIImpl::num_instances()); - - SelfDestructingMathCalculatorUIImpl* impl = - new SelfDestructingMathCalculatorUIImpl(proxy.Pass()); - impl->BeginTest(false); - - PumpMessages(); - - EXPECT_EQ(0, SelfDestructingMathCalculatorUIImpl::num_instances()); -} - -TEST_F(InterfacePtrTest, NestedDestroyInterfacePtrOnClientMethod) { - math::CalculatorPtr proxy; - BindToProxy(new MathCalculatorImpl(), &proxy); - - EXPECT_EQ(0, SelfDestructingMathCalculatorUIImpl::num_instances()); - - SelfDestructingMathCalculatorUIImpl* impl = - new SelfDestructingMathCalculatorUIImpl(proxy.Pass()); - impl->BeginTest(true); - - PumpMessages(); - - EXPECT_EQ(0, SelfDestructingMathCalculatorUIImpl::num_instances()); -} - -TEST_F(InterfacePtrTest, ReentrantWaitForIncomingMethodCall) { - sample::ServicePtr proxy; - ReentrantServiceImpl* impl = BindToProxy(new ReentrantServiceImpl(), &proxy); - - proxy->Frobinate(nullptr, sample::Service::BAZ_OPTIONS_REGULAR, nullptr); - proxy->Frobinate(nullptr, sample::Service::BAZ_OPTIONS_REGULAR, nullptr); - - PumpMessages(); - - EXPECT_EQ(2, impl->max_call_depth()); -} - -class StrongMathCalculatorImpl : public math::Calculator, public ErrorHandler { - public: - StrongMathCalculatorImpl(ScopedMessagePipeHandle handle, - bool* error_received, - bool* destroyed) - : error_received_(error_received), - destroyed_(destroyed), - binding_(this, handle.Pass()) { - binding_.set_error_handler(this); - } - ~StrongMathCalculatorImpl() override { *destroyed_ = true; } - - // math::Calculator implementation. - void Clear() override { binding_.client()->Output(total_); } - - void Add(double value) override { - total_ += value; - binding_.client()->Output(total_); - } - - void Multiply(double value) override { - total_ *= value; - binding_.client()->Output(total_); - } - - // ErrorHandler implementation. - void OnConnectionError() override { *error_received_ = true; } - - private: - double total_ = 0.0; - bool* error_received_; - bool* destroyed_; - - StrongBinding<math::Calculator> binding_; -}; - -TEST(StrongConnectorTest, Math) { - Environment env; - RunLoop loop; - - bool error_received = false; - bool destroyed = false; - MessagePipe pipe; - new StrongMathCalculatorImpl(pipe.handle0.Pass(), &error_received, - &destroyed); - - math::CalculatorPtr calc; - calc.Bind(pipe.handle1.Pass()); - - { - // Suppose this is instantiated in a process that has the other end of the - // message pipe. - MathCalculatorUIImpl calculator_ui(calc.Pass()); - - calculator_ui.Add(2.0); - calculator_ui.Multiply(5.0); - - loop.RunUntilIdle(); - - EXPECT_EQ(10.0, calculator_ui.GetOutput()); - EXPECT_FALSE(error_received); - EXPECT_FALSE(destroyed); - } - // Destroying calculator_ui should close the pipe and generate an error on the - // other - // end which will destroy the instance since it is strongly bound. - - loop.RunUntilIdle(); - EXPECT_TRUE(error_received); - EXPECT_TRUE(destroyed); -} - -class WeakMathCalculatorImpl : public math::Calculator, public ErrorHandler { - public: - WeakMathCalculatorImpl(ScopedMessagePipeHandle handle, - bool* error_received, - bool* destroyed) - : error_received_(error_received), - destroyed_(destroyed), - binding_(this, handle.Pass()) { - binding_.set_error_handler(this); - } - ~WeakMathCalculatorImpl() override { *destroyed_ = true; } - - void Clear() override { binding_.client()->Output(total_); } - - void Add(double value) override { - total_ += value; - binding_.client()->Output(total_); - } - - void Multiply(double value) override { - total_ *= value; - binding_.client()->Output(total_); - } - - // ErrorHandler implementation. - void OnConnectionError() override { *error_received_ = true; } - - private: - double total_ = 0.0; - bool* error_received_; - bool* destroyed_; - - Binding<math::Calculator> binding_; -}; - -TEST(WeakConnectorTest, Math) { - Environment env; - RunLoop loop; - - bool error_received = false; - bool destroyed = false; - MessagePipe pipe; - WeakMathCalculatorImpl impl(pipe.handle0.Pass(), &error_received, &destroyed); - - math::CalculatorPtr calc; - calc.Bind(pipe.handle1.Pass()); - - { - // Suppose this is instantiated in a process that has the other end of the - // message pipe. - MathCalculatorUIImpl calculator_ui(calc.Pass()); - - calculator_ui.Add(2.0); - calculator_ui.Multiply(5.0); - - loop.RunUntilIdle(); - - EXPECT_EQ(10.0, calculator_ui.GetOutput()); - EXPECT_FALSE(error_received); - EXPECT_FALSE(destroyed); - // Destroying calculator_ui should close the pipe and generate an error on - // the other - // end which will destroy the instance since it is strongly bound. - } - - loop.RunUntilIdle(); - EXPECT_TRUE(error_received); - EXPECT_FALSE(destroyed); -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/map_unittest.cc b/mojo/public/cpp/bindings/tests/map_unittest.cc deleted file mode 100644 index 698f407..0000000 --- a/mojo/public/cpp/bindings/tests/map_unittest.cc +++ /dev/null @@ -1,326 +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/array.h" -#include "mojo/public/cpp/bindings/lib/array_serialization.h" -#include "mojo/public/cpp/bindings/lib/bindings_internal.h" -#include "mojo/public/cpp/bindings/lib/fixed_buffer.h" -#include "mojo/public/cpp/bindings/lib/validate_params.h" -#include "mojo/public/cpp/bindings/map.h" -#include "mojo/public/cpp/bindings/string.h" -#include "mojo/public/cpp/bindings/tests/container_test_util.h" -#include "mojo/public/cpp/environment/environment.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { - -namespace { - -using mojo::internal::Array_Data; -using mojo::internal::ArrayValidateParams; -using mojo::internal::FixedBuffer; -using mojo::internal::Map_Data; -using mojo::internal::NoValidateParams; -using mojo::internal::String_Data; - -struct StringIntData { - const char* string_data; - int int_data; -} kStringIntData[] = { - {"one", 1}, - {"two", 2}, - {"three", 3}, - {"four", 4}, -}; - -const size_t kStringIntDataSize = 4; - -class MapTest : public testing::Test { - public: - ~MapTest() override {} - - private: - Environment env_; -}; - -// Tests that basic Map operations work. -TEST_F(MapTest, InsertWorks) { - Map<String, int> map; - for (size_t i = 0; i < kStringIntDataSize; ++i) - map.insert(kStringIntData[i].string_data, kStringIntData[i].int_data); - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - EXPECT_EQ(kStringIntData[i].int_data, - map.at(kStringIntData[i].string_data)); - } -} - -TEST_F(MapTest, TestIndexOperator) { - Map<String, int> map; - for (size_t i = 0; i < kStringIntDataSize; ++i) - map[kStringIntData[i].string_data] = kStringIntData[i].int_data; - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - EXPECT_EQ(kStringIntData[i].int_data, - map.at(kStringIntData[i].string_data)); - } -} - -TEST_F(MapTest, TestIndexOperatorAsRValue) { - Map<String, int> map; - for (size_t i = 0; i < kStringIntDataSize; ++i) - map.insert(kStringIntData[i].string_data, kStringIntData[i].int_data); - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - EXPECT_EQ(kStringIntData[i].int_data, map[kStringIntData[i].string_data]); - } -} - -TEST_F(MapTest, TestIndexOperatorMoveOnly) { - ASSERT_EQ(0u, MoveOnlyType::num_instances()); - mojo::Map<mojo::String, mojo::Array<int32_t>> map; - std::vector<MoveOnlyType*> value_ptrs; - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - const char* key = kStringIntData[i].string_data; - Array<int32_t> array(1); - array[0] = kStringIntData[i].int_data; - map[key] = array.Pass(); - EXPECT_TRUE(map); - } - - // We now read back that data, to test the behavior of operator[]. - for (size_t i = 0; i < kStringIntDataSize; ++i) { - auto it = map.find(kStringIntData[i].string_data); - ASSERT_TRUE(it != map.end()); - ASSERT_EQ(1u, it.GetValue().size()); - EXPECT_EQ(kStringIntData[i].int_data, it.GetValue()[0]); - } -} - -TEST_F(MapTest, ConstructedFromArray) { - Array<String> keys(kStringIntDataSize); - Array<int> values(kStringIntDataSize); - for (size_t i = 0; i < kStringIntDataSize; ++i) { - keys[i] = kStringIntData[i].string_data; - values[i] = kStringIntData[i].int_data; - } - - Map<String, int> map(keys.Pass(), values.Pass()); - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - EXPECT_EQ(kStringIntData[i].int_data, - map.at(mojo::String(kStringIntData[i].string_data))); - } -} - -TEST_F(MapTest, DecomposeMapTo) { - Array<String> keys(kStringIntDataSize); - Array<int> values(kStringIntDataSize); - for (size_t i = 0; i < kStringIntDataSize; ++i) { - keys[i] = kStringIntData[i].string_data; - values[i] = kStringIntData[i].int_data; - } - - Map<String, int> map(keys.Pass(), values.Pass()); - EXPECT_EQ(kStringIntDataSize, map.size()); - - Array<String> keys2; - Array<int> values2; - map.DecomposeMapTo(&keys2, &values2); - EXPECT_EQ(0u, map.size()); - - EXPECT_EQ(kStringIntDataSize, keys2.size()); - EXPECT_EQ(kStringIntDataSize, values2.size()); - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - // We are not guaranteed that the copies have the same sorting as the - // originals. - String key = kStringIntData[i].string_data; - int value = kStringIntData[i].int_data; - - bool found = false; - for (size_t j = 0; j < keys2.size(); ++j) { - if (keys2[j] == key) { - EXPECT_EQ(value, values2[j]); - found = true; - break; - } - } - - EXPECT_TRUE(found); - } -} - -TEST_F(MapTest, Insert_Copyable) { - ASSERT_EQ(0u, CopyableType::num_instances()); - mojo::Map<mojo::String, CopyableType> map; - std::vector<CopyableType*> value_ptrs; - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - const char* key = kStringIntData[i].string_data; - CopyableType value; - value_ptrs.push_back(value.ptr()); - map.insert(key, value); - ASSERT_EQ(i + 1, map.size()); - ASSERT_EQ(i + 1, value_ptrs.size()); - EXPECT_EQ(map.size() + 1, CopyableType::num_instances()); - EXPECT_TRUE(map.at(key).copied()); - EXPECT_EQ(value_ptrs[i], map.at(key).ptr()); - map.at(key).ResetCopied(); - EXPECT_TRUE(map); - } - - // std::map doesn't have a capacity() method like std::vector so this test is - // a lot more boring. - - map.reset(); - EXPECT_EQ(0u, CopyableType::num_instances()); -} - -TEST_F(MapTest, Insert_MoveOnly) { - ASSERT_EQ(0u, MoveOnlyType::num_instances()); - mojo::Map<mojo::String, MoveOnlyType> map; - std::vector<MoveOnlyType*> value_ptrs; - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - const char* key = kStringIntData[i].string_data; - MoveOnlyType value; - value_ptrs.push_back(value.ptr()); - map.insert(key, value.Pass()); - ASSERT_EQ(i + 1, map.size()); - ASSERT_EQ(i + 1, value_ptrs.size()); - EXPECT_EQ(map.size() + 1, MoveOnlyType::num_instances()); - EXPECT_TRUE(map.at(key).moved()); - EXPECT_EQ(value_ptrs[i], map.at(key).ptr()); - map.at(key).ResetMoved(); - EXPECT_TRUE(map); - } - - // std::map doesn't have a capacity() method like std::vector so this test is - // a lot more boring. - - map.reset(); - EXPECT_EQ(0u, MoveOnlyType::num_instances()); -} - -TEST_F(MapTest, IndexOperator_MoveOnly) { - ASSERT_EQ(0u, MoveOnlyType::num_instances()); - mojo::Map<mojo::String, MoveOnlyType> map; - std::vector<MoveOnlyType*> value_ptrs; - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - const char* key = kStringIntData[i].string_data; - MoveOnlyType value; - value_ptrs.push_back(value.ptr()); - map[key] = value.Pass(); - ASSERT_EQ(i + 1, map.size()); - ASSERT_EQ(i + 1, value_ptrs.size()); - EXPECT_EQ(map.size() + 1, MoveOnlyType::num_instances()); - EXPECT_TRUE(map.at(key).moved()); - EXPECT_EQ(value_ptrs[i], map.at(key).ptr()); - map.at(key).ResetMoved(); - EXPECT_TRUE(map); - } - - // std::map doesn't have a capacity() method like std::vector so this test is - // a lot more boring. - - map.reset(); - EXPECT_EQ(0u, MoveOnlyType::num_instances()); -} - -TEST_F(MapTest, STLToMojo) { - std::map<std::string, int> stl_data; - for (size_t i = 0; i < kStringIntDataSize; ++i) - stl_data[kStringIntData[i].string_data] = kStringIntData[i].int_data; - - Map<String, int32_t> mojo_data = Map<String, int32_t>::From(stl_data); - - for (size_t i = 0; i < kStringIntDataSize; ++i) { - EXPECT_EQ(kStringIntData[i].int_data, - mojo_data.at(kStringIntData[i].string_data)); - } -} - -TEST_F(MapTest, MojoToSTL) { - Map<String, int32_t> mojo_map; - for (size_t i = 0; i < kStringIntDataSize; ++i) - mojo_map.insert(kStringIntData[i].string_data, kStringIntData[i].int_data); - - std::map<std::string, int> stl_map = - mojo_map.To<std::map<std::string, int>>(); - for (size_t i = 0; i < kStringIntDataSize; ++i) { - auto it = stl_map.find(kStringIntData[i].string_data); - ASSERT_TRUE(it != stl_map.end()); - EXPECT_EQ(kStringIntData[i].int_data, it->second); - } -} - -TEST_F(MapTest, MapArrayClone) { - Map<String, Array<String>> m; - for (size_t i = 0; i < kStringIntDataSize; ++i) { - Array<String> s; - s.push_back(kStringIntData[i].string_data); - m.insert(kStringIntData[i].string_data, s.Pass()); - } - - Map<String, Array<String>> m2 = m.Clone(); - - for (auto it = m2.begin(); it != m2.end(); ++it) { - ASSERT_EQ(1u, it.GetValue().size()); - EXPECT_EQ(it.GetKey(), it.GetValue().at(0)); - } -} - -TEST_F(MapTest, ArrayOfMap) { - { - Array<Map<int32_t, int8_t>> array(1); - array[0].insert(1, 42); - - size_t size = GetSerializedSize_(array); - FixedBuffer buf(size); - Array_Data<Map_Data<int32_t, int8_t>*>* data; - SerializeArray_<ArrayValidateParams< - 0, false, ArrayValidateParams<0, false, NoValidateParams>>>( - array.Pass(), &buf, &data); - - Array<Map<int32_t, int8_t>> deserialized_array; - Deserialize_(data, &deserialized_array); - - ASSERT_EQ(1u, deserialized_array.size()); - ASSERT_EQ(1u, deserialized_array[0].size()); - ASSERT_EQ(42, deserialized_array[0].at(1)); - } - - { - Array<Map<String, Array<bool>>> array(1); - Array<bool> map_value(2); - map_value[0] = false; - map_value[1] = true; - array[0].insert("hello world", map_value.Pass()); - - size_t size = GetSerializedSize_(array); - FixedBuffer buf(size); - Array_Data<Map_Data<String_Data*, Array_Data<bool>*>*>* data; - SerializeArray_<ArrayValidateParams< - 0, false, - ArrayValidateParams<0, false, - ArrayValidateParams<0, false, NoValidateParams>>>>( - array.Pass(), &buf, &data); - - Array<Map<String, Array<bool>>> deserialized_array; - Deserialize_(data, &deserialized_array); - - ASSERT_EQ(1u, deserialized_array.size()); - ASSERT_EQ(1u, deserialized_array[0].size()); - ASSERT_FALSE(deserialized_array[0].at("hello world")[0]); - ASSERT_TRUE(deserialized_array[0].at("hello world")[1]); - } -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/request_response_unittest.cc b/mojo/public/cpp/bindings/tests/request_response_unittest.cc deleted file mode 100644 index 4864e35..0000000 --- a/mojo/public/cpp/bindings/tests/request_response_unittest.cc +++ /dev/null @@ -1,142 +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/environment/environment.h" -#include "mojo/public/cpp/test_support/test_utils.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "mojo/public/interfaces/bindings/tests/sample_import.mojom.h" -#include "mojo/public/interfaces/bindings/tests/sample_interfaces.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -class ProviderImpl : public InterfaceImpl<sample::Provider> { - public: - void EchoString(const String& a, - const Callback<void(String)>& callback) override { - Callback<void(String)> callback_copy; - // Make sure operator= is used. - callback_copy = callback; - callback_copy.Run(a); - } - - void EchoStrings(const String& a, - const String& b, - const Callback<void(String, String)>& callback) override { - callback.Run(a, b); - } - - void EchoMessagePipeHandle( - ScopedMessagePipeHandle a, - const Callback<void(ScopedMessagePipeHandle)>& callback) override { - callback.Run(a.Pass()); - } - - void EchoEnum(sample::Enum a, - const Callback<void(sample::Enum)>& callback) override { - callback.Run(a); - } -}; - -class StringRecorder { - public: - explicit StringRecorder(std::string* buf) : buf_(buf) {} - void Run(const String& a) const { *buf_ = a; } - void Run(const String& a, const String& b) const { - *buf_ = a.get() + b.get(); - } - - private: - std::string* buf_; -}; - -class EnumRecorder { - public: - explicit EnumRecorder(sample::Enum* value) : value_(value) {} - void Run(sample::Enum a) const { *value_ = a; } - - private: - sample::Enum* value_; -}; - -class MessagePipeWriter { - public: - explicit MessagePipeWriter(const char* text) : text_(text) {} - void Run(ScopedMessagePipeHandle handle) const { - WriteTextMessage(handle.get(), text_); - } - - private: - std::string text_; -}; - -class RequestResponseTest : public testing::Test { - public: - ~RequestResponseTest() override { loop_.RunUntilIdle(); } - - void PumpMessages() { loop_.RunUntilIdle(); } - - private: - Environment env_; - RunLoop loop_; -}; - -TEST_F(RequestResponseTest, EchoString) { - sample::ProviderPtr provider; - BindToProxy(new ProviderImpl(), &provider); - - std::string buf; - provider->EchoString(String::From("hello"), StringRecorder(&buf)); - - PumpMessages(); - - EXPECT_EQ(std::string("hello"), buf); -} - -TEST_F(RequestResponseTest, EchoStrings) { - sample::ProviderPtr provider; - BindToProxy(new ProviderImpl(), &provider); - - std::string buf; - provider->EchoStrings( - String::From("hello"), String::From(" world"), StringRecorder(&buf)); - - PumpMessages(); - - EXPECT_EQ(std::string("hello world"), buf); -} - -TEST_F(RequestResponseTest, EchoMessagePipeHandle) { - sample::ProviderPtr provider; - BindToProxy(new ProviderImpl(), &provider); - - MessagePipe pipe2; - provider->EchoMessagePipeHandle(pipe2.handle1.Pass(), - MessagePipeWriter("hello")); - - PumpMessages(); - - std::string value; - ReadTextMessage(pipe2.handle0.get(), &value); - - EXPECT_EQ(std::string("hello"), value); -} - -TEST_F(RequestResponseTest, EchoEnum) { - sample::ProviderPtr provider; - BindToProxy(new ProviderImpl(), &provider); - - sample::Enum value; - provider->EchoEnum(sample::ENUM_VALUE, EnumRecorder(&value)); - - PumpMessages(); - - EXPECT_EQ(sample::ENUM_VALUE, value); -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/router_unittest.cc b/mojo/public/cpp/bindings/tests/router_unittest.cc deleted file mode 100644 index c4efdb0..0000000 --- a/mojo/public/cpp/bindings/tests/router_unittest.cc +++ /dev/null @@ -1,221 +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 <stdlib.h> -#include <string.h> - -#include "mojo/public/cpp/bindings/lib/message_builder.h" -#include "mojo/public/cpp/bindings/lib/message_queue.h" -#include "mojo/public/cpp/bindings/lib/router.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/macros.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -void AllocRequestMessage(uint32_t name, const char* text, Message* message) { - size_t payload_size = strlen(text) + 1; // Plus null terminator. - internal::RequestMessageBuilder builder(name, payload_size); - memcpy(builder.buffer()->Allocate(payload_size), text, payload_size); - builder.Finish(message); -} - -void AllocResponseMessage(uint32_t name, - const char* text, - uint64_t request_id, - Message* message) { - size_t payload_size = strlen(text) + 1; // Plus null terminator. - internal::ResponseMessageBuilder builder(name, payload_size, request_id); - memcpy(builder.buffer()->Allocate(payload_size), text, payload_size); - builder.Finish(message); -} - -class MessageAccumulator : public MessageReceiver { - public: - explicit MessageAccumulator(internal::MessageQueue* queue) : queue_(queue) {} - - bool Accept(Message* message) override { - queue_->Push(message); - return true; - } - - private: - internal::MessageQueue* queue_; -}; - -class ResponseGenerator : public MessageReceiverWithResponder { - public: - ResponseGenerator() {} - - bool Accept(Message* message) override { return false; } - - bool AcceptWithResponder(Message* message, - MessageReceiver* responder) override { - EXPECT_TRUE(message->has_flag(internal::kMessageExpectsResponse)); - - return SendResponse(message->name(), message->request_id(), responder); - } - - bool SendResponse(uint32_t name, - uint64_t request_id, - MessageReceiver* responder) { - Message response; - AllocResponseMessage(name, "world", request_id, &response); - - bool result = responder->Accept(&response); - delete responder; - return result; - } -}; - -class LazyResponseGenerator : public ResponseGenerator { - public: - LazyResponseGenerator() : responder_(nullptr), name_(0), request_id_(0) {} - - ~LazyResponseGenerator() override { delete responder_; } - - bool AcceptWithResponder(Message* message, - MessageReceiver* responder) override { - name_ = message->name(); - request_id_ = message->request_id(); - responder_ = responder; - return true; - } - - bool has_responder() const { return !!responder_; } - - void Complete() { - SendResponse(name_, request_id_, responder_); - responder_ = nullptr; - } - - private: - MessageReceiver* responder_; - uint32_t name_; - uint64_t request_id_; -}; - -class RouterTest : public testing::Test { - public: - RouterTest() {} - - void SetUp() override { - CreateMessagePipe(nullptr, &handle0_, &handle1_); - } - - void TearDown() override {} - - void PumpMessages() { loop_.RunUntilIdle(); } - - protected: - ScopedMessagePipeHandle handle0_; - ScopedMessagePipeHandle handle1_; - - private: - Environment env_; - RunLoop loop_; -}; - -TEST_F(RouterTest, BasicRequestResponse) { - internal::Router router0(handle0_.Pass(), internal::FilterChain()); - internal::Router router1(handle1_.Pass(), internal::FilterChain()); - - ResponseGenerator generator; - router1.set_incoming_receiver(&generator); - - Message request; - AllocRequestMessage(1, "hello", &request); - - internal::MessageQueue message_queue; - router0.AcceptWithResponder(&request, new MessageAccumulator(&message_queue)); - - PumpMessages(); - - EXPECT_FALSE(message_queue.IsEmpty()); - - Message response; - message_queue.Pop(&response); - - EXPECT_EQ(std::string("world"), - std::string(reinterpret_cast<const char*>(response.payload()))); -} - -TEST_F(RouterTest, BasicRequestResponse_Synchronous) { - internal::Router router0(handle0_.Pass(), internal::FilterChain()); - internal::Router router1(handle1_.Pass(), internal::FilterChain()); - - ResponseGenerator generator; - router1.set_incoming_receiver(&generator); - - Message request; - AllocRequestMessage(1, "hello", &request); - - internal::MessageQueue message_queue; - router0.AcceptWithResponder(&request, new MessageAccumulator(&message_queue)); - - router1.WaitForIncomingMessage(); - router0.WaitForIncomingMessage(); - - EXPECT_FALSE(message_queue.IsEmpty()); - - Message response; - message_queue.Pop(&response); - - EXPECT_EQ(std::string("world"), - std::string(reinterpret_cast<const char*>(response.payload()))); -} - -TEST_F(RouterTest, RequestWithNoReceiver) { - internal::Router router0(handle0_.Pass(), internal::FilterChain()); - internal::Router router1(handle1_.Pass(), internal::FilterChain()); - - // Without an incoming receiver set on router1, we expect router0 to observe - // an error as a result of sending a message. - - Message request; - AllocRequestMessage(1, "hello", &request); - - internal::MessageQueue message_queue; - router0.AcceptWithResponder(&request, new MessageAccumulator(&message_queue)); - - PumpMessages(); - - EXPECT_TRUE(router0.encountered_error()); - EXPECT_TRUE(router1.encountered_error()); - EXPECT_TRUE(message_queue.IsEmpty()); -} - -TEST_F(RouterTest, LateResponse) { - // Test that things won't blow up if we try to send a message to a - // MessageReceiver, which was given to us via AcceptWithResponder, - // after the router has gone away. - - LazyResponseGenerator generator; - { - internal::Router router0(handle0_.Pass(), internal::FilterChain()); - internal::Router router1(handle1_.Pass(), internal::FilterChain()); - - router1.set_incoming_receiver(&generator); - - Message request; - AllocRequestMessage(1, "hello", &request); - - internal::MessageQueue message_queue; - router0.AcceptWithResponder(&request, - new MessageAccumulator(&message_queue)); - - PumpMessages(); - - EXPECT_TRUE(generator.has_responder()); - } - - generator.Complete(); // This should end up doing nothing. -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/sample_service_unittest.cc b/mojo/public/cpp/bindings/tests/sample_service_unittest.cc deleted file mode 100644 index ff047cb..0000000 --- a/mojo/public/cpp/bindings/tests/sample_service_unittest.cc +++ /dev/null @@ -1,377 +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 <algorithm> -#include <ostream> -#include <string> - -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/macros.h" -#include "mojo/public/interfaces/bindings/tests/sample_service.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { - -template <> -struct TypeConverter<int32_t, sample::BarPtr> { - static int32_t Convert(const sample::BarPtr& bar) { - return static_cast<int32_t>(bar->alpha) << 16 | - static_cast<int32_t>(bar->beta) << 8 | - static_cast<int32_t>(bar->gamma); - } -}; - -} // namespace mojo - -namespace sample { -namespace { - -// Set this variable to true to print the message in hex. -bool g_dump_message_as_hex = false; - -// Set this variable to true to print the message in human readable form. -bool g_dump_message_as_text = false; - -// Make a sample |Foo|. -FooPtr MakeFoo() { - mojo::String name("foopy"); - - BarPtr bar(Bar::New()); - bar->alpha = 20; - bar->beta = 40; - bar->gamma = 60; - bar->type = Bar::TYPE_VERTICAL; - - mojo::Array<BarPtr> extra_bars(3); - for (size_t i = 0; i < extra_bars.size(); ++i) { - Bar::Type type = i % 2 == 0 ? Bar::TYPE_VERTICAL : Bar::TYPE_HORIZONTAL; - BarPtr bar(Bar::New()); - uint8_t base = static_cast<uint8_t>(i * 100); - bar->alpha = base; - bar->beta = base + 20; - bar->gamma = base + 40; - bar->type = type; - extra_bars[i] = bar.Pass(); - } - - mojo::Array<uint8_t> data(10); - for (size_t i = 0; i < data.size(); ++i) - data[i] = static_cast<uint8_t>(data.size() - i); - - mojo::Array<mojo::ScopedDataPipeConsumerHandle> input_streams(2); - mojo::Array<mojo::ScopedDataPipeProducerHandle> output_streams(2); - for (size_t i = 0; i < input_streams.size(); ++i) { - MojoCreateDataPipeOptions options; - options.struct_size = sizeof(MojoCreateDataPipeOptions); - options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE; - options.element_num_bytes = 1; - options.capacity_num_bytes = 1024; - mojo::ScopedDataPipeProducerHandle producer; - mojo::ScopedDataPipeConsumerHandle consumer; - mojo::CreateDataPipe(&options, &producer, &consumer); - input_streams[i] = consumer.Pass(); - output_streams[i] = producer.Pass(); - } - - mojo::Array<mojo::Array<bool>> array_of_array_of_bools(2); - for (size_t i = 0; i < 2; ++i) { - mojo::Array<bool> array_of_bools(2); - for (size_t j = 0; j < 2; ++j) - array_of_bools[j] = j; - array_of_array_of_bools[i] = array_of_bools.Pass(); - } - - mojo::MessagePipe pipe; - FooPtr foo(Foo::New()); - foo->name = name; - foo->x = 1; - foo->y = 2; - foo->a = false; - foo->b = true; - foo->c = false; - foo->bar = bar.Pass(); - foo->extra_bars = extra_bars.Pass(); - foo->data = data.Pass(); - foo->source = pipe.handle1.Pass(); - foo->input_streams = input_streams.Pass(); - foo->output_streams = output_streams.Pass(); - foo->array_of_array_of_bools = array_of_array_of_bools.Pass(); - - return foo.Pass(); -} - -// Check that the given |Foo| is identical to the one made by |MakeFoo()|. -void CheckFoo(const Foo& foo) { - const std::string kName("foopy"); - ASSERT_FALSE(foo.name.is_null()); - EXPECT_EQ(kName.size(), foo.name.size()); - for (size_t i = 0; i < std::min(kName.size(), foo.name.size()); i++) { - // Test both |operator[]| and |at|. - EXPECT_EQ(kName[i], foo.name.at(i)) << i; - EXPECT_EQ(kName[i], foo.name[i]) << i; - } - EXPECT_EQ(kName, foo.name.get()); - - EXPECT_EQ(1, foo.x); - EXPECT_EQ(2, foo.y); - EXPECT_FALSE(foo.a); - EXPECT_TRUE(foo.b); - EXPECT_FALSE(foo.c); - - EXPECT_EQ(20, foo.bar->alpha); - EXPECT_EQ(40, foo.bar->beta); - EXPECT_EQ(60, foo.bar->gamma); - EXPECT_EQ(Bar::TYPE_VERTICAL, foo.bar->type); - - EXPECT_EQ(3u, foo.extra_bars.size()); - for (size_t i = 0; i < foo.extra_bars.size(); i++) { - uint8_t base = static_cast<uint8_t>(i * 100); - Bar::Type type = i % 2 == 0 ? Bar::TYPE_VERTICAL : Bar::TYPE_HORIZONTAL; - EXPECT_EQ(base, foo.extra_bars[i]->alpha) << i; - EXPECT_EQ(base + 20, foo.extra_bars[i]->beta) << i; - EXPECT_EQ(base + 40, foo.extra_bars[i]->gamma) << i; - EXPECT_EQ(type, foo.extra_bars[i]->type) << i; - } - - EXPECT_EQ(10u, foo.data.size()); - for (size_t i = 0; i < foo.data.size(); ++i) { - EXPECT_EQ(static_cast<uint8_t>(foo.data.size() - i), foo.data[i]) << i; - } - - EXPECT_FALSE(foo.input_streams.is_null()); - EXPECT_EQ(2u, foo.input_streams.size()); - - EXPECT_FALSE(foo.output_streams.is_null()); - EXPECT_EQ(2u, foo.output_streams.size()); - - EXPECT_EQ(2u, foo.array_of_array_of_bools.size()); - for (size_t i = 0; i < foo.array_of_array_of_bools.size(); ++i) { - EXPECT_EQ(2u, foo.array_of_array_of_bools[i].size()); - for (size_t j = 0; j < foo.array_of_array_of_bools[i].size(); ++j) { - EXPECT_EQ(bool(j), foo.array_of_array_of_bools[i][j]); - } - } -} - -void PrintSpacer(int depth) { - for (int i = 0; i < depth; ++i) - std::cout << " "; -} - -void Print(int depth, const char* name, bool value) { - PrintSpacer(depth); - std::cout << name << ": " << (value ? "true" : "false") << std::endl; -} - -void Print(int depth, const char* name, int32_t value) { - PrintSpacer(depth); - std::cout << name << ": " << value << std::endl; -} - -void Print(int depth, const char* name, uint8_t value) { - PrintSpacer(depth); - std::cout << name << ": " << uint32_t(value) << std::endl; -} - -template <typename H> -void Print(int depth, - const char* name, - const mojo::ScopedHandleBase<H>& value) { - PrintSpacer(depth); - std::cout << name << ": 0x" << std::hex << value.get().value() << std::endl; -} - -void Print(int depth, const char* name, const mojo::String& str) { - PrintSpacer(depth); - std::cout << name << ": \"" << str.get() << "\"" << std::endl; -} - -void Print(int depth, const char* name, const BarPtr& bar) { - PrintSpacer(depth); - std::cout << name << ":" << std::endl; - if (!bar.is_null()) { - ++depth; - Print(depth, "alpha", bar->alpha); - Print(depth, "beta", bar->beta); - Print(depth, "gamma", bar->gamma); - Print(depth, "packed", bar.To<int32_t>()); - --depth; - } -} - -template <typename T> -void Print(int depth, const char* name, const mojo::Array<T>& array) { - PrintSpacer(depth); - std::cout << name << ":" << std::endl; - if (!array.is_null()) { - ++depth; - for (size_t i = 0; i < array.size(); ++i) { - std::stringstream buf; - buf << i; - Print(depth, buf.str().data(), array.at(i)); - } - --depth; - } -} - -void Print(int depth, const char* name, const FooPtr& foo) { - PrintSpacer(depth); - std::cout << name << ":" << std::endl; - if (!foo.is_null()) { - ++depth; - Print(depth, "name", foo->name); - Print(depth, "x", foo->x); - Print(depth, "y", foo->y); - Print(depth, "a", foo->a); - Print(depth, "b", foo->b); - Print(depth, "c", foo->c); - Print(depth, "bar", foo->bar); - Print(depth, "extra_bars", foo->extra_bars); - Print(depth, "data", foo->data); - Print(depth, "source", foo->source); - Print(depth, "input_streams", foo->input_streams); - Print(depth, "output_streams", foo->output_streams); - Print(depth, "array_of_array_of_bools", foo->array_of_array_of_bools); - --depth; - } -} - -void DumpHex(const uint8_t* bytes, uint32_t num_bytes) { - for (uint32_t i = 0; i < num_bytes; ++i) { - std::cout << std::setw(2) << std::setfill('0') << std::hex - << uint32_t(bytes[i]); - - if (i % 16 == 15) { - std::cout << std::endl; - continue; - } - - if (i % 2 == 1) - std::cout << " "; - if (i % 8 == 7) - std::cout << " "; - } -} - -class ServiceImpl : public Service { - public: - void Frobinate(FooPtr foo, BazOptions baz, PortPtr port) override { - // Users code goes here to handle the incoming Frobinate message. - - // We mainly check that we're given the expected arguments. - EXPECT_FALSE(foo.is_null()); - if (!foo.is_null()) - CheckFoo(*foo); - EXPECT_EQ(BAZ_OPTIONS_EXTRA, baz); - - if (g_dump_message_as_text) { - // Also dump the Foo structure and all of its members. - std::cout << "Frobinate:" << std::endl; - int depth = 1; - Print(depth, "foo", foo); - Print(depth, "baz", baz); - Print(depth, "port", port.get()); - } - } - - void GetPort(mojo::InterfaceRequest<Port> port_request) override {} -}; - -class ServiceProxyImpl : public ServiceProxy { - public: - explicit ServiceProxyImpl(mojo::MessageReceiverWithResponder* receiver) - : ServiceProxy(receiver) {} -}; - -class SimpleMessageReceiver : public mojo::MessageReceiverWithResponder { - public: - bool Accept(mojo::Message* message) override { - // Imagine some IPC happened here. - - if (g_dump_message_as_hex) { - DumpHex(reinterpret_cast<const uint8_t*>(message->data()), - message->data_num_bytes()); - } - - // In the receiving process, an implementation of ServiceStub is known to - // the system. It receives the incoming message. - ServiceImpl impl; - - ServiceStub stub; - stub.set_sink(&impl); - return stub.Accept(message); - } - - bool AcceptWithResponder(mojo::Message* message, - mojo::MessageReceiver* responder) override { - return false; - } -}; - -class BindingsSampleTest : public testing::Test { - public: - BindingsSampleTest() {} - ~BindingsSampleTest() override {} - - private: - mojo::Environment env_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(BindingsSampleTest); -}; - -TEST_F(BindingsSampleTest, Basic) { - SimpleMessageReceiver receiver; - - // User has a proxy to a Service somehow. - Service* service = new ServiceProxyImpl(&receiver); - - // User constructs a message to send. - - // Notice that it doesn't matter in what order the structs / arrays are - // allocated. Here, the various members of Foo are allocated before Foo is - // allocated. - - FooPtr foo = MakeFoo(); - CheckFoo(*foo); - - PortPtr port; - service->Frobinate(foo.Pass(), Service::BAZ_OPTIONS_EXTRA, port.Pass()); - - delete service; -} - -TEST_F(BindingsSampleTest, DefaultValues) { - DefaultsTestPtr defaults(DefaultsTest::New()); - EXPECT_EQ(-12, defaults->a0); - EXPECT_EQ(kTwelve, defaults->a1); - EXPECT_EQ(1234, defaults->a2); - EXPECT_EQ(34567U, defaults->a3); - EXPECT_EQ(123456, defaults->a4); - EXPECT_EQ(3456789012U, defaults->a5); - EXPECT_EQ(-111111111111LL, defaults->a6); - EXPECT_EQ(9999999999999999999ULL, defaults->a7); - EXPECT_EQ(0x12345, defaults->a8); - EXPECT_EQ(-0x12345, defaults->a9); - EXPECT_EQ(1234, defaults->a10); - EXPECT_TRUE(defaults->a11); - EXPECT_FALSE(defaults->a12); - EXPECT_FLOAT_EQ(123.25f, defaults->a13); - EXPECT_DOUBLE_EQ(1234567890.123, defaults->a14); - EXPECT_DOUBLE_EQ(1E10, defaults->a15); - EXPECT_DOUBLE_EQ(-1.2E+20, defaults->a16); - EXPECT_DOUBLE_EQ(1.23E-20, defaults->a17); - EXPECT_TRUE(defaults->a18.is_null()); - EXPECT_TRUE(defaults->a19.is_null()); - EXPECT_EQ(Bar::TYPE_BOTH, defaults->a20); - EXPECT_TRUE(defaults->a21.is_null()); - ASSERT_FALSE(defaults->a22.is_null()); - EXPECT_EQ(imported::SHAPE_RECTANGLE, defaults->a22->shape); - EXPECT_EQ(imported::COLOR_BLACK, defaults->a22->color); - EXPECT_EQ(0xFFFFFFFFFFFFFFFFULL, defaults->a23); - EXPECT_EQ(0x123456789, defaults->a24); - EXPECT_EQ(-0x123456789, defaults->a25); -} - -} // namespace -} // namespace sample diff --git a/mojo/public/cpp/bindings/tests/serialization_warning_unittest.cc b/mojo/public/cpp/bindings/tests/serialization_warning_unittest.cc deleted file mode 100644 index 4359be8..0000000 --- a/mojo/public/cpp/bindings/tests/serialization_warning_unittest.cc +++ /dev/null @@ -1,223 +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. - -// Serialization warnings are only recorded in debug build. -#ifndef NDEBUG - -#include "mojo/public/cpp/bindings/array.h" -#include "mojo/public/cpp/bindings/lib/array_internal.h" -#include "mojo/public/cpp/bindings/lib/array_serialization.h" -#include "mojo/public/cpp/bindings/lib/fixed_buffer.h" -#include "mojo/public/cpp/bindings/lib/validation_errors.h" -#include "mojo/public/cpp/bindings/string.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/message_pipe.h" -#include "mojo/public/interfaces/bindings/tests/serialization_test_structs.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -using mojo::internal::ArrayValidateParams; -using mojo::internal::NoValidateParams; - -// Creates an array of arrays of handles (2 X 3) for testing. -Array<Array<ScopedHandle>> CreateTestNestedHandleArray() { - Array<Array<ScopedHandle>> array(2); - for (size_t i = 0; i < array.size(); ++i) { - Array<ScopedHandle> nested_array(3); - for (size_t j = 0; j < nested_array.size(); ++j) { - MessagePipe pipe; - nested_array[j] = ScopedHandle::From(pipe.handle1.Pass()); - } - array[i] = nested_array.Pass(); - } - - return array.Pass(); -} - -class SerializationWarningTest : public testing::Test { - public: - ~SerializationWarningTest() override {} - - protected: - template <typename T> - void TestWarning(StructPtr<T> obj, - mojo::internal::ValidationError expected_warning) { - warning_observer_.set_last_warning(mojo::internal::VALIDATION_ERROR_NONE); - - mojo::internal::FixedBuffer buf(GetSerializedSize_(obj)); - typename T::Data_* data; - Serialize_(obj.Pass(), &buf, &data); - - EXPECT_EQ(expected_warning, warning_observer_.last_warning()); - } - - template <typename ValidateParams, typename T> - void TestArrayWarning(T obj, - mojo::internal::ValidationError expected_warning) { - warning_observer_.set_last_warning(mojo::internal::VALIDATION_ERROR_NONE); - - mojo::internal::FixedBuffer buf(GetSerializedSize_(obj)); - typename T::Data_* data; - SerializeArray_<ValidateParams>(obj.Pass(), &buf, &data); - - EXPECT_EQ(expected_warning, warning_observer_.last_warning()); - } - - mojo::internal::SerializationWarningObserverForTesting warning_observer_; - Environment env_; -}; - -TEST_F(SerializationWarningTest, HandleInStruct) { - Struct2Ptr test_struct(Struct2::New()); - EXPECT_FALSE(test_struct->hdl.is_valid()); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE); - - test_struct = Struct2::New(); - MessagePipe pipe; - test_struct->hdl = ScopedHandle::From(pipe.handle1.Pass()); - - TestWarning(test_struct.Pass(), mojo::internal::VALIDATION_ERROR_NONE); -} - -TEST_F(SerializationWarningTest, StructInStruct) { - Struct3Ptr test_struct(Struct3::New()); - EXPECT_TRUE(!test_struct->struct_1); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_struct = Struct3::New(); - test_struct->struct_1 = Struct1::New(); - - TestWarning(test_struct.Pass(), mojo::internal::VALIDATION_ERROR_NONE); -} - -TEST_F(SerializationWarningTest, ArrayOfStructsInStruct) { - Struct4Ptr test_struct(Struct4::New()); - EXPECT_TRUE(!test_struct->data); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_struct = Struct4::New(); - test_struct->data.resize(1); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_struct = Struct4::New(); - test_struct->data.resize(0); - - TestWarning(test_struct.Pass(), mojo::internal::VALIDATION_ERROR_NONE); - - test_struct = Struct4::New(); - test_struct->data.resize(1); - test_struct->data[0] = Struct1::New(); - - TestWarning(test_struct.Pass(), mojo::internal::VALIDATION_ERROR_NONE); -} - -TEST_F(SerializationWarningTest, FixedArrayOfStructsInStruct) { - Struct5Ptr test_struct(Struct5::New()); - EXPECT_TRUE(!test_struct->pair); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_struct = Struct5::New(); - test_struct->pair.resize(1); - test_struct->pair[0] = Struct1::New(); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER); - - test_struct = Struct5::New(); - test_struct->pair.resize(2); - test_struct->pair[0] = Struct1::New(); - test_struct->pair[1] = Struct1::New(); - - TestWarning(test_struct.Pass(), mojo::internal::VALIDATION_ERROR_NONE); -} - -TEST_F(SerializationWarningTest, StringInStruct) { - Struct6Ptr test_struct(Struct6::New()); - EXPECT_TRUE(!test_struct->str); - - TestWarning(test_struct.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_struct = Struct6::New(); - test_struct->str = "hello world"; - - TestWarning(test_struct.Pass(), mojo::internal::VALIDATION_ERROR_NONE); -} - -TEST_F(SerializationWarningTest, ArrayOfArraysOfHandles) { - Array<Array<ScopedHandle>> test_array = CreateTestNestedHandleArray(); - test_array[0] = Array<ScopedHandle>(); - test_array[1][0] = ScopedHandle(); - - TestArrayWarning< - ArrayValidateParams<0, - true, - ArrayValidateParams<0, true, NoValidateParams>>>( - test_array.Pass(), mojo::internal::VALIDATION_ERROR_NONE); - - test_array = CreateTestNestedHandleArray(); - test_array[0] = Array<ScopedHandle>(); - TestArrayWarning< - ArrayValidateParams<0, - false, - ArrayValidateParams<0, true, NoValidateParams>>>( - test_array.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_array = CreateTestNestedHandleArray(); - test_array[1][0] = ScopedHandle(); - TestArrayWarning< - ArrayValidateParams<0, - true, - ArrayValidateParams<0, false, NoValidateParams>>>( - test_array.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE); -} - -TEST_F(SerializationWarningTest, ArrayOfStrings) { - Array<String> test_array(3); - for (size_t i = 0; i < test_array.size(); ++i) - test_array[i] = "hello"; - - TestArrayWarning< - ArrayValidateParams<0, - true, - ArrayValidateParams<0, false, NoValidateParams>>>( - test_array.Pass(), mojo::internal::VALIDATION_ERROR_NONE); - - test_array = Array<String>(3); - TestArrayWarning< - ArrayValidateParams<0, - false, - ArrayValidateParams<0, false, NoValidateParams>>>( - test_array.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER); - - test_array = Array<String>(2); - TestArrayWarning< - ArrayValidateParams<3, - true, - ArrayValidateParams<0, false, NoValidateParams>>>( - test_array.Pass(), - mojo::internal::VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER); -} - -} // namespace -} // namespace test -} // namespace mojo - -#endif diff --git a/mojo/public/cpp/bindings/tests/string_unittest.cc b/mojo/public/cpp/bindings/tests/string_unittest.cc deleted file mode 100644 index 7e3d910..0000000 --- a/mojo/public/cpp/bindings/tests/string_unittest.cc +++ /dev/null @@ -1,76 +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/string.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { - -TEST(StringTest, DefaultIsNull) { - String s; - EXPECT_TRUE(s.is_null()); -} - -TEST(StringTest, ConstructedWithNULL) { - String s(nullptr); - EXPECT_TRUE(s.is_null()); -} - -TEST(StringTest, ConstructedWithNullCharPointer) { - const char* null = nullptr; - String s(null); - EXPECT_TRUE(s.is_null()); -} - -TEST(StringTest, AssignedNULL) { - String s(""); - EXPECT_FALSE(s.is_null()); - s = nullptr; - EXPECT_TRUE(s.is_null()); -} - -TEST(StringTest, Empty) { - String s(""); - EXPECT_FALSE(s.is_null()); - EXPECT_TRUE(s.get().empty()); -} - -TEST(StringTest, Basic) { - String s("hello world"); - EXPECT_EQ(std::string("hello world"), s.get()); -} - -TEST(StringTest, Assignment) { - String s("hello world"); - String t = s; // Makes a copy. - EXPECT_FALSE(t.is_null()); - EXPECT_EQ(std::string("hello world"), t.get()); - EXPECT_FALSE(s.is_null()); -} - -TEST(StringTest, Equality) { - String s("hello world"); - String t("hello world"); - EXPECT_EQ(s, t); - EXPECT_TRUE(s == t); - EXPECT_TRUE("hello world" == s); - EXPECT_TRUE(s == "hello world"); - EXPECT_TRUE("not" != s); - EXPECT_TRUE(s != "not"); -} - -TEST(StringTest, LessThanNullness) { - String null; - String null2; - EXPECT_FALSE(null < null2); - EXPECT_FALSE(null2 < null); - - String real("real"); - EXPECT_TRUE(null < real); - EXPECT_FALSE(real < null); -} - -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/struct_unittest.cc b/mojo/public/cpp/bindings/tests/struct_unittest.cc deleted file mode 100644 index 52d1313..0000000 --- a/mojo/public/cpp/bindings/tests/struct_unittest.cc +++ /dev/null @@ -1,201 +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 "mojo/public/cpp/environment/environment.h" -#include "mojo/public/interfaces/bindings/tests/test_structs.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -RectPtr MakeRect(int32_t factor = 1) { - RectPtr rect(Rect::New()); - rect->x = 1 * factor; - rect->y = 2 * factor; - rect->width = 10 * factor; - rect->height = 20 * factor; - return rect.Pass(); -} - -void CheckRect(const Rect& rect, int32_t factor = 1) { - EXPECT_EQ(1 * factor, rect.x); - EXPECT_EQ(2 * factor, rect.y); - EXPECT_EQ(10 * factor, rect.width); - EXPECT_EQ(20 * factor, rect.height); -} - -class StructTest : public testing::Test { - public: - ~StructTest() override {} - - private: - Environment env_; -}; - -} // namespace - -TEST_F(StructTest, Rect) { - RectPtr rect; - EXPECT_TRUE(rect.is_null()); - EXPECT_TRUE(!rect); - EXPECT_FALSE(rect); - - rect = nullptr; - EXPECT_TRUE(rect.is_null()); - EXPECT_TRUE(!rect); - EXPECT_FALSE(rect); - - rect = MakeRect(); - EXPECT_FALSE(rect.is_null()); - EXPECT_FALSE(!rect); - EXPECT_TRUE(rect); - - RectPtr null_rect = nullptr; - EXPECT_TRUE(null_rect.is_null()); - EXPECT_TRUE(!null_rect); - EXPECT_FALSE(null_rect); - - CheckRect(*rect); -} - -TEST_F(StructTest, Clone) { - NamedRegionPtr region; - - NamedRegionPtr clone_region = region.Clone(); - EXPECT_TRUE(clone_region.is_null()); - - region = NamedRegion::New(); - clone_region = region.Clone(); - EXPECT_TRUE(clone_region->name.is_null()); - EXPECT_TRUE(clone_region->rects.is_null()); - - region->name = "hello world"; - clone_region = region.Clone(); - EXPECT_EQ(region->name, clone_region->name); - - region->rects = Array<RectPtr>(2); - region->rects[1] = MakeRect(); - clone_region = region.Clone(); - EXPECT_EQ(2u, clone_region->rects.size()); - EXPECT_TRUE(clone_region->rects[0].is_null()); - CheckRect(*clone_region->rects[1]); - - // NoDefaultFieldValues contains handles, so Clone() is not available, but - // NoDefaultFieldValuesPtr should still compile. - NoDefaultFieldValuesPtr no_default_field_values(NoDefaultFieldValues::New()); - EXPECT_FALSE(no_default_field_values->f13.is_valid()); -} - -// Serialization test of a struct with no pointer or handle members. -TEST_F(StructTest, Serialization_Basic) { - RectPtr rect(MakeRect()); - - size_t size = GetSerializedSize_(rect); - EXPECT_EQ(8U + 16U, size); - - mojo::internal::FixedBuffer buf(size); - internal::Rect_Data* data; - Serialize_(rect.Pass(), &buf, &data); - - RectPtr rect2; - Deserialize_(data, &rect2); - - CheckRect(*rect2); -} - -// Construction of a struct with struct pointers from null. -TEST_F(StructTest, Construction_StructPointers) { - RectPairPtr pair; - EXPECT_TRUE(pair.is_null()); - - pair = RectPair::New(); - EXPECT_FALSE(pair.is_null()); - EXPECT_TRUE(pair->first.is_null()); - EXPECT_TRUE(pair->first.is_null()); - - pair = nullptr; - EXPECT_TRUE(pair.is_null()); -} - -// Serialization test of a struct with struct pointers. -TEST_F(StructTest, Serialization_StructPointers) { - RectPairPtr pair(RectPair::New()); - pair->first = MakeRect(); - pair->second = MakeRect(); - - size_t size = GetSerializedSize_(pair); - EXPECT_EQ(8U + 16U + 2 * (8U + 16U), size); - - mojo::internal::FixedBuffer buf(size); - internal::RectPair_Data* data; - Serialize_(pair.Pass(), &buf, &data); - - RectPairPtr pair2; - Deserialize_(data, &pair2); - - CheckRect(*pair2->first); - CheckRect(*pair2->second); -} - -// Serialization test of a struct with an array member. -TEST_F(StructTest, Serialization_ArrayPointers) { - NamedRegionPtr region(NamedRegion::New()); - region->name = "region"; - region->rects = Array<RectPtr>::New(4); - for (size_t i = 0; i < region->rects.size(); ++i) - region->rects[i] = MakeRect(static_cast<int32_t>(i) + 1); - - size_t size = GetSerializedSize_(region); - EXPECT_EQ(8U + // header - 8U + // name pointer - 8U + // rects pointer - 8U + // name header - 8U + // name payload (rounded up) - 8U + // rects header - 4 * 8U + // rects payload (four pointers) - 4 * (8U + // rect header - 16U), // rect payload (four ints) - size); - - mojo::internal::FixedBuffer buf(size); - internal::NamedRegion_Data* data; - Serialize_(region.Pass(), &buf, &data); - - NamedRegionPtr region2; - Deserialize_(data, ®ion2); - - EXPECT_EQ(String("region"), region2->name); - - EXPECT_EQ(4U, region2->rects.size()); - for (size_t i = 0; i < region2->rects.size(); ++i) - CheckRect(*region2->rects[i], static_cast<int32_t>(i) + 1); -} - -// Serialization test of a struct with null array pointers. -TEST_F(StructTest, Serialization_NullArrayPointers) { - NamedRegionPtr region(NamedRegion::New()); - EXPECT_TRUE(region->name.is_null()); - EXPECT_TRUE(region->rects.is_null()); - - size_t size = GetSerializedSize_(region); - EXPECT_EQ(8U + // header - 8U + // name pointer - 8U, // rects pointer - size); - - mojo::internal::FixedBuffer buf(size); - internal::NamedRegion_Data* data; - Serialize_(region.Pass(), &buf, &data); - - NamedRegionPtr region2; - Deserialize_(data, ®ion2); - - EXPECT_TRUE(region2->name.is_null()); - EXPECT_TRUE(region2->rects.is_null()); -} - -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/type_conversion_unittest.cc b/mojo/public/cpp/bindings/tests/type_conversion_unittest.cc deleted file mode 100644 index 776ac14..0000000 --- a/mojo/public/cpp/bindings/tests/type_conversion_unittest.cc +++ /dev/null @@ -1,205 +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/environment/environment.h" -#include "mojo/public/interfaces/bindings/tests/test_structs.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -struct RedmondRect { - int32_t left; - int32_t top; - int32_t right; - int32_t bottom; -}; - -struct RedmondNamedRegion { - std::string name; - std::vector<RedmondRect> rects; -}; - -bool AreEqualRectArrays(const Array<test::RectPtr>& rects1, - const Array<test::RectPtr>& rects2) { - if (rects1.size() != rects2.size()) - return false; - - for (size_t i = 0; i < rects1.size(); ++i) { - if (rects1[i]->x != rects2[i]->x || rects1[i]->y != rects2[i]->y || - rects1[i]->width != rects2[i]->width || - rects1[i]->height != rects2[i]->height) { - return false; - } - } - - return true; -} - -} // namespace - -template <> -struct TypeConverter<test::RectPtr, RedmondRect> { - static test::RectPtr Convert(const RedmondRect& input) { - test::RectPtr rect(test::Rect::New()); - rect->x = input.left; - rect->y = input.top; - rect->width = input.right - input.left; - rect->height = input.bottom - input.top; - return rect.Pass(); - } -}; - -template <> -struct TypeConverter<RedmondRect, test::RectPtr> { - static RedmondRect Convert(const test::RectPtr& input) { - RedmondRect rect; - rect.left = input->x; - rect.top = input->y; - rect.right = input->x + input->width; - rect.bottom = input->y + input->height; - return rect; - } -}; - -template <> -struct TypeConverter<test::NamedRegionPtr, RedmondNamedRegion> { - static test::NamedRegionPtr Convert(const RedmondNamedRegion& input) { - test::NamedRegionPtr region(test::NamedRegion::New()); - region->name = input.name; - region->rects = Array<test::RectPtr>::From(input.rects); - return region.Pass(); - } -}; - -template <> -struct TypeConverter<RedmondNamedRegion, test::NamedRegionPtr> { - static RedmondNamedRegion Convert(const test::NamedRegionPtr& input) { - RedmondNamedRegion region; - region.name = input->name; - region.rects = input->rects.To<std::vector<RedmondRect>>(); - return region; - } -}; - -namespace test { -namespace { - -TEST(TypeConversionTest, String) { - const char kText[6] = "hello"; - - String a = std::string(kText); - String b(kText); - String c(static_cast<const char*>(kText)); - - EXPECT_EQ(std::string(kText), a.To<std::string>()); - EXPECT_EQ(std::string(kText), b.To<std::string>()); - EXPECT_EQ(std::string(kText), c.To<std::string>()); -} - -TEST(TypeConversionTest, String_Null) { - String a; - EXPECT_TRUE(a.is_null()); - EXPECT_EQ(std::string(), a.To<std::string>()); - - String b = String::From(static_cast<const char*>(nullptr)); - EXPECT_TRUE(b.is_null()); -} - -TEST(TypeConversionTest, String_Empty) { - String a = ""; - EXPECT_EQ(std::string(), a.To<std::string>()); - - String b = std::string(); - EXPECT_FALSE(b.is_null()); - EXPECT_EQ(std::string(), b.To<std::string>()); -} - -TEST(TypeConversionTest, StringWithEmbeddedNull) { - const std::string kText("hel\0lo", 6); - - String a(kText); - EXPECT_EQ(kText, a.To<std::string>()); - - // Expect truncation: - String b(kText.c_str()); - EXPECT_EQ(std::string("hel"), b.To<std::string>()); -} - -TEST(TypeConversionTest, CustomTypeConverter) { - RectPtr rect(Rect::New()); - rect->x = 10; - rect->y = 20; - rect->width = 50; - rect->height = 45; - - RedmondRect rr = rect.To<RedmondRect>(); - EXPECT_EQ(10, rr.left); - EXPECT_EQ(20, rr.top); - EXPECT_EQ(60, rr.right); - EXPECT_EQ(65, rr.bottom); - - RectPtr rect2(Rect::From(rr)); - EXPECT_EQ(rect->x, rect2->x); - EXPECT_EQ(rect->y, rect2->y); - EXPECT_EQ(rect->width, rect2->width); - EXPECT_EQ(rect->height, rect2->height); -} - -TEST(TypeConversionTest, CustomTypeConverter_Array_Null) { - Array<RectPtr> rects; - - std::vector<RedmondRect> redmond_rects = rects.To<std::vector<RedmondRect>>(); - - EXPECT_TRUE(redmond_rects.empty()); -} - -TEST(TypeConversionTest, CustomTypeConverter_Array) { - const RedmondRect kBase = {10, 20, 30, 40}; - - Array<RectPtr> rects(10); - for (size_t i = 0; i < rects.size(); ++i) { - RedmondRect rr = kBase; - rr.left += static_cast<int32_t>(i); - rr.top += static_cast<int32_t>(i); - rects[i] = Rect::From(rr); - } - - std::vector<RedmondRect> redmond_rects = rects.To<std::vector<RedmondRect>>(); - - Array<RectPtr> rects2 = Array<RectPtr>::From(redmond_rects); - EXPECT_TRUE(AreEqualRectArrays(rects, rects2)); -} - -TEST(TypeConversionTest, CustomTypeConverter_Nested) { - RedmondNamedRegion redmond_region; - redmond_region.name = "foopy"; - - const RedmondRect kBase = {10, 20, 30, 40}; - - for (size_t i = 0; i < 10; ++i) { - RedmondRect rect = kBase; - rect.left += static_cast<int32_t>(i); - rect.top += static_cast<int32_t>(i); - redmond_region.rects.push_back(rect); - } - - // Round-trip through generated struct and TypeConverter. - - NamedRegionPtr copy = NamedRegion::From(redmond_region); - RedmondNamedRegion redmond_region2 = copy.To<RedmondNamedRegion>(); - - EXPECT_EQ(redmond_region.name, redmond_region2.name); - EXPECT_EQ(redmond_region.rects.size(), redmond_region2.rects.size()); - for (size_t i = 0; i < redmond_region.rects.size(); ++i) { - EXPECT_EQ(redmond_region.rects[i].left, redmond_region2.rects[i].left); - EXPECT_EQ(redmond_region.rects[i].top, redmond_region2.rects[i].top); - EXPECT_EQ(redmond_region.rects[i].right, redmond_region2.rects[i].right); - EXPECT_EQ(redmond_region.rects[i].bottom, redmond_region2.rects[i].bottom); - } -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/union_unittest.cc b/mojo/public/cpp/bindings/tests/union_unittest.cc deleted file mode 100644 index a8d8a95..0000000 --- a/mojo/public/cpp/bindings/tests/union_unittest.cc +++ /dev/null @@ -1,172 +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 "mojo/public/cpp/bindings/string.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/interfaces/bindings/tests/test_unions.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { - -TEST(UnionTest, PlainOldDataGetterSetter) { - PodUnionPtr pod(PodUnion::New()); - - pod->set_f_int8(10); - EXPECT_EQ(10, pod->get_f_int8()); - EXPECT_TRUE(pod->is_f_int8()); - EXPECT_FALSE(pod->is_f_int8_other()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT8); - - pod->set_f_uint8(11); - EXPECT_EQ(11, pod->get_f_uint8()); - EXPECT_TRUE(pod->is_f_uint8()); - EXPECT_FALSE(pod->is_f_int8()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT8); - - pod->set_f_int16(12); - EXPECT_EQ(12, pod->get_f_int16()); - EXPECT_TRUE(pod->is_f_int16()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT16); - - pod->set_f_uint16(13); - EXPECT_EQ(13, pod->get_f_uint16()); - EXPECT_TRUE(pod->is_f_uint16()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT16); - - pod->set_f_int32(14); - EXPECT_EQ(14, pod->get_f_int32()); - EXPECT_TRUE(pod->is_f_int32()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT32); - - pod->set_f_uint32(static_cast<uint32_t>(15)); - EXPECT_EQ(static_cast<uint32_t>(15), pod->get_f_uint32()); - EXPECT_TRUE(pod->is_f_uint32()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT32); - - pod->set_f_int64(16); - EXPECT_EQ(16, pod->get_f_int64()); - EXPECT_TRUE(pod->is_f_int64()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT64); - - pod->set_f_uint64(static_cast<uint64_t>(17)); - EXPECT_EQ(static_cast<uint64_t>(17), pod->get_f_uint64()); - EXPECT_TRUE(pod->is_f_uint64()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT64); - - pod->set_f_float(1.5); - EXPECT_EQ(1.5, pod->get_f_float()); - EXPECT_TRUE(pod->is_f_float()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_FLOAT); - - pod->set_f_double(1.9); - EXPECT_EQ(1.9, pod->get_f_double()); - EXPECT_TRUE(pod->is_f_double()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_DOUBLE); - - pod->set_f_bool(true); - EXPECT_TRUE(pod->get_f_bool()); - pod->set_f_bool(false); - EXPECT_FALSE(pod->get_f_bool()); - EXPECT_TRUE(pod->is_f_bool()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_BOOL); -} - -TEST(UnionTest, PodEquals) { - PodUnionPtr pod1(PodUnion::New()); - PodUnionPtr pod2(PodUnion::New()); - - pod1->set_f_int8(10); - pod2->set_f_int8(10); - EXPECT_TRUE(pod1.Equals(pod2)); - - pod2->set_f_int8(11); - EXPECT_FALSE(pod1.Equals(pod2)); - - pod2->set_f_int8_other(10); - EXPECT_FALSE(pod1.Equals(pod2)); -} - -TEST(UnionTest, PodClone) { - PodUnionPtr pod(PodUnion::New()); - pod->set_f_int8(10); - - PodUnionPtr pod_clone = pod.Clone(); - EXPECT_EQ(10, pod_clone->get_f_int8()); - EXPECT_TRUE(pod_clone->is_f_int8()); - EXPECT_EQ(pod_clone->which(), PodUnion::Tag::F_INT8); -} - -TEST(UnionTest, SerializationPod) { - PodUnionPtr pod1(PodUnion::New()); - pod1->set_f_int8(10); - - size_t size = GetSerializedSize_(pod1); - EXPECT_EQ(16U, size); - - mojo::internal::FixedBuffer buf(size); - internal::PodUnion_Data* data; - Serialize_(pod1.Pass(), &buf, &data); - - PodUnionPtr pod2; - Deserialize_(data, &pod2); - - EXPECT_EQ(10, pod2->get_f_int8()); - EXPECT_TRUE(pod2->is_f_int8()); - EXPECT_EQ(pod2->which(), PodUnion::Tag::F_INT8); -} - -TEST(UnionTest, StringGetterSetter) { - PodUnionPtr pod(PodUnion::New()); - - String hello("hello world"); - pod->set_f_string(hello); - EXPECT_EQ(hello, pod->get_f_string()); - EXPECT_TRUE(pod->is_f_string()); - EXPECT_EQ(pod->which(), PodUnion::Tag::F_STRING); -} - -TEST(UnionTest, StringEquals) { - PodUnionPtr pod1(PodUnion::New()); - PodUnionPtr pod2(PodUnion::New()); - - pod1->set_f_string("hello world"); - pod2->set_f_string("hello world"); - EXPECT_TRUE(pod1.Equals(pod2)); - - pod2->set_f_string("hello universe"); - EXPECT_FALSE(pod1.Equals(pod2)); -} - -TEST(UnionTest, StringClone) { - PodUnionPtr pod(PodUnion::New()); - - String hello("hello world"); - pod->set_f_string(hello); - PodUnionPtr pod_clone = pod.Clone(); - EXPECT_EQ(hello, pod_clone->get_f_string()); - EXPECT_TRUE(pod_clone->is_f_string()); - EXPECT_EQ(pod_clone->which(), PodUnion::Tag::F_STRING); -} - -TEST(UnionTest, StringSerialization) { - PodUnionPtr pod1(PodUnion::New()); - - String hello("hello world"); - pod1->set_f_string(hello); - - size_t size = GetSerializedSize_(pod1); - mojo::internal::FixedBuffer buf(size); - internal::PodUnion_Data* data; - Serialize_(pod1.Pass(), &buf, &data); - - PodUnionPtr pod2; - Deserialize_(data, &pod2); - EXPECT_EQ(hello, pod2->get_f_string()); - EXPECT_TRUE(pod2->is_f_string()); - EXPECT_EQ(pod2->which(), PodUnion::Tag::F_STRING); -} -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/validation_test_input_parser.cc b/mojo/public/cpp/bindings/tests/validation_test_input_parser.cc deleted file mode 100644 index 9d2607d..0000000 --- a/mojo/public/cpp/bindings/tests/validation_test_input_parser.cc +++ /dev/null @@ -1,410 +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/tests/validation_test_input_parser.h" - -#include <assert.h> -#include <stdio.h> -#include <string.h> - -#include <limits> -#include <map> -#include <set> -#include <utility> - -#include "mojo/public/c/system/macros.h" - -namespace mojo { -namespace test { -namespace { - -class ValidationTestInputParser { - public: - ValidationTestInputParser(const std::string& input, - std::vector<uint8_t>* data, - size_t* num_handles, - std::string* error_message); - ~ValidationTestInputParser(); - - bool Run(); - - private: - struct DataType; - - typedef std::pair<const char*, const char*> Range; - - typedef bool (ValidationTestInputParser::*ParseDataFunc)( - const DataType& type, - const std::string& value_string); - - struct DataType { - const char* name; - size_t name_size; - size_t data_size; - ParseDataFunc parse_data_func; - }; - - // A dist4/8 item that hasn't been matched with an anchr item. - struct PendingDistanceItem { - // Where this data item is located in |data_|. - size_t pos; - // Either 4 or 8 (bytes). - size_t data_size; - }; - - bool GetNextItem(Range* range); - - bool ParseItem(const Range& range); - - bool ParseUnsignedInteger(const DataType& type, - const std::string& value_string); - bool ParseSignedInteger(const DataType& type, - const std::string& value_string); - bool ParseFloat(const DataType& type, const std::string& value_string); - bool ParseDouble(const DataType& type, const std::string& value_string); - bool ParseBinarySequence(const DataType& type, - const std::string& value_string); - bool ParseDistance(const DataType& type, const std::string& value_string); - bool ParseAnchor(const DataType& type, const std::string& value_string); - bool ParseHandles(const DataType& type, const std::string& value_string); - - bool StartsWith(const Range& range, const char* prefix, size_t prefix_length); - - bool ConvertToUnsignedInteger(const std::string& value_string, - unsigned long long int* value); - - template <typename T> - void AppendData(T data) { - size_t pos = data_->size(); - data_->resize(pos + sizeof(T)); - memcpy(&(*data_)[pos], &data, sizeof(T)); - } - - template <typename TargetType, typename InputType> - bool ConvertAndAppendData(InputType value) { - if (value > std::numeric_limits<TargetType>::max() || - value < std::numeric_limits<TargetType>::min()) { - return false; - } - AppendData(static_cast<TargetType>(value)); - return true; - } - - template <typename TargetType, typename InputType> - bool ConvertAndFillData(size_t pos, InputType value) { - if (value > std::numeric_limits<TargetType>::max() || - value < std::numeric_limits<TargetType>::min()) { - return false; - } - TargetType target_value = static_cast<TargetType>(value); - assert(pos + sizeof(TargetType) <= data_->size()); - memcpy(&(*data_)[pos], &target_value, sizeof(TargetType)); - return true; - } - - static const DataType kDataTypes[]; - static const size_t kDataTypeCount; - - const std::string& input_; - size_t input_cursor_; - - std::vector<uint8_t>* data_; - size_t* num_handles_; - std::string* error_message_; - - std::map<std::string, PendingDistanceItem> pending_distance_items_; - std::set<std::string> anchors_; -}; - -#define DATA_TYPE(name, data_size, parse_data_func) \ - { name, sizeof(name) - 1, data_size, parse_data_func } - -const ValidationTestInputParser::DataType - ValidationTestInputParser::kDataTypes[] = { - DATA_TYPE("[u1]", 1, &ValidationTestInputParser::ParseUnsignedInteger), - DATA_TYPE("[u2]", 2, &ValidationTestInputParser::ParseUnsignedInteger), - DATA_TYPE("[u4]", 4, &ValidationTestInputParser::ParseUnsignedInteger), - DATA_TYPE("[u8]", 8, &ValidationTestInputParser::ParseUnsignedInteger), - DATA_TYPE("[s1]", 1, &ValidationTestInputParser::ParseSignedInteger), - DATA_TYPE("[s2]", 2, &ValidationTestInputParser::ParseSignedInteger), - DATA_TYPE("[s4]", 4, &ValidationTestInputParser::ParseSignedInteger), - DATA_TYPE("[s8]", 8, &ValidationTestInputParser::ParseSignedInteger), - DATA_TYPE("[b]", 1, &ValidationTestInputParser::ParseBinarySequence), - DATA_TYPE("[f]", 4, &ValidationTestInputParser::ParseFloat), - DATA_TYPE("[d]", 8, &ValidationTestInputParser::ParseDouble), - DATA_TYPE("[dist4]", 4, &ValidationTestInputParser::ParseDistance), - DATA_TYPE("[dist8]", 8, &ValidationTestInputParser::ParseDistance), - DATA_TYPE("[anchr]", 0, &ValidationTestInputParser::ParseAnchor), - DATA_TYPE("[handles]", 0, &ValidationTestInputParser::ParseHandles)}; - -const size_t ValidationTestInputParser::kDataTypeCount = - sizeof(ValidationTestInputParser::kDataTypes) / - sizeof(ValidationTestInputParser::kDataTypes[0]); - -ValidationTestInputParser::ValidationTestInputParser(const std::string& input, - std::vector<uint8_t>* data, - size_t* num_handles, - std::string* error_message) - : input_(input), - input_cursor_(0), - data_(data), - num_handles_(num_handles), - error_message_(error_message) { - assert(data_); - assert(num_handles_); - assert(error_message_); - data_->clear(); - *num_handles_ = 0; - error_message_->clear(); -} - -ValidationTestInputParser::~ValidationTestInputParser() { -} - -bool ValidationTestInputParser::Run() { - Range range; - bool result = true; - while (result && GetNextItem(&range)) - result = ParseItem(range); - - if (!result) { - *error_message_ = - "Error occurred when parsing " + std::string(range.first, range.second); - } else if (!pending_distance_items_.empty()) { - // We have parsed all the contents in |input_| successfully, but there are - // unmatched dist4/8 items. - *error_message_ = "Error occurred when matching [dist4/8] and [anchr]."; - result = false; - } - if (!result) { - data_->clear(); - *num_handles_ = 0; - } else { - assert(error_message_->empty()); - } - - return result; -} - -bool ValidationTestInputParser::GetNextItem(Range* range) { - const char kWhitespaceChars[] = " \t\n\r"; - const char kItemDelimiters[] = " \t\n\r/"; - const char kEndOfLineChars[] = "\n\r"; - while (true) { - // Skip leading whitespaces. - // If there are no non-whitespace characters left, |input_cursor_| will be - // set to std::npos. - input_cursor_ = input_.find_first_not_of(kWhitespaceChars, input_cursor_); - - if (input_cursor_ >= input_.size()) - return false; - - if (StartsWith( - Range(&input_[0] + input_cursor_, &input_[0] + input_.size()), - "//", - 2)) { - // Skip contents until the end of the line. - input_cursor_ = input_.find_first_of(kEndOfLineChars, input_cursor_); - } else { - range->first = &input_[0] + input_cursor_; - input_cursor_ = input_.find_first_of(kItemDelimiters, input_cursor_); - range->second = input_cursor_ >= input_.size() - ? &input_[0] + input_.size() - : &input_[0] + input_cursor_; - return true; - } - } - return false; -} - -bool ValidationTestInputParser::ParseItem(const Range& range) { - for (size_t i = 0; i < kDataTypeCount; ++i) { - if (StartsWith(range, kDataTypes[i].name, kDataTypes[i].name_size)) { - return (this->*kDataTypes[i].parse_data_func)( - kDataTypes[i], - std::string(range.first + kDataTypes[i].name_size, range.second)); - } - } - - // "[u1]" is optional. - return ParseUnsignedInteger(kDataTypes[0], - std::string(range.first, range.second)); -} - -bool ValidationTestInputParser::ParseUnsignedInteger( - const DataType& type, - const std::string& value_string) { - unsigned long long int value; - if (!ConvertToUnsignedInteger(value_string, &value)) - return false; - - switch (type.data_size) { - case 1: - return ConvertAndAppendData<uint8_t>(value); - case 2: - return ConvertAndAppendData<uint16_t>(value); - case 4: - return ConvertAndAppendData<uint32_t>(value); - case 8: - return ConvertAndAppendData<uint64_t>(value); - default: - assert(false); - return false; - } -} - -bool ValidationTestInputParser::ParseSignedInteger( - const DataType& type, - const std::string& value_string) { - long long int value; - if (sscanf(value_string.c_str(), "%lli", &value) != 1) - return false; - - switch (type.data_size) { - case 1: - return ConvertAndAppendData<int8_t>(value); - case 2: - return ConvertAndAppendData<int16_t>(value); - case 4: - return ConvertAndAppendData<int32_t>(value); - case 8: - return ConvertAndAppendData<int64_t>(value); - default: - assert(false); - return false; - } -} - -bool ValidationTestInputParser::ParseFloat(const DataType& type, - const std::string& value_string) { - static_assert(sizeof(float) == 4, "sizeof(float) is not 4"); - - float value; - if (sscanf(value_string.c_str(), "%f", &value) != 1) - return false; - - AppendData(value); - return true; -} - -bool ValidationTestInputParser::ParseDouble(const DataType& type, - const std::string& value_string) { - static_assert(sizeof(double) == 8, "sizeof(double) is not 8"); - - double value; - if (sscanf(value_string.c_str(), "%lf", &value) != 1) - return false; - - AppendData(value); - return true; -} - -bool ValidationTestInputParser::ParseBinarySequence( - const DataType& type, - const std::string& value_string) { - if (value_string.size() != 8) - return false; - - uint8_t value = 0; - for (std::string::const_iterator iter = value_string.begin(); - iter != value_string.end(); - ++iter) { - value <<= 1; - if (*iter == '1') - value++; - else if (*iter != '0') - return false; - } - AppendData(value); - return true; -} - -bool ValidationTestInputParser::ParseDistance(const DataType& type, - const std::string& value_string) { - if (pending_distance_items_.find(value_string) != - pending_distance_items_.end()) - return false; - - PendingDistanceItem item = {data_->size(), type.data_size}; - data_->resize(data_->size() + type.data_size); - pending_distance_items_[value_string] = item; - - return true; -} - -bool ValidationTestInputParser::ParseAnchor(const DataType& type, - const std::string& value_string) { - if (anchors_.find(value_string) != anchors_.end()) - return false; - anchors_.insert(value_string); - - std::map<std::string, PendingDistanceItem>::iterator iter = - pending_distance_items_.find(value_string); - if (iter == pending_distance_items_.end()) - return false; - - PendingDistanceItem dist_item = iter->second; - pending_distance_items_.erase(iter); - - size_t distance = data_->size() - dist_item.pos; - switch (dist_item.data_size) { - case 4: - return ConvertAndFillData<uint32_t>(dist_item.pos, distance); - case 8: - return ConvertAndFillData<uint64_t>(dist_item.pos, distance); - default: - assert(false); - return false; - } -} - -bool ValidationTestInputParser::ParseHandles(const DataType& type, - const std::string& value_string) { - // It should be the first item. - if (!data_->empty()) - return false; - - unsigned long long int value; - if (!ConvertToUnsignedInteger(value_string, &value)) - return false; - - if (value > std::numeric_limits<size_t>::max()) - return false; - - *num_handles_ = static_cast<size_t>(value); - return true; -} - -bool ValidationTestInputParser::StartsWith(const Range& range, - const char* prefix, - size_t prefix_length) { - if (static_cast<size_t>(range.second - range.first) < prefix_length) - return false; - - return memcmp(range.first, prefix, prefix_length) == 0; -} - -bool ValidationTestInputParser::ConvertToUnsignedInteger( - const std::string& value_string, - unsigned long long int* value) { - const char* format = nullptr; - if (value_string.find_first_of("xX") != std::string::npos) - format = "%llx"; - else - format = "%llu"; - return sscanf(value_string.c_str(), format, value) == 1; -} - -} // namespace - -bool ParseValidationTestInput(const std::string& input, - std::vector<uint8_t>* data, - size_t* num_handles, - std::string* error_message) { - ValidationTestInputParser parser(input, data, num_handles, error_message); - return parser.Run(); -} - -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/tests/validation_test_input_parser.h b/mojo/public/cpp/bindings/tests/validation_test_input_parser.h deleted file mode 100644 index c8821cd..0000000 --- a/mojo/public/cpp/bindings/tests/validation_test_input_parser.h +++ /dev/null @@ -1,120 +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_TESTS_VALIDATION_TEST_INPUT_PARSER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_TESTS_VALIDATION_TEST_INPUT_PARSER_H_ - -#include <stdint.h> - -#include <string> -#include <vector> - -namespace mojo { -namespace test { - -// Input Format of Mojo Message Validation Tests. -// -// Data items are separated by whitespaces: -// - ' ' (0x20) space; -// - '\t' (0x09) horizontal tab; -// - '\n' (0x0a) newline; -// - '\r' (0x0d) carriage return. -// A comment starts with //, extending to the end of the line. -// Each data item is of the format [<type>]<value>. The types defined and the -// corresponding value formats are described below. -// -// Type: u1 / u2 / u4 / u8 -// Description: Little-endian 1/2/4/8-byte unsigned integer. -// Value Format: -// - Decimal integer: 0|[1-9][0-9]* -// - Hexadecimal integer: 0[xX][0-9a-fA-F]+ -// - The type prefix (including the square brackets) of 1-byte unsigned -// integer is optional. -// -// Type: s1 / s2 / s4 / s8 -// Description: Little-endian 1/2/4/8-byte signed integer. -// Value Format: -// - Decimal integer: [-+]?(0|[1-9][0-9]*) -// - Hexadecimal integer: [-+]?0[xX][0-9a-fA-F]+ -// -// Type: b -// Description: Binary sequence of 1 byte. -// Value Format: [01]{8} -// -// Type: f / d -// Description: Little-endian IEEE-754 format of float (4 bytes) and double (8 -// bytes). -// Value Format: [-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)? -// -// Type: dist4 / dist8 -// Description: Little-endian 4/8-byte unsigned integer. The actual value is set -// to the byte distance from the location of this integer to the location of the -// anchr item with the same ID. A dist8 and anchr pair can be used to easily -// represent an encoded pointer. A dist4 and anchr pair can be used to easily -// calculate struct/array size. -// Value Format: The value is an ID: [0-9a-zA-Z_]+ -// -// Type: anchr -// Description: Mark an anchor location. It doesn’t translate into any actual -// data. -// Value Format: The value is an ID of the same format as that of dist4/8. -// -// Type: handles -// Description: The number of handles that are associated with the message. This -// special item is not part of the message data. If specified, it should be the -// first item. -// Value Format: The same format as u1/2/4/8. -// -// EXAMPLE: -// -// Suppose you have the following Mojo types defined: -// struct Bar { -// int32 a; -// bool b; -// bool c; -// }; -// struct Foo { -// Bar x; -// uint32 y; -// }; -// -// The following describes a valid message whose payload is a Foo struct: -// // message header -// [dist4]message_header // num_bytes -// [u4]3 // num_fields -// [u4]0 // type -// [u4]1 // flags -// [u8]1234 // request_id -// [anchr]message_header -// -// // payload -// [dist4]foo // num_bytes -// [u4]2 // num_fields -// [dist8]bar_ptr // x -// [u4]0xABCD // y -// [u4]0 // padding -// [anchr]foo -// -// [anchr]bar_ptr -// [dist4]bar // num_bytes -// [u4]3 // num_fields -// [s4]-1 // a -// [b]00000010 // b and c -// 0 0 0 // padding -// [anchr]bar - -// Parses validation test input. -// On success, |data| and |num_handles| store the parsing result, -// |error_message| is cleared; on failure, |error_message| is set to a message -// describing the error, |data| is cleared and |num_handles| set to 0. -// Note: For now, this method only works on little-endian platforms. -bool ParseValidationTestInput(const std::string& input, - std::vector<uint8_t>* data, - size_t* num_handles, - std::string* error_message); - -} // namespace test -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_TESTS_VALIDATION_TEST_INPUT_PARSER_H_ diff --git a/mojo/public/cpp/bindings/tests/validation_unittest.cc b/mojo/public/cpp/bindings/tests/validation_unittest.cc deleted file mode 100644 index 6507f21..0000000 --- a/mojo/public/cpp/bindings/tests/validation_unittest.cc +++ /dev/null @@ -1,419 +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 <stdio.h> - -#include <algorithm> -#include <string> -#include <vector> - -#include "mojo/public/c/system/macros.h" -#include "mojo/public/cpp/bindings/interface_impl.h" -#include "mojo/public/cpp/bindings/interface_ptr.h" -#include "mojo/public/cpp/bindings/lib/connector.h" -#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/bindings/lib/validation_errors.h" -#include "mojo/public/cpp/bindings/message.h" -#include "mojo/public/cpp/bindings/tests/validation_test_input_parser.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/core.h" -#include "mojo/public/cpp/test_support/test_support.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "mojo/public/interfaces/bindings/tests/validation_test_interfaces.mojom.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace test { -namespace { - -template <typename T> -void Append(std::vector<uint8_t>* data_vector, T data) { - size_t pos = data_vector->size(); - data_vector->resize(pos + sizeof(T)); - memcpy(&(*data_vector)[pos], &data, sizeof(T)); -} - -bool TestInputParser(const std::string& input, - bool expected_result, - const std::vector<uint8_t>& expected_data, - size_t expected_num_handles) { - std::vector<uint8_t> data; - size_t num_handles; - std::string error_message; - - bool result = - ParseValidationTestInput(input, &data, &num_handles, &error_message); - if (expected_result) { - if (result && error_message.empty() && expected_data == data && - expected_num_handles == num_handles) { - return true; - } - - // Compare with an empty string instead of checking |error_message.empty()|, - // so that the message will be printed out if the two are not equal. - EXPECT_EQ(std::string(), error_message); - EXPECT_EQ(expected_data, data); - EXPECT_EQ(expected_num_handles, num_handles); - return false; - } - - EXPECT_FALSE(error_message.empty()); - return !result && !error_message.empty(); -} - -std::vector<std::string> GetMatchingTests(const std::vector<std::string>& names, - const std::string& prefix) { - const std::string suffix = ".data"; - std::vector<std::string> tests; - for (size_t i = 0; i < names.size(); ++i) { - if (names[i].size() >= suffix.size() && - names[i].substr(0, prefix.size()) == prefix && - names[i].substr(names[i].size() - suffix.size()) == suffix) - tests.push_back(names[i].substr(0, names[i].size() - suffix.size())); - } - return tests; -} - -bool ReadFile(const std::string& path, std::string* result) { - FILE* fp = OpenSourceRootRelativeFile(path.c_str()); - if (!fp) { - ADD_FAILURE() << "File not found: " << path; - return false; - } - fseek(fp, 0, SEEK_END); - size_t size = static_cast<size_t>(ftell(fp)); - if (size == 0) { - result->clear(); - fclose(fp); - return true; - } - fseek(fp, 0, SEEK_SET); - result->resize(size); - size_t size_read = fread(&result->at(0), 1, size, fp); - fclose(fp); - return size == size_read; -} - -bool ReadAndParseDataFile(const std::string& path, - std::vector<uint8_t>* data, - size_t* num_handles) { - std::string input; - if (!ReadFile(path, &input)) - return false; - - std::string error_message; - if (!ParseValidationTestInput(input, data, num_handles, &error_message)) { - ADD_FAILURE() << error_message; - return false; - } - - return true; -} - -bool ReadResultFile(const std::string& path, std::string* result) { - if (!ReadFile(path, result)) - return false; - - // Result files are new-line delimited text files. Remove any CRs. - result->erase(std::remove(result->begin(), result->end(), '\r'), - result->end()); - - // Remove trailing LFs. - size_t pos = result->find_last_not_of('\n'); - if (pos == std::string::npos) - result->clear(); - else - result->resize(pos + 1); - - return true; -} - -std::string GetPath(const std::string& root, const std::string& suffix) { - return "mojo/public/interfaces/bindings/tests/data/validation/" + root + - suffix; -} - -// |message| should be a newly created object. -bool ReadTestCase(const std::string& test, - Message* message, - std::string* expected) { - std::vector<uint8_t> data; - size_t num_handles; - if (!ReadAndParseDataFile(GetPath(test, ".data"), &data, &num_handles) || - !ReadResultFile(GetPath(test, ".expected"), expected)) { - return false; - } - - message->AllocUninitializedData(static_cast<uint32_t>(data.size())); - if (!data.empty()) - memcpy(message->mutable_data(), &data[0], data.size()); - message->mutable_handles()->resize(num_handles); - - return true; -} - -void RunValidationTests(const std::string& prefix, - MessageReceiver* test_message_receiver) { - std::vector<std::string> names = - EnumerateSourceRootRelativeDirectory(GetPath("", "")); - std::vector<std::string> tests = GetMatchingTests(names, prefix); - - for (size_t i = 0; i < tests.size(); ++i) { - Message message; - std::string expected; - ASSERT_TRUE(ReadTestCase(tests[i], &message, &expected)); - - std::string result; - mojo::internal::ValidationErrorObserverForTesting observer; - mojo_ignore_result(test_message_receiver->Accept(&message)); - if (observer.last_error() == mojo::internal::VALIDATION_ERROR_NONE) - result = "PASS"; - else - result = mojo::internal::ValidationErrorToString(observer.last_error()); - - EXPECT_EQ(expected, result) << "failed test: " << tests[i]; - } -} - -class DummyMessageReceiver : public MessageReceiver { - public: - bool Accept(Message* message) override { - return true; // Any message is OK. - } -}; - -class ValidationTest : public testing::Test { - public: - ~ValidationTest() override {} - - private: - Environment env_; -}; - -class ValidationIntegrationTest : public ValidationTest { - public: - ValidationIntegrationTest() : test_message_receiver_(nullptr) {} - - ~ValidationIntegrationTest() override {} - - void SetUp() override { - ScopedMessagePipeHandle tester_endpoint; - ASSERT_EQ(MOJO_RESULT_OK, - CreateMessagePipe(nullptr, &tester_endpoint, &testee_endpoint_)); - test_message_receiver_ = - new TestMessageReceiver(this, tester_endpoint.Pass()); - } - - void TearDown() override { - delete test_message_receiver_; - test_message_receiver_ = nullptr; - - // Make sure that the other end receives the OnConnectionError() - // notification. - PumpMessages(); - } - - MessageReceiver* test_message_receiver() { return test_message_receiver_; } - - ScopedMessagePipeHandle testee_endpoint() { return testee_endpoint_.Pass(); } - - private: - class TestMessageReceiver : public MessageReceiver { - public: - TestMessageReceiver(ValidationIntegrationTest* owner, - ScopedMessagePipeHandle handle) - : owner_(owner), connector_(handle.Pass()) {} - ~TestMessageReceiver() override {} - - bool Accept(Message* message) override { - bool rv = connector_.Accept(message); - owner_->PumpMessages(); - return rv; - } - - public: - ValidationIntegrationTest* owner_; - mojo::internal::Connector connector_; - }; - - void PumpMessages() { loop_.RunUntilIdle(); } - - RunLoop loop_; - TestMessageReceiver* test_message_receiver_; - ScopedMessagePipeHandle testee_endpoint_; -}; - -class IntegrationTestInterface1Client : public IntegrationTestInterface1 { - public: - ~IntegrationTestInterface1Client() override {} - - void Method0(BasicStructPtr param0) override {} -}; - -class IntegrationTestInterface1Impl - : public InterfaceImpl<IntegrationTestInterface1> { - public: - ~IntegrationTestInterface1Impl() override {} - - void Method0(BasicStructPtr param0) override {} -}; - -TEST_F(ValidationTest, InputParser) { - { - // The parser, as well as Append() defined above, assumes that this code is - // running on a little-endian platform. Test whether that is true. - uint16_t x = 1; - ASSERT_EQ(1, *(reinterpret_cast<char*>(&x))); - } - { - // Test empty input. - std::string input; - std::vector<uint8_t> expected; - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - // Test input that only consists of comments and whitespaces. - std::string input = " \t // hello world \n\r \t// the answer is 42 "; - std::vector<uint8_t> expected; - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - std::string input = - "[u1]0x10// hello world !! \n\r \t [u2]65535 \n" - "[u4]65536 [u8]0xFFFFFFFFFFFFFFFF 0 0Xff"; - std::vector<uint8_t> expected; - Append(&expected, static_cast<uint8_t>(0x10)); - Append(&expected, static_cast<uint16_t>(65535)); - Append(&expected, static_cast<uint32_t>(65536)); - Append(&expected, static_cast<uint64_t>(0xffffffffffffffff)); - Append(&expected, static_cast<uint8_t>(0)); - Append(&expected, static_cast<uint8_t>(0xff)); - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - std::string input = "[s8]-0x800 [s1]-128\t[s2]+0 [s4]-40"; - std::vector<uint8_t> expected; - Append(&expected, -static_cast<int64_t>(0x800)); - Append(&expected, static_cast<int8_t>(-128)); - Append(&expected, static_cast<int16_t>(0)); - Append(&expected, static_cast<int32_t>(-40)); - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - std::string input = "[b]00001011 [b]10000000 // hello world\r [b]00000000"; - std::vector<uint8_t> expected; - Append(&expected, static_cast<uint8_t>(11)); - Append(&expected, static_cast<uint8_t>(128)); - Append(&expected, static_cast<uint8_t>(0)); - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - std::string input = "[f]+.3e9 [d]-10.03"; - std::vector<uint8_t> expected; - Append(&expected, +.3e9f); - Append(&expected, -10.03); - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - std::string input = "[dist4]foo 0 [dist8]bar 0 [anchr]foo [anchr]bar"; - std::vector<uint8_t> expected; - Append(&expected, static_cast<uint32_t>(14)); - Append(&expected, static_cast<uint8_t>(0)); - Append(&expected, static_cast<uint64_t>(9)); - Append(&expected, static_cast<uint8_t>(0)); - - EXPECT_TRUE(TestInputParser(input, true, expected, 0)); - } - { - std::string input = "// This message has handles! \n[handles]50 [u8]2"; - std::vector<uint8_t> expected; - Append(&expected, static_cast<uint64_t>(2)); - - EXPECT_TRUE(TestInputParser(input, true, expected, 50)); - } - - // Test some failure cases. - { - const char* error_inputs[] = {"/ hello world", - "[u1]x", - "[u2]-1000", - "[u1]0x100", - "[s2]-0x8001", - "[b]1", - "[b]1111111k", - "[dist4]unmatched", - "[anchr]hello [dist8]hello", - "[dist4]a [dist4]a [anchr]a", - "[dist4]a [anchr]a [dist4]a [anchr]a", - "0 [handles]50", - nullptr}; - - for (size_t i = 0; error_inputs[i]; ++i) { - std::vector<uint8_t> expected; - if (!TestInputParser(error_inputs[i], false, expected, 0)) - ADD_FAILURE() << "Unexpected test result for: " << error_inputs[i]; - } - } -} - -TEST_F(ValidationTest, Conformance) { - DummyMessageReceiver dummy_receiver; - mojo::internal::FilterChain validators(&dummy_receiver); - validators.Append<mojo::internal::MessageHeaderValidator>(); - validators.Append<ConformanceTestInterface::RequestValidator_>(); - - RunValidationTests("conformance_", validators.GetHead()); -} - -TEST_F(ValidationTest, NotImplemented) { - DummyMessageReceiver dummy_receiver; - mojo::internal::FilterChain validators(&dummy_receiver); - validators.Append<mojo::internal::MessageHeaderValidator>(); - validators.Append<ConformanceTestInterface::RequestValidator_>(); - - RunValidationTests("not_implemented_", validators.GetHead()); -} - -TEST_F(ValidationIntegrationTest, InterfacePtr) { - // Test that InterfacePtr<X> applies the correct validators and they don't - // conflict with each other: - // - MessageHeaderValidator - // - X::Client::RequestValidator_ - // - X::ResponseValidator_ - - IntegrationTestInterface1Client interface1_client; - IntegrationTestInterface2Ptr interface2_ptr = - MakeProxy<IntegrationTestInterface2>(testee_endpoint().Pass()); - interface2_ptr.set_client(&interface1_client); - interface2_ptr.internal_state()->router_for_testing()->EnableTestingMode(); - - RunValidationTests("integration_", test_message_receiver()); -} - -TEST_F(ValidationIntegrationTest, InterfaceImpl) { - // Test that InterfaceImpl<X> applies the correct validators and they don't - // conflict with each other: - // - MessageHeaderValidator - // - X::RequestValidator_ - // - X::Client::ResponseValidator_ - - // |interface1_impl| will delete itself when the pipe is closed. - IntegrationTestInterface1Impl* interface1_impl = - BindToPipe(new IntegrationTestInterface1Impl(), testee_endpoint().Pass()); - interface1_impl->internal_router()->EnableTestingMode(); - - RunValidationTests("integration_", test_message_receiver()); -} - -} // namespace -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/bindings/type_converter.h b/mojo/public/cpp/bindings/type_converter.h deleted file mode 100644 index ff94cda..0000000 --- a/mojo/public/cpp/bindings/type_converter.h +++ /dev/null @@ -1,92 +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_TYPE_CONVERTER_H_ -#define MOJO_PUBLIC_CPP_BINDINGS_TYPE_CONVERTER_H_ - -namespace mojo { - -// Specialize the following class: -// template <typename T, typename U> struct TypeConverter; -// to perform type conversion for Mojom-defined structs and arrays. Here, T is -// the target type; U is the input type. -// -// Specializations should implement the following interfaces: -// namespace mojo { -// template <> -// struct TypeConverter<X, Y> { -// static X Convert(const Y& input); -// }; -// template <> -// struct TypeConverter<Y, X> { -// static Y Convert(const X& input); -// }; -// } -// -// EXAMPLE: -// -// Suppose you have the following Mojom-defined struct: -// -// module geometry { -// struct Point { -// int32 x; -// int32 y; -// }; -// } -// -// Now, imagine you wanted to write a TypeConverter specialization for -// gfx::Point. It might look like this: -// -// namespace mojo { -// template <> -// struct TypeConverter<geometry::PointPtr, gfx::Point> { -// static geometry::PointPtr Convert(const gfx::Point& input) { -// geometry::PointPtr result; -// result->x = input.x(); -// result->y = input.y(); -// return result.Pass(); -// } -// }; -// template <> -// struct TypeConverter<gfx::Point, geometry::PointPtr> { -// static gfx::Point Convert(const geometry::PointPtr& input) { -// return input ? gfx::Point(input->x, input->y) : gfx::Point(); -// } -// }; -// } -// -// With the above TypeConverter defined, it is possible to write code like this: -// -// void AcceptPoint(const geometry::PointPtr& input) { -// // With an explicit cast using the .To<> method. -// gfx::Point pt = input.To<gfx::Point>(); -// -// // With an explicit cast using the static From() method. -// geometry::PointPtr output = geometry::Point::From(pt); -// -// // Inferring the input type using the ConvertTo helper function. -// gfx::Point pt2 = ConvertTo<gfx::Point>(input); -// } -// -template <typename T, typename U> -struct TypeConverter; - -// The following specialization is useful when you are converting between -// Array<POD> and std::vector<POD>. -template <typename T> -struct TypeConverter<T, T> { - static T Convert(const T& obj) { return obj; } -}; - -// The following helper function is useful for shorthand. The compiler can infer -// the input type, so you can write: -// OutputType out = ConvertTo<OutputType>(input); -template <typename T, typename U> -inline T ConvertTo(const U& obj) { - return TypeConverter<T, U>::Convert(obj); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_BINDINGS_TYPE_CONVERTER_H_ diff --git a/mojo/public/cpp/environment/BUILD.gn b/mojo/public/cpp/environment/BUILD.gn deleted file mode 100644 index 87f24ff..0000000 --- a/mojo/public/cpp/environment/BUILD.gn +++ /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. - -import("../../mojo_sdk.gni") - -mojo_sdk_source_set("environment") { - sources = [ - "async_waiter.h", - "logging.h", - "environment.h", - ] - - mojo_sdk_public_deps = [ "mojo/public/c/environment" ] - - mojo_sdk_deps = [ - "mojo/public/cpp/bindings:callback", - "mojo/public/cpp/system", - ] -} - -mojo_sdk_source_set("standalone") { - sources = [ - "lib/async_waiter.cc", - "lib/default_async_waiter.cc", - "lib/default_async_waiter.h", - "lib/default_logger.cc", - "lib/default_logger.h", - "lib/environment.cc", - "lib/logging.cc", - ] - - public_deps = [ - ":environment", - ] - - mojo_sdk_deps = [ - "mojo/public/c/environment", - "mojo/public/cpp/utility", - ] -} diff --git a/mojo/public/cpp/environment/DEPS b/mojo/public/cpp/environment/DEPS deleted file mode 100644 index 04346d9..0000000 --- a/mojo/public/cpp/environment/DEPS +++ /dev/null @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/bindings/callback.h", -] diff --git a/mojo/public/cpp/environment/async_waiter.h b/mojo/public/cpp/environment/async_waiter.h deleted file mode 100644 index 83b7c8a..0000000 --- a/mojo/public/cpp/environment/async_waiter.h +++ /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. - -#ifndef MOJO_PUBLIC_CPP_ENVIRONMENT_ASYNC_WAITER_H_ -#define MOJO_PUBLIC_CPP_ENVIRONMENT_ASYNC_WAITER_H_ - -#include "mojo/public/c/environment/async_waiter.h" -#include "mojo/public/cpp/bindings/callback.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/handle.h" - -namespace mojo { - -// A class that waits until a handle is ready and calls |callback| with the -// result. If the AsyncWaiter is deleted before the handle is ready, the wait is -// cancelled and the callback will not be called. -class AsyncWaiter { - public: - typedef mojo::Callback<void(MojoResult)> Callback; - - AsyncWaiter(Handle handle, - MojoHandleSignals signals, - const Callback& callback); - ~AsyncWaiter(); - - private: - static void WaitComplete(void* waiter, MojoResult result); - void WaitCompleteInternal(MojoResult result); - - const MojoAsyncWaiter* waiter_; - MojoAsyncWaitID id_; - const Callback callback_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(AsyncWaiter); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_ENVIRONMENT_ASYNC_WAITER_H_ diff --git a/mojo/public/cpp/environment/environment.h b/mojo/public/cpp/environment/environment.h deleted file mode 100644 index ce3f7d0..0000000 --- a/mojo/public/cpp/environment/environment.h +++ /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. - -#ifndef MOJO_PUBLIC_CPP_ENVIRONMENT_ENVIRONMENT_H_ -#define MOJO_PUBLIC_CPP_ENVIRONMENT_ENVIRONMENT_H_ - -#include "mojo/public/cpp/system/macros.h" - -struct MojoAsyncWaiter; -struct MojoLogger; - -namespace mojo { - -// Other parts of the Mojo C++ APIs use the *static* methods of this class. -// -// The "standalone" implementation of this class requires that this class (in -// the lib/ subdirectory) be instantiated (and remain so) while using the Mojo -// C++ APIs. I.e., the static methods depend on things set up by the constructor -// and torn down by the destructor. -// -// Other implementations may not have this requirement. -class Environment { - public: - Environment(); - // This constructor allows the standard implementations to be overridden (set - // a parameter to null to get the standard implementation). - Environment(const MojoAsyncWaiter* default_async_waiter, - const MojoLogger* default_logger); - ~Environment(); - - static const MojoAsyncWaiter* GetDefaultAsyncWaiter(); - static const MojoLogger* GetDefaultLogger(); - - // These instantiate and destroy an environment-specific run loop for the - // current thread, allowing |GetDefaultAsyncWaiter()| to be used. (The run - // loop itself should be accessible via thread-local storage, using methods - // specific to the run loop implementation.) Creating and destroying nested - // run loops is not supported. - static void InstantiateDefaultRunLoop(); - static void DestroyDefaultRunLoop(); - - private: - MOJO_DISALLOW_COPY_AND_ASSIGN(Environment); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_ENVIRONMENT_ENVIRONMENT_H_ diff --git a/mojo/public/cpp/environment/lib/DEPS b/mojo/public/cpp/environment/lib/DEPS deleted file mode 100644 index 1889e1f..0000000 --- a/mojo/public/cpp/environment/lib/DEPS +++ /dev/null @@ -1,4 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/environment", - "+mojo/public/cpp/utility", -] diff --git a/mojo/public/cpp/environment/lib/async_waiter.cc b/mojo/public/cpp/environment/lib/async_waiter.cc deleted file mode 100644 index 599a649..0000000 --- a/mojo/public/cpp/environment/lib/async_waiter.cc +++ /dev/null @@ -1,34 +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/environment/async_waiter.h" - -namespace mojo { - -AsyncWaiter::AsyncWaiter(Handle handle, - MojoHandleSignals signals, - const Callback& callback) - : waiter_(Environment::GetDefaultAsyncWaiter()), - id_(0), - callback_(callback) { - id_ = waiter_->AsyncWait(handle.value(), signals, MOJO_DEADLINE_INDEFINITE, - &AsyncWaiter::WaitComplete, this); -} - -AsyncWaiter::~AsyncWaiter() { - if (id_) - waiter_->CancelWait(id_); -} - -// static -void AsyncWaiter::WaitComplete(void* waiter, MojoResult result) { - static_cast<AsyncWaiter*>(waiter)->WaitCompleteInternal(result); -} - -void AsyncWaiter::WaitCompleteInternal(MojoResult result) { - id_ = 0; - callback_.Run(result); -} - -} // namespace mojo diff --git a/mojo/public/cpp/environment/lib/default_async_waiter.cc b/mojo/public/cpp/environment/lib/default_async_waiter.cc deleted file mode 100644 index 4a588a9..0000000 --- a/mojo/public/cpp/environment/lib/default_async_waiter.cc +++ /dev/null @@ -1,85 +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/environment/lib/default_async_waiter.h" - -#include <assert.h> - -#include "mojo/public/c/environment/async_waiter.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "mojo/public/cpp/utility/run_loop_handler.h" - -namespace mojo { - -namespace { - -// RunLoopHandler implementation used for a request to AsyncWait(). There are -// two ways RunLoopHandlerImpl is deleted: -// . when the handle is ready (or errored). -// . when CancelWait() is invoked. -class RunLoopHandlerImpl : public RunLoopHandler { - public: - RunLoopHandlerImpl(const Handle& handle, - MojoAsyncWaitCallback callback, - void* closure) - : handle_(handle), callback_(callback), closure_(closure) {} - - ~RunLoopHandlerImpl() override { RunLoop::current()->RemoveHandler(handle_); } - - // RunLoopHandler: - void OnHandleReady(const Handle& handle) override { - NotifyCallback(MOJO_RESULT_OK); - } - - void OnHandleError(const Handle& handle, MojoResult result) override { - NotifyCallback(result); - } - - private: - void NotifyCallback(MojoResult result) { - // Delete this to unregister the handle. That way if the callback - // reregisters everything is ok. - MojoAsyncWaitCallback callback = callback_; - void* closure = closure_; - delete this; - - callback(closure, result); - } - - const Handle handle_; - MojoAsyncWaitCallback callback_; - void* closure_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(RunLoopHandlerImpl); -}; - -MojoAsyncWaitID AsyncWait(MojoHandle handle, - MojoHandleSignals signals, - MojoDeadline deadline, - MojoAsyncWaitCallback callback, - void* closure) { - RunLoop* run_loop = RunLoop::current(); - assert(run_loop); - - // |run_loop_handler| is destroyed either when the handle is ready or if - // CancelWait is invoked. - RunLoopHandlerImpl* run_loop_handler = - new RunLoopHandlerImpl(Handle(handle), callback, closure); - run_loop->AddHandler(run_loop_handler, Handle(handle), signals, deadline); - return reinterpret_cast<MojoAsyncWaitID>(run_loop_handler); -} - -void CancelWait(MojoAsyncWaitID wait_id) { - delete reinterpret_cast<RunLoopHandlerImpl*>(wait_id); -} - -} // namespace - -namespace internal { - -const MojoAsyncWaiter kDefaultAsyncWaiter = {AsyncWait, CancelWait}; - -} // namespace internal - -} // namespace mojo diff --git a/mojo/public/cpp/environment/lib/default_async_waiter.h b/mojo/public/cpp/environment/lib/default_async_waiter.h deleted file mode 100644 index 49ce233..0000000 --- a/mojo/public/cpp/environment/lib/default_async_waiter.h +++ /dev/null @@ -1,18 +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_ENVIRONMENT_LIB_DEFAULT_ASYNC_WAITER_H_ -#define MOJO_PUBLIC_CPP_ENVIRONMENT_LIB_DEFAULT_ASYNC_WAITER_H_ - -struct MojoAsyncWaiter; - -namespace mojo { -namespace internal { - -extern const MojoAsyncWaiter kDefaultAsyncWaiter; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_ENVIRONMENT_LIB_DEFAULT_ASYNC_WAITER_H_ diff --git a/mojo/public/cpp/environment/lib/default_logger.cc b/mojo/public/cpp/environment/lib/default_logger.cc deleted file mode 100644 index 05cafbd..0000000 --- a/mojo/public/cpp/environment/lib/default_logger.cc +++ /dev/null @@ -1,69 +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/environment/lib/default_logger.h" - -#include <stdio.h> -#include <stdlib.h> // For |abort()|. - -#include <algorithm> - -#include "mojo/public/c/environment/logger.h" - -namespace mojo { - -namespace { - -MojoLogLevel g_minimum_log_level = MOJO_LOG_LEVEL_INFO; - -const char* GetLogLevelString(MojoLogLevel log_level) { - if (log_level <= MOJO_LOG_LEVEL_VERBOSE - 3) - return "VERBOSE4+"; - switch (log_level) { - case MOJO_LOG_LEVEL_VERBOSE - 2: - return "VERBOSE3"; - case MOJO_LOG_LEVEL_VERBOSE - 1: - return "VERBOSE2"; - case MOJO_LOG_LEVEL_VERBOSE: - return "VERBOSE1"; - case MOJO_LOG_LEVEL_INFO: - return "INFO"; - case MOJO_LOG_LEVEL_WARNING: - return "WARNING"; - case MOJO_LOG_LEVEL_ERROR: - return "ERROR"; - } - // Consider everything higher to be fatal. - return "FATAL"; -} - -void LogMessage(MojoLogLevel log_level, const char* message) { - if (log_level < g_minimum_log_level) - return; - - // TODO(vtl): Add timestamp also? - fprintf(stderr, "%s: %s\n", GetLogLevelString(log_level), message); - if (log_level >= MOJO_LOG_LEVEL_FATAL) - abort(); -} - -MojoLogLevel GetMinimumLogLevel() { - return g_minimum_log_level; -} - -void SetMinimumLogLevel(MojoLogLevel minimum_log_level) { - g_minimum_log_level = std::min(minimum_log_level, MOJO_LOG_LEVEL_FATAL); -} - -} // namespace - -namespace internal { - -const MojoLogger kDefaultLogger = {LogMessage, - GetMinimumLogLevel, - SetMinimumLogLevel}; - -} // namespace internal - -} // namespace mojo diff --git a/mojo/public/cpp/environment/lib/default_logger.h b/mojo/public/cpp/environment/lib/default_logger.h deleted file mode 100644 index 4db3233..0000000 --- a/mojo/public/cpp/environment/lib/default_logger.h +++ /dev/null @@ -1,18 +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_ENVIRONMENT_LIB_DEFAULT_LOGGER_H_ -#define MOJO_PUBLIC_CPP_ENVIRONMENT_LIB_DEFAULT_LOGGER_H_ - -struct MojoLogger; - -namespace mojo { -namespace internal { - -extern const MojoLogger kDefaultLogger; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_ENVIRONMENT_LIB_DEFAULT_LOGGER_H_ diff --git a/mojo/public/cpp/environment/lib/environment.cc b/mojo/public/cpp/environment/lib/environment.cc deleted file mode 100644 index 6fb7e22..0000000 --- a/mojo/public/cpp/environment/lib/environment.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/environment/environment.h" - -#include <assert.h> - -#include "mojo/public/c/environment/logger.h" -#include "mojo/public/cpp/environment/lib/default_async_waiter.h" -#include "mojo/public/cpp/environment/lib/default_logger.h" -#include "mojo/public/cpp/utility/run_loop.h" - -namespace mojo { - -namespace { - -const MojoAsyncWaiter* g_default_async_waiter = nullptr; -const MojoLogger* g_default_logger = nullptr; - -void Init(const MojoAsyncWaiter* default_async_waiter, - const MojoLogger* default_logger) { - g_default_async_waiter = default_async_waiter - ? default_async_waiter - : &internal::kDefaultAsyncWaiter; - g_default_logger = - default_logger ? default_logger : &internal::kDefaultLogger; - - RunLoop::SetUp(); -} - -} // namespace - -Environment::Environment() { - Init(nullptr, nullptr); -} - -Environment::Environment(const MojoAsyncWaiter* default_async_waiter, - const MojoLogger* default_logger) { - Init(default_async_waiter, default_logger); -} - -Environment::~Environment() { - RunLoop::TearDown(); - - // TODO(vtl): Maybe we should allow nesting, and restore previous default - // async waiters and loggers? - g_default_async_waiter = nullptr; - g_default_logger = nullptr; -} - -// static -const MojoAsyncWaiter* Environment::GetDefaultAsyncWaiter() { - assert(g_default_async_waiter); // Fails if not "inside" |Environment|. - return g_default_async_waiter; -} - -// static -const MojoLogger* Environment::GetDefaultLogger() { - assert(g_default_logger); // Fails if not "inside" |Environment|. - return g_default_logger; -} - -// static -void Environment::InstantiateDefaultRunLoop() { - assert(!RunLoop::current()); - // Not leaked: accessible from |RunLoop::current()|. - RunLoop* run_loop = new RunLoop(); - MOJO_ALLOW_UNUSED_LOCAL(run_loop); - assert(run_loop == RunLoop::current()); -} - -// static -void Environment::DestroyDefaultRunLoop() { - assert(RunLoop::current()); - delete RunLoop::current(); - assert(!RunLoop::current()); -} - -} // namespace mojo diff --git a/mojo/public/cpp/environment/lib/logging.cc b/mojo/public/cpp/environment/lib/logging.cc deleted file mode 100644 index 990626d..0000000 --- a/mojo/public/cpp/environment/lib/logging.cc +++ /dev/null @@ -1,45 +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/environment/logging.h" - -#include "mojo/public/cpp/environment/environment.h" - -namespace mojo { -namespace internal { - -namespace { - -// Gets a pointer to the filename portion of |s|. Assumes that the filename -// follows the last slash or backslash in |s|, or is |s| if no slash or -// backslash is present. -// -// E.g., a pointer to "foo.cc" is returned for the following inputs: "foo.cc", -// "./foo.cc", ".\foo.cc", "/absolute/path/to/foo.cc", -// "relative/path/to/foo.cc", "C:\absolute\path\to\foo.cc", etc. -const char* GetFilename(const char* s) { - const char* rv = s; - while (*s) { - if (*s == '/' || *s == '\\') - rv = s + 1; - s++; - } - return rv; -} - -} // namespace - -LogMessage::LogMessage(const char* file, int line, MojoLogLevel log_level) - : log_level_(log_level) { - // Note: Don't include the log level in the message, since that's passed on. - stream_ << GetFilename(file) << '(' << line << "): "; -} - -LogMessage::~LogMessage() { - Environment::GetDefaultLogger()->LogMessage(log_level_, - stream_.str().c_str()); -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/environment/logging.h b/mojo/public/cpp/environment/logging.h deleted file mode 100644 index 5df18fb..0000000 --- a/mojo/public/cpp/environment/logging.h +++ /dev/null @@ -1,86 +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. - -// Logging macros, similar to Chromium's base/logging.h, except with |MOJO_| -// prefixes and missing some features (notably |CHECK_EQ()|, etc.). - -// TODO(vtl): It's weird that this is in the environment directory, since its -// implementation (in environment/lib) is meant to be used by any implementation -// of the environment. - -#ifndef MOJO_PUBLIC_CPP_ENVIRONMENT_LOGGING_H_ -#define MOJO_PUBLIC_CPP_ENVIRONMENT_LOGGING_H_ - -#include <sstream> - -#include "mojo/public/c/environment/logger.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/macros.h" - -#define MOJO_LOG_STREAM(level) \ - ::mojo::internal::LogMessage(__FILE__, __LINE__, MOJO_LOG_LEVEL_##level) \ - .stream() - -#define MOJO_LAZY_LOG_STREAM(level, condition) \ - !(condition) ? (void)0 \ - : ::mojo::internal::VoidifyOstream() & MOJO_LOG_STREAM(level) - -#define MOJO_SHOULD_LOG(level) \ - (MOJO_LOG_LEVEL_##level >= \ - ::mojo::Environment::GetDefaultLogger()->GetMinimumLogLevel()) - -#define MOJO_LOG(level) MOJO_LAZY_LOG_STREAM(level, MOJO_SHOULD_LOG(level)) - -#define MOJO_LOG_IF(level, condition) \ - MOJO_LAZY_LOG_STREAM(level, MOJO_SHOULD_LOG(level) && (condition)) - -#define MOJO_CHECK(condition) \ - MOJO_LAZY_LOG_STREAM(FATAL, !(condition)) << "Check failed: " #condition "." \ - " " - -// Note: For non-debug builds, |MOJO_DLOG_IF()| *eliminates* (i.e., doesn't -// compile) the condition, whereas |MOJO_DCHECK()| "neuters" the condition -// (i.e., compiles, but doesn't evaluate). -#ifdef NDEBUG - -#define MOJO_DLOG(level) MOJO_LAZY_LOG_STREAM(level, false) -#define MOJO_DLOG_IF(level, condition) MOJO_LAZY_LOG_STREAM(level, false) -#define MOJO_DCHECK(condition) \ - MOJO_LAZY_LOG_STREAM(FATAL, false ? !(condition) : false) - -#else - -#define MOJO_DLOG(level) MOJO_LOG(level) -#define MOJO_DLOG_IF(level, condition) MOJO_LOG_IF(level, condition) -#define MOJO_DCHECK(condition) MOJO_CHECK(condition) - -#endif // NDEBUG - -namespace mojo { -namespace internal { - -class LogMessage { - public: - LogMessage(const char* file, int line, MojoLogLevel log_level); - ~LogMessage(); - - std::ostream& stream() { return stream_; } - - private: - const MojoLogLevel log_level_; - std::ostringstream stream_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(LogMessage); -}; - -// Used to ignore a stream. -struct VoidifyOstream { - // Use & since it has precedence lower than << but higher than ?:. - void operator&(std::ostream&) {} -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_ENVIRONMENT_LOGGING_H_ diff --git a/mojo/public/cpp/environment/tests/BUILD.gn b/mojo/public/cpp/environment/tests/BUILD.gn deleted file mode 100644 index 10fd056..0000000 --- a/mojo/public/cpp/environment/tests/BUILD.gn +++ /dev/null @@ -1,29 +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. - -import("../../../mojo_sdk.gni") - -mojo_sdk_source_set("tests") { - testonly = true - - sources = [ - "async_wait_unittest.cc", - "async_waiter_unittest.cc", - "logger_unittest.cc", - "logging_unittest.cc", - ] - - deps = [ - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/c/environment", - "mojo/public/cpp/bindings:callback", - "mojo/public/cpp/environment:standalone", - "mojo/public/cpp/system", - "mojo/public/cpp/test_support:test_utils", - "mojo/public/cpp/utility", - ] -} diff --git a/mojo/public/cpp/environment/tests/async_wait_unittest.cc b/mojo/public/cpp/environment/tests/async_wait_unittest.cc deleted file mode 100644 index 83c5ca0..0000000 --- a/mojo/public/cpp/environment/tests/async_wait_unittest.cc +++ /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. - -#include <string> - -#include "mojo/public/c/environment/async_waiter.h" -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/system/core.h" -#include "mojo/public/cpp/system/macros.h" -#include "mojo/public/cpp/test_support/test_utils.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -class TestAsyncWaitCallback { - public: - TestAsyncWaitCallback() : result_count_(0), last_result_(MOJO_RESULT_OK) {} - ~TestAsyncWaitCallback() {} - - int result_count() const { return result_count_; } - - MojoResult last_result() const { return last_result_; } - - // MojoAsyncWaitCallback: - static void OnHandleReady(void* closure, MojoResult result) { - TestAsyncWaitCallback* self = static_cast<TestAsyncWaitCallback*>(closure); - self->result_count_++; - self->last_result_ = result; - } - - private: - int result_count_; - MojoResult last_result_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(TestAsyncWaitCallback); -}; - -MojoAsyncWaitID CallAsyncWait(const Handle& handle, - MojoHandleSignals signals, - TestAsyncWaitCallback* callback) { - return Environment::GetDefaultAsyncWaiter()->AsyncWait( - handle.value(), - signals, - MOJO_DEADLINE_INDEFINITE, - &TestAsyncWaitCallback::OnHandleReady, - callback); -} - -void CallCancelWait(MojoAsyncWaitID wait_id) { - Environment::GetDefaultAsyncWaiter()->CancelWait(wait_id); -} - -class AsyncWaitTest : public testing::Test { - public: - AsyncWaitTest() {} - - private: - Environment environment_; - RunLoop run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(AsyncWaitTest); -}; - -// Verifies AsyncWaitCallback is notified when pipe is ready. -TEST_F(AsyncWaitTest, CallbackNotified) { - TestAsyncWaitCallback callback; - MessagePipe test_pipe; - EXPECT_TRUE(test::WriteTextMessage(test_pipe.handle1.get(), std::string())); - - CallAsyncWait( - test_pipe.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, &callback); - RunLoop::current()->Run(); - EXPECT_EQ(1, callback.result_count()); - EXPECT_EQ(MOJO_RESULT_OK, callback.last_result()); -} - -// Verifies 2 AsyncWaitCallbacks are notified when there pipes are ready. -TEST_F(AsyncWaitTest, TwoCallbacksNotified) { - TestAsyncWaitCallback callback1; - TestAsyncWaitCallback callback2; - MessagePipe test_pipe1; - MessagePipe test_pipe2; - EXPECT_TRUE(test::WriteTextMessage(test_pipe1.handle1.get(), std::string())); - EXPECT_TRUE(test::WriteTextMessage(test_pipe2.handle1.get(), std::string())); - - CallAsyncWait( - test_pipe1.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, &callback1); - CallAsyncWait( - test_pipe2.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, &callback2); - - RunLoop::current()->Run(); - EXPECT_EQ(1, callback1.result_count()); - EXPECT_EQ(MOJO_RESULT_OK, callback1.last_result()); - EXPECT_EQ(1, callback2.result_count()); - EXPECT_EQ(MOJO_RESULT_OK, callback2.last_result()); -} - -// Verifies cancel works. -TEST_F(AsyncWaitTest, CancelCallback) { - TestAsyncWaitCallback callback; - MessagePipe test_pipe; - EXPECT_TRUE(test::WriteTextMessage(test_pipe.handle1.get(), std::string())); - - CallCancelWait(CallAsyncWait( - test_pipe.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, &callback)); - RunLoop::current()->Run(); - EXPECT_EQ(0, callback.result_count()); -} - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/environment/tests/async_waiter_unittest.cc b/mojo/public/cpp/environment/tests/async_waiter_unittest.cc deleted file mode 100644 index 1c1c2bf..0000000 --- a/mojo/public/cpp/environment/tests/async_waiter_unittest.cc +++ /dev/null @@ -1,107 +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/callback.h" -#include "mojo/public/cpp/environment/async_waiter.h" -#include "mojo/public/cpp/test_support/test_utils.h" -#include "mojo/public/cpp/utility/run_loop.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -class TestAsyncWaitCallback { - public: - TestAsyncWaitCallback() : result_count_(0), last_result_(MOJO_RESULT_OK) {} - ~TestAsyncWaitCallback() {} - - int result_count() const { return result_count_; } - - MojoResult last_result() const { return last_result_; } - - void OnHandleReady(MojoResult result) { - result_count_++; - last_result_ = result; - } - - private: - int result_count_; - MojoResult last_result_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(TestAsyncWaitCallback); -}; - -// Manual code to create a callback since we don't have mojo::Bind yet. -class ManualCallback { - public: - explicit ManualCallback(TestAsyncWaitCallback* callback) - : callback_(callback) {} - - void Run(MojoResult result) const { callback_->OnHandleReady(result); } - - private: - TestAsyncWaitCallback* callback_; -}; - -class AsyncWaiterTest : public testing::Test { - public: - AsyncWaiterTest() {} - - private: - Environment environment_; - RunLoop run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(AsyncWaiterTest); -}; - -// Verifies AsyncWaitCallback is notified when pipe is ready. -TEST_F(AsyncWaiterTest, CallbackNotified) { - TestAsyncWaitCallback callback; - MessagePipe test_pipe; - EXPECT_TRUE(test::WriteTextMessage(test_pipe.handle1.get(), std::string())); - - AsyncWaiter waiter(test_pipe.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, - ManualCallback(&callback)); - RunLoop::current()->Run(); - EXPECT_EQ(1, callback.result_count()); - EXPECT_EQ(MOJO_RESULT_OK, callback.last_result()); -} - -// Verifies 2 AsyncWaitCallbacks are notified when there pipes are ready. -TEST_F(AsyncWaiterTest, TwoCallbacksNotified) { - TestAsyncWaitCallback callback1; - TestAsyncWaitCallback callback2; - MessagePipe test_pipe1; - MessagePipe test_pipe2; - EXPECT_TRUE(test::WriteTextMessage(test_pipe1.handle1.get(), std::string())); - EXPECT_TRUE(test::WriteTextMessage(test_pipe2.handle1.get(), std::string())); - - AsyncWaiter waiter1(test_pipe1.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, - ManualCallback(&callback1)); - AsyncWaiter waiter2(test_pipe2.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, - ManualCallback(&callback2)); - - RunLoop::current()->Run(); - EXPECT_EQ(1, callback1.result_count()); - EXPECT_EQ(MOJO_RESULT_OK, callback1.last_result()); - EXPECT_EQ(1, callback2.result_count()); - EXPECT_EQ(MOJO_RESULT_OK, callback2.last_result()); -} - -// Verifies cancel works. -TEST_F(AsyncWaiterTest, CancelCallback) { - TestAsyncWaitCallback callback; - MessagePipe test_pipe; - EXPECT_TRUE(test::WriteTextMessage(test_pipe.handle1.get(), std::string())); - - { - AsyncWaiter waiter(test_pipe.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE, - ManualCallback(&callback)); - } - RunLoop::current()->Run(); - EXPECT_EQ(0, callback.result_count()); -} - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/environment/tests/logger_unittest.cc b/mojo/public/cpp/environment/tests/logger_unittest.cc deleted file mode 100644 index 7aef2ee..0000000 --- a/mojo/public/cpp/environment/tests/logger_unittest.cc +++ /dev/null @@ -1,56 +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/c/environment/logger.h" -#include "mojo/public/cpp/environment/environment.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -TEST(LoggerTest, Basic) { - Environment environment; - const MojoLogger* const logger = Environment::GetDefaultLogger(); - - logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE - 1, "Logged at VERBOSE-1 level"); - logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE, "Logged at VERBOSE level"); - logger->LogMessage(MOJO_LOG_LEVEL_INFO, "Logged at INFO level"); - logger->LogMessage(MOJO_LOG_LEVEL_WARNING, "Logged at WARNING level"); - logger->LogMessage(MOJO_LOG_LEVEL_ERROR, "Logged at ERROR level"); - - // This should kill us: - EXPECT_DEATH_IF_SUPPORTED( - { logger->LogMessage(MOJO_LOG_LEVEL_FATAL, "Logged at FATAL level"); }, - ""); -} - -TEST(LoggerTest, LogLevels) { - Environment environment; - const MojoLogger* const logger = Environment::GetDefaultLogger(); - - for (MojoLogLevel log_level = MOJO_LOG_LEVEL_VERBOSE - 1; - log_level <= MOJO_LOG_LEVEL_FATAL + 1; - log_level++) { - logger->SetMinimumLogLevel(log_level); - - if (log_level <= MOJO_LOG_LEVEL_FATAL) - EXPECT_EQ(log_level, logger->GetMinimumLogLevel()); - else - EXPECT_EQ(MOJO_LOG_LEVEL_FATAL, logger->GetMinimumLogLevel()); - - logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE - 1, "Logged at VERBOSE-1 level"); - logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE, "Logged at VERBOSE level"); - logger->LogMessage(MOJO_LOG_LEVEL_INFO, "Logged at INFO level"); - logger->LogMessage(MOJO_LOG_LEVEL_WARNING, "Logged at WARNING level"); - logger->LogMessage(MOJO_LOG_LEVEL_ERROR, "Logged at ERROR level"); - - // This should kill us: - EXPECT_DEATH_IF_SUPPORTED( - { logger->LogMessage(MOJO_LOG_LEVEL_FATAL, "Logged at FATAL level"); }, - ""); - } -} - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/environment/tests/logging_unittest.cc b/mojo/public/cpp/environment/tests/logging_unittest.cc deleted file mode 100644 index 53a1f88..0000000 --- a/mojo/public/cpp/environment/tests/logging_unittest.cc +++ /dev/null @@ -1,479 +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 <stdlib.h> - -#include <sstream> -#include <string> - -#include "mojo/public/cpp/environment/environment.h" -#include "mojo/public/cpp/environment/logging.h" -#include "mojo/public/cpp/system/macros.h" -#include "testing/gtest/include/gtest/gtest.h" - -// A macro, so it can be automatically joined with other string literals. (Not -// simply __FILE__, since that may contain a path.) -#define OUR_FILENAME "logging_unittest.cc" - -namespace mojo { -namespace { - -class PtrToMemberHelper { - public: - int member; -}; - -bool DcheckTestHelper(bool* was_called) { - *was_called = true; - return false; -} - -class LoggingTest : public testing::Test { - public: - LoggingTest() : environment_(nullptr, &kMockLogger) { - minimum_log_level_ = MOJO_LOG_LEVEL_INFO; - ResetMockLogger(); - } - ~LoggingTest() override {} - - protected: - // Note: Does not reset |minimum_log_level_|. - static void ResetMockLogger() { - log_message_was_called_ = false; - last_log_level_ = MOJO_LOG_LEVEL_INFO; - last_message_.clear(); - } - - // A function returning |bool| that shouldn't be called. - static bool NotCalledCondition() { - not_called_condition_was_called_ = true; - return false; - } - - static bool log_message_was_called() { return log_message_was_called_; } - static MojoLogLevel last_log_level() { return last_log_level_; } - static const std::string& last_message() { return last_message_; } - static bool not_called_condition_was_called() { - return not_called_condition_was_called_; - } - - private: - // Note: We record calls even if |log_level| is below |minimum_log_level_| - // (since the macros should mostly avoid this, and we want to be able to check - // that they do). - static void MockLogMessage(MojoLogLevel log_level, const char* message) { - log_message_was_called_ = true; - last_log_level_ = log_level; - last_message_ = message; - } - - static MojoLogLevel MockGetMinimumLogLevel() { return minimum_log_level_; } - - static void MockSetMinimumLogLevel(MojoLogLevel minimum_log_level) { - minimum_log_level_ = minimum_log_level; - } - - Environment environment_; - - static const MojoLogger kMockLogger; - static MojoLogLevel minimum_log_level_; - static bool log_message_was_called_; - static MojoLogLevel last_log_level_; - static std::string last_message_; - static bool not_called_condition_was_called_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(LoggingTest); -}; - -// static -const MojoLogger LoggingTest::kMockLogger = { - &LoggingTest::MockLogMessage, - &LoggingTest::MockGetMinimumLogLevel, - &LoggingTest::MockSetMinimumLogLevel}; - -// static -MojoLogLevel LoggingTest::minimum_log_level_ = MOJO_LOG_LEVEL_INFO; - -// static -bool LoggingTest::log_message_was_called_ = MOJO_LOG_LEVEL_INFO; - -// static -MojoLogLevel LoggingTest::last_log_level_ = MOJO_LOG_LEVEL_INFO; - -// static -std::string LoggingTest::last_message_; - -// static -bool LoggingTest::not_called_condition_was_called_ = false; - -std::string ExpectedLogMessage(int line, const char* message) { - std::ostringstream s; - s << OUR_FILENAME "(" << line << "): " << message; - return s.str(); -} - -TEST_F(LoggingTest, InternalLogMessage) { - internal::LogMessage("foo.cc", 123, MOJO_LOG_LEVEL_INFO).stream() << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage("./path/to/foo.cc", 123, MOJO_LOG_LEVEL_WARNING).stream() - << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_WARNING, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage("/path/to/foo.cc", 123, MOJO_LOG_LEVEL_ERROR).stream() - << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_ERROR, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage("path/to/foo.cc", 123, MOJO_LOG_LEVEL_FATAL).stream() - << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_FATAL, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage(".\\xy\\foo.cc", 123, MOJO_LOG_LEVEL_VERBOSE).stream() - << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_VERBOSE, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage("xy\\foo.cc", 123, MOJO_LOG_LEVEL_VERBOSE - 1).stream() - << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_VERBOSE - 1, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage("C:\\xy\\foo.cc", 123, MOJO_LOG_LEVEL_VERBOSE - 9) - .stream() - << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_VERBOSE - 9, last_log_level()); - EXPECT_EQ("foo.cc(123): hello world", last_message()); - - ResetMockLogger(); - - internal::LogMessage(__FILE__, 123, MOJO_LOG_LEVEL_INFO).stream() << "hello " - << "world"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ(OUR_FILENAME "(123): hello world", last_message()); -} - -TEST_F(LoggingTest, LogStream) { - MOJO_LOG_STREAM(INFO) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hello"), last_message()); - - ResetMockLogger(); - - MOJO_LOG_STREAM(ERROR) << "hi " << 123; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_ERROR, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hi 123"), last_message()); -} - -TEST_F(LoggingTest, LazyLogStream) { - MOJO_LAZY_LOG_STREAM(INFO, true) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hello"), last_message()); - - ResetMockLogger(); - - MOJO_LAZY_LOG_STREAM(ERROR, true) << "hi " << 123; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_ERROR, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hi 123"), last_message()); - - ResetMockLogger(); - - MOJO_LAZY_LOG_STREAM(INFO, false) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LAZY_LOG_STREAM(FATAL, false) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - PtrToMemberHelper helper; - helper.member = 1; - int PtrToMemberHelper::*member_ptr = &PtrToMemberHelper::member; - - // This probably fails to compile if we forget to parenthesize the condition - // in the macro (.* has lower precedence than !, which can't apply to - // |helper|). - MOJO_LAZY_LOG_STREAM(ERROR, helper.*member_ptr == 1) << "hello"; - EXPECT_TRUE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LAZY_LOG_STREAM(WARNING, helper.*member_ptr == 0) << "hello"; - EXPECT_FALSE(log_message_was_called()); -} - -TEST_F(LoggingTest, ShouldLog) { - // We start at |MOJO_LOG_LEVEL_INFO|. - EXPECT_FALSE(MOJO_SHOULD_LOG(VERBOSE)); - EXPECT_TRUE(MOJO_SHOULD_LOG(INFO)); - EXPECT_TRUE(MOJO_SHOULD_LOG(WARNING)); - EXPECT_TRUE(MOJO_SHOULD_LOG(ERROR)); - EXPECT_TRUE(MOJO_SHOULD_LOG(FATAL)); - - Environment::GetDefaultLogger()->SetMinimumLogLevel(MOJO_LOG_LEVEL_ERROR); - EXPECT_FALSE(MOJO_SHOULD_LOG(VERBOSE)); - EXPECT_FALSE(MOJO_SHOULD_LOG(INFO)); - EXPECT_FALSE(MOJO_SHOULD_LOG(WARNING)); - EXPECT_TRUE(MOJO_SHOULD_LOG(ERROR)); - EXPECT_TRUE(MOJO_SHOULD_LOG(FATAL)); - - Environment::GetDefaultLogger()->SetMinimumLogLevel(MOJO_LOG_LEVEL_VERBOSE - - 1); - EXPECT_TRUE(MOJO_SHOULD_LOG(VERBOSE)); - EXPECT_TRUE(MOJO_SHOULD_LOG(INFO)); - EXPECT_TRUE(MOJO_SHOULD_LOG(WARNING)); - EXPECT_TRUE(MOJO_SHOULD_LOG(ERROR)); - EXPECT_TRUE(MOJO_SHOULD_LOG(FATAL)); -} - -TEST_F(LoggingTest, Log) { - // We start at |MOJO_LOG_LEVEL_INFO|. - MOJO_LOG(VERBOSE) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG(INFO) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hello"), last_message()); - - ResetMockLogger(); - - MOJO_LOG(ERROR) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_ERROR, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hello"), last_message()); - - ResetMockLogger(); - - Environment::GetDefaultLogger()->SetMinimumLogLevel(MOJO_LOG_LEVEL_ERROR); - - MOJO_LOG(VERBOSE) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG(INFO) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG(ERROR) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_ERROR, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hello"), last_message()); -} - -TEST_F(LoggingTest, LogIf) { - // We start at |MOJO_LOG_LEVEL_INFO|. - MOJO_LOG_IF(VERBOSE, true) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG_IF(VERBOSE, false) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - Environment::GetDefaultLogger()->SetMinimumLogLevel(MOJO_LOG_LEVEL_ERROR); - - bool x = true; - // Also try to make sure that we parenthesize the condition properly. - MOJO_LOG_IF(INFO, false || x) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG_IF(INFO, 0 != 1) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG_IF(WARNING, 1 + 1 == 2) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_LOG_IF(ERROR, 1 * 2 == 2) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_ERROR, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 3, "hello"), last_message()); - - ResetMockLogger(); - - MOJO_LOG_IF(FATAL, 1 * 2 == 3) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - // |MOJO_LOG_IF()| shouldn't evaluate its condition if the level is below the - // minimum. - MOJO_LOG_IF(INFO, NotCalledCondition()) << "hello"; - EXPECT_FALSE(not_called_condition_was_called()); - EXPECT_FALSE(log_message_was_called()); -} - -TEST_F(LoggingTest, Check) { - MOJO_CHECK(true) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - PtrToMemberHelper helper; - helper.member = 0; - int PtrToMemberHelper::*member_ptr = &PtrToMemberHelper::member; - - // Also try to make sure that we parenthesize the condition properly. - MOJO_CHECK(helper.*member_ptr == 1) << "hello"; - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_FATAL, last_log_level()); - // Different compilers have different ideas about the line number of a split - // line. - int line = __LINE__; - EXPECT_EQ(ExpectedLogMessage(line - 5, - "Check failed: helper.*member_ptr == 1. hello"), - last_message()); - - ResetMockLogger(); - - // Also test a "naked" |MOJO_CHECK()|s. - MOJO_CHECK(1 + 2 == 3); - EXPECT_FALSE(log_message_was_called()); -} - -TEST_F(LoggingTest, Dlog) { - // We start at |MOJO_LOG_LEVEL_INFO|. - MOJO_DLOG(VERBOSE) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_DLOG(INFO) << "hello"; -#ifdef NDEBUG - EXPECT_FALSE(log_message_was_called()); -#else - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 6, "hello"), last_message()); -#endif -} - -TEST_F(LoggingTest, DlogIf) { - // We start at |MOJO_LOG_LEVEL_INFO|. It shouldn't evaluate the condition in - // this case. - MOJO_DLOG_IF(VERBOSE, NotCalledCondition()) << "hello"; - EXPECT_FALSE(not_called_condition_was_called()); - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_DLOG_IF(INFO, 1 == 0) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_DLOG_IF(INFO, 1 == 1) << "hello"; -#ifdef NDEBUG - EXPECT_FALSE(log_message_was_called()); -#else - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 6, "hello"), last_message()); -#endif - - ResetMockLogger(); - -// |MOJO_DLOG_IF()| shouldn't compile its condition for non-debug builds. -#ifndef NDEBUG - bool debug_only = true; -#endif - MOJO_DLOG_IF(WARNING, debug_only) << "hello"; -#ifdef NDEBUG - EXPECT_FALSE(log_message_was_called()); -#else - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_WARNING, last_log_level()); - EXPECT_EQ(ExpectedLogMessage(__LINE__ - 6, "hello"), last_message()); -#endif -} - -TEST_F(LoggingTest, Dcheck) { - MOJO_DCHECK(true); - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - MOJO_DCHECK(true) << "hello"; - EXPECT_FALSE(log_message_was_called()); - - ResetMockLogger(); - - // |MOJO_DCHECK()| should compile (but not evaluate) its condition even for - // non-debug builds. (Hopefully, we'll get an unused variable error if it - // fails to compile the condition.) - bool was_called = false; - MOJO_DCHECK(DcheckTestHelper(&was_called)) << "hello"; -#ifdef NDEBUG - EXPECT_FALSE(was_called); - EXPECT_FALSE(log_message_was_called()); -#else - EXPECT_TRUE(was_called); - EXPECT_TRUE(log_message_was_called()); - EXPECT_EQ(MOJO_LOG_LEVEL_FATAL, last_log_level()); - // Different compilers have different ideas about the line number of a split - // line. - int line = __LINE__; - EXPECT_EQ( - ExpectedLogMessage(line - 10, - "Check failed: DcheckTestHelper(&was_called). hello"), - last_message()); -#endif - - ResetMockLogger(); - - // Also try to make sure that we parenthesize the condition properly. - bool x = true; - MOJO_DCHECK(false || x) << "hello"; - EXPECT_FALSE(log_message_was_called()); -} - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/system/BUILD.gn b/mojo/public/cpp/system/BUILD.gn deleted file mode 100644 index e120462..0000000 --- a/mojo/public/cpp/system/BUILD.gn +++ /dev/null @@ -1,19 +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. - -import("../../mojo_sdk.gni") - -mojo_sdk_source_set("system") { - sources = [ - "buffer.h", - "core.h", - "data_pipe.h", - "functions.h", - "handle.h", - "macros.h", - "message_pipe.h", - ] - - mojo_sdk_public_deps = [ "mojo/public/c/system" ] -} diff --git a/mojo/public/cpp/system/buffer.h b/mojo/public/cpp/system/buffer.h deleted file mode 100644 index 6817297..0000000 --- a/mojo/public/cpp/system/buffer.h +++ /dev/null @@ -1,112 +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_SYSTEM_BUFFER_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_BUFFER_H_ - -#include <assert.h> - -#include "mojo/public/c/system/buffer.h" -#include "mojo/public/cpp/system/handle.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// SharedBufferHandle ---------------------------------------------------------- - -class SharedBufferHandle : public Handle { - public: - SharedBufferHandle() {} - explicit SharedBufferHandle(MojoHandle value) : Handle(value) {} - - // Copying and assignment allowed. -}; - -static_assert(sizeof(SharedBufferHandle) == sizeof(Handle), - "Bad size for C++ SharedBufferHandle"); - -typedef ScopedHandleBase<SharedBufferHandle> ScopedSharedBufferHandle; -static_assert(sizeof(ScopedSharedBufferHandle) == sizeof(SharedBufferHandle), - "Bad size for C++ ScopedSharedBufferHandle"); - -inline MojoResult CreateSharedBuffer( - const MojoCreateSharedBufferOptions* options, - uint64_t num_bytes, - ScopedSharedBufferHandle* shared_buffer) { - assert(shared_buffer); - SharedBufferHandle handle; - MojoResult rv = - MojoCreateSharedBuffer(options, num_bytes, handle.mutable_value()); - // Reset even on failure (reduces the chances that a "stale"/incorrect handle - // will be used). - shared_buffer->reset(handle); - return rv; -} - -// TODO(vtl): This (and also the functions below) are templatized to allow for -// future/other buffer types. A bit "safer" would be to overload this function -// manually. (The template enforces that the in and out handles to be of the -// same type.) -template <class BufferHandleType> -inline MojoResult DuplicateBuffer( - BufferHandleType buffer, - const MojoDuplicateBufferHandleOptions* options, - ScopedHandleBase<BufferHandleType>* new_buffer) { - assert(new_buffer); - BufferHandleType handle; - MojoResult rv = MojoDuplicateBufferHandle( - buffer.value(), options, handle.mutable_value()); - // Reset even on failure (reduces the chances that a "stale"/incorrect handle - // will be used). - new_buffer->reset(handle); - return rv; -} - -template <class BufferHandleType> -inline MojoResult MapBuffer(BufferHandleType buffer, - uint64_t offset, - uint64_t num_bytes, - void** pointer, - MojoMapBufferFlags flags) { - assert(buffer.is_valid()); - return MojoMapBuffer(buffer.value(), offset, num_bytes, pointer, flags); -} - -inline MojoResult UnmapBuffer(void* pointer) { - assert(pointer); - return MojoUnmapBuffer(pointer); -} - -// A wrapper class that automatically creates a shared buffer and owns the -// handle. -class SharedBuffer { - public: - explicit SharedBuffer(uint64_t num_bytes); - SharedBuffer(uint64_t num_bytes, - const MojoCreateSharedBufferOptions& options); - ~SharedBuffer(); - - ScopedSharedBufferHandle handle; -}; - -inline SharedBuffer::SharedBuffer(uint64_t num_bytes) { - MojoResult result = CreateSharedBuffer(nullptr, num_bytes, &handle); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); -} - -inline SharedBuffer::SharedBuffer( - uint64_t num_bytes, - const MojoCreateSharedBufferOptions& options) { - MojoResult result = CreateSharedBuffer(&options, num_bytes, &handle); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); -} - -inline SharedBuffer::~SharedBuffer() { -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_SYSTEM_BUFFER_H_ diff --git a/mojo/public/cpp/system/core.h b/mojo/public/cpp/system/core.h deleted file mode 100644 index b08a5a6..0000000 --- a/mojo/public/cpp/system/core.h +++ /dev/null @@ -1,15 +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_SYSTEM_CORE_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_CORE_H_ - -#include "mojo/public/cpp/system/buffer.h" -#include "mojo/public/cpp/system/data_pipe.h" -#include "mojo/public/cpp/system/functions.h" -#include "mojo/public/cpp/system/handle.h" -#include "mojo/public/cpp/system/macros.h" -#include "mojo/public/cpp/system/message_pipe.h" - -#endif // MOJO_PUBLIC_CPP_SYSTEM_CORE_H_ diff --git a/mojo/public/cpp/system/data_pipe.h b/mojo/public/cpp/system/data_pipe.h deleted file mode 100644 index 5d3396c..0000000 --- a/mojo/public/cpp/system/data_pipe.h +++ /dev/null @@ -1,141 +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_SYSTEM_DATA_PIPE_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_DATA_PIPE_H_ - -#include <assert.h> - -#include "mojo/public/c/system/data_pipe.h" -#include "mojo/public/cpp/system/handle.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// DataPipeProducerHandle and DataPipeConsumerHandle --------------------------- - -class DataPipeProducerHandle : public Handle { - public: - DataPipeProducerHandle() {} - explicit DataPipeProducerHandle(MojoHandle value) : Handle(value) {} - - // Copying and assignment allowed. -}; - -static_assert(sizeof(DataPipeProducerHandle) == sizeof(Handle), - "Bad size for C++ DataPipeProducerHandle"); - -typedef ScopedHandleBase<DataPipeProducerHandle> ScopedDataPipeProducerHandle; -static_assert(sizeof(ScopedDataPipeProducerHandle) == - sizeof(DataPipeProducerHandle), - "Bad size for C++ ScopedDataPipeProducerHandle"); - -class DataPipeConsumerHandle : public Handle { - public: - DataPipeConsumerHandle() {} - explicit DataPipeConsumerHandle(MojoHandle value) : Handle(value) {} - - // Copying and assignment allowed. -}; - -static_assert(sizeof(DataPipeConsumerHandle) == sizeof(Handle), - "Bad size for C++ DataPipeConsumerHandle"); - -typedef ScopedHandleBase<DataPipeConsumerHandle> ScopedDataPipeConsumerHandle; -static_assert(sizeof(ScopedDataPipeConsumerHandle) == - sizeof(DataPipeConsumerHandle), - "Bad size for C++ ScopedDataPipeConsumerHandle"); - -inline MojoResult CreateDataPipe( - const MojoCreateDataPipeOptions* options, - ScopedDataPipeProducerHandle* data_pipe_producer, - ScopedDataPipeConsumerHandle* data_pipe_consumer) { - assert(data_pipe_producer); - assert(data_pipe_consumer); - DataPipeProducerHandle producer_handle; - DataPipeConsumerHandle consumer_handle; - MojoResult rv = MojoCreateDataPipe(options, - producer_handle.mutable_value(), - consumer_handle.mutable_value()); - // Reset even on failure (reduces the chances that a "stale"/incorrect handle - // will be used). - data_pipe_producer->reset(producer_handle); - data_pipe_consumer->reset(consumer_handle); - return rv; -} - -inline MojoResult WriteDataRaw(DataPipeProducerHandle data_pipe_producer, - const void* elements, - uint32_t* num_bytes, - MojoWriteDataFlags flags) { - return MojoWriteData(data_pipe_producer.value(), elements, num_bytes, flags); -} - -inline MojoResult BeginWriteDataRaw(DataPipeProducerHandle data_pipe_producer, - void** buffer, - uint32_t* buffer_num_bytes, - MojoWriteDataFlags flags) { - return MojoBeginWriteData( - data_pipe_producer.value(), buffer, buffer_num_bytes, flags); -} - -inline MojoResult EndWriteDataRaw(DataPipeProducerHandle data_pipe_producer, - uint32_t num_bytes_written) { - return MojoEndWriteData(data_pipe_producer.value(), num_bytes_written); -} - -inline MojoResult ReadDataRaw(DataPipeConsumerHandle data_pipe_consumer, - void* elements, - uint32_t* num_bytes, - MojoReadDataFlags flags) { - return MojoReadData(data_pipe_consumer.value(), elements, num_bytes, flags); -} - -inline MojoResult BeginReadDataRaw(DataPipeConsumerHandle data_pipe_consumer, - const void** buffer, - uint32_t* buffer_num_bytes, - MojoReadDataFlags flags) { - return MojoBeginReadData( - data_pipe_consumer.value(), buffer, buffer_num_bytes, flags); -} - -inline MojoResult EndReadDataRaw(DataPipeConsumerHandle data_pipe_consumer, - uint32_t num_bytes_read) { - return MojoEndReadData(data_pipe_consumer.value(), num_bytes_read); -} - -// A wrapper class that automatically creates a data pipe and owns both handles. -// TODO(vtl): Make an even more friendly version? (Maybe templatized for a -// particular type instead of some "element"? Maybe functions that take -// vectors?) -class DataPipe { - public: - DataPipe(); - explicit DataPipe(const MojoCreateDataPipeOptions& options); - ~DataPipe(); - - ScopedDataPipeProducerHandle producer_handle; - ScopedDataPipeConsumerHandle consumer_handle; -}; - -inline DataPipe::DataPipe() { - MojoResult result = - CreateDataPipe(nullptr, &producer_handle, &consumer_handle); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); -} - -inline DataPipe::DataPipe(const MojoCreateDataPipeOptions& options) { - MojoResult result = - CreateDataPipe(&options, &producer_handle, &consumer_handle); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); -} - -inline DataPipe::~DataPipe() { -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_SYSTEM_DATA_PIPE_H_ diff --git a/mojo/public/cpp/system/functions.h b/mojo/public/cpp/system/functions.h deleted file mode 100644 index d73d27a..0000000 --- a/mojo/public/cpp/system/functions.h +++ /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. - -#ifndef MOJO_PUBLIC_CPP_SYSTEM_FUNCTIONS_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_FUNCTIONS_H_ - -#include "mojo/public/c/system/functions.h" - -namespace mojo { - -// Standalone functions -------------------------------------------------------- - -inline MojoTimeTicks GetTimeTicksNow() { - return MojoGetTimeTicksNow(); -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_SYSTEM_FUNCTIONS_H_ diff --git a/mojo/public/cpp/system/handle.h b/mojo/public/cpp/system/handle.h deleted file mode 100644 index 0c5adc7..0000000 --- a/mojo/public/cpp/system/handle.h +++ /dev/null @@ -1,305 +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_SYSTEM_HANDLE_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_ - -#include <assert.h> -#include <limits> - -#include "mojo/public/c/system/functions.h" -#include "mojo/public/c/system/types.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// OVERVIEW -// -// |Handle| and |...Handle|: -// -// |Handle| is a simple, copyable wrapper for the C type |MojoHandle| (which is -// just an integer). Its purpose is to increase type-safety, not provide -// lifetime management. For the same purpose, we have trivial *subclasses* of -// |Handle|, e.g., |MessagePipeHandle| and |DataPipeProducerHandle|. |Handle| -// and its subclasses impose *no* extra overhead over using |MojoHandle|s -// directly. -// -// Note that though we provide constructors for |Handle|/|...Handle| from a -// |MojoHandle|, we do not provide, e.g., a constructor for |MessagePipeHandle| -// from a |Handle|. This is for type safety: If we did, you'd then be able to -// construct a |MessagePipeHandle| from, e.g., a |DataPipeProducerHandle| (since -// it's a |Handle|). -// -// |ScopedHandleBase| and |Scoped...Handle|: -// -// |ScopedHandleBase<HandleType>| is a templated scoped wrapper, for the handle -// types above (in the same sense that a C++11 |unique_ptr<T>| is a scoped -// wrapper for a |T*|). It provides lifetime management, closing its owned -// handle on destruction. It also provides (emulated) move semantics, again -// along the lines of C++11's |unique_ptr| (and exactly like Chromium's -// |scoped_ptr|). -// -// |ScopedHandle| is just (a typedef of) a |ScopedHandleBase<Handle>|. -// Similarly, |ScopedMessagePipeHandle| is just a -// |ScopedHandleBase<MessagePipeHandle>|. Etc. Note that a -// |ScopedMessagePipeHandle| is *not* a (subclass of) |ScopedHandle|. -// -// Wrapper functions: -// -// We provide simple wrappers for the |Mojo...()| functions (in -// mojo/public/c/system/core.h -- see that file for details on individual -// functions). -// -// The general guideline is functions that imply ownership transfer of a handle -// should take (or produce) an appropriate |Scoped...Handle|, while those that -// don't take a |...Handle|. For example, |CreateMessagePipe()| has two -// |ScopedMessagePipe| "out" parameters, whereas |Wait()| and |WaitMany()| take -// |Handle| parameters. Some, have both: e.g., |DuplicatedBuffer()| takes a -// suitable (unscoped) handle (e.g., |SharedBufferHandle|) "in" parameter and -// produces a suitable scoped handle (e.g., |ScopedSharedBufferHandle| a.k.a. -// |ScopedHandleBase<SharedBufferHandle>|) as an "out" parameter. -// -// An exception are some of the |...Raw()| functions. E.g., |CloseRaw()| takes a -// |Handle|, leaving the user to discard the handle. -// -// More significantly, |WriteMessageRaw()| exposes the full API complexity of -// |MojoWriteMessage()| (but doesn't require any extra overhead). It takes a raw -// array of |Handle|s as input, and takes ownership of them (i.e., invalidates -// them) on *success* (but not on failure). There are a number of reasons for -// this. First, C++03 |std::vector|s cannot contain the move-only -// |Scoped...Handle|s. Second, |std::vector|s impose extra overhead -// (necessitating heap-allocation of the buffer). Third, |std::vector|s wouldn't -// provide the desired level of flexibility/safety: a vector of handles would -// have to be all of the same type (probably |Handle|/|ScopedHandle|). Fourth, -// it's expected to not be used directly, but instead be used by generated -// bindings. -// -// Other |...Raw()| functions expose similar rough edges, e.g., dealing with raw -// pointers (and lengths) instead of taking |std::vector|s or similar. - -// ScopedHandleBase ------------------------------------------------------------ - -// Scoper for the actual handle types defined further below. It's move-only, -// like the C++11 |unique_ptr|. -template <class HandleType> -class ScopedHandleBase { - MOJO_MOVE_ONLY_TYPE(ScopedHandleBase) - - public: - ScopedHandleBase() {} - explicit ScopedHandleBase(HandleType handle) : handle_(handle) {} - ~ScopedHandleBase() { CloseIfNecessary(); } - - template <class CompatibleHandleType> - explicit ScopedHandleBase(ScopedHandleBase<CompatibleHandleType> other) - : handle_(other.release()) {} - - // Move-only constructor and operator=. - ScopedHandleBase(ScopedHandleBase&& other) : handle_(other.release()) {} - ScopedHandleBase& operator=(ScopedHandleBase&& other) { - if (&other != this) { - CloseIfNecessary(); - handle_ = other.release(); - } - return *this; - } - - const HandleType& get() const { return handle_; } - - template <typename PassedHandleType> - static ScopedHandleBase<HandleType> From( - ScopedHandleBase<PassedHandleType> other) { - static_assert( - sizeof(static_cast<PassedHandleType*>(static_cast<HandleType*>(0))), - "HandleType is not a subtype of PassedHandleType"); - return ScopedHandleBase<HandleType>( - static_cast<HandleType>(other.release().value())); - } - - void swap(ScopedHandleBase& other) { handle_.swap(other.handle_); } - - HandleType release() MOJO_WARN_UNUSED_RESULT { - HandleType rv; - rv.swap(handle_); - return rv; - } - - void reset(HandleType handle = HandleType()) { - CloseIfNecessary(); - handle_ = handle; - } - - bool is_valid() const { return handle_.is_valid(); } - - private: - void CloseIfNecessary() { - if (!handle_.is_valid()) - return; - MojoResult result = MojoClose(handle_.value()); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); - } - - HandleType handle_; -}; - -template <typename HandleType> -inline ScopedHandleBase<HandleType> MakeScopedHandle(HandleType handle) { - return ScopedHandleBase<HandleType>(handle); -} - -// Handle ---------------------------------------------------------------------- - -const MojoHandle kInvalidHandleValue = MOJO_HANDLE_INVALID; - -// Wrapper base class for |MojoHandle|. -class Handle { - public: - Handle() : value_(kInvalidHandleValue) {} - explicit Handle(MojoHandle value) : value_(value) {} - ~Handle() {} - - void swap(Handle& other) { - MojoHandle temp = value_; - value_ = other.value_; - other.value_ = temp; - } - - bool is_valid() const { return value_ != kInvalidHandleValue; } - - const MojoHandle& value() const { return value_; } - MojoHandle* mutable_value() { return &value_; } - void set_value(MojoHandle value) { value_ = value; } - - private: - MojoHandle value_; - - // Copying and assignment allowed. -}; - -// Should have zero overhead. -static_assert(sizeof(Handle) == sizeof(MojoHandle), "Bad size for C++ Handle"); - -// The scoper should also impose no more overhead. -typedef ScopedHandleBase<Handle> ScopedHandle; -static_assert(sizeof(ScopedHandle) == sizeof(Handle), - "Bad size for C++ ScopedHandle"); - -inline MojoResult Wait(Handle handle, - MojoHandleSignals signals, - MojoDeadline deadline, - MojoHandleSignalsState* signals_state) { - return MojoWait(handle.value(), signals, deadline, signals_state); -} - -const uint32_t kInvalidWaitManyIndexValue = static_cast<uint32_t>(-1); - -// Simplify the interpretation of the output from |MojoWaitMany()|. -class WaitManyResult { - public: - explicit WaitManyResult(MojoResult mojo_wait_many_result) - : result(mojo_wait_many_result), index(kInvalidWaitManyIndexValue) {} - - WaitManyResult(MojoResult mojo_wait_many_result, uint32_t result_index) - : result(mojo_wait_many_result), index(result_index) {} - - // A valid handle index is always returned if |WaitMany()| succeeds, but may - // or may not be returned if |WaitMany()| returns an error. Use this helper - // function to check if |index| is a valid index into the handle array. - bool IsIndexValid() const { return index != kInvalidWaitManyIndexValue; } - - // The |signals_states| array is always returned by |WaitMany()| on success, - // but may or may not be returned if |WaitMany()| returns an error. Use this - // helper function to check if |signals_states| holds valid data. - bool AreSignalsStatesValid() const { - return result != MOJO_RESULT_INVALID_ARGUMENT && - result != MOJO_RESULT_RESOURCE_EXHAUSTED; - } - - MojoResult result; - uint32_t index; -}; - -// |HandleVectorType| and |FlagsVectorType| should be similar enough to -// |std::vector<Handle>| and |std::vector<MojoHandleSignals>|, respectively: -// - They should have a (const) |size()| method that returns an unsigned type. -// - They must provide contiguous storage, with access via (const) reference to -// that storage provided by a (const) |operator[]()| (by reference). -template <class HandleVectorType, - class FlagsVectorType, - class SignalsStateVectorType> -inline WaitManyResult WaitMany(const HandleVectorType& handles, - const FlagsVectorType& signals, - MojoDeadline deadline, - SignalsStateVectorType* signals_states) { - if (signals.size() != handles.size() || - (signals_states && signals_states->size() != signals.size())) - return WaitManyResult(MOJO_RESULT_INVALID_ARGUMENT); - if (handles.size() >= kInvalidWaitManyIndexValue) - return WaitManyResult(MOJO_RESULT_RESOURCE_EXHAUSTED); - - if (handles.size() == 0) { - return WaitManyResult( - MojoWaitMany(nullptr, nullptr, 0, deadline, nullptr, nullptr)); - } - - uint32_t result_index = kInvalidWaitManyIndexValue; - const Handle& first_handle = handles[0]; - const MojoHandleSignals& first_signals = signals[0]; - MojoHandleSignalsState* first_state = - signals_states ? &(*signals_states)[0] : nullptr; - MojoResult result = - MojoWaitMany(reinterpret_cast<const MojoHandle*>(&first_handle), - &first_signals, static_cast<uint32_t>(handles.size()), - deadline, &result_index, first_state); - return WaitManyResult(result, result_index); -} - -// C++ 4.10, regarding pointer conversion, says that an integral null pointer -// constant can be converted to |std::nullptr_t| (which is a typedef for -// |decltype(nullptr)|). The opposite direction is not allowed. -template <class HandleVectorType, class FlagsVectorType> -inline WaitManyResult WaitMany(const HandleVectorType& handles, - const FlagsVectorType& signals, - MojoDeadline deadline, - decltype(nullptr) signals_states) { - if (signals.size() != handles.size()) - return WaitManyResult(MOJO_RESULT_INVALID_ARGUMENT); - if (handles.size() >= kInvalidWaitManyIndexValue) - return WaitManyResult(MOJO_RESULT_RESOURCE_EXHAUSTED); - - if (handles.size() == 0) { - return WaitManyResult( - MojoWaitMany(nullptr, nullptr, 0, deadline, nullptr, nullptr)); - } - - uint32_t result_index = kInvalidWaitManyIndexValue; - const Handle& first_handle = handles[0]; - const MojoHandleSignals& first_signals = signals[0]; - MojoResult result = MojoWaitMany( - reinterpret_cast<const MojoHandle*>(&first_handle), &first_signals, - static_cast<uint32_t>(handles.size()), deadline, &result_index, nullptr); - return WaitManyResult(result, result_index); -} - -// |Close()| takes ownership of the handle, since it'll invalidate it. -// Note: There's nothing to do, since the argument will be destroyed when it -// goes out of scope. -template <class HandleType> -inline void Close(ScopedHandleBase<HandleType> /*handle*/) { -} - -// Most users should typically use |Close()| (above) instead. -inline MojoResult CloseRaw(Handle handle) { - return MojoClose(handle.value()); -} - -// Strict weak ordering, so that |Handle|s can be used as keys in |std::map|s, -inline bool operator<(const Handle a, const Handle b) { - return a.value() < b.value(); -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_ diff --git a/mojo/public/cpp/system/macros.h b/mojo/public/cpp/system/macros.h deleted file mode 100644 index f2bd0bc..0000000 --- a/mojo/public/cpp/system/macros.h +++ /dev/null @@ -1,45 +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_SYSTEM_MACROS_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_MACROS_H_ - -#include "mojo/public/c/system/macros.h" - -// Define a set of C++ specific macros. -// Mojo C++ API users can assume that mojo/public/cpp/system/macros.h -// includes mojo/public/c/system/macros.h. - -// A macro to disallow the copy constructor and operator= functions. -// This should be used in the private: declarations for a class. -#define MOJO_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - void operator=(const TypeName&) - -// Used to calculate the number of elements in an array. -// (See |arraysize()| in Chromium's base/basictypes.h for more details.) -namespace mojo { -template <typename T, size_t N> -char(&ArraySizeHelper(T(&array)[N]))[N]; -#if !defined(_MSC_VER) -template <typename T, size_t N> -char(&ArraySizeHelper(const T(&array)[N]))[N]; -#endif -} // namespace mojo -#define MOJO_ARRAYSIZE(array) (sizeof(::mojo::ArraySizeHelper(array))) - -// Used to make a type move-only. See Chromium's base/move.h for more -// details. The MoveOnlyTypeForCPP03 typedef is for Chromium's base/callback to -// tell that this type is move-only. -#define MOJO_MOVE_ONLY_TYPE(type) \ - private: \ - type(type&); \ - void operator=(type&); \ - \ - public: \ - type&& Pass() MOJO_WARN_UNUSED_RESULT { return static_cast<type&&>(*this); } \ - typedef void MoveOnlyTypeForCPP03; \ - \ - private: -#endif // MOJO_PUBLIC_CPP_SYSTEM_MACROS_H_ diff --git a/mojo/public/cpp/system/message_pipe.h b/mojo/public/cpp/system/message_pipe.h deleted file mode 100644 index b41469e..0000000 --- a/mojo/public/cpp/system/message_pipe.h +++ /dev/null @@ -1,101 +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_SYSTEM_MESSAGE_PIPE_H_ -#define MOJO_PUBLIC_CPP_SYSTEM_MESSAGE_PIPE_H_ - -#include <assert.h> - -#include "mojo/public/c/system/message_pipe.h" -#include "mojo/public/cpp/system/handle.h" -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// MessagePipeHandle ----------------------------------------------------------- - -class MessagePipeHandle : public Handle { - public: - MessagePipeHandle() {} - explicit MessagePipeHandle(MojoHandle value) : Handle(value) {} - - // Copying and assignment allowed. -}; - -static_assert(sizeof(MessagePipeHandle) == sizeof(Handle), - "Bad size for C++ MessagePipeHandle"); - -typedef ScopedHandleBase<MessagePipeHandle> ScopedMessagePipeHandle; -static_assert(sizeof(ScopedMessagePipeHandle) == sizeof(MessagePipeHandle), - "Bad size for C++ ScopedMessagePipeHandle"); - -inline MojoResult CreateMessagePipe(const MojoCreateMessagePipeOptions* options, - ScopedMessagePipeHandle* message_pipe0, - ScopedMessagePipeHandle* message_pipe1) { - assert(message_pipe0); - assert(message_pipe1); - MessagePipeHandle handle0; - MessagePipeHandle handle1; - MojoResult rv = MojoCreateMessagePipe( - options, handle0.mutable_value(), handle1.mutable_value()); - // Reset even on failure (reduces the chances that a "stale"/incorrect handle - // will be used). - message_pipe0->reset(handle0); - message_pipe1->reset(handle1); - return rv; -} - -// These "raw" versions fully expose the underlying API, but don't help with -// ownership of handles (especially when writing messages). -// TODO(vtl): Write "baked" versions. -inline MojoResult WriteMessageRaw(MessagePipeHandle message_pipe, - const void* bytes, - uint32_t num_bytes, - const MojoHandle* handles, - uint32_t num_handles, - MojoWriteMessageFlags flags) { - return MojoWriteMessage( - message_pipe.value(), bytes, num_bytes, handles, num_handles, flags); -} - -inline MojoResult ReadMessageRaw(MessagePipeHandle message_pipe, - void* bytes, - uint32_t* num_bytes, - MojoHandle* handles, - uint32_t* num_handles, - MojoReadMessageFlags flags) { - return MojoReadMessage( - message_pipe.value(), bytes, num_bytes, handles, num_handles, flags); -} - -// A wrapper class that automatically creates a message pipe and owns both -// handles. -class MessagePipe { - public: - MessagePipe(); - explicit MessagePipe(const MojoCreateMessagePipeOptions& options); - ~MessagePipe(); - - ScopedMessagePipeHandle handle0; - ScopedMessagePipeHandle handle1; -}; - -inline MessagePipe::MessagePipe() { - MojoResult result = CreateMessagePipe(nullptr, &handle0, &handle1); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); -} - -inline MessagePipe::MessagePipe(const MojoCreateMessagePipeOptions& options) { - MojoResult result = CreateMessagePipe(&options, &handle0, &handle1); - MOJO_ALLOW_UNUSED_LOCAL(result); - assert(result == MOJO_RESULT_OK); -} - -inline MessagePipe::~MessagePipe() { -} - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_SYSTEM_MESSAGE_PIPE_H_ diff --git a/mojo/public/cpp/system/tests/BUILD.gn b/mojo/public/cpp/system/tests/BUILD.gn deleted file mode 100644 index 7a5b7ed..0000000 --- a/mojo/public/cpp/system/tests/BUILD.gn +++ /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. - -import("../../../mojo_sdk.gni") - -mojo_sdk_source_set("tests") { - testonly = true - - sources = [ - "core_unittest.cc", - "macros_unittest.cc", - ] - - deps = [ - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/c/system/tests", - "mojo/public/cpp/system", - "mojo/public/cpp/test_support:test_utils", - ] -} diff --git a/mojo/public/cpp/system/tests/core_unittest.cc b/mojo/public/cpp/system/tests/core_unittest.cc deleted file mode 100644 index 4dcad43..0000000 --- a/mojo/public/cpp/system/tests/core_unittest.cc +++ /dev/null @@ -1,495 +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. - -// This file tests the C++ Mojo system core wrappers. -// TODO(vtl): Maybe rename "CoreCppTest" -> "CoreTest" if/when this gets -// compiled into a different binary from the C API tests. - -#include "mojo/public/cpp/system/core.h" - -#include <stddef.h> - -#include <map> - -#include "mojo/public/cpp/system/macros.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -const MojoHandleSignals kSignalReadableWritable = - MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE; - -const MojoHandleSignals kSignalAll = MOJO_HANDLE_SIGNAL_READABLE | - MOJO_HANDLE_SIGNAL_WRITABLE | - MOJO_HANDLE_SIGNAL_PEER_CLOSED; - -TEST(CoreCppTest, GetTimeTicksNow) { - const MojoTimeTicks start = GetTimeTicksNow(); - EXPECT_NE(static_cast<MojoTimeTicks>(0), start) - << "GetTimeTicksNow should return nonzero value"; -} - -TEST(CoreCppTest, Basic) { - // Basic |Handle| implementation: - { - EXPECT_EQ(MOJO_HANDLE_INVALID, kInvalidHandleValue); - - Handle h0; - EXPECT_EQ(kInvalidHandleValue, h0.value()); - EXPECT_EQ(kInvalidHandleValue, *h0.mutable_value()); - EXPECT_FALSE(h0.is_valid()); - - Handle h1(static_cast<MojoHandle>(123)); - EXPECT_EQ(static_cast<MojoHandle>(123), h1.value()); - EXPECT_EQ(static_cast<MojoHandle>(123), *h1.mutable_value()); - EXPECT_TRUE(h1.is_valid()); - *h1.mutable_value() = static_cast<MojoHandle>(456); - EXPECT_EQ(static_cast<MojoHandle>(456), h1.value()); - EXPECT_TRUE(h1.is_valid()); - - h1.swap(h0); - EXPECT_EQ(static_cast<MojoHandle>(456), h0.value()); - EXPECT_TRUE(h0.is_valid()); - EXPECT_FALSE(h1.is_valid()); - - h1.set_value(static_cast<MojoHandle>(789)); - h0.swap(h1); - EXPECT_EQ(static_cast<MojoHandle>(789), h0.value()); - EXPECT_TRUE(h0.is_valid()); - EXPECT_EQ(static_cast<MojoHandle>(456), h1.value()); - EXPECT_TRUE(h1.is_valid()); - - // Make sure copy constructor works. - Handle h2(h0); - EXPECT_EQ(static_cast<MojoHandle>(789), h2.value()); - // And assignment. - h2 = h1; - EXPECT_EQ(static_cast<MojoHandle>(456), h2.value()); - - // Make sure that we can put |Handle|s into |std::map|s. - h0 = Handle(static_cast<MojoHandle>(987)); - h1 = Handle(static_cast<MojoHandle>(654)); - h2 = Handle(static_cast<MojoHandle>(321)); - Handle h3; - std::map<Handle, int> handle_to_int; - handle_to_int[h0] = 0; - handle_to_int[h1] = 1; - handle_to_int[h2] = 2; - handle_to_int[h3] = 3; - - EXPECT_EQ(4u, handle_to_int.size()); - EXPECT_FALSE(handle_to_int.find(h0) == handle_to_int.end()); - EXPECT_EQ(0, handle_to_int[h0]); - EXPECT_FALSE(handle_to_int.find(h1) == handle_to_int.end()); - EXPECT_EQ(1, handle_to_int[h1]); - EXPECT_FALSE(handle_to_int.find(h2) == handle_to_int.end()); - EXPECT_EQ(2, handle_to_int[h2]); - EXPECT_FALSE(handle_to_int.find(h3) == handle_to_int.end()); - EXPECT_EQ(3, handle_to_int[h3]); - EXPECT_TRUE(handle_to_int.find(Handle(static_cast<MojoHandle>(13579))) == - handle_to_int.end()); - - // TODO(vtl): With C++11, support |std::unordered_map|s, etc. (Or figure out - // how to support the variations of |hash_map|.) - } - - // |Handle|/|ScopedHandle| functions: - { - ScopedHandle h; - - EXPECT_EQ(kInvalidHandleValue, h.get().value()); - - // This should be a no-op. - Close(h.Pass()); - - // It should still be invalid. - EXPECT_EQ(kInvalidHandleValue, h.get().value()); - - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, - Wait(h.get(), ~MOJO_HANDLE_SIGNAL_NONE, 1000000, nullptr)); - - std::vector<Handle> wh; - wh.push_back(h.get()); - std::vector<MojoHandleSignals> sigs; - sigs.push_back(~MOJO_HANDLE_SIGNAL_NONE); - WaitManyResult wait_many_result = - WaitMany(wh, sigs, MOJO_DEADLINE_INDEFINITE, nullptr); - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, wait_many_result.result); - EXPECT_TRUE(wait_many_result.IsIndexValid()); - EXPECT_FALSE(wait_many_result.AreSignalsStatesValid()); - - // Make sure that our specialized template correctly handles |NULL| as well - // as |nullptr|. - wait_many_result = WaitMany(wh, sigs, MOJO_DEADLINE_INDEFINITE, NULL); - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, wait_many_result.result); - EXPECT_EQ(0u, wait_many_result.index); - EXPECT_TRUE(wait_many_result.IsIndexValid()); - EXPECT_FALSE(wait_many_result.AreSignalsStatesValid()); - } - - // |MakeScopedHandle| (just compilation tests): - { - EXPECT_FALSE(MakeScopedHandle(Handle()).is_valid()); - EXPECT_FALSE(MakeScopedHandle(MessagePipeHandle()).is_valid()); - EXPECT_FALSE(MakeScopedHandle(DataPipeProducerHandle()).is_valid()); - EXPECT_FALSE(MakeScopedHandle(DataPipeConsumerHandle()).is_valid()); - EXPECT_FALSE(MakeScopedHandle(SharedBufferHandle()).is_valid()); - } - - // |MessagePipeHandle|/|ScopedMessagePipeHandle| functions: - { - MessagePipeHandle h_invalid; - EXPECT_FALSE(h_invalid.is_valid()); - EXPECT_EQ( - MOJO_RESULT_INVALID_ARGUMENT, - WriteMessageRaw( - h_invalid, nullptr, 0, nullptr, 0, MOJO_WRITE_MESSAGE_FLAG_NONE)); - char buffer[10] = {0}; - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, - WriteMessageRaw(h_invalid, - buffer, - sizeof(buffer), - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, - ReadMessageRaw(h_invalid, - nullptr, - nullptr, - nullptr, - nullptr, - MOJO_READ_MESSAGE_FLAG_NONE)); - uint32_t buffer_size = static_cast<uint32_t>(sizeof(buffer)); - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, - ReadMessageRaw(h_invalid, - buffer, - &buffer_size, - nullptr, - nullptr, - MOJO_READ_MESSAGE_FLAG_NONE)); - - // Basic tests of waiting and closing. - MojoHandle hv0 = kInvalidHandleValue; - { - ScopedMessagePipeHandle h0; - ScopedMessagePipeHandle h1; - EXPECT_FALSE(h0.get().is_valid()); - EXPECT_FALSE(h1.get().is_valid()); - - CreateMessagePipe(nullptr, &h0, &h1); - EXPECT_TRUE(h0.get().is_valid()); - EXPECT_TRUE(h1.get().is_valid()); - EXPECT_NE(h0.get().value(), h1.get().value()); - // Save the handle values, so we can check that things got closed - // correctly. - hv0 = h0.get().value(); - MojoHandle hv1 = h1.get().value(); - MojoHandleSignalsState state; - - EXPECT_EQ(MOJO_RESULT_DEADLINE_EXCEEDED, - Wait(h0.get(), MOJO_HANDLE_SIGNAL_READABLE, 0, &state)); - - EXPECT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, state.satisfied_signals); - EXPECT_EQ(kSignalAll, state.satisfiable_signals); - - std::vector<Handle> wh; - wh.push_back(h0.get()); - wh.push_back(h1.get()); - std::vector<MojoHandleSignals> sigs; - sigs.push_back(MOJO_HANDLE_SIGNAL_READABLE); - sigs.push_back(MOJO_HANDLE_SIGNAL_WRITABLE); - std::vector<MojoHandleSignalsState> states(sigs.size()); - WaitManyResult wait_many_result = WaitMany(wh, sigs, 1000, &states); - EXPECT_EQ(MOJO_RESULT_OK, wait_many_result.result); - EXPECT_EQ(1u, wait_many_result.index); - EXPECT_TRUE(wait_many_result.IsIndexValid()); - EXPECT_TRUE(wait_many_result.AreSignalsStatesValid()); - EXPECT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, states[0].satisfied_signals); - EXPECT_EQ(kSignalAll, states[0].satisfiable_signals); - EXPECT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, states[1].satisfied_signals); - EXPECT_EQ(kSignalAll, states[1].satisfiable_signals); - - // Test closing |h1| explicitly. - Close(h1.Pass()); - EXPECT_FALSE(h1.get().is_valid()); - - // Make sure |h1| is closed. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, - Wait(Handle(hv1), ~MOJO_HANDLE_SIGNAL_NONE, - MOJO_DEADLINE_INDEFINITE, nullptr)); - - EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, - Wait(h0.get(), MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, &state)); - - EXPECT_EQ(MOJO_HANDLE_SIGNAL_PEER_CLOSED, state.satisfied_signals); - EXPECT_EQ(MOJO_HANDLE_SIGNAL_PEER_CLOSED, state.satisfiable_signals); - } - // |hv0| should have been closed when |h0| went out of scope, so this close - // should fail. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(hv0)); - - // Actually test writing/reading messages. - { - ScopedMessagePipeHandle h0; - ScopedMessagePipeHandle h1; - CreateMessagePipe(nullptr, &h0, &h1); - - const char kHello[] = "hello"; - const uint32_t kHelloSize = static_cast<uint32_t>(sizeof(kHello)); - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h0.get(), - kHello, - kHelloSize, - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - - MojoHandleSignalsState state; - EXPECT_EQ(MOJO_RESULT_OK, Wait(h1.get(), MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, &state)); - EXPECT_EQ(kSignalReadableWritable, state.satisfied_signals); - EXPECT_EQ(kSignalAll, state.satisfiable_signals); - - char buffer[10] = {0}; - uint32_t buffer_size = static_cast<uint32_t>(sizeof(buffer)); - EXPECT_EQ(MOJO_RESULT_OK, - ReadMessageRaw(h1.get(), - buffer, - &buffer_size, - nullptr, - nullptr, - MOJO_READ_MESSAGE_FLAG_NONE)); - EXPECT_EQ(kHelloSize, buffer_size); - EXPECT_STREQ(kHello, buffer); - - // Send a handle over the previously-establish message pipe. Use the - // |MessagePipe| wrapper (to test it), which automatically creates a - // message pipe. - MessagePipe mp; - - // Write a message to |mp.handle0|, before we send |mp.handle1|. - const char kWorld[] = "world!"; - const uint32_t kWorldSize = static_cast<uint32_t>(sizeof(kWorld)); - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(mp.handle0.get(), - kWorld, - kWorldSize, - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - - // Send |mp.handle1| over |h1| to |h0|. - MojoHandle handles[5]; - handles[0] = mp.handle1.release().value(); - EXPECT_NE(kInvalidHandleValue, handles[0]); - EXPECT_FALSE(mp.handle1.get().is_valid()); - uint32_t handles_count = 1; - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h1.get(), - kHello, - kHelloSize, - handles, - handles_count, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - // |handles[0]| should actually be invalid now. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(handles[0])); - - // Read "hello" and the sent handle. - EXPECT_EQ(MOJO_RESULT_OK, Wait(h0.get(), MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, &state)); - EXPECT_EQ(kSignalReadableWritable, state.satisfied_signals); - EXPECT_EQ(kSignalAll, state.satisfiable_signals); - - memset(buffer, 0, sizeof(buffer)); - buffer_size = static_cast<uint32_t>(sizeof(buffer)); - for (size_t i = 0; i < MOJO_ARRAYSIZE(handles); i++) - handles[i] = kInvalidHandleValue; - handles_count = static_cast<uint32_t>(MOJO_ARRAYSIZE(handles)); - EXPECT_EQ(MOJO_RESULT_OK, - ReadMessageRaw(h0.get(), - buffer, - &buffer_size, - handles, - &handles_count, - MOJO_READ_MESSAGE_FLAG_NONE)); - EXPECT_EQ(kHelloSize, buffer_size); - EXPECT_STREQ(kHello, buffer); - EXPECT_EQ(1u, handles_count); - EXPECT_NE(kInvalidHandleValue, handles[0]); - - // Read from the sent/received handle. - mp.handle1.reset(MessagePipeHandle(handles[0])); - // Save |handles[0]| to check that it gets properly closed. - hv0 = handles[0]; - - EXPECT_EQ(MOJO_RESULT_OK, - Wait(mp.handle1.get(), MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, &state)); - EXPECT_EQ(kSignalReadableWritable, state.satisfied_signals); - EXPECT_EQ(kSignalAll, state.satisfiable_signals); - - memset(buffer, 0, sizeof(buffer)); - buffer_size = static_cast<uint32_t>(sizeof(buffer)); - for (size_t i = 0; i < MOJO_ARRAYSIZE(handles); i++) - handles[i] = kInvalidHandleValue; - handles_count = static_cast<uint32_t>(MOJO_ARRAYSIZE(handles)); - EXPECT_EQ(MOJO_RESULT_OK, - ReadMessageRaw(mp.handle1.get(), - buffer, - &buffer_size, - handles, - &handles_count, - MOJO_READ_MESSAGE_FLAG_NONE)); - EXPECT_EQ(kWorldSize, buffer_size); - EXPECT_STREQ(kWorld, buffer); - EXPECT_EQ(0u, handles_count); - } - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(hv0)); - } - - // TODO(vtl): Test |CloseRaw()|. - // TODO(vtl): Test |reset()| more thoroughly? -} - -TEST(CoreCppTest, TearDownWithMessagesEnqueued) { - // Tear down a message pipe which still has a message enqueued, with the - // message also having a valid message pipe handle. - { - ScopedMessagePipeHandle h0; - ScopedMessagePipeHandle h1; - CreateMessagePipe(nullptr, &h0, &h1); - - // Send a handle over the previously-establish message pipe. - ScopedMessagePipeHandle h2; - ScopedMessagePipeHandle h3; - CreateMessagePipe(nullptr, &h2, &h3); - - // Write a message to |h2|, before we send |h3|. - const char kWorld[] = "world!"; - const uint32_t kWorldSize = static_cast<uint32_t>(sizeof(kWorld)); - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h2.get(), - kWorld, - kWorldSize, - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - // And also a message to |h3|. - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h3.get(), - kWorld, - kWorldSize, - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - - // Send |h3| over |h1| to |h0|. - const char kHello[] = "hello"; - const uint32_t kHelloSize = static_cast<uint32_t>(sizeof(kHello)); - MojoHandle h3_value; - h3_value = h3.release().value(); - EXPECT_NE(kInvalidHandleValue, h3_value); - EXPECT_FALSE(h3.get().is_valid()); - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h1.get(), - kHello, - kHelloSize, - &h3_value, - 1, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - // |h3_value| should actually be invalid now. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(h3_value)); - - EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h0.release().value())); - EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h1.release().value())); - EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h2.release().value())); - } - - // Do this in a different order: make the enqueued message pipe handle only - // half-alive. - { - ScopedMessagePipeHandle h0; - ScopedMessagePipeHandle h1; - CreateMessagePipe(nullptr, &h0, &h1); - - // Send a handle over the previously-establish message pipe. - ScopedMessagePipeHandle h2; - ScopedMessagePipeHandle h3; - CreateMessagePipe(nullptr, &h2, &h3); - - // Write a message to |h2|, before we send |h3|. - const char kWorld[] = "world!"; - const uint32_t kWorldSize = static_cast<uint32_t>(sizeof(kWorld)); - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h2.get(), - kWorld, - kWorldSize, - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - // And also a message to |h3|. - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h3.get(), - kWorld, - kWorldSize, - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - - // Send |h3| over |h1| to |h0|. - const char kHello[] = "hello"; - const uint32_t kHelloSize = static_cast<uint32_t>(sizeof(kHello)); - MojoHandle h3_value; - h3_value = h3.release().value(); - EXPECT_NE(kInvalidHandleValue, h3_value); - EXPECT_FALSE(h3.get().is_valid()); - EXPECT_EQ(MOJO_RESULT_OK, - WriteMessageRaw(h1.get(), - kHello, - kHelloSize, - &h3_value, - 1, - MOJO_WRITE_MESSAGE_FLAG_NONE)); - // |h3_value| should actually be invalid now. - EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(h3_value)); - - EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h2.release().value())); - EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h0.release().value())); - EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h1.release().value())); - } -} - -TEST(CoreCppTest, ScopedHandleMoveCtor) { - ScopedSharedBufferHandle buffer1; - EXPECT_EQ(MOJO_RESULT_OK, CreateSharedBuffer(nullptr, 1024, &buffer1)); - EXPECT_TRUE(buffer1.is_valid()); - - ScopedSharedBufferHandle buffer2; - EXPECT_EQ(MOJO_RESULT_OK, CreateSharedBuffer(nullptr, 1024, &buffer2)); - EXPECT_TRUE(buffer2.is_valid()); - - // If this fails to close buffer1, ScopedHandleBase::CloseIfNecessary() will - // assert. - buffer1 = buffer2.Pass(); - - EXPECT_TRUE(buffer1.is_valid()); - EXPECT_FALSE(buffer2.is_valid()); -} - -TEST(CoreCppTest, ScopedHandleMoveCtorSelf) { - ScopedSharedBufferHandle buffer1; - EXPECT_EQ(MOJO_RESULT_OK, CreateSharedBuffer(nullptr, 1024, &buffer1)); - EXPECT_TRUE(buffer1.is_valid()); - - buffer1 = buffer1.Pass(); - - EXPECT_TRUE(buffer1.is_valid()); -} - -// TODO(vtl): Write data pipe tests. - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/system/tests/macros_unittest.cc b/mojo/public/cpp/system/tests/macros_unittest.cc deleted file mode 100644 index 27a61bd..0000000 --- a/mojo/public/cpp/system/tests/macros_unittest.cc +++ /dev/null @@ -1,128 +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. - -// This file tests the C++ Mojo system macros and consists of "positive" tests, -// i.e., those verifying that things work (without compile errors, or even -// warnings if warnings are treated as errors). -// TODO(vtl): Maybe rename "MacrosCppTest" -> "MacrosTest" if/when this gets -// compiled into a different binary from the C API tests. -// TODO(vtl): Fix no-compile tests (which are all disabled; crbug.com/105388) -// and write some "negative" tests. - -#include "mojo/public/cpp/system/macros.h" - -#include <assert.h> -#include <stdint.h> -#include <stdlib.h> - -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -// Note: MSVS is very strict (and arguably buggy) about warnings for classes -// defined in a local scope, so define these globally. -struct TestOverrideBaseClass { - virtual ~TestOverrideBaseClass() {} - virtual void ToBeOverridden() {} - virtual void AlsoToBeOverridden() = 0; -}; - -struct TestOverrideSubclass : public TestOverrideBaseClass { - ~TestOverrideSubclass() override {} - void ToBeOverridden() override {} - void AlsoToBeOverridden() override {} -}; - -TEST(MacrosCppTest, Override) { - TestOverrideSubclass x; - x.ToBeOverridden(); - x.AlsoToBeOverridden(); -} - -// Note: MSVS is very strict (and arguably buggy) about warnings for classes -// defined in a local scope, so define these globally. -class TestDisallowCopyAndAssignClass { - public: - TestDisallowCopyAndAssignClass() {} - explicit TestDisallowCopyAndAssignClass(int) {} - void NoOp() {} - - private: - MOJO_DISALLOW_COPY_AND_ASSIGN(TestDisallowCopyAndAssignClass); -}; - -TEST(MacrosCppTest, DisallowCopyAndAssign) { - TestDisallowCopyAndAssignClass x; - x.NoOp(); - TestDisallowCopyAndAssignClass y(789); - y.NoOp(); -} - -// Test that |MOJO_ARRAYSIZE()| works in a |static_assert()|. -const int kGlobalArray[5] = {1, 2, 3, 4, 5}; -static_assert(MOJO_ARRAYSIZE(kGlobalArray) == 5u, - "MOJO_ARRAY_SIZE() failed in static_assert()"); - -TEST(MacrosCppTest, ArraySize) { - double local_array[4] = {6.7, 7.8, 8.9, 9.0}; - // MSVS considers this local variable unused since MOJO_ARRAYSIZE only takes - // the size of the type of the local and not the values itself. - MOJO_ALLOW_UNUSED_LOCAL(local_array); - EXPECT_EQ(4u, MOJO_ARRAYSIZE(local_array)); -} - -// Note: MSVS is very strict (and arguably buggy) about warnings for classes -// defined in a local scope, so define these globally. -class MoveOnlyInt { - MOJO_MOVE_ONLY_TYPE(MoveOnlyInt) - - public: - MoveOnlyInt() : is_set_(false), value_() {} - explicit MoveOnlyInt(int value) : is_set_(true), value_(value) {} - ~MoveOnlyInt() {} - - // Move-only constructor and operator=. - MoveOnlyInt(MoveOnlyInt&& other) { *this = other.Pass(); } - MoveOnlyInt& operator=(MoveOnlyInt&& other) { - if (&other != this) { - is_set_ = other.is_set_; - value_ = other.value_; - other.is_set_ = false; - } - return *this; - } - - int value() const { - assert(is_set()); - return value_; - } - bool is_set() const { return is_set_; } - - private: - bool is_set_; - int value_; -}; - -TEST(MacrosCppTest, MoveOnlyTypeForCpp03) { - MoveOnlyInt x(123); - EXPECT_TRUE(x.is_set()); - EXPECT_EQ(123, x.value()); - MoveOnlyInt y; - EXPECT_FALSE(y.is_set()); - y = x.Pass(); - EXPECT_FALSE(x.is_set()); - EXPECT_TRUE(y.is_set()); - EXPECT_EQ(123, y.value()); - MoveOnlyInt z(y.Pass()); - EXPECT_FALSE(y.is_set()); - EXPECT_TRUE(z.is_set()); - EXPECT_EQ(123, z.value()); - z = z.Pass(); - EXPECT_TRUE(z.is_set()); - EXPECT_EQ(123, z.value()); -} - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/test_support/BUILD.gn b/mojo/public/cpp/test_support/BUILD.gn deleted file mode 100644 index a1f7d31..0000000 --- a/mojo/public/cpp/test_support/BUILD.gn +++ /dev/null @@ -1,25 +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. - -import("../../mojo_sdk.gni") - -# GYP version: mojo/public/mojo_public.gyp:mojo_public_test_utils -mojo_sdk_source_set("test_utils") { - testonly = true - - sources = [ - "lib/test_support.cc", - "lib/test_utils.cc", - "test_utils.h", - ] - - deps = [ - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/c/test_support", - "mojo/public/cpp/system", - ] -} diff --git a/mojo/public/cpp/test_support/DEPS b/mojo/public/cpp/test_support/DEPS deleted file mode 100644 index 6dc5394..0000000 --- a/mojo/public/cpp/test_support/DEPS +++ /dev/null @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/public/c/test_support", -] diff --git a/mojo/public/cpp/test_support/lib/test_support.cc b/mojo/public/cpp/test_support/lib/test_support.cc deleted file mode 100644 index 0b6035b..0000000 --- a/mojo/public/cpp/test_support/lib/test_support.cc +++ /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. - -#include "mojo/public/cpp/test_support/test_support.h" - -#include <stdlib.h> - -namespace mojo { -namespace test { - -std::vector<std::string> EnumerateSourceRootRelativeDirectory( - const std::string& relative_path) { - char** names = MojoTestSupportEnumerateSourceRootRelativeDirectory( - relative_path.c_str()); - std::vector<std::string> results; - for (char** ptr = names; *ptr != nullptr; ++ptr) { - results.push_back(*ptr); - free(*ptr); - } - free(names); - return results; -} - -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/test_support/lib/test_utils.cc b/mojo/public/cpp/test_support/lib/test_utils.cc deleted file mode 100644 index 210c6b1..0000000 --- a/mojo/public/cpp/test_support/lib/test_utils.cc +++ /dev/null @@ -1,97 +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/test_support/test_utils.h" - -#include "mojo/public/cpp/system/core.h" -#include "mojo/public/cpp/test_support/test_support.h" - -namespace mojo { -namespace test { - -bool WriteTextMessage(const MessagePipeHandle& handle, - const std::string& text) { - MojoResult rv = WriteMessageRaw(handle, - text.data(), - static_cast<uint32_t>(text.size()), - nullptr, - 0, - MOJO_WRITE_MESSAGE_FLAG_NONE); - return rv == MOJO_RESULT_OK; -} - -bool ReadTextMessage(const MessagePipeHandle& handle, std::string* text) { - MojoResult rv; - bool did_wait = false; - - uint32_t num_bytes = 0, num_handles = 0; - for (;;) { - rv = ReadMessageRaw(handle, - nullptr, - &num_bytes, - nullptr, - &num_handles, - MOJO_READ_MESSAGE_FLAG_NONE); - if (rv == MOJO_RESULT_SHOULD_WAIT) { - if (did_wait) { - assert(false); // Looping endlessly!? - return false; - } - rv = Wait(handle, MOJO_HANDLE_SIGNAL_READABLE, MOJO_DEADLINE_INDEFINITE, - nullptr); - if (rv != MOJO_RESULT_OK) - return false; - did_wait = true; - } else { - assert(!num_handles); - break; - } - } - - text->resize(num_bytes); - rv = ReadMessageRaw(handle, - &text->at(0), - &num_bytes, - nullptr, - &num_handles, - MOJO_READ_MESSAGE_FLAG_NONE); - return rv == MOJO_RESULT_OK; -} - -bool DiscardMessage(const MessagePipeHandle& handle) { - MojoResult rv = ReadMessageRaw(handle, - nullptr, - nullptr, - nullptr, - nullptr, - MOJO_READ_MESSAGE_FLAG_MAY_DISCARD); - return rv == MOJO_RESULT_OK; -} - -void IterateAndReportPerf(const char* test_name, - const char* sub_test_name, - PerfTestSingleIteration single_iteration, - void* closure) { - // TODO(vtl): These should be specifiable using command-line flags. - static const size_t kGranularity = 100; - static const MojoTimeTicks kPerftestTimeMicroseconds = 3 * 1000000; - - const MojoTimeTicks start_time = GetTimeTicksNow(); - MojoTimeTicks end_time; - size_t iterations = 0; - do { - for (size_t i = 0; i < kGranularity; i++) - (*single_iteration)(closure); - iterations += kGranularity; - - end_time = GetTimeTicksNow(); - } while (end_time - start_time < kPerftestTimeMicroseconds); - - MojoTestSupportLogPerfResult(test_name, sub_test_name, - 1000000.0 * iterations / (end_time - start_time), - "iterations/second"); -} - -} // namespace test -} // namespace mojo diff --git a/mojo/public/cpp/test_support/test_support.h b/mojo/public/cpp/test_support/test_support.h deleted file mode 100644 index 9a536e6..0000000 --- a/mojo/public/cpp/test_support/test_support.h +++ /dev/null @@ -1,35 +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_TEST_SUPPORT_TEST_SUPPORT_H_ -#define MOJO_PUBLIC_CPP_TEST_SUPPORT_TEST_SUPPORT_H_ - -#include <string> -#include <vector> - -#include "mojo/public/c/test_support/test_support.h" - -namespace mojo { -namespace test { - -inline void LogPerfResult(const char* test_name, - const char* sub_test_name, - double value, - const char* units) { - MojoTestSupportLogPerfResult(test_name, sub_test_name, value, units); -} - -// Opens text file relative to the source root for reading. -inline FILE* OpenSourceRootRelativeFile(const std::string& relative_path) { - return MojoTestSupportOpenSourceRootRelativeFile(relative_path.c_str()); -} - -// Returns the list of regular files in a directory relative to the source root. -std::vector<std::string> EnumerateSourceRootRelativeDirectory( - const std::string& relative_path); - -} // namespace test -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_TEST_SUPPORT_TEST_SUPPORT_H_ diff --git a/mojo/public/cpp/test_support/test_utils.h b/mojo/public/cpp/test_support/test_utils.h deleted file mode 100644 index 6fd5a9e..0000000 --- a/mojo/public/cpp/test_support/test_utils.h +++ /dev/null @@ -1,40 +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_TEST_SUPPORT_TEST_UTILS_H_ -#define MOJO_PUBLIC_CPP_TEST_SUPPORT_TEST_UTILS_H_ - -#include <string> - -#include "mojo/public/cpp/system/core.h" - -namespace mojo { -namespace test { - -// Writes a message to |handle| with message data |text|. Returns true on -// success. -bool WriteTextMessage(const MessagePipeHandle& handle, const std::string& text); - -// Reads a message from |handle|, putting its contents into |*text|. Returns -// true on success. (This blocks if necessary and will call |MojoReadMessage()| -// multiple times, e.g., to query the size of the message.) -bool ReadTextMessage(const MessagePipeHandle& handle, std::string* text); - -// Discards a message from |handle|. Returns true on success. (This does not -// block. It will fail if no message is available to discard.) -bool DiscardMessage(const MessagePipeHandle& handle); - -// Run |single_iteration| an appropriate number of times and report its -// performance appropriately. (This actually runs |single_iteration| for a fixed -// amount of time and reports the number of iterations per unit time.) -typedef void (*PerfTestSingleIteration)(void* closure); -void IterateAndReportPerf(const char* test_name, - const char* sub_test_name, - PerfTestSingleIteration single_iteration, - void* closure); - -} // namespace test -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_TEST_SUPPORT_TEST_UTILS_H_ diff --git a/mojo/public/cpp/utility/BUILD.gn b/mojo/public/cpp/utility/BUILD.gn deleted file mode 100644 index 9660a07..0000000 --- a/mojo/public/cpp/utility/BUILD.gn +++ /dev/null @@ -1,35 +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. - -import("../../mojo_sdk.gni") - -mojo_sdk_source_set("utility") { - sources = [ - "mutex.h", - "run_loop.h", - "run_loop_handler.h", - "thread.h", - "lib/mutex.cc", - "lib/run_loop.cc", - "lib/thread.cc", - "lib/thread_local.h", - "lib/thread_local_posix.cc", - "lib/thread_local_win.cc", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/bindings:callback", - "mojo/public/cpp/system", - ] - - if (is_win) { - # See crbug.com/342893: - sources -= [ - "mutex.h", - "thread.h", - "lib/mutex.cc", - "lib/thread.cc", - ] - } -} diff --git a/mojo/public/cpp/utility/DEPS b/mojo/public/cpp/utility/DEPS deleted file mode 100644 index a9dfbd1..0000000 --- a/mojo/public/cpp/utility/DEPS +++ /dev/null @@ -1,3 +0,0 @@ -include_rules = [ - "+mojo/public/cpp/bindings/callback.h" -] diff --git a/mojo/public/cpp/utility/lib/mutex.cc b/mojo/public/cpp/utility/lib/mutex.cc deleted file mode 100644 index 23370e1..0000000 --- a/mojo/public/cpp/utility/lib/mutex.cc +++ /dev/null @@ -1,52 +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/utility/mutex.h" - -#include <assert.h> -#include <errno.h> - -namespace mojo { - -// Release builds have inlined (non-error-checking) definitions in the header. -#if !defined(NDEBUG) -Mutex::Mutex() { - pthread_mutexattr_t mutexattr; - int rv = pthread_mutexattr_init(&mutexattr); - assert(rv == 0); - rv = pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK); - assert(rv == 0); - rv = pthread_mutex_init(&mutex_, &mutexattr); - assert(rv == 0); - rv = pthread_mutexattr_destroy(&mutexattr); - assert(rv == 0); -} - -Mutex::~Mutex() { - int rv = pthread_mutex_destroy(&mutex_); - assert(rv == 0); -} - -void Mutex::Lock() { - int rv = pthread_mutex_lock(&mutex_); - assert(rv == 0); -} - -void Mutex::Unlock() { - int rv = pthread_mutex_unlock(&mutex_); - assert(rv == 0); -} - -bool Mutex::TryLock() { - int rv = pthread_mutex_trylock(&mutex_); - assert(rv == 0 || rv == EBUSY); - return rv == 0; -} - -void Mutex::AssertHeld() { - assert(pthread_mutex_lock(&mutex_) == EDEADLK); -} -#endif // !defined(NDEBUG) - -} // namespace mojo diff --git a/mojo/public/cpp/utility/lib/run_loop.cc b/mojo/public/cpp/utility/lib/run_loop.cc deleted file mode 100644 index 7faf748..0000000 --- a/mojo/public/cpp/utility/lib/run_loop.cc +++ /dev/null @@ -1,267 +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/utility/run_loop.h" - -#include <assert.h> - -#include <algorithm> -#include <vector> - -#include "mojo/public/cpp/utility/lib/thread_local.h" -#include "mojo/public/cpp/utility/run_loop_handler.h" - -namespace mojo { -namespace { - -internal::ThreadLocalPointer<RunLoop> current_run_loop; - -const MojoTimeTicks kInvalidTimeTicks = static_cast<MojoTimeTicks>(0); - -} // namespace - -// State needed for one iteration of WaitMany(). -struct RunLoop::WaitState { - WaitState() : deadline(MOJO_DEADLINE_INDEFINITE) {} - - std::vector<Handle> handles; - std::vector<MojoHandleSignals> handle_signals; - MojoDeadline deadline; -}; - -struct RunLoop::RunState { - RunState() : should_quit(false) {} - - bool should_quit; -}; - -RunLoop::RunLoop() - : run_state_(nullptr), next_handler_id_(0), next_sequence_number_(0) { - assert(!current()); - current_run_loop.Set(this); -} - -RunLoop::~RunLoop() { - assert(current() == this); - NotifyHandlers(MOJO_RESULT_ABORTED, IGNORE_DEADLINE); - current_run_loop.Set(nullptr); -} - -// static -void RunLoop::SetUp() { - current_run_loop.Allocate(); -} - -// static -void RunLoop::TearDown() { - assert(!current()); - current_run_loop.Free(); -} - -// static -RunLoop* RunLoop::current() { - return current_run_loop.Get(); -} - -void RunLoop::AddHandler(RunLoopHandler* handler, - const Handle& handle, - MojoHandleSignals handle_signals, - MojoDeadline deadline) { - assert(current() == this); - assert(handler); - assert(handle.is_valid()); - // Assume it's an error if someone tries to reregister an existing handle. - assert(0u == handler_data_.count(handle)); - HandlerData handler_data; - handler_data.handler = handler; - handler_data.handle_signals = handle_signals; - handler_data.deadline = - (deadline == MOJO_DEADLINE_INDEFINITE) - ? kInvalidTimeTicks - : GetTimeTicksNow() + static_cast<MojoTimeTicks>(deadline); - handler_data.id = next_handler_id_++; - handler_data_[handle] = handler_data; -} - -void RunLoop::RemoveHandler(const Handle& handle) { - assert(current() == this); - handler_data_.erase(handle); -} - -bool RunLoop::HasHandler(const Handle& handle) const { - return handler_data_.find(handle) != handler_data_.end(); -} - -void RunLoop::Run() { - RunInternal(UNTIL_EMPTY); -} - -void RunLoop::RunUntilIdle() { - RunInternal(UNTIL_IDLE); -} - -void RunLoop::RunInternal(RunMode run_mode) { - assert(current() == this); - RunState* old_state = run_state_; - RunState run_state; - run_state_ = &run_state; - for (;;) { - bool did_work = DoDelayedWork(); - if (run_state.should_quit) - break; - did_work |= Wait(run_mode == UNTIL_IDLE); - if (run_state.should_quit) - break; - if (!did_work && run_mode == UNTIL_IDLE) - break; - } - run_state_ = old_state; -} - -bool RunLoop::DoDelayedWork() { - MojoTimeTicks now = GetTimeTicksNow(); - if (!delayed_tasks_.empty() && delayed_tasks_.top().run_time <= now) { - PendingTask task = delayed_tasks_.top(); - delayed_tasks_.pop(); - task.task.Run(); - return true; - } - return false; -} - -void RunLoop::Quit() { - assert(current() == this); - if (run_state_) - run_state_->should_quit = true; -} - -void RunLoop::PostDelayedTask(const Closure& task, MojoTimeTicks delay) { - assert(current() == this); - MojoTimeTicks run_time = delay + GetTimeTicksNow(); - delayed_tasks_.push(PendingTask(task, run_time, next_sequence_number_++)); -} - -bool RunLoop::Wait(bool non_blocking) { - const WaitState wait_state = GetWaitState(non_blocking); - if (wait_state.handles.empty()) { - if (delayed_tasks_.empty()) - Quit(); - return false; - } - - const WaitManyResult wmr = - WaitMany(wait_state.handles, wait_state.handle_signals, - wait_state.deadline, nullptr); - - if (!wmr.IsIndexValid()) { - assert(wmr.result == MOJO_RESULT_DEADLINE_EXCEEDED); - return NotifyHandlers(MOJO_RESULT_DEADLINE_EXCEEDED, CHECK_DEADLINE); - } - - Handle handle = wait_state.handles[wmr.index]; - assert(handler_data_.find(handle) != handler_data_.end()); - RunLoopHandler* handler = handler_data_[handle].handler; - - switch (wmr.result) { - case MOJO_RESULT_OK: - handler->OnHandleReady(handle); - return true; - case MOJO_RESULT_INVALID_ARGUMENT: - case MOJO_RESULT_FAILED_PRECONDITION: - // Remove the handle first, this way if OnHandleError() tries to remove - // the handle our iterator isn't invalidated. - handler_data_.erase(handle); - handler->OnHandleError(handle, wmr.result); - return true; - default: - assert(false); - return false; - } -} - -bool RunLoop::NotifyHandlers(MojoResult error, CheckDeadline check) { - bool notified = false; - - // Make a copy in case someone tries to add/remove new handlers as part of - // notifying. - const HandleToHandlerData cloned_handlers(handler_data_); - const MojoTimeTicks now(GetTimeTicksNow()); - for (HandleToHandlerData::const_iterator i = cloned_handlers.begin(); - i != cloned_handlers.end(); - ++i) { - // Only check deadline exceeded if that's what we're notifying. - if (check == CHECK_DEADLINE && - (i->second.deadline == kInvalidTimeTicks || i->second.deadline > now)) { - continue; - } - - // Since we're iterating over a clone of the handlers, verify the handler - // is still valid before notifying. - if (handler_data_.find(i->first) == handler_data_.end() || - handler_data_[i->first].id != i->second.id) { - continue; - } - - RunLoopHandler* handler = i->second.handler; - handler_data_.erase(i->first); - handler->OnHandleError(i->first, error); - notified = true; - } - - return notified; -} - -RunLoop::WaitState RunLoop::GetWaitState(bool non_blocking) const { - WaitState wait_state; - MojoTimeTicks min_time = kInvalidTimeTicks; - for (HandleToHandlerData::const_iterator i = handler_data_.begin(); - i != handler_data_.end(); - ++i) { - wait_state.handles.push_back(i->first); - wait_state.handle_signals.push_back(i->second.handle_signals); - if (!non_blocking && i->second.deadline != kInvalidTimeTicks && - (min_time == kInvalidTimeTicks || i->second.deadline < min_time)) { - min_time = i->second.deadline; - } - } - if (!delayed_tasks_.empty()) { - MojoTimeTicks delayed_min_time = delayed_tasks_.top().run_time; - if (min_time == kInvalidTimeTicks) - min_time = delayed_min_time; - else - min_time = std::min(min_time, delayed_min_time); - } - if (non_blocking) { - wait_state.deadline = static_cast<MojoDeadline>(0); - } else if (min_time != kInvalidTimeTicks) { - const MojoTimeTicks now = GetTimeTicksNow(); - if (min_time < now) - wait_state.deadline = static_cast<MojoDeadline>(0); - else - wait_state.deadline = static_cast<MojoDeadline>(min_time - now); - } - return wait_state; -} - -RunLoop::PendingTask::PendingTask(const Closure& task, - MojoTimeTicks run_time, - uint64_t sequence_number) - : task(task), run_time(run_time), sequence_number(sequence_number) { -} - -RunLoop::PendingTask::~PendingTask() { -} - -bool RunLoop::PendingTask::operator<(const RunLoop::PendingTask& other) const { - if (run_time != other.run_time) { - // std::priority_queue<> puts the least element at the end of the queue. We - // want the soonest eligible task to be at the head of the queue, so - // run_times further in the future are considered lesser. - return run_time > other.run_time; - } - - return sequence_number > other.sequence_number; -} - -} // namespace mojo diff --git a/mojo/public/cpp/utility/lib/thread.cc b/mojo/public/cpp/utility/lib/thread.cc deleted file mode 100644 index 40f0bdd..0000000 --- a/mojo/public/cpp/utility/lib/thread.cc +++ /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. - -#include "mojo/public/cpp/utility/thread.h" - -#include <assert.h> - -namespace mojo { - -Thread::Thread() : options_(), thread_(), started_(false), joined_(false) { -} - -Thread::Thread(const Options& options) - : options_(options), thread_(), started_(false), joined_(false) { -} - -Thread::~Thread() { - // If it was started, it must have been joined. - assert(!started_ || joined_); -} - -void Thread::Start() { - assert(!started_); - assert(!joined_); - - pthread_attr_t attr; - int rv = pthread_attr_init(&attr); - MOJO_ALLOW_UNUSED_LOCAL(rv); - assert(rv == 0); - - // Non-default stack size? - if (options_.stack_size() != 0) { - rv = pthread_attr_setstacksize(&attr, options_.stack_size()); - assert(rv == 0); - } - - started_ = true; - rv = pthread_create(&thread_, &attr, &ThreadRunTrampoline, this); - assert(rv == 0); - - rv = pthread_attr_destroy(&attr); - assert(rv == 0); -} - -void Thread::Join() { - // Must have been started but not yet joined. - assert(started_); - assert(!joined_); - - joined_ = true; - int rv = pthread_join(thread_, nullptr); - MOJO_ALLOW_UNUSED_LOCAL(rv); - assert(rv == 0); -} - -// static -void* Thread::ThreadRunTrampoline(void* arg) { - Thread* self = static_cast<Thread*>(arg); - self->Run(); - return nullptr; -} - -} // namespace mojo diff --git a/mojo/public/cpp/utility/lib/thread_local.h b/mojo/public/cpp/utility/lib/thread_local.h deleted file mode 100644 index f5461ee..0000000 --- a/mojo/public/cpp/utility/lib/thread_local.h +++ /dev/null @@ -1,54 +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_UTILITY_LIB_THREAD_LOCAL_H_ -#define MOJO_PUBLIC_CPP_UTILITY_LIB_THREAD_LOCAL_H_ - -#ifndef _WIN32 -#include <pthread.h> -#endif - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { -namespace internal { - -// Helper functions that abstract the cross-platform APIs. -struct ThreadLocalPlatform { -#ifdef _WIN32 - typedef unsigned long SlotType; -#else - typedef pthread_key_t SlotType; -#endif - - static void AllocateSlot(SlotType* slot); - static void FreeSlot(SlotType slot); - static void* GetValueFromSlot(SlotType slot); - static void SetValueInSlot(SlotType slot, void* value); -}; - -// This class is intended to be statically allocated. -template <typename P> -class ThreadLocalPointer { - public: - ThreadLocalPointer() : slot_() {} - - void Allocate() { ThreadLocalPlatform::AllocateSlot(&slot_); } - - void Free() { ThreadLocalPlatform::FreeSlot(slot_); } - - P* Get() { - return static_cast<P*>(ThreadLocalPlatform::GetValueFromSlot(slot_)); - } - - void Set(P* value) { ThreadLocalPlatform::SetValueInSlot(slot_, value); } - - private: - ThreadLocalPlatform::SlotType slot_; -}; - -} // namespace internal -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_UTILITY_LIB_THREAD_LOCAL_H_ diff --git a/mojo/public/cpp/utility/lib/thread_local_posix.cc b/mojo/public/cpp/utility/lib/thread_local_posix.cc deleted file mode 100644 index ea7343e..0000000 --- a/mojo/public/cpp/utility/lib/thread_local_posix.cc +++ /dev/null @@ -1,39 +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/utility/lib/thread_local.h" - -#include <assert.h> - -namespace mojo { -namespace internal { - -// static -void ThreadLocalPlatform::AllocateSlot(SlotType* slot) { - if (pthread_key_create(slot, nullptr) != 0) { - assert(false); - } -} - -// static -void ThreadLocalPlatform::FreeSlot(SlotType slot) { - if (pthread_key_delete(slot) != 0) { - assert(false); - } -} - -// static -void* ThreadLocalPlatform::GetValueFromSlot(SlotType slot) { - return pthread_getspecific(slot); -} - -// static -void ThreadLocalPlatform::SetValueInSlot(SlotType slot, void* value) { - if (pthread_setspecific(slot, value) != 0) { - assert(false); - } -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/utility/lib/thread_local_win.cc b/mojo/public/cpp/utility/lib/thread_local_win.cc deleted file mode 100644 index 98841f7..0000000 --- a/mojo/public/cpp/utility/lib/thread_local_win.cc +++ /dev/null @@ -1,39 +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/utility/lib/thread_local.h" - -#include <assert.h> -#include <windows.h> - -namespace mojo { -namespace internal { - -// static -void ThreadLocalPlatform::AllocateSlot(SlotType* slot) { - *slot = TlsAlloc(); - assert(*slot != TLS_OUT_OF_INDEXES); -} - -// static -void ThreadLocalPlatform::FreeSlot(SlotType slot) { - if (!TlsFree(slot)) { - assert(false); - } -} - -// static -void* ThreadLocalPlatform::GetValueFromSlot(SlotType slot) { - return TlsGetValue(slot); -} - -// static -void ThreadLocalPlatform::SetValueInSlot(SlotType slot, void* value) { - if (!TlsSetValue(slot, value)) { - assert(false); - } -} - -} // namespace internal -} // namespace mojo diff --git a/mojo/public/cpp/utility/mutex.h b/mojo/public/cpp/utility/mutex.h deleted file mode 100644 index 4dc4aee..0000000 --- a/mojo/public/cpp/utility/mutex.h +++ /dev/null @@ -1,70 +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_UTILITY_MUTEX_H_ -#define MOJO_PUBLIC_CPP_UTILITY_MUTEX_H_ - -#ifdef _WIN32 -#error "Not implemented: See crbug.com/342893." -#endif - -#include <pthread.h> - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -#ifdef NDEBUG -// Note: Make a C++ constant for |PTHREAD_MUTEX_INITIALIZER|. (We can't directly -// use the C macro in an initializer list, since it might expand to |{ ... }|.) -namespace internal { -const pthread_mutex_t kPthreadMutexInitializer = PTHREAD_MUTEX_INITIALIZER; -} -#endif - -class Mutex { - public: -#ifdef NDEBUG - Mutex() : mutex_(internal::kPthreadMutexInitializer) {} - ~Mutex() { pthread_mutex_destroy(&mutex_); } - - void Lock() { pthread_mutex_lock(&mutex_); } - void Unlock() { pthread_mutex_unlock(&mutex_); } - bool TryLock() { return pthread_mutex_trylock(&mutex_) == 0; } - - void AssertHeld() {} -#else - Mutex(); - ~Mutex(); - - void Lock(); - void Unlock(); - bool TryLock(); - - void AssertHeld(); -#endif - - private: - pthread_mutex_t mutex_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(Mutex); -}; - -class MutexLock { - public: - explicit MutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } - ~MutexLock() { mutex_->Unlock(); } - - private: - Mutex* const mutex_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(MutexLock); -}; - -// Catch bug where variable name is omitted (e.g., |MutexLock (&mu)|). -#define MutexLock(x) static_assert(0, "MutexLock() missing variable name"); - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_UTILITY_MUTEX_H_ diff --git a/mojo/public/cpp/utility/run_loop.h b/mojo/public/cpp/utility/run_loop.h deleted file mode 100644 index 5ebe63e..0000000 --- a/mojo/public/cpp/utility/run_loop.h +++ /dev/null @@ -1,145 +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_UTILITY_RUN_LOOP_H_ -#define MOJO_PUBLIC_CPP_UTILITY_RUN_LOOP_H_ - -#include <map> -#include <queue> - -#include "mojo/public/cpp/bindings/callback.h" -#include "mojo/public/cpp/system/core.h" - -namespace mojo { - -class RunLoopHandler; - -class RunLoop { - public: - RunLoop(); - ~RunLoop(); - - // Sets up state needed for RunLoop. This must be invoked before creating a - // RunLoop. - static void SetUp(); - - // Cleans state created by Setup(). - static void TearDown(); - - // Returns the RunLoop for the current thread. Returns null if not yet - // created. - static RunLoop* current(); - - // Registers a RunLoopHandler for the specified handle. Only one handler can - // be registered for a specified handle. - void AddHandler(RunLoopHandler* handler, - const Handle& handle, - MojoHandleSignals handle_signals, - MojoDeadline deadline); - void RemoveHandler(const Handle& handle); - bool HasHandler(const Handle& handle) const; - - // Runs the loop servicing handles and tasks as they are ready. This returns - // when Quit() is invoked, or there are no more handles nor tasks. - void Run(); - - // Runs the loop servicing any handles and tasks that are ready. Does not wait - // for handles or tasks to become ready before returning. Returns early if - // Quit() is invoked. - void RunUntilIdle(); - - void Quit(); - - // Adds a task to be performed after delay has elapsed. Must be posted to the - // current thread's RunLoop. - void PostDelayedTask(const Closure& task, MojoTimeTicks delay); - - private: - struct RunState; - struct WaitState; - - // Contains the data needed to track a request to AddHandler(). - struct HandlerData { - HandlerData() - : handler(nullptr), - handle_signals(MOJO_HANDLE_SIGNAL_NONE), - deadline(0), - id(0) {} - - RunLoopHandler* handler; - MojoHandleSignals handle_signals; - MojoTimeTicks deadline; - // See description of |RunLoop::next_handler_id_| for details. - int id; - }; - - typedef std::map<Handle, HandlerData> HandleToHandlerData; - - // Used for NotifyHandlers to specify whether HandlerData's |deadline| - // should be checked prior to notifying. - enum CheckDeadline { CHECK_DEADLINE, IGNORE_DEADLINE }; - - // Mode of operation of the run loop. - enum RunMode { UNTIL_EMPTY, UNTIL_IDLE }; - - // Runs the loop servicing any handles and tasks that are ready. If - // |run_mode| is |UNTIL_IDLE|, does not wait for handles or tasks to become - // ready before returning. Returns early if Quit() is invoked. - void RunInternal(RunMode run_mode); - - // Do one unit of delayed work, if eligible. Returns true is a task was run. - bool DoDelayedWork(); - - // Waits for a handle to be ready or until the next task must be run. Returns - // after servicing at least one handle (or there are no more handles) unless - // a task must be run or |non_blocking| is true, in which case it will also - // return if no task is registered and servicing at least one handle would - // require blocking. Returns true if a RunLoopHandler was notified. - bool Wait(bool non_blocking); - - // Notifies handlers of |error|. If |check| == CHECK_DEADLINE, this will - // only notify handlers whose deadline has expired and skips the rest. - // Returns true if a RunLoopHandler was notified. - bool NotifyHandlers(MojoResult error, CheckDeadline check); - - // Returns the state needed to pass to WaitMany(). - WaitState GetWaitState(bool non_blocking) const; - - HandleToHandlerData handler_data_; - - // If non-null we're running (inside Run()). Member references a value on the - // stack. - RunState* run_state_; - - // An ever increasing value assigned to each HandlerData::id. Used to detect - // uniqueness while notifying. That is, while notifying expired timers we copy - // |handler_data_| and only notify handlers whose id match. If the id does not - // match it means the handler was removed then added so that we shouldn't - // notify it. - int next_handler_id_; - - struct PendingTask { - PendingTask(const Closure& task, - MojoTimeTicks runtime, - uint64_t sequence_number); - ~PendingTask(); - - bool operator<(const PendingTask& other) const; - - Closure task; - MojoTimeTicks run_time; - uint64_t sequence_number; - }; - // An ever increasing sequence number attached to each pending task in order - // to preserve relative order of tasks posted at the 'same' time. - uint64_t next_sequence_number_; - typedef std::priority_queue<PendingTask> DelayedTaskQueue; - DelayedTaskQueue delayed_tasks_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(RunLoop); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_UTILITY_RUN_LOOP_H_ diff --git a/mojo/public/cpp/utility/run_loop_handler.h b/mojo/public/cpp/utility/run_loop_handler.h deleted file mode 100644 index 69838d5..0000000 --- a/mojo/public/cpp/utility/run_loop_handler.h +++ /dev/null @@ -1,25 +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_UTILITY_RUN_LOOP_HANDLER_H_ -#define MOJO_PUBLIC_CPP_UTILITY_RUN_LOOP_HANDLER_H_ - -#include "mojo/public/cpp/system/core.h" - -namespace mojo { - -// Used by RunLoop to notify when a handle is either ready or has become -// invalid. -class RunLoopHandler { - public: - virtual void OnHandleReady(const Handle& handle) = 0; - virtual void OnHandleError(const Handle& handle, MojoResult result) = 0; - - protected: - virtual ~RunLoopHandler() {} -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_UTILITY_RUN_LOOP_HANDLER_H_ diff --git a/mojo/public/cpp/utility/tests/BUILD.gn b/mojo/public/cpp/utility/tests/BUILD.gn deleted file mode 100644 index a8a96c1..0000000 --- a/mojo/public/cpp/utility/tests/BUILD.gn +++ /dev/null @@ -1,31 +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. - -import("../../../mojo_sdk.gni") - -mojo_sdk_source_set("tests") { - testonly = true - - sources = [ - "run_loop_unittest.cc", - ] - - deps = [ - "//testing/gtest", - ] - - mojo_sdk_deps = [ - "mojo/public/cpp/system", - "mojo/public/cpp/test_support:test_utils", - "mojo/public/cpp/utility", - ] - - # crbug.com/342893 - if (!is_win) { - sources += [ - "mutex_unittest.cc", - "thread_unittest.cc", - ] - } -} diff --git a/mojo/public/cpp/utility/tests/mutex_unittest.cc b/mojo/public/cpp/utility/tests/mutex_unittest.cc deleted file mode 100644 index 78e95c5..0000000 --- a/mojo/public/cpp/utility/tests/mutex_unittest.cc +++ /dev/null @@ -1,259 +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/utility/mutex.h" - -#include <stdlib.h> // For |rand()|. -#include <time.h> // For |nanosleep()| (defined by POSIX). - -#include <vector> - -#include "mojo/public/cpp/system/macros.h" -#include "mojo/public/cpp/utility/thread.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -TEST(MutexTest, TrivialSingleThreaded) { - Mutex mutex; - - mutex.Lock(); - mutex.AssertHeld(); - mutex.Unlock(); - - EXPECT_TRUE(mutex.TryLock()); - mutex.AssertHeld(); - mutex.Unlock(); - - { - MutexLock lock(&mutex); - mutex.AssertHeld(); - } - - EXPECT_TRUE(mutex.TryLock()); - mutex.Unlock(); -} - -class Fiddler { - public: - enum Type { kTypeLock, kTypeTry }; - Fiddler(size_t times_to_lock, - Type type, - bool should_sleep, - Mutex* mutex, - int* shared_value) - : times_to_lock_(times_to_lock), - type_(type), - should_sleep_(should_sleep), - mutex_(mutex), - shared_value_(shared_value) { - } - - ~Fiddler() { - } - - void Fiddle() { - for (size_t i = 0; i < times_to_lock_;) { - switch (type_) { - case kTypeLock: { - mutex_->Lock(); - int old_shared_value = *shared_value_; - if (should_sleep_) - SleepALittle(); - *shared_value_ = old_shared_value + 1; - mutex_->Unlock(); - i++; - break; - } - case kTypeTry: - if (mutex_->TryLock()) { - int old_shared_value = *shared_value_; - if (should_sleep_) - SleepALittle(); - *shared_value_ = old_shared_value + 1; - mutex_->Unlock(); - i++; - } else { - SleepALittle(); // Don't spin. - } - break; - } - } - } - - private: - static void SleepALittle() { - static const long kNanosPerMilli = 1000000; - struct timespec req = { - 0, // Seconds. - (rand() % 10) * kNanosPerMilli // Nanoseconds. - }; - int rv = nanosleep(&req, nullptr); - MOJO_ALLOW_UNUSED_LOCAL(rv); - assert(rv == 0); - } - - const size_t times_to_lock_; - const Type type_; - const bool should_sleep_; - Mutex* const mutex_; - int* const shared_value_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(Fiddler); -}; - -class FiddlerThread : public Thread { - public: - // Takes ownership of |fiddler|. - FiddlerThread(Fiddler* fiddler) - : fiddler_(fiddler) { - } - - ~FiddlerThread() override { delete fiddler_; } - - void Run() override { fiddler_->Fiddle(); } - - private: - Fiddler* const fiddler_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(FiddlerThread); -}; - -// This does a stress test (that also checks exclusion). -TEST(MutexTest, ThreadedStress) { - static const size_t kNumThreads = 20; - static const int kTimesToLockEach = 20; - assert(kNumThreads % 4 == 0); - - Mutex mutex; - int shared_value = 0; - - std::vector<FiddlerThread*> fiddler_threads; - - for (size_t i = 0; i < kNumThreads; i += 4) { - fiddler_threads.push_back(new FiddlerThread(new Fiddler( - kTimesToLockEach, Fiddler::kTypeLock, false, &mutex, &shared_value))); - fiddler_threads.push_back(new FiddlerThread(new Fiddler( - kTimesToLockEach, Fiddler::kTypeTry, false, &mutex, &shared_value))); - fiddler_threads.push_back(new FiddlerThread(new Fiddler( - kTimesToLockEach, Fiddler::kTypeLock, true, &mutex, &shared_value))); - fiddler_threads.push_back(new FiddlerThread(new Fiddler( - kTimesToLockEach, Fiddler::kTypeTry, true, &mutex, &shared_value))); - } - - for (size_t i = 0; i < kNumThreads; i++) - fiddler_threads[i]->Start(); - - // Do some fiddling ourselves. - Fiddler(kTimesToLockEach, Fiddler::kTypeLock, true, &mutex, &shared_value) - .Fiddle(); - - // Join. - for (size_t i = 0; i < kNumThreads; i++) - fiddler_threads[i]->Join(); - - EXPECT_EQ(static_cast<int>(kNumThreads + 1) * kTimesToLockEach, shared_value); - - // Delete. - for (size_t i = 0; i < kNumThreads; i++) - delete fiddler_threads[i]; - fiddler_threads.clear(); -} - -class TryThread : public Thread { - public: - explicit TryThread(Mutex* mutex) : mutex_(mutex), try_lock_succeeded_() {} - ~TryThread() override {} - - void Run() override { - try_lock_succeeded_ = mutex_->TryLock(); - if (try_lock_succeeded_) - mutex_->Unlock(); - } - - bool try_lock_succeeded() const { return try_lock_succeeded_; } - - private: - Mutex* const mutex_; - bool try_lock_succeeded_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(TryThread); -}; - -TEST(MutexTest, TryLock) { - Mutex mutex; - - // |TryLock()| should succeed -- we don't have the lock. - { - TryThread thread(&mutex); - thread.Start(); - thread.Join(); - EXPECT_TRUE(thread.try_lock_succeeded()); - } - - // Take the lock. - ASSERT_TRUE(mutex.TryLock()); - - // Now it should fail. - { - TryThread thread(&mutex); - thread.Start(); - thread.Join(); - EXPECT_FALSE(thread.try_lock_succeeded()); - } - - // Release the lock. - mutex.Unlock(); - - // It should succeed again. - { - TryThread thread(&mutex); - thread.Start(); - thread.Join(); - EXPECT_TRUE(thread.try_lock_succeeded()); - } -} - - -// Tests of assertions for Debug builds. -#if !defined(NDEBUG) -// Test |AssertHeld()| (which is an actual user API). -TEST(MutexTest, DebugAssertHeldFailure) { - Mutex mutex; - EXPECT_DEATH_IF_SUPPORTED(mutex.AssertHeld(), ""); -} - -// Test other consistency checks. -TEST(MutexTest, DebugAssertionFailures) { - // Unlock without lock held. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex mutex; - mutex.Unlock(); - }, ""); - - // Lock with lock held (on same thread). - EXPECT_DEATH_IF_SUPPORTED({ - Mutex mutex; - mutex.Lock(); - mutex.Lock(); - }, ""); - - // Try lock with lock held. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex mutex; - mutex.Lock(); - mutex.TryLock(); - }, ""); - - // Destroy lock with lock held. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex mutex; - mutex.Lock(); - }, ""); -} -#endif // !defined(NDEBUG) - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/utility/tests/run_loop_unittest.cc b/mojo/public/cpp/utility/tests/run_loop_unittest.cc deleted file mode 100644 index 4ab4876..0000000 --- a/mojo/public/cpp/utility/tests/run_loop_unittest.cc +++ /dev/null @@ -1,425 +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/utility/run_loop.h" - -#include <string> - -#include "mojo/public/cpp/system/core.h" -#include "mojo/public/cpp/test_support/test_utils.h" -#include "mojo/public/cpp/utility/run_loop_handler.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -class TestRunLoopHandler : public RunLoopHandler { - public: - TestRunLoopHandler() - : ready_count_(0), - error_count_(0), - last_error_result_(MOJO_RESULT_OK) { - } - ~TestRunLoopHandler() override {} - - void clear_ready_count() { ready_count_ = 0; } - int ready_count() const { return ready_count_; } - - void clear_error_count() { error_count_ = 0; } - int error_count() const { return error_count_; } - - MojoResult last_error_result() const { return last_error_result_; } - - // RunLoopHandler: - void OnHandleReady(const Handle& handle) override { ready_count_++; } - void OnHandleError(const Handle& handle, MojoResult result) override { - error_count_++; - last_error_result_ = result; - } - - private: - int ready_count_; - int error_count_; - MojoResult last_error_result_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(TestRunLoopHandler); -}; - -class RunLoopTest : public testing::Test { - public: - RunLoopTest() {} - - void SetUp() override { - Test::SetUp(); - RunLoop::SetUp(); - } - void TearDown() override { - RunLoop::TearDown(); - Test::TearDown(); - } - - private: - MOJO_DISALLOW_COPY_AND_ASSIGN(RunLoopTest); -}; - -// Trivial test to verify Run() with no added handles returns. -TEST_F(RunLoopTest, ExitsWithNoHandles) { - RunLoop run_loop; - run_loop.Run(); -} - -class RemoveOnReadyRunLoopHandler : public TestRunLoopHandler { - public: - RemoveOnReadyRunLoopHandler() : run_loop_(nullptr) {} - ~RemoveOnReadyRunLoopHandler() override {} - - void set_run_loop(RunLoop* run_loop) { run_loop_ = run_loop; } - - // RunLoopHandler: - void OnHandleReady(const Handle& handle) override { - run_loop_->RemoveHandler(handle); - TestRunLoopHandler::OnHandleReady(handle); - } - - private: - RunLoop* run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(RemoveOnReadyRunLoopHandler); -}; - -// Verifies RunLoop quits when no more handles (handle is removed when ready). -TEST_F(RunLoopTest, HandleReady) { - RemoveOnReadyRunLoopHandler handler; - MessagePipe test_pipe; - EXPECT_TRUE(test::WriteTextMessage(test_pipe.handle1.get(), std::string())); - - RunLoop run_loop; - handler.set_run_loop(&run_loop); - run_loop.AddHandler(&handler, test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, MOJO_DEADLINE_INDEFINITE); - run_loop.Run(); - EXPECT_EQ(1, handler.ready_count()); - EXPECT_EQ(0, handler.error_count()); - EXPECT_FALSE(run_loop.HasHandler(test_pipe.handle0.get())); -} - -class QuitOnReadyRunLoopHandler : public TestRunLoopHandler { - public: - QuitOnReadyRunLoopHandler() : run_loop_(nullptr) {} - ~QuitOnReadyRunLoopHandler() override {} - - void set_run_loop(RunLoop* run_loop) { run_loop_ = run_loop; } - - // RunLoopHandler: - void OnHandleReady(const Handle& handle) override { - run_loop_->Quit(); - TestRunLoopHandler::OnHandleReady(handle); - } - - private: - RunLoop* run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(QuitOnReadyRunLoopHandler); -}; - -// Verifies Quit() from OnHandleReady() quits the loop. -TEST_F(RunLoopTest, QuitFromReady) { - QuitOnReadyRunLoopHandler handler; - MessagePipe test_pipe; - EXPECT_TRUE(test::WriteTextMessage(test_pipe.handle1.get(), std::string())); - - RunLoop run_loop; - handler.set_run_loop(&run_loop); - run_loop.AddHandler(&handler, test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, MOJO_DEADLINE_INDEFINITE); - run_loop.Run(); - EXPECT_EQ(1, handler.ready_count()); - EXPECT_EQ(0, handler.error_count()); - EXPECT_TRUE(run_loop.HasHandler(test_pipe.handle0.get())); -} - -class QuitOnErrorRunLoopHandler : public TestRunLoopHandler { - public: - QuitOnErrorRunLoopHandler() : run_loop_(nullptr) {} - ~QuitOnErrorRunLoopHandler() override {} - - void set_run_loop(RunLoop* run_loop) { run_loop_ = run_loop; } - - // RunLoopHandler: - void OnHandleError(const Handle& handle, MojoResult result) override { - run_loop_->Quit(); - TestRunLoopHandler::OnHandleError(handle, result); - } - - private: - RunLoop* run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(QuitOnErrorRunLoopHandler); -}; - -// Verifies Quit() when the deadline is reached works. -TEST_F(RunLoopTest, QuitWhenDeadlineExpired) { - QuitOnErrorRunLoopHandler handler; - MessagePipe test_pipe; - RunLoop run_loop; - handler.set_run_loop(&run_loop); - run_loop.AddHandler(&handler, test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - static_cast<MojoDeadline>(10000)); - run_loop.Run(); - EXPECT_EQ(0, handler.ready_count()); - EXPECT_EQ(1, handler.error_count()); - EXPECT_EQ(MOJO_RESULT_DEADLINE_EXCEEDED, handler.last_error_result()); - EXPECT_FALSE(run_loop.HasHandler(test_pipe.handle0.get())); -} - -// Test that handlers are notified of loop destruction. -TEST_F(RunLoopTest, Destruction) { - TestRunLoopHandler handler; - MessagePipe test_pipe; - { - RunLoop run_loop; - run_loop.AddHandler(&handler, - test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - } - EXPECT_EQ(1, handler.error_count()); - EXPECT_EQ(MOJO_RESULT_ABORTED, handler.last_error_result()); -} - -class RemoveManyRunLoopHandler : public TestRunLoopHandler { - public: - RemoveManyRunLoopHandler() : run_loop_(nullptr) {} - ~RemoveManyRunLoopHandler() override {} - - void set_run_loop(RunLoop* run_loop) { run_loop_ = run_loop; } - void add_handle(const Handle& handle) { handles_.push_back(handle); } - - // RunLoopHandler: - void OnHandleError(const Handle& handle, MojoResult result) override { - for (size_t i = 0; i < handles_.size(); i++) - run_loop_->RemoveHandler(handles_[i]); - TestRunLoopHandler::OnHandleError(handle, result); - } - - private: - std::vector<Handle> handles_; - RunLoop* run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(RemoveManyRunLoopHandler); -}; - -// Test that handlers are notified of loop destruction. -TEST_F(RunLoopTest, MultipleHandleDestruction) { - RemoveManyRunLoopHandler odd_handler; - TestRunLoopHandler even_handler; - MessagePipe test_pipe1, test_pipe2, test_pipe3; - { - RunLoop run_loop; - odd_handler.set_run_loop(&run_loop); - odd_handler.add_handle(test_pipe1.handle0.get()); - odd_handler.add_handle(test_pipe3.handle0.get()); - run_loop.AddHandler(&odd_handler, - test_pipe1.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - run_loop.AddHandler(&even_handler, - test_pipe2.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - run_loop.AddHandler(&odd_handler, - test_pipe3.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - } - EXPECT_EQ(1, odd_handler.error_count()); - EXPECT_EQ(1, even_handler.error_count()); - EXPECT_EQ(MOJO_RESULT_ABORTED, odd_handler.last_error_result()); - EXPECT_EQ(MOJO_RESULT_ABORTED, even_handler.last_error_result()); -} - -class AddHandlerOnErrorHandler : public TestRunLoopHandler { - public: - AddHandlerOnErrorHandler() : run_loop_(nullptr) {} - ~AddHandlerOnErrorHandler() override {} - - void set_run_loop(RunLoop* run_loop) { run_loop_ = run_loop; } - - // RunLoopHandler: - void OnHandleError(const Handle& handle, MojoResult result) override { - run_loop_->AddHandler(this, handle, - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - TestRunLoopHandler::OnHandleError(handle, result); - } - - private: - RunLoop* run_loop_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(AddHandlerOnErrorHandler); -}; - -TEST_F(RunLoopTest, AddHandlerOnError) { - AddHandlerOnErrorHandler handler; - MessagePipe test_pipe; - { - RunLoop run_loop; - handler.set_run_loop(&run_loop); - run_loop.AddHandler(&handler, - test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - } - EXPECT_EQ(1, handler.error_count()); - EXPECT_EQ(MOJO_RESULT_ABORTED, handler.last_error_result()); -} - -TEST_F(RunLoopTest, Current) { - EXPECT_TRUE(RunLoop::current() == nullptr); - { - RunLoop run_loop; - EXPECT_EQ(&run_loop, RunLoop::current()); - } - EXPECT_TRUE(RunLoop::current() == nullptr); -} - -class NestingRunLoopHandler : public TestRunLoopHandler { - public: - static const size_t kDepthLimit; - static const char kSignalMagic; - - NestingRunLoopHandler() - : run_loop_(nullptr), - pipe_(nullptr), - depth_(0), - reached_depth_limit_(false) {} - - ~NestingRunLoopHandler() override {} - - void set_run_loop(RunLoop* run_loop) { run_loop_ = run_loop; } - void set_pipe(MessagePipe* pipe) { pipe_ = pipe; } - bool reached_depth_limit() const { return reached_depth_limit_; } - - // RunLoopHandler: - void OnHandleReady(const Handle& handle) override { - TestRunLoopHandler::OnHandleReady(handle); - EXPECT_EQ(handle.value(), pipe_->handle0.get().value()); - - ReadSignal(); - size_t current_depth = ++depth_; - if (current_depth < kDepthLimit) { - WriteSignal(); - run_loop_->Run(); - if (current_depth == kDepthLimit - 1) { - // The topmost loop Quit()-ed, so its parent takes back the - // control without exeeding deadline. - EXPECT_EQ(error_count(), 0); - } else { - EXPECT_EQ(error_count(), 1); - } - - } else { - EXPECT_EQ(current_depth, kDepthLimit); - reached_depth_limit_ = true; - run_loop_->Quit(); - } - --depth_; - } - - void WriteSignal() { - char write_byte = kSignalMagic; - MojoResult write_result = - WriteMessageRaw(pipe_->handle1.get(), &write_byte, 1, nullptr, 0, - MOJO_WRITE_MESSAGE_FLAG_NONE); - EXPECT_EQ(write_result, MOJO_RESULT_OK); - } - - void ReadSignal() { - char read_byte = 0; - uint32_t bytes_read = 1; - uint32_t handles_read = 0; - MojoResult read_result = - ReadMessageRaw(pipe_->handle0.get(), &read_byte, &bytes_read, nullptr, - &handles_read, MOJO_READ_MESSAGE_FLAG_NONE); - EXPECT_EQ(read_result, MOJO_RESULT_OK); - EXPECT_EQ(read_byte, kSignalMagic); - } - - private: - RunLoop* run_loop_; - MessagePipe* pipe_; - size_t depth_; - bool reached_depth_limit_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(NestingRunLoopHandler); -}; - -const size_t NestingRunLoopHandler::kDepthLimit = 10; -const char NestingRunLoopHandler::kSignalMagic = 'X'; - -TEST_F(RunLoopTest, NestedRun) { - NestingRunLoopHandler handler; - MessagePipe test_pipe; - RunLoop run_loop; - handler.set_run_loop(&run_loop); - handler.set_pipe(&test_pipe); - run_loop.AddHandler(&handler, test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - static_cast<MojoDeadline>(10000)); - handler.WriteSignal(); - run_loop.Run(); - - EXPECT_TRUE(handler.reached_depth_limit()); - // Got MOJO_RESULT_DEADLINE_EXCEEDED once then removed from the - // RunLoop's handler list. - EXPECT_EQ(handler.error_count(), 1); - EXPECT_EQ(handler.last_error_result(), MOJO_RESULT_DEADLINE_EXCEEDED); -} - -struct Task { - Task(int num, std::vector<int>* sequence) : num(num), sequence(sequence) {} - - void Run() const { sequence->push_back(num); } - - int num; - std::vector<int>* sequence; -}; - -TEST_F(RunLoopTest, DelayedTaskOrder) { - std::vector<int> sequence; - RunLoop run_loop; - run_loop.PostDelayedTask(Closure(Task(1, &sequence)), 0); - run_loop.PostDelayedTask(Closure(Task(2, &sequence)), 0); - run_loop.PostDelayedTask(Closure(Task(3, &sequence)), 0); - run_loop.RunUntilIdle(); - - ASSERT_EQ(3u, sequence.size()); - EXPECT_EQ(1, sequence[0]); - EXPECT_EQ(2, sequence[1]); - EXPECT_EQ(3, sequence[2]); -} - -struct QuittingTask { - explicit QuittingTask(RunLoop* run_loop) : run_loop(run_loop) {} - - void Run() const { run_loop->Quit(); } - - RunLoop* run_loop; -}; - -TEST_F(RunLoopTest, QuitFromDelayedTask) { - TestRunLoopHandler handler; - MessagePipe test_pipe; - RunLoop run_loop; - run_loop.AddHandler(&handler, - test_pipe.handle0.get(), - MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE); - run_loop.PostDelayedTask(Closure(QuittingTask(&run_loop)), 0); - run_loop.Run(); -} - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/utility/tests/thread_unittest.cc b/mojo/public/cpp/utility/tests/thread_unittest.cc deleted file mode 100644 index 57c4ad9..0000000 --- a/mojo/public/cpp/utility/tests/thread_unittest.cc +++ /dev/null @@ -1,106 +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/utility/thread.h" - -#include "mojo/public/cpp/system/macros.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace mojo { -namespace { - -class SetIntThread : public Thread { - public: - SetIntThread(int* int_to_set, int value) - : int_to_set_(int_to_set), - value_(value) { - } - SetIntThread(const Options& options, int* int_to_set, int value) - : Thread(options), - int_to_set_(int_to_set), - value_(value) { - } - - ~SetIntThread() override {} - - void Run() override { *int_to_set_ = value_; } - - private: - int* const int_to_set_; - const int value_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(SetIntThread); -}; - -TEST(ThreadTest, CreateAndJoin) { - int value = 0; - - // Not starting the thread should result in a no-op. - { - SetIntThread thread(&value, 1234567); - } - EXPECT_EQ(0, value); - - // Start and join. - { - SetIntThread thread(&value, 12345678); - thread.Start(); - thread.Join(); - EXPECT_EQ(12345678, value); - } - - // Ditto, with non-default (but reasonable) stack size. - { - Thread::Options options; - options.set_stack_size(1024 * 1024); // 1 MB. - SetIntThread thread(options, &value, 12345678); - thread.Start(); - thread.Join(); - EXPECT_EQ(12345678, value); - } -} - -// Tests of assertions for Debug builds. -// Note: It's okay to create threads, despite gtest having to fork. (The threads -// are in the child process.) -#if !defined(NDEBUG) -TEST(ThreadTest, DebugAssertionFailures) { - // Can only start once. - EXPECT_DEATH_IF_SUPPORTED({ - int value = 0; - SetIntThread thread(&value, 1); - thread.Start(); - thread.Start(); - }, ""); - - // Must join (if you start). - EXPECT_DEATH_IF_SUPPORTED({ - int value = 0; - SetIntThread thread(&value, 2); - thread.Start(); - }, ""); - - // Can only join once. - EXPECT_DEATH_IF_SUPPORTED({ - int value = 0; - SetIntThread thread(&value, 3); - thread.Start(); - thread.Join(); - thread.Join(); - }, ""); - - // Stack too big (we're making certain assumptions here). - EXPECT_DEATH_IF_SUPPORTED({ - int value = 0; - Thread::Options options; - options.set_stack_size(static_cast<size_t>(-1)); - SetIntThread thread(options, &value, 4); - thread.Start(); - thread.Join(); - }, ""); -} -#endif // !defined(NDEBUG) - -} // namespace -} // namespace mojo diff --git a/mojo/public/cpp/utility/thread.h b/mojo/public/cpp/utility/thread.h deleted file mode 100644 index b7d10ee..0000000 --- a/mojo/public/cpp/utility/thread.h +++ /dev/null @@ -1,62 +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_UTILITY_THREAD_H_ -#define MOJO_PUBLIC_CPP_UTILITY_THREAD_H_ - -#ifdef _WIN32 -#error "Not implemented: See crbug.com/342893." -#endif - -#include <pthread.h> -#include <stddef.h> - -#include "mojo/public/cpp/system/macros.h" - -namespace mojo { - -// This class is thread-friendly, not thread-safe (e.g., you mustn't call -// |Join()| from multiple threads and/or simultaneously try to destroy the -// object). -class Thread { - public: - // TODO(vtl): Support non-joinable? priority? - class Options { - public: - Options() : stack_size_(0) {} - - // A stack size of 0 means the default. - size_t stack_size() const { return stack_size_; } - void set_stack_size(size_t stack_size) { stack_size_ = stack_size; } - - private: - size_t stack_size_; - - // Copy and assign allowed. - }; - - // TODO(vtl): Add name or name prefix? - Thread(); - explicit Thread(const Options& options); - virtual ~Thread(); - - void Start(); - void Join(); - - virtual void Run() = 0; - - private: - static void* ThreadRunTrampoline(void* arg); - - const Options options_; - pthread_t thread_; - bool started_; - bool joined_; - - MOJO_DISALLOW_COPY_AND_ASSIGN(Thread); -}; - -} // namespace mojo - -#endif // MOJO_PUBLIC_CPP_UTILITY_THREAD_H_ |