summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorrockot <rockot@chromium.org>2015-05-23 23:18:09 -0700
committerCommit bot <commit-bot@chromium.org>2015-05-24 06:18:50 +0000
commit7b6d64a6dabbba0f2ce3dd4429fdc79d4aabc898 (patch)
tree7f69d5459b2193b348bbdfd22a8f1592aee2d121
parent0404d85f873341ea50b47a8220126b24dc2030d9 (diff)
downloadchromium_src-7b6d64a6dabbba0f2ce3dd4429fdc79d4aabc898.zip
chromium_src-7b6d64a6dabbba0f2ce3dd4429fdc79d4aabc898.tar.gz
chromium_src-7b6d64a6dabbba0f2ce3dd4429fdc79d4aabc898.tar.bz2
Update mojo sdk to rev 1dc8a9a5db73d3718d99917fadf31f5fb2ebad4f
Relanding this. Was reverted due to some type conversion errors on Win x64 GN dbg (guess because MSVS 2012?) Just noticed the revert. Will upstream the Mojo fix later. BUG=None TBR=jam@chromium.org Review URL: https://codereview.chromium.org/1157843002 Cr-Commit-Position: refs/heads/master@{#331246}
-rw-r--r--build/module_args/mojo.gni3
-rw-r--r--components/filesystem/directory_impl_unittest.cc30
-rw-r--r--components/filesystem/file_impl_unittest.cc122
-rw-r--r--components/filesystem/files_test_base.cc2
-rw-r--r--components/html_viewer/web_clipboard_impl.cc14
-rw-r--r--components/html_viewer/web_cookie_jar_impl.cc6
-rw-r--r--components/resource_provider/public/cpp/resource_loader.cc2
-rw-r--r--mandoline/ui/aura/surface_binding.cc2
-rw-r--r--mojo/environment/default_logger_impl.cc5
-rw-r--r--mojo/runner/shell_apptest.cc4
-rw-r--r--mojo/services/network/http_server_apptest.cc2
-rwxr-xr-xmojo/tools/rev_sdk.py20
-rw-r--r--net/proxy/proxy_resolver_mojo_unittest.cc4
-rw-r--r--third_party/mojo/mojom_bindings_generator_variables.gypi5
-rw-r--r--third_party/mojo/src/mojo/edk/embedder/embedder.cc41
-rw-r--r--third_party/mojo/src/mojo/edk/embedder/embedder.h44
-rw-r--r--third_party/mojo/src/mojo/edk/embedder/embedder_unittest.cc84
-rw-r--r--third_party/mojo/src/mojo/edk/embedder/platform_channel_pair_posix_unittest.cc1
-rw-r--r--third_party/mojo/src/mojo/edk/system/connection_manager_unittest.cc129
-rw-r--r--third_party/mojo/src/mojo/edk/system/master_connection_manager.cc76
-rw-r--r--third_party/mojo/src/mojo/edk/system/master_connection_manager.h21
-rw-r--r--third_party/mojo/src/mojo/edk/system/multiprocess_message_pipe_unittest.cc3
-rw-r--r--third_party/mojo/src/mojo/edk/system/raw_channel.cc1
-rw-r--r--third_party/mojo/src/mojo/edk/system/slave_connection_manager.cc8
-rw-r--r--third_party/mojo/src/mojo/edk/system/unique_identifier.cc29
-rw-r--r--third_party/mojo/src/mojo/edk/system/unique_identifier.h21
-rw-r--r--third_party/mojo/src/mojo/edk/system/unique_identifier_unittest.cc65
-rw-r--r--third_party/mojo/src/mojo/edk/test/BUILD.gn14
-rw-r--r--third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.cc15
-rw-r--r--third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.h6
-rw-r--r--third_party/mojo/src/mojo/edk/test/scoped_ipc_support.cc97
-rw-r--r--third_party/mojo/src/mojo/edk/test/scoped_ipc_support.h87
-rw-r--r--third_party/mojo/src/mojo/public/BUILD.gn15
-rw-r--r--third_party/mojo/src/mojo/public/VERSION2
-rw-r--r--third_party/mojo/src/mojo/public/c/environment/logger.h15
-rw-r--r--third_party/mojo/src/mojo/public/c/gles2/BUILD.gn12
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h6
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/lib/interface_ptr_internal.h2
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/tests/BUILD.gn55
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc8
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/tests/union_unittest.cc99
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_apptest.cc20
-rw-r--r--third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_test_service.cc8
-rw-r--r--third_party/mojo/src/mojo/public/cpp/environment/lib/default_logger.cc12
-rw-r--r--third_party/mojo/src/mojo/public/cpp/environment/lib/logging.cc12
-rw-r--r--third_party/mojo/src/mojo/public/cpp/environment/logging.h6
-rw-r--r--third_party/mojo/src/mojo/public/cpp/environment/tests/logger_unittest.cc65
-rw-r--r--third_party/mojo/src/mojo/public/cpp/environment/tests/logging_unittest.cc144
-rw-r--r--third_party/mojo/src/mojo/public/dart/.gitignore2
-rw-r--r--third_party/mojo/src/mojo/public/dart/BUILD.gn60
-rw-r--r--third_party/mojo/src/mojo/public/dart/README.md8
-rw-r--r--third_party/mojo/src/mojo/public/dart/io.dart49
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/application.dart (renamed from third_party/mojo/src/mojo/public/dart/application.dart)4
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/bindings.dart (renamed from third_party/mojo/src/mojo/public/dart/bindings.dart)4
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/core.dart (renamed from third_party/mojo/src/mojo/public/dart/core.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/internal.dart (renamed from third_party/mojo/src/mojo/public/dart/internal.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/io.dart49
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/application.dart (renamed from third_party/mojo/src/mojo/public/dart/src/application.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/application_connection.dart (renamed from third_party/mojo/src/mojo/public/dart/src/application_connection.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/buffer.dart (renamed from third_party/mojo/src/mojo/public/dart/src/buffer.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/codec.dart (renamed from third_party/mojo/src/mojo/public/dart/src/codec.dart)18
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/control_message.dart61
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/data_pipe.dart (renamed from third_party/mojo/src/mojo/public/dart/src/data_pipe.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/drain_data.dart (renamed from third_party/mojo/src/mojo/public/dart/src/drain_data.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/event_stream.dart (renamed from third_party/mojo/src/mojo/public/dart/src/event_stream.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/handle.dart (renamed from third_party/mojo/src/mojo/public/dart/src/handle.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/handle_watcher.dart (renamed from third_party/mojo/src/mojo/public/dart/src/handle_watcher.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/message.dart (renamed from third_party/mojo/src/mojo/public/dart/src/message.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/message_pipe.dart (renamed from third_party/mojo/src/mojo/public/dart/src/message_pipe.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/natives.dart (renamed from third_party/mojo/src/mojo/public/dart/src/natives.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/proxy.dart (renamed from third_party/mojo/src/mojo/public/dart/src/proxy.dart)65
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/struct.dart (renamed from third_party/mojo/src/mojo/public/dart/src/struct.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/stub.dart (renamed from third_party/mojo/src/mojo/public/dart/src/stub.dart)2
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/timer_queue.dart (renamed from third_party/mojo/src/mojo/public/dart/src/timer_queue.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/lib/src/types.dart (renamed from third_party/mojo/src/mojo/public/dart/src/types.dart)0
-rw-r--r--third_party/mojo/src/mojo/public/dart/pubspec.yaml4
-rw-r--r--third_party/mojo/src/mojo/public/dart/rules.gni116
-rw-r--r--third_party/mojo/src/mojo/public/go/bindings/decoder.go15
-rw-r--r--third_party/mojo/src/mojo/public/go/bindings/encoder.go22
-rw-r--r--third_party/mojo/src/mojo/public/interfaces/bindings/tests/BUILD.gn13
-rw-r--r--third_party/mojo/src/mojo/public/interfaces/bindings/tests/test_unions.mojom16
-rw-r--r--third_party/mojo/src/mojo/public/java/BUILD.gn21
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/BindingsHelper.java6
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/DataHeader.java70
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Decoder.java63
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Encoder.java50
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/MessageHeader.java11
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Struct.java79
-rw-r--r--third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Union.java30
-rw-r--r--third_party/mojo/src/mojo/public/mojo.gni7
-rw-r--r--third_party/mojo/src/mojo/public/tools/BUILD.gn2
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_definition.tmpl12
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl14
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl3
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl14
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl17
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl4
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl16
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/encoding_macros.tmpl192
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/source.tmpl6
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/struct.tmpl197
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/union.tmpl66
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/data_types_definition.tmpl367
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl2
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl2
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl220
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/union.java.tmpl4
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_cpp_generator.py4
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_dart_generator.py12
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_go_generator.py16
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_java_generator.py27
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_python_generator.py5
-rw-r--r--third_party/mojo/src/mojo/public/tools/bindings/mojom.gni25
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/dart_analyze.py5
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/dart_list_mojoms.py38
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/dart_list_packages_contents.py17
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/dart_package.py135
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/dart_package_name.py38
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/dart_pkg.py242
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/download_network_service.py4
-rwxr-xr-xthird_party/mojo/src/mojo/public/tools/git/dart_pub_get.py14
121 files changed, 3025 insertions, 984 deletions
diff --git a/build/module_args/mojo.gni b/build/module_args/mojo.gni
index efa5535..26ac3eb 100644
--- a/build/module_args/mojo.gni
+++ b/build/module_args/mojo.gni
@@ -16,6 +16,9 @@ mojo_disable_dart_apptest_framework = true
# Points to the directory network_service is built from.
mojo_network_service_root = "//mojo/services"
+# We use our own custom application code. Don't build Mojo's.
+mojo_disable_application_in_sdk = true
+
declare_args() {
# The mojo shell is forked and built in the chromium repo.
mojo_build_mojo_shell_from_source = true
diff --git a/components/filesystem/directory_impl_unittest.cc b/components/filesystem/directory_impl_unittest.cc
index c702295..556d323 100644
--- a/components/filesystem/directory_impl_unittest.cc
+++ b/components/filesystem/directory_impl_unittest.cc
@@ -30,7 +30,7 @@ TEST_F(DirectoryImplTest, Read) {
error = ERROR_INTERNAL;
directory->OpenFile(files_to_create[i].name, nullptr,
files_to_create[i].open_flags, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
// Make a directory.
@@ -38,13 +38,13 @@ TEST_F(DirectoryImplTest, Read) {
directory->OpenDirectory("my_dir", nullptr,
kOpenFlagRead | kOpenFlagWrite | kOpenFlagCreate,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
error = ERROR_INTERNAL;
mojo::Array<DirectoryEntryPtr> directory_contents;
directory->Read(Capture(&error, &directory_contents));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Expected contents of the directory.
@@ -81,7 +81,7 @@ TEST_F(DirectoryImplTest, StatTouch) {
error = ERROR_INTERNAL;
FileInformationPtr file_info;
directory->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
EXPECT_EQ(FILE_TYPE_DIRECTORY, file_info->type);
@@ -100,14 +100,14 @@ TEST_F(DirectoryImplTest, StatTouch) {
const int64_t kPartyTime1 = 1234567890; // Party like it's 2009-02-13.
t->timespec->seconds = kPartyTime1;
directory->Touch(t.Pass(), nullptr, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Stat again.
error = ERROR_INTERNAL;
file_info.reset();
directory->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
ASSERT_FALSE(file_info->atime.is_null());
@@ -122,14 +122,14 @@ TEST_F(DirectoryImplTest, StatTouch) {
const int64_t kPartyTime2 = 1425059525; // No time like the present.
t->timespec->seconds = kPartyTime2;
directory->Touch(nullptr, t.Pass(), Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Stat again.
error = ERROR_INTERNAL;
file_info.reset();
directory->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
ASSERT_FALSE(file_info->atime.is_null());
@@ -152,41 +152,41 @@ TEST_F(DirectoryImplTest, BasicRenameDelete) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", nullptr, kOpenFlagWrite | kOpenFlagCreate,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Opening my_file should succeed.
error = ERROR_INTERNAL;
directory->OpenFile("my_file", nullptr, kOpenFlagRead, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Rename my_file to my_new_file.
directory->Rename("my_file", "my_new_file", Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Opening my_file should fail.
error = ERROR_INTERNAL;
directory->OpenFile("my_file", nullptr, kOpenFlagRead, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_UNKNOWN, error);
// Opening my_new_file should succeed.
error = ERROR_INTERNAL;
directory->OpenFile("my_new_file", nullptr, kOpenFlagRead, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Delete my_new_file (no flags).
directory->Delete("my_new_file", 0, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Opening my_new_file should fail.
error = ERROR_INTERNAL;
directory->OpenFile("my_new_file", nullptr, kOpenFlagRead, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_UNKNOWN, error);
}
diff --git a/components/filesystem/file_impl_unittest.cc b/components/filesystem/file_impl_unittest.cc
index 543f6ee..39ab57f 100644
--- a/components/filesystem/file_impl_unittest.cc
+++ b/components/filesystem/file_impl_unittest.cc
@@ -24,7 +24,7 @@ TEST_F(FileImplTest, CreateWriteCloseRenameOpenRead) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -38,21 +38,21 @@ TEST_F(FileImplTest, CreateWriteCloseRenameOpenRead) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
// Rename it.
error = ERROR_INTERNAL;
directory->Rename("my_file", "your_file", Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
{
@@ -61,14 +61,14 @@ TEST_F(FileImplTest, CreateWriteCloseRenameOpenRead) {
error = ERROR_INTERNAL;
directory->OpenFile("your_file", GetProxy(&file), kOpenFlagRead,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Read from it.
mojo::Array<uint8_t> bytes_read;
error = ERROR_INTERNAL;
file->Read(3, 1, WHENCE_FROM_START, Capture(&error, &bytes_read));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_EQ(3u, bytes_read.size());
EXPECT_EQ(static_cast<uint8_t>('e'), bytes_read[0]);
@@ -97,7 +97,7 @@ TEST_F(FileImplTest, CantWriteInReadMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -105,14 +105,14 @@ TEST_F(FileImplTest, CantWriteInReadMode) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
@@ -122,7 +122,7 @@ TEST_F(FileImplTest, CantWriteInReadMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file), kOpenFlagRead,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Try to write in read mode; it should fail.
@@ -130,14 +130,14 @@ TEST_F(FileImplTest, CantWriteInReadMode) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_UNKNOWN, error);
EXPECT_EQ(0u, num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
}
@@ -154,13 +154,13 @@ TEST_F(FileImplTest, OpenExclusive) {
directory->OpenFile("temp_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate |kOpenFlagExclusive,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
@@ -171,7 +171,7 @@ TEST_F(FileImplTest, OpenExclusive) {
directory->OpenFile("temp_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate | kOpenFlagExclusive,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_UNKNOWN, error);
}
}
@@ -187,7 +187,7 @@ TEST_F(FileImplTest, OpenInAppendMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -201,14 +201,14 @@ TEST_F(FileImplTest, OpenInAppendMode) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
@@ -218,7 +218,7 @@ TEST_F(FileImplTest, OpenInAppendMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagAppend, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -234,14 +234,14 @@ TEST_F(FileImplTest, OpenInAppendMode) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
@@ -251,14 +251,14 @@ TEST_F(FileImplTest, OpenInAppendMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file), kOpenFlagRead,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Read from it.
mojo::Array<uint8_t> bytes_read;
error = ERROR_INTERNAL;
file->Read(12, 0, WHENCE_FROM_START, Capture(&error, &bytes_read));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_EQ(12u, bytes_read.size());
EXPECT_EQ(static_cast<uint8_t>('l'), bytes_read[3]);
@@ -279,7 +279,7 @@ TEST_F(FileImplTest, OpenInTruncateMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -293,14 +293,14 @@ TEST_F(FileImplTest, OpenInTruncateMode) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
@@ -310,7 +310,7 @@ TEST_F(FileImplTest, OpenInTruncateMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagTruncate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -326,14 +326,14 @@ TEST_F(FileImplTest, OpenInTruncateMode) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
// Close it.
error = ERROR_INTERNAL;
file->Close(Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
}
@@ -343,14 +343,14 @@ TEST_F(FileImplTest, OpenInTruncateMode) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file), kOpenFlagRead,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Read from it.
mojo::Array<uint8_t> bytes_read;
error = ERROR_INTERNAL;
file->Read(7, 0, WHENCE_FROM_START, Capture(&error, &bytes_read));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_EQ(7u, bytes_read.size());
EXPECT_EQ(static_cast<uint8_t>('g'), bytes_read[0]);
@@ -372,14 +372,14 @@ TEST_F(FileImplTest, StatTouch) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Stat it.
error = ERROR_INTERNAL;
FileInformationPtr file_info;
file->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
EXPECT_EQ(FILE_TYPE_REGULAR_FILE, file_info->type);
@@ -398,14 +398,14 @@ TEST_F(FileImplTest, StatTouch) {
const int64_t kPartyTime1 = 1234567890; // Party like it's 2009-02-13.
t->timespec->seconds = kPartyTime1;
file->Touch(t.Pass(), nullptr, Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Stat again.
error = ERROR_INTERNAL;
file_info.reset();
file->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
ASSERT_FALSE(file_info->atime.is_null());
@@ -420,14 +420,14 @@ TEST_F(FileImplTest, StatTouch) {
const int64_t kPartyTime2 = 1425059525; // No time like the present.
t->timespec->seconds = kPartyTime2;
file->Touch(nullptr, t.Pass(), Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Stat again.
error = ERROR_INTERNAL;
file_info.reset();
file->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
ASSERT_FALSE(file_info->atime.is_null());
@@ -450,7 +450,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -459,7 +459,7 @@ TEST_F(FileImplTest, TellSeek) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
const int size = static_cast<int>(num_bytes_written);
@@ -468,7 +468,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
int64_t position = -1;
file->Tell(Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
// Should be at the end.
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(size, position);
@@ -477,7 +477,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
position = -1;
file->Seek(-100, WHENCE_FROM_CURRENT, Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(size - 100, position);
@@ -485,7 +485,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
position = -1;
file->Tell(Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(size - 100, position);
@@ -493,7 +493,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
position = -1;
file->Seek(123, WHENCE_FROM_START, Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(123, position);
@@ -501,7 +501,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
position = -1;
file->Tell(Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(123, position);
@@ -509,7 +509,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
position = -1;
file->Seek(-123, WHENCE_FROM_END, Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(size - 123, position);
@@ -517,7 +517,7 @@ TEST_F(FileImplTest, TellSeek) {
error = ERROR_INTERNAL;
position = -1;
file->Tell(Capture(&error, &position));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(size - 123, position);
@@ -536,7 +536,7 @@ TEST_F(FileImplTest, Dup) {
directory->OpenFile("my_file", GetProxy(&file1),
kOpenFlagRead | kOpenFlagWrite | kOpenFlagCreate,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -550,7 +550,7 @@ TEST_F(FileImplTest, Dup) {
uint32_t num_bytes_written = 0;
file1->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file1.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file1.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(bytes_to_write.size(), num_bytes_written);
const int end_hello_pos = static_cast<int>(num_bytes_written);
@@ -559,14 +559,14 @@ TEST_F(FileImplTest, Dup) {
FilePtr file2;
error = ERROR_INTERNAL;
file1->Dup(GetProxy(&file2), Capture(&error));
- ASSERT_TRUE(file1.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file1.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// |file2| should have the same position.
error = ERROR_INTERNAL;
int64_t position = -1;
file2->Tell(Capture(&error, &position));
- ASSERT_TRUE(file2.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file2.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(end_hello_pos, position);
@@ -581,7 +581,7 @@ TEST_F(FileImplTest, Dup) {
num_bytes_written = 0;
file2->Write(mojo::Array<uint8_t>::From(more_bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file2.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file2.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(more_bytes_to_write.size(), num_bytes_written);
const int end_world_pos = end_hello_pos + static_cast<int>(num_bytes_written);
@@ -590,21 +590,21 @@ TEST_F(FileImplTest, Dup) {
error = ERROR_INTERNAL;
position = -1;
file1->Tell(Capture(&error, &position));
- ASSERT_TRUE(file1.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file1.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(end_world_pos, position);
// Close |file1|.
error = ERROR_INTERNAL;
file1->Close(Capture(&error));
- ASSERT_TRUE(file1.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file1.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Read everything using |file2|.
mojo::Array<uint8_t> bytes_read;
error = ERROR_INTERNAL;
file2->Read(1000, 0, WHENCE_FROM_START, Capture(&error, &bytes_read));
- ASSERT_TRUE(file2.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file2.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_EQ(static_cast<size_t>(end_world_pos), bytes_read.size());
// Just check the first and last bytes.
@@ -627,7 +627,7 @@ TEST_F(FileImplTest, Truncate) {
error = ERROR_INTERNAL;
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagWrite | kOpenFlagCreate, Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Write to it.
@@ -636,7 +636,7 @@ TEST_F(FileImplTest, Truncate) {
uint32_t num_bytes_written = 0;
file->Write(mojo::Array<uint8_t>::From(bytes_to_write), 0,
WHENCE_FROM_CURRENT, Capture(&error, &num_bytes_written));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
EXPECT_EQ(kInitialSize, num_bytes_written);
@@ -644,7 +644,7 @@ TEST_F(FileImplTest, Truncate) {
error = ERROR_INTERNAL;
FileInformationPtr file_info;
file->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
EXPECT_EQ(kInitialSize, file_info->size);
@@ -652,14 +652,14 @@ TEST_F(FileImplTest, Truncate) {
// Truncate it.
error = ERROR_INTERNAL;
file->Truncate(kTruncatedSize, Capture(&error));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Stat again.
error = ERROR_INTERNAL;
file_info.reset();
file->Stat(Capture(&error, &file_info));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
ASSERT_FALSE(file_info.is_null());
EXPECT_EQ(kTruncatedSize, file_info->size);
@@ -676,13 +676,13 @@ TEST_F(FileImplTest, Ioctl) {
directory->OpenFile("my_file", GetProxy(&file),
kOpenFlagRead | kOpenFlagWrite | kOpenFlagCreate,
Capture(&error));
- ASSERT_TRUE(directory.WaitForIncomingMethodCall());
+ ASSERT_TRUE(directory.WaitForIncomingResponse());
EXPECT_EQ(ERROR_OK, error);
// Normal files don't support any ioctls.
mojo::Array<uint32_t> out_values;
file->Ioctl(0, mojo::Array<uint32_t>(), Capture(&error, &out_values));
- ASSERT_TRUE(file.WaitForIncomingMethodCall());
+ ASSERT_TRUE(file.WaitForIncomingResponse());
EXPECT_EQ(ERROR_UNAVAILABLE, error);
EXPECT_TRUE(out_values.is_null());
}
diff --git a/components/filesystem/files_test_base.cc b/components/filesystem/files_test_base.cc
index b9d39dc..bbe052a 100644
--- a/components/filesystem/files_test_base.cc
+++ b/components/filesystem/files_test_base.cc
@@ -27,7 +27,7 @@ void FilesTestBase::SetUp() {
void FilesTestBase::GetTemporaryRoot(DirectoryPtr* directory) {
Error error = ERROR_INTERNAL;
files()->OpenFileSystem(nullptr, GetProxy(directory), Capture(&error));
- ASSERT_TRUE(files().WaitForIncomingMethodCall());
+ ASSERT_TRUE(files().WaitForIncomingResponse());
ASSERT_EQ(ERROR_OK, error);
}
diff --git a/components/html_viewer/web_clipboard_impl.cc b/components/html_viewer/web_clipboard_impl.cc
index 8810c3d..0641a93 100644
--- a/components/html_viewer/web_clipboard_impl.cc
+++ b/components/html_viewer/web_clipboard_impl.cc
@@ -69,7 +69,7 @@ uint64_t WebClipboardImpl::sequenceNumber(Buffer buffer) {
base::Bind(&CopyUint64, &number));
// Force this to be synchronous.
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
return number;
}
@@ -81,7 +81,7 @@ bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) {
clipboard_type, base::Bind(&CopyVectorString, &types));
// Force this to be synchronous.
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
switch (format) {
case FormatPlainText:
@@ -108,7 +108,7 @@ blink::WebVector<blink::WebString> WebClipboardImpl::readAvailableTypes(
clipboard_type, base::Bind(&CopyVectorString, &types));
// Force this to be synchronous.
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
// AFAICT, every instance of setting contains_filenames is false.
*contains_filenames = false;
@@ -129,7 +129,7 @@ blink::WebString WebClipboardImpl::readPlainText(Buffer buffer) {
base::Bind(&CopyWebString, &text));
// Force this to be synchronous.
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
return text;
}
@@ -143,14 +143,14 @@ blink::WebString WebClipboardImpl::readHTML(Buffer buffer,
blink::WebString html;
clipboard_->ReadMimeType(type, Clipboard::MIME_TYPE_HTML,
base::Bind(&CopyWebString, &html));
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
*fragment_start = 0;
*fragment_end = static_cast<unsigned>(html.length());
clipboard_->ReadMimeType(type, Clipboard::MIME_TYPE_URL,
base::Bind(&CopyURL, page_url));
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
return html;
}
@@ -165,7 +165,7 @@ blink::WebString WebClipboardImpl::readCustomData(
clipboard_type, mime_type.utf8(), base::Bind(&CopyWebString, &data));
// Force this to be synchronous.
- clipboard_.WaitForIncomingMethodCall();
+ clipboard_.WaitForIncomingResponse();
return data;
}
diff --git a/components/html_viewer/web_cookie_jar_impl.cc b/components/html_viewer/web_cookie_jar_impl.cc
index 019acfb..c59bfd2 100644
--- a/components/html_viewer/web_cookie_jar_impl.cc
+++ b/components/html_viewer/web_cookie_jar_impl.cc
@@ -43,7 +43,7 @@ void WebCookieJarImpl::setCookie(const blink::WebURL& url,
// and URLLoader, so that we could let this method call run asynchronously
// without suffering an ordering problem. See crbug/386825.
//
- store_.WaitForIncomingMethodCall();
+ store_.WaitForIncomingResponse();
}
blink::WebString WebCookieJarImpl::cookies(
@@ -53,9 +53,9 @@ blink::WebString WebCookieJarImpl::cookies(
store_->Get(url.string().utf8(), base::Bind(&CopyString, &result));
// Wait for the result. Since every outbound request we make to the cookie
- // store is followed up with WaitForIncomingMethodCall, we can be sure that
+ // store is followed up with WaitForIncomingResponse, we can be sure that
// the next incoming method call will be the response to our request.
- store_.WaitForIncomingMethodCall();
+ store_.WaitForIncomingResponse();
if (!result)
return blink::WebString();
diff --git a/components/resource_provider/public/cpp/resource_loader.cc b/components/resource_provider/public/cpp/resource_loader.cc
index d5e4f8f..ba31461 100644
--- a/components/resource_provider/public/cpp/resource_loader.cc
+++ b/components/resource_provider/public/cpp/resource_loader.cc
@@ -38,7 +38,7 @@ bool ResourceLoader::BlockUntilLoaded() {
return loaded_;
did_block_ = true;
- resource_provider_.WaitForIncomingMethodCall();
+ resource_provider_.WaitForIncomingResponse();
return loaded_;
}
diff --git a/mandoline/ui/aura/surface_binding.cc b/mandoline/ui/aura/surface_binding.cc
index 3f1dd1de..6f71d1e 100644
--- a/mandoline/ui/aura/surface_binding.cc
+++ b/mandoline/ui/aura/surface_binding.cc
@@ -214,7 +214,7 @@ void SurfaceBinding::PerViewManagerState::Init() {
base::Bind(&SurfaceBinding::PerViewManagerState::SetIdNamespace,
base::Unretained(this)));
// Block until we receive our id namespace.
- surface_.WaitForIncomingMethodCall();
+ surface_.WaitForIncomingResponse();
DCHECK_NE(0u, id_namespace_);
mojo::ResourceReturnerPtr returner_ptr;
diff --git a/mojo/environment/default_logger_impl.cc b/mojo/environment/default_logger_impl.cc
index 575feb3..9a32100 100644
--- a/mojo/environment/default_logger_impl.cc
+++ b/mojo/environment/default_logger_impl.cc
@@ -33,7 +33,10 @@ MojoLogLevel ChromiumToMojoLogLevel(int chromium_log_level) {
return static_cast<MojoLogLevel>(chromium_log_level);
}
-void LogMessage(MojoLogLevel log_level, const char* message) {
+void LogMessage(MojoLogLevel log_level,
+ const char* source_file,
+ uint32_t source_line,
+ const char* message) {
int chromium_log_level = MojoToChromiumLogLevel(log_level);
int chromium_min_log_level = logging::GetMinLogLevel();
// "Fatal" errors aren't suppressable.
diff --git a/mojo/runner/shell_apptest.cc b/mojo/runner/shell_apptest.cc
index 38519ef..a2bf37d 100644
--- a/mojo/runner/shell_apptest.cc
+++ b/mojo/runner/shell_apptest.cc
@@ -91,13 +91,13 @@ class ShellHTTPAppTest : public test::ApplicationTestBase {
local_address.Pass());
http_server_->GetPort([this](uint16_t p) { port_ = p; });
- EXPECT_TRUE(http_server_.WaitForIncomingMethodCall());
+ EXPECT_TRUE(http_server_.WaitForIncomingResponse());
InterfacePtr<http_server::HttpHandler> http_handler;
handler_.reset(new GetHandler(GetProxy(&http_handler).Pass(), port_));
http_server_->SetHandler(".*", http_handler.Pass(),
[](bool result) { EXPECT_TRUE(result); });
- EXPECT_TRUE(http_server_.WaitForIncomingMethodCall());
+ EXPECT_TRUE(http_server_.WaitForIncomingResponse());
}
std::string GetURL(const std::string& path) {
diff --git a/mojo/services/network/http_server_apptest.cc b/mojo/services/network/http_server_apptest.cc
index 9652c05a..32c249c 100644
--- a/mojo/services/network/http_server_apptest.cc
+++ b/mojo/services/network/http_server_apptest.cc
@@ -567,7 +567,7 @@ class HttpServerAppTest : public test::ApplicationTestBase {
EXPECT_NE(0u, bound_to->ipv4->port);
*out_bound_to = bound_to.Pass();
});
- network_service_.WaitForIncomingMethodCall();
+ network_service_.WaitForIncomingResponse();
}
NetworkServicePtr network_service_;
diff --git a/mojo/tools/rev_sdk.py b/mojo/tools/rev_sdk.py
index 15812c5..06241ee 100755
--- a/mojo/tools/rev_sdk.py
+++ b/mojo/tools/rev_sdk.py
@@ -23,7 +23,7 @@ sdk_dirs_to_clone = [
sdk_dirs_to_not_clone = [
"mojo/public/cpp/application",
"mojo/public/interfaces/application",
- "third_party/mojo/src/mojo/public/java/application",
+ "mojo/public/java/application",
]
# Individual files to preserve within the target repository during roll. These
@@ -43,8 +43,9 @@ for sdk_dir in sdk_dirs_to_clone:
sdk_dir_in_chromium = os.path.join(sdk_prefix_in_chromium, sdk_dir)
dirs_to_clone[sdk_dir] = sdk_dir_in_chromium
-def rev(source_dir, chromium_dir):
- src_commit = system(["git", "show-ref", "HEAD", "-s"], cwd=source_dir).strip()
+def rev(source_dir, chromium_dir, mojo_revision):
+ src_commit = system(["git", "rev-parse", mojo_revision],
+ cwd=source_dir).strip()
for input_dir, dest_dir in dirs_to_clone.iteritems():
if os.path.exists(os.path.join(chromium_dir, dest_dir)):
@@ -89,8 +90,15 @@ def rev(source_dir, chromium_dir):
commit("Update mojo sdk to rev " + src_commit, cwd=chromium_dir)
-if len(sys.argv) != 2:
- print "usage: rev_sdk.py <mojo source dir>"
+if len(sys.argv) < 2:
+ print "usage: rev_sdk.py <mojo source dir> [<mojo revision>]"
sys.exit(1)
-rev(sys.argv[1], chromium_root_dir)
+# Allow override of the roll revision.
+if len(sys.argv) == 3:
+ mojo_revision = sys.argv[2]
+else:
+ mojo_revision = 'origin/HEAD'
+
+rev(sys.argv[1], chromium_root_dir, mojo_revision)
+
diff --git a/net/proxy/proxy_resolver_mojo_unittest.cc b/net/proxy/proxy_resolver_mojo_unittest.cc
index a99e755..dd62518 100644
--- a/net/proxy/proxy_resolver_mojo_unittest.cc
+++ b/net/proxy/proxy_resolver_mojo_unittest.cc
@@ -248,7 +248,7 @@ void MockMojoProxyResolver::GetProxyForUrl(
binding_.Close();
break;
case GetProxyForUrlAction::WAIT_FOR_CLIENT_DISCONNECT:
- ASSERT_FALSE(client.WaitForIncomingMethodCall());
+ ASSERT_FALSE(client.WaitForIncomingResponse());
break;
case GetProxyForUrlAction::SEND_LOAD_STATE_AND_BLOCK:
client->LoadStateChanged(LOAD_STATE_RESOLVING_HOST_IN_PROXY_SCRIPT);
@@ -400,7 +400,7 @@ void MockMojoProxyResolverFactory::CreateResolver(
// Both |request| and |client| will be closed.
break;
case CreateProxyResolverAction::WAIT_FOR_CLIENT_DISCONNECT:
- ASSERT_FALSE(client.WaitForIncomingMethodCall());
+ ASSERT_FALSE(client.WaitForIncomingResponse());
break;
}
WakeWaiter();
diff --git a/third_party/mojo/mojom_bindings_generator_variables.gypi b/third_party/mojo/mojom_bindings_generator_variables.gypi
index ad28869..d1ea5fc 100644
--- a/third_party/mojo/mojom_bindings_generator_variables.gypi
+++ b/third_party/mojo/mojom_bindings_generator_variables.gypi
@@ -27,14 +27,15 @@
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/constant_definition.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/constants.java.tmpl',
+ '<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/data_types_definition.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/enum_definition.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/enum.java.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/header.java.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl',
- '<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface.java.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_internal.java.tmpl',
- '<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl',
+ '<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface.java.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl',
+ '<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/union.java.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/js_templates/enum_definition.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/js_templates/interface_definition.tmpl',
'<(DEPTH)/third_party/mojo/src/mojo/public/tools/bindings/generators/js_templates/module_definition.tmpl',
diff --git a/third_party/mojo/src/mojo/edk/embedder/embedder.cc b/third_party/mojo/src/mojo/edk/embedder/embedder.cc
index 58919fb..29c5217 100644
--- a/third_party/mojo/src/mojo/edk/embedder/embedder.cc
+++ b/third_party/mojo/src/mojo/edk/embedder/embedder.cc
@@ -251,11 +251,46 @@ void ShutdownIPCSupport() {
}
void ConnectToSlave(SlaveInfo slave_info,
- ScopedPlatformHandle platform_handle) {
+ ScopedPlatformHandle platform_handle,
+ ScopedPlatformHandle* platform_connection_handle,
+ std::string* platform_connection_id) {
DCHECK(platform_handle.is_valid());
+ DCHECK(platform_connection_handle);
+ DCHECK(platform_connection_id);
DCHECK(internal::g_process_type == ProcessType::MASTER);
- static_cast<system::MasterConnectionManager*>(g_connection_manager)
- ->AddSlave(slave_info, platform_handle.Pass());
+ DCHECK(g_connection_manager);
+
+ system::ConnectionIdentifier connection_id =
+ g_connection_manager->GenerateConnectionIdentifier();
+ system::ProcessIdentifier slave_id = system::kInvalidProcessIdentifier;
+ CHECK(static_cast<system::MasterConnectionManager*>(g_connection_manager)
+ ->AddSlaveAndBootstrap(slave_info, platform_handle.Pass(),
+ connection_id, &slave_id));
+
+ system::ProcessIdentifier peer_id = system::kInvalidProcessIdentifier;
+ CHECK(g_connection_manager->Connect(connection_id, &peer_id,
+ platform_connection_handle));
+ DCHECK_EQ(peer_id, slave_id);
+ DCHECK(platform_connection_handle->is_valid());
+
+ *platform_connection_id = connection_id.ToString();
+}
+
+void ConnectToMaster(const std::string& platform_connection_id,
+ ScopedPlatformHandle* platform_connection_handle) {
+ DCHECK(internal::g_process_type == ProcessType::SLAVE);
+ DCHECK(g_connection_manager);
+
+ bool ok = false;
+ system::ConnectionIdentifier connection_id =
+ system::ConnectionIdentifier::FromString(platform_connection_id, &ok);
+ CHECK(ok);
+
+ system::ProcessIdentifier peer_id;
+ CHECK(g_connection_manager->Connect(connection_id, &peer_id,
+ platform_connection_handle));
+ DCHECK_EQ(peer_id, system::kMasterProcessIdentifier);
+ DCHECK(platform_connection_handle->is_valid());
}
// TODO(vtl): Write tests for this.
diff --git a/third_party/mojo/src/mojo/edk/embedder/embedder.h b/third_party/mojo/src/mojo/edk/embedder/embedder.h
index 142c86f..50ec184 100644
--- a/third_party/mojo/src/mojo/edk/embedder/embedder.h
+++ b/third_party/mojo/src/mojo/edk/embedder/embedder.h
@@ -5,6 +5,8 @@
#ifndef MOJO_EDK_EMBEDDER_EMBEDDER_H_
#define MOJO_EDK_EMBEDDER_EMBEDDER_H_
+#include <string>
+
#include "base/callback.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
@@ -108,16 +110,42 @@ MOJO_SYSTEM_IMPL_EXPORT void ShutdownIPCSupport();
// Interprocess communication (IPC) functions ----------------------------------
-// Connects to a slave process to the IPC system. This should only be called in
-// a process initialized (using |InitIPCSupport()|) with process type
-// |ProcessType::MASTER|. |slave_info| is caller-dependent slave information,
-// which should remain alive until the master process delegate's
-// |OnSlaveDisconnect()| is called. |platform_handle| should be a handle to one
-// end of an OS "pipe"; the slave process should |InitIPCSupport()| with
-// |ProcessType::SLAVE| and the handle to the other end of this OS "pipe".
+// Called in the master process to connect to a slave process to the IPC system.
+// (This should only be called in a process initialized (using
+// |InitIPCSupport()|) with process type |ProcessType::MASTER|.)
+//
+// This should typically be called *before* the slave process is even created.
+// It requires an OS "pipe" to be established between the master and slave
+// processes, with |platform_handle| being a handle to the end that remains on
+// the master. This will create a second OS "pipe" (returned in
+// |*platform_connection_handle|), and an ID string (returned in
+// |*platform_connection_id|) that must be passed to the slave, e.g., on the
+// command line.
+//
+// The slave should call |InitIPCSupport()| with |ProcessType::SLAVE| and the
+// handle to the other end of the first "pipe" above. Then it should call
+// |ConnectToMaster()| with the ID string |*platform_connection_id|.
+//
+// |slave_info| is caller-dependent slave information, which should typically
+// remain alive until the master process delegate's |OnSlaveDisconnect()| is
+// called. (It may, however, be null.)
MOJO_SYSTEM_IMPL_EXPORT void ConnectToSlave(
SlaveInfo slave_info,
- ScopedPlatformHandle platform_handle);
+ ScopedPlatformHandle platform_handle,
+ ScopedPlatformHandle* platform_connection_handle,
+ std::string* platform_connection_id);
+
+// Called in a slave process to connect it to the IPC system. (This should only
+// be called in a process initialized (using |InitIPCSupport()|) with process
+// type |ProcessType::SLAVE|.) This should be called exactly once in each slave
+// process.
+//
+// See |ConnectToSlave()| for details. (Note that if this fails in any way,
+// e.g., if |platform_connection_id| is invalid, this will CHECK-fail and
+// terminate the process.)
+MOJO_SYSTEM_IMPL_EXPORT void ConnectToMaster(
+ const std::string& platform_connection_id,
+ ScopedPlatformHandle* platform_connection_handle);
// A "channel" is a connection on top of an OS "pipe", on top of which Mojo
// message pipes (etc.) can be multiplexed. It must "live" on some I/O thread.
diff --git a/third_party/mojo/src/mojo/edk/embedder/embedder_unittest.cc b/third_party/mojo/src/mojo/edk/embedder/embedder_unittest.cc
index 48a59c1..5dc34b1e 100644
--- a/third_party/mojo/src/mojo/edk/embedder/embedder_unittest.cc
+++ b/third_party/mojo/src/mojo/edk/embedder/embedder_unittest.cc
@@ -7,6 +7,7 @@
#include <string.h>
#include "base/bind.h"
+#include "base/command_line.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
@@ -19,6 +20,7 @@
#include "mojo/edk/system/test_utils.h"
#include "mojo/edk/test/multiprocess_test_helper.h"
#include "mojo/edk/test/scoped_ipc_support.h"
+#include "mojo/edk/test/test_utils.h"
#include "mojo/public/c/system/core.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -33,6 +35,8 @@ const MojoHandleSignals kSignalAll = MOJO_HANDLE_SIGNAL_READABLE |
MOJO_HANDLE_SIGNAL_WRITABLE |
MOJO_HANDLE_SIGNAL_PEER_CLOSED;
+const char kConnectionIdFlag[] = "test-connection-id";
+
class ScopedTestChannel {
public:
// Creates a channel that lives on a given I/O thread (determined by the given
@@ -215,8 +219,7 @@ void CloseScopedHandle(ScopedMessagePipeHandle handle) {
TEST_F(EmbedderTest, AsyncWait) {
ScopedMessagePipeHandle client_mp;
ScopedMessagePipeHandle server_mp;
- EXPECT_EQ(MOJO_RESULT_OK,
- mojo::CreateMessagePipe(nullptr, &client_mp, &server_mp));
+ EXPECT_EQ(MOJO_RESULT_OK, CreateMessagePipe(nullptr, &client_mp, &server_mp));
TestAsyncWaiter waiter;
EXPECT_EQ(MOJO_RESULT_OK,
@@ -380,6 +383,83 @@ TEST_F(EmbedderTest, ChannelsHandlePassing) {
EXPECT_TRUE(client_channel.channel_info());
}
+#if defined(OS_ANDROID) || defined(OS_WIN)
+// Android multi-process tests are not executing the new process. This is flaky.
+// TODO(vtl): I'm guessing this is true of this test too?
+#define MAYBE_MultiprocessMasterSlave DISABLED_MultiprocessMasterSlave
+#else
+#define MAYBE_MultiprocessMasterSlave MultiprocessMasterSlave
+#endif // defined(OS_ANDROID)
+TEST_F(EmbedderTest, MAYBE_MultiprocessMasterSlave) {
+ mojo::test::ScopedMasterIPCSupport ipc_support(test_io_task_runner());
+
+ mojo::test::MultiprocessTestHelper multiprocess_test_helper;
+ ScopedPlatformHandle second_platform_handle;
+ std::string connection_id;
+ ConnectToSlave(nullptr,
+ multiprocess_test_helper.server_platform_handle.Pass(),
+ &second_platform_handle, &connection_id);
+ ASSERT_TRUE(second_platform_handle.is_valid());
+ ASSERT_FALSE(connection_id.empty());
+
+ multiprocess_test_helper.StartChildWithExtraSwitch(
+ "MultiprocessMasterSlave", kConnectionIdFlag, connection_id);
+
+ // We write a '?'. The slave should write a '!' in response.
+ size_t n = 0;
+ EXPECT_TRUE(
+ mojo::test::BlockingWrite(second_platform_handle.get(), "?", 1, &n));
+ EXPECT_EQ(1u, n);
+
+ char c = '\0';
+ n = 0;
+ EXPECT_TRUE(
+ mojo::test::BlockingRead(second_platform_handle.get(), &c, 1, &n));
+ EXPECT_EQ(1u, n);
+ EXPECT_EQ('!', c);
+
+ EXPECT_TRUE(multiprocess_test_helper.WaitForChildTestShutdown());
+}
+
+MOJO_MULTIPROCESS_TEST_CHILD_TEST(MultiprocessMasterSlave) {
+ ScopedPlatformHandle client_platform_handle =
+ mojo::test::MultiprocessTestHelper::client_platform_handle.Pass();
+ EXPECT_TRUE(client_platform_handle.is_valid());
+
+ base::TestIOThread test_io_thread(base::TestIOThread::kAutoStart);
+ test::InitWithSimplePlatformSupport();
+
+ {
+ mojo::test::ScopedSlaveIPCSupport ipc_support(
+ test_io_thread.task_runner(), client_platform_handle.Pass());
+
+ const base::CommandLine& command_line =
+ *base::CommandLine::ForCurrentProcess();
+ ASSERT_TRUE(command_line.HasSwitch(kConnectionIdFlag));
+ std::string connection_id =
+ command_line.GetSwitchValueASCII(kConnectionIdFlag);
+ ASSERT_FALSE(connection_id.empty());
+ ScopedPlatformHandle second_platform_handle;
+ ConnectToMaster(connection_id, &second_platform_handle);
+ ASSERT_TRUE(second_platform_handle.is_valid());
+
+ // The master should write a '?'. We'll write a '!' in response.
+ char c = '\0';
+ size_t n = 0;
+ EXPECT_TRUE(
+ mojo::test::BlockingRead(second_platform_handle.get(), &c, 1, &n));
+ EXPECT_EQ(1u, n);
+ EXPECT_EQ('?', c);
+
+ n = 0;
+ EXPECT_TRUE(
+ mojo::test::BlockingWrite(second_platform_handle.get(), "!", 1, &n));
+ EXPECT_EQ(1u, n);
+ }
+
+ EXPECT_TRUE(test::Shutdown());
+}
+
// The sequence of messages sent is:
// server_mp client_mp mp0 mp1 mp2 mp3
// 1. "hello"
diff --git a/third_party/mojo/src/mojo/edk/embedder/platform_channel_pair_posix_unittest.cc b/third_party/mojo/src/mojo/edk/embedder/platform_channel_pair_posix_unittest.cc
index 5ac8ef8..945ab89 100644
--- a/third_party/mojo/src/mojo/edk/embedder/platform_channel_pair_posix_unittest.cc
+++ b/third_party/mojo/src/mojo/edk/embedder/platform_channel_pair_posix_unittest.cc
@@ -133,6 +133,7 @@ TEST_F(PlatformChannelPairPosixTest, SendReceiveData) {
#else
#define MAYBE_SendReceiveFDs SendReceiveFDs
#endif
+
TEST_F(PlatformChannelPairPosixTest, MAYBE_SendReceiveFDs) {
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
diff --git a/third_party/mojo/src/mojo/edk/system/connection_manager_unittest.cc b/third_party/mojo/src/mojo/edk/system/connection_manager_unittest.cc
index 2545788..0d8f479 100644
--- a/third_party/mojo/src/mojo/edk/system/connection_manager_unittest.cc
+++ b/third_party/mojo/src/mojo/edk/system/connection_manager_unittest.cc
@@ -84,10 +84,12 @@ class TestSlaveInfo {
void ConnectSlave(MasterConnectionManager* master,
embedder::SlaveProcessDelegate* slave_process_delegate,
SlaveConnectionManager* slave,
- const std::string& slave_name) {
+ const std::string& slave_name,
+ ProcessIdentifier* slave_process_identifier) {
embedder::PlatformChannelPair platform_channel_pair;
master->AddSlave(new TestSlaveInfo(slave_name),
- platform_channel_pair.PassServerHandle());
+ platform_channel_pair.PassServerHandle(),
+ slave_process_identifier);
slave->Init(base::MessageLoop::current()->task_runner(),
slave_process_delegate, platform_channel_pair.PassClientHandle());
}
@@ -205,11 +207,20 @@ TEST_F(ConnectionManagerTest, BasicConnectSlaves) {
MockSlaveProcessDelegate slave1_process_delegate;
SlaveConnectionManager slave1(platform_support());
- ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1");
+ ProcessIdentifier slave1_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1",
+ &slave1_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave1_id));
MockSlaveProcessDelegate slave2_process_delegate;
SlaveConnectionManager slave2(platform_support());
- ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2");
+ ProcessIdentifier slave2_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2",
+ &slave2_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave2_id));
+ // TODO(vtl): If/when I add the ability to get one's own process identifier,
+ // there'll be more we can check.
+ EXPECT_NE(slave1_id, slave2_id);
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(slave1.AllowConnect(connection_id));
@@ -218,17 +229,14 @@ TEST_F(ConnectionManagerTest, BasicConnectSlaves) {
ProcessIdentifier peer1 = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle h1;
EXPECT_TRUE(slave1.Connect(connection_id, &peer1, &h1));
- EXPECT_TRUE(IsValidSlaveProcessIdentifier(peer1));
+ EXPECT_EQ(slave2_id, peer1);
EXPECT_TRUE(h1.is_valid());
ProcessIdentifier peer2 = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle h2;
EXPECT_TRUE(slave2.Connect(connection_id, &peer2, &h2));
- EXPECT_TRUE(IsValidSlaveProcessIdentifier(peer2));
+ EXPECT_EQ(slave1_id, peer2);
EXPECT_TRUE(h2.is_valid());
- // TODO(vtl): If/when I add the ability to get one's own process identifier,
- // there'll be more we can check.
- EXPECT_NE(peer1, peer2);
EXPECT_TRUE(ArePlatformHandlesConnected(h1.get(), h2.get()));
// The process manager shouldn't have gotten any notifications yet. (Spin the
@@ -265,7 +273,9 @@ TEST_F(ConnectionManagerTest, ShutdownMasterBeforeSlave) {
MockSlaveProcessDelegate slave_process_delegate;
SlaveConnectionManager slave(platform_support());
- ConnectSlave(&master, &slave_process_delegate, &slave, "slave");
+ ProcessIdentifier slave_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave_process_delegate, &slave, "slave", &slave_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave_id));
// The process manager shouldn't have gotten any notifications yet. (Spin the
// message loop to make sure none were enqueued.)
@@ -293,11 +303,18 @@ TEST_F(ConnectionManagerTest, SlaveCancelConnect) {
MockSlaveProcessDelegate slave1_process_delegate;
SlaveConnectionManager slave1(platform_support());
- ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1");
+ ProcessIdentifier slave1_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1",
+ &slave1_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave1_id));
MockSlaveProcessDelegate slave2_process_delegate;
SlaveConnectionManager slave2(platform_support());
- ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2");
+ ProcessIdentifier slave2_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2",
+ &slave2_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave2_id));
+ EXPECT_NE(slave1_id, slave2_id);
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(slave1.AllowConnect(connection_id));
@@ -323,11 +340,18 @@ TEST_F(ConnectionManagerTest, ErrorRemovePending) {
MockSlaveProcessDelegate slave1_process_delegate;
SlaveConnectionManager slave1(platform_support());
- ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1");
+ ProcessIdentifier slave1_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1",
+ &slave1_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave1_id));
MockSlaveProcessDelegate slave2_process_delegate;
SlaveConnectionManager slave2(platform_support());
- ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2");
+ ProcessIdentifier slave2_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2",
+ &slave2_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave2_id));
+ EXPECT_NE(slave1_id, slave2_id);
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(slave1.AllowConnect(connection_id));
@@ -358,7 +382,9 @@ TEST_F(ConnectionManagerTest, ConnectSlaveToSelf) {
MockSlaveProcessDelegate slave_process_delegate;
SlaveConnectionManager slave(platform_support());
- ConnectSlave(&master, &slave_process_delegate, &slave, "slave");
+ ProcessIdentifier slave_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave_process_delegate, &slave, "slave", &slave_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave_id));
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(slave.AllowConnect(connection_id));
@@ -369,16 +395,14 @@ TEST_F(ConnectionManagerTest, ConnectSlaveToSelf) {
ProcessIdentifier peer1 = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle h1;
EXPECT_TRUE(slave.Connect(connection_id, &peer1, &h1));
- EXPECT_TRUE(IsValidSlaveProcessIdentifier(peer1));
+ EXPECT_EQ(slave_id, peer1);
EXPECT_FALSE(h1.is_valid());
ProcessIdentifier peer2 = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle h2;
EXPECT_TRUE(slave.Connect(connection_id, &peer2, &h2));
- EXPECT_TRUE(IsValidSlaveProcessIdentifier(peer2));
+ EXPECT_EQ(slave_id, peer2);
EXPECT_FALSE(h2.is_valid());
- EXPECT_EQ(peer1, peer2);
-
slave.Shutdown();
master.Shutdown();
}
@@ -390,11 +414,18 @@ TEST_F(ConnectionManagerTest, ConnectSlavesTwice) {
MockSlaveProcessDelegate slave1_process_delegate;
SlaveConnectionManager slave1(platform_support());
- ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1");
+ ProcessIdentifier slave1_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave1_process_delegate, &slave1, "slave1",
+ &slave1_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave1_id));
MockSlaveProcessDelegate slave2_process_delegate;
SlaveConnectionManager slave2(platform_support());
- ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2");
+ ProcessIdentifier slave2_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave2_process_delegate, &slave2, "slave2",
+ &slave2_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave2_id));
+ EXPECT_NE(slave1_id, slave2_id);
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(slave1.AllowConnect(connection_id));
@@ -403,11 +434,12 @@ TEST_F(ConnectionManagerTest, ConnectSlavesTwice) {
ProcessIdentifier peer1 = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle h1;
EXPECT_TRUE(slave1.Connect(connection_id, &peer1, &h1));
+ EXPECT_EQ(slave2_id, peer1);
ProcessIdentifier peer2 = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle h2;
EXPECT_TRUE(slave2.Connect(connection_id, &peer2, &h2));
+ EXPECT_EQ(slave1_id, peer2);
- EXPECT_NE(peer1, peer2);
EXPECT_TRUE(ArePlatformHandlesConnected(h1.get(), h2.get()));
// Currently, the master doesn't detect the case of connecting a pair of
@@ -442,7 +474,9 @@ TEST_F(ConnectionManagerTest, ConnectMasterToSlave) {
MockSlaveProcessDelegate slave_process_delegate;
SlaveConnectionManager slave(platform_support());
- ConnectSlave(&master, &slave_process_delegate, &slave, "slave");
+ ProcessIdentifier slave_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave_process_delegate, &slave, "slave", &slave_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave_id));
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(master.AllowConnect(connection_id));
@@ -451,7 +485,7 @@ TEST_F(ConnectionManagerTest, ConnectMasterToSlave) {
ProcessIdentifier master_peer = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle master_h;
EXPECT_TRUE(master.Connect(connection_id, &master_peer, &master_h));
- EXPECT_TRUE(IsValidSlaveProcessIdentifier(master_peer));
+ EXPECT_EQ(slave_id, master_peer);
EXPECT_TRUE(master_h.is_valid());
ProcessIdentifier slave_peer = kInvalidProcessIdentifier;
embedder::ScopedPlatformHandle slave_h;
@@ -459,7 +493,6 @@ TEST_F(ConnectionManagerTest, ConnectMasterToSlave) {
EXPECT_EQ(kMasterProcessIdentifier, slave_peer);
EXPECT_TRUE(slave_h.is_valid());
- EXPECT_NE(master_peer, slave_peer);
EXPECT_TRUE(ArePlatformHandlesConnected(master_h.get(), slave_h.get()));
slave.Shutdown();
@@ -500,7 +533,9 @@ TEST_F(ConnectionManagerTest, MasterCancelConnect) {
MockSlaveProcessDelegate slave_process_delegate;
SlaveConnectionManager slave(platform_support());
- ConnectSlave(&master, &slave_process_delegate, &slave, "slave");
+ ProcessIdentifier slave_id = kInvalidProcessIdentifier;
+ ConnectSlave(&master, &slave_process_delegate, &slave, "slave", &slave_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave_id));
ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
EXPECT_TRUE(master.AllowConnect(connection_id));
@@ -525,12 +560,52 @@ TEST_F(ConnectionManagerTest, AddSlaveThenImmediateShutdown) {
MockSlaveProcessDelegate slave_process_delegate;
SlaveConnectionManager slave(platform_support());
embedder::PlatformChannelPair platform_channel_pair;
+ ProcessIdentifier slave_id = kInvalidProcessIdentifier;
master.AddSlave(new TestSlaveInfo("slave"),
- platform_channel_pair.PassServerHandle());
+ platform_channel_pair.PassServerHandle(), &slave_id);
master.Shutdown();
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave_id));
// Since we never initialized |slave|, we don't have to shut it down.
}
+TEST_F(ConnectionManagerTest, AddSlaveAndBootstrap) {
+ MasterConnectionManager master(platform_support());
+ master.Init(base::MessageLoop::current()->task_runner(),
+ &master_process_delegate());
+
+ embedder::PlatformChannelPair platform_channel_pair;
+ ConnectionIdentifier connection_id = master.GenerateConnectionIdentifier();
+ ProcessIdentifier slave_id = kInvalidProcessIdentifier;
+ master.AddSlaveAndBootstrap(new TestSlaveInfo("slave"),
+ platform_channel_pair.PassServerHandle(),
+ connection_id, &slave_id);
+ EXPECT_TRUE(IsValidSlaveProcessIdentifier(slave_id));
+
+ embedder::ScopedPlatformHandle h1;
+ ProcessIdentifier master_peer = kInvalidProcessIdentifier;
+ EXPECT_TRUE(master.Connect(connection_id, &master_peer, &h1));
+ EXPECT_EQ(slave_id, master_peer);
+ EXPECT_TRUE(h1.is_valid());
+
+ // We can delay creating/initializing |slave| for quite a while.
+ MockSlaveProcessDelegate slave_process_delegate;
+ SlaveConnectionManager slave(platform_support());
+ slave.Init(base::MessageLoop::current()->task_runner(),
+ &slave_process_delegate, platform_channel_pair.PassClientHandle());
+
+ ProcessIdentifier slave_peer = kInvalidProcessIdentifier;
+ embedder::ScopedPlatformHandle h2;
+ EXPECT_TRUE(slave.Connect(connection_id, &slave_peer, &h2));
+ EXPECT_EQ(kMasterProcessIdentifier, slave_peer);
+
+ EXPECT_TRUE(ArePlatformHandlesConnected(h1.get(), h2.get()));
+
+ slave.Shutdown();
+ master.Shutdown();
+}
+
+// TODO(vtl): More shutdown cases for |AddSlaveAndBootstrap()|?
+
} // namespace
} // namespace system
} // namespace mojo
diff --git a/third_party/mojo/src/mojo/edk/system/master_connection_manager.cc b/third_party/mojo/src/mojo/edk/system/master_connection_manager.cc
index f8dd744..afd7f07 100644
--- a/third_party/mojo/src/mojo/edk/system/master_connection_manager.cc
+++ b/third_party/mojo/src/mojo/edk/system/master_connection_manager.cc
@@ -252,11 +252,20 @@ void MasterConnectionManager::Init(
void MasterConnectionManager::AddSlave(
embedder::SlaveInfo slave_info,
- embedder::ScopedPlatformHandle platform_handle) {
+ embedder::ScopedPlatformHandle platform_handle,
+ ProcessIdentifier* slave_process_identifier) {
// We don't really care if |slave_info| is non-null or not.
DCHECK(platform_handle.is_valid());
+ DCHECK(slave_process_identifier);
AssertNotOnPrivateThread();
+ {
+ base::AutoLock locker(lock_);
+ CHECK_NE(next_process_identifier_, kMasterProcessIdentifier);
+ *slave_process_identifier = next_process_identifier_;
+ next_process_identifier_++;
+ }
+
// We have to wait for the task to be executed, in case someone calls
// |AddSlave()| followed immediately by |Shutdown()|.
base::WaitableEvent event(false, false);
@@ -264,10 +273,32 @@ void MasterConnectionManager::AddSlave(
FROM_HERE,
base::Bind(&MasterConnectionManager::AddSlaveOnPrivateThread,
base::Unretained(this), base::Unretained(slave_info),
- base::Passed(&platform_handle), base::Unretained(&event)));
+ base::Passed(&platform_handle), *slave_process_identifier,
+ base::Unretained(&event)));
event.Wait();
}
+bool MasterConnectionManager::AddSlaveAndBootstrap(
+ embedder::SlaveInfo slave_info,
+ embedder::ScopedPlatformHandle platform_handle,
+ const ConnectionIdentifier& connection_id,
+ ProcessIdentifier* slave_process_identifier) {
+ AddSlave(slave_info, platform_handle.Pass(), slave_process_identifier);
+
+ base::AutoLock locker(lock_);
+
+ auto it = pending_connections_.find(connection_id);
+ if (it != pending_connections_.end())
+ return false;
+
+ PendingConnectionInfo* info =
+ new PendingConnectionInfo(kMasterProcessIdentifier);
+ info->state = PendingConnectionInfo::AWAITING_CONNECTS_FROM_BOTH;
+ info->second = *slave_process_identifier;
+ pending_connections_[connection_id] = info;
+ return true;
+}
+
void MasterConnectionManager::Shutdown() {
AssertNotOnPrivateThread();
DCHECK(master_process_delegate_);
@@ -318,7 +349,7 @@ bool MasterConnectionManager::AllowConnectImpl(
new PendingConnectionInfo(process_identifier);
// TODO(vtl): Track process identifier -> pending connections also (so these
// can be removed efficiently if that process disconnects).
- DVLOG(1) << "New pending connection ID " << connection_id
+ DVLOG(1) << "New pending connection ID " << connection_id.ToString()
<< ": AllowConnect() from first process identifier "
<< process_identifier;
return true;
@@ -328,7 +359,7 @@ bool MasterConnectionManager::AllowConnectImpl(
if (info->state == PendingConnectionInfo::AWAITING_SECOND_ALLOW_CONNECT) {
info->state = PendingConnectionInfo::AWAITING_CONNECTS_FROM_BOTH;
info->second = process_identifier;
- DVLOG(1) << "Pending connection ID " << connection_id
+ DVLOG(1) << "Pending connection ID " << connection_id.ToString()
<< ": AllowConnect() from second process identifier "
<< process_identifier;
return true;
@@ -337,8 +368,8 @@ bool MasterConnectionManager::AllowConnectImpl(
// Someone's behaving badly, but we don't know who (it might not be the
// caller).
LOG(ERROR) << "AllowConnect() from process " << process_identifier
- << " for connection ID " << connection_id << " already in state "
- << info->state;
+ << " for connection ID " << connection_id.ToString()
+ << " already in state " << info->state;
pending_connections_.erase(it);
delete info;
return false;
@@ -355,7 +386,7 @@ bool MasterConnectionManager::CancelConnectImpl(
if (it == pending_connections_.end()) {
// Not necessarily the caller's fault, and not necessarily an error.
DVLOG(1) << "CancelConnect() from process " << process_identifier
- << " for connection ID " << connection_id
+ << " for connection ID " << connection_id.ToString()
<< " which is not (or no longer) pending";
return true;
}
@@ -363,7 +394,7 @@ bool MasterConnectionManager::CancelConnectImpl(
PendingConnectionInfo* info = it->second;
if (process_identifier != info->first && process_identifier != info->second) {
LOG(ERROR) << "CancelConnect() from process " << process_identifier
- << " for connection ID " << connection_id
+ << " for connection ID " << connection_id.ToString()
<< " which is neither connectee";
return false;
}
@@ -392,7 +423,7 @@ bool MasterConnectionManager::ConnectImpl(
if (it == pending_connections_.end()) {
// Not necessarily the caller's fault.
LOG(ERROR) << "Connect() from process " << process_identifier
- << " for connection ID " << connection_id
+ << " for connection ID " << connection_id.ToString()
<< " which is not pending";
return false;
}
@@ -409,7 +440,7 @@ bool MasterConnectionManager::ConnectImpl(
*peer_process_identifier = info->first;
} else {
LOG(ERROR) << "Connect() from process " << process_identifier
- << " for connection ID " << connection_id
+ << " for connection ID " << connection_id.ToString()
<< " which is neither connectee";
return false;
}
@@ -424,7 +455,7 @@ bool MasterConnectionManager::ConnectImpl(
info->remaining_handle = platform_channel_pair.PassClientHandle();
DCHECK(info->remaining_handle.is_valid());
}
- DVLOG(1) << "Connection ID " << connection_id
+ DVLOG(1) << "Connection ID " << connection_id.ToString()
<< ": first Connect() from process identifier "
<< process_identifier;
return true;
@@ -443,8 +474,8 @@ bool MasterConnectionManager::ConnectImpl(
// Someone's behaving badly, but we don't know who (it might not be the
// caller).
LOG(ERROR) << "Connect() from process " << process_identifier
- << " for connection ID " << connection_id << " in state "
- << info->state;
+ << " for connection ID " << connection_id.ToString()
+ << " in state " << info->state;
pending_connections_.erase(it);
delete info;
return false;
@@ -452,7 +483,7 @@ bool MasterConnectionManager::ConnectImpl(
if (process_identifier != remaining_connectee) {
LOG(ERROR) << "Connect() from process " << process_identifier
- << " for connection ID " << connection_id
+ << " for connection ID " << connection_id.ToString()
<< " which is not the remaining connectee";
pending_connections_.erase(it);
delete info;
@@ -464,7 +495,7 @@ bool MasterConnectionManager::ConnectImpl(
DCHECK((info->first == info->second) ^ platform_handle->is_valid());
pending_connections_.erase(it);
delete info;
- DVLOG(1) << "Connection ID " << connection_id
+ DVLOG(1) << "Connection ID " << connection_id.ToString()
<< ": second Connect() from process identifier "
<< process_identifier;
return true;
@@ -494,23 +525,20 @@ void MasterConnectionManager::ShutdownOnPrivateThread() {
void MasterConnectionManager::AddSlaveOnPrivateThread(
embedder::SlaveInfo slave_info,
embedder::ScopedPlatformHandle platform_handle,
+ ProcessIdentifier slave_process_identifier,
base::WaitableEvent* event) {
DCHECK(platform_handle.is_valid());
DCHECK(event);
AssertOnPrivateThread();
- CHECK_NE(next_process_identifier_, kMasterProcessIdentifier);
- ProcessIdentifier process_identifier = next_process_identifier_;
- next_process_identifier_++;
-
- scoped_ptr<Helper> helper(
- new Helper(this, process_identifier, slave_info, platform_handle.Pass()));
+ scoped_ptr<Helper> helper(new Helper(this, slave_process_identifier,
+ slave_info, platform_handle.Pass()));
helper->Init();
- DCHECK(helpers_.find(process_identifier) == helpers_.end());
- helpers_[process_identifier] = helper.release();
+ DCHECK(helpers_.find(slave_process_identifier) == helpers_.end());
+ helpers_[slave_process_identifier] = helper.release();
- DVLOG(1) << "Added process identifier " << process_identifier;
+ DVLOG(1) << "Added slave process identifier " << slave_process_identifier;
event->Signal();
}
diff --git a/third_party/mojo/src/mojo/edk/system/master_connection_manager.h b/third_party/mojo/src/mojo/edk/system/master_connection_manager.h
index c6b6863..3210361 100644
--- a/third_party/mojo/src/mojo/edk/system/master_connection_manager.h
+++ b/third_party/mojo/src/mojo/edk/system/master_connection_manager.h
@@ -61,9 +61,22 @@ class MOJO_SYSTEM_IMPL_EXPORT MasterConnectionManager
// |embedder::MasterProcessDelegate| to track this process. It must remain
// alive until the delegate's |OnSlaveDisconnect()| is called with it as the
// argument. |OnSlaveDisconnect()| will always be called for each slave,
- // assuming proper shutdown.)
+ // assuming proper shutdown. |*slave_process_identifier| will be set to the
+ // process identifier for the newly-added slave.
void AddSlave(embedder::SlaveInfo slave_info,
- embedder::ScopedPlatformHandle platform_handle);
+ embedder::ScopedPlatformHandle platform_handle,
+ ProcessIdentifier* slave_process_identifier);
+
+ // Like |AddSlave()|, but allows a connection to be bootstrapped: both the
+ // master and slave may call |Connect()| with |connection_id| immediately (as
+ // if both had already called |AllowConnect()|). Returns false if |Connect()|
+ // will not be possible.
+ // TODO(vtl): Is |AddSlave()| really needed? (It's probably mostly useful for
+ // tests.)
+ bool AddSlaveAndBootstrap(embedder::SlaveInfo slave_info,
+ embedder::ScopedPlatformHandle platform_handle,
+ const ConnectionIdentifier& connection_id,
+ ProcessIdentifier* slave_process_identifier);
// |ConnectionManager| methods:
void Shutdown() override;
@@ -92,6 +105,7 @@ class MOJO_SYSTEM_IMPL_EXPORT MasterConnectionManager
// Signals |*event| on completion.
void AddSlaveOnPrivateThread(embedder::SlaveInfo slave_info,
embedder::ScopedPlatformHandle platform_handle,
+ ProcessIdentifier slave_process_identifier,
base::WaitableEvent* event);
// Called by |Helper::OnError()|.
void OnError(ProcessIdentifier process_identifier);
@@ -120,13 +134,14 @@ class MOJO_SYSTEM_IMPL_EXPORT MasterConnectionManager
base::Thread private_thread_;
// The following members are only accessed on |private_thread_|:
- ProcessIdentifier next_process_identifier_;
base::hash_map<ProcessIdentifier, Helper*> helpers_; // Owns its values.
// Protects the members below (except in the constructor, |Init()|,
// |Shutdown()|/|ShutdownOnPrivateThread()|, and the destructor).
base::Lock lock_;
+ ProcessIdentifier next_process_identifier_;
+
struct PendingConnectionInfo;
base::hash_map<ConnectionIdentifier, PendingConnectionInfo*>
pending_connections_; // Owns its values.
diff --git a/third_party/mojo/src/mojo/edk/system/multiprocess_message_pipe_unittest.cc b/third_party/mojo/src/mojo/edk/system/multiprocess_message_pipe_unittest.cc
index cf5049e..1570007 100644
--- a/third_party/mojo/src/mojo/edk/system/multiprocess_message_pipe_unittest.cc
+++ b/third_party/mojo/src/mojo/edk/system/multiprocess_message_pipe_unittest.cc
@@ -450,7 +450,8 @@ class MultiprocessMessagePipeTestWithPipeCount
#if defined(OS_MACOSX)
// http://crbug.com/488260
-TEST_P(MultiprocessMessagePipeTestWithPipeCount, DISABLED_PlatformHandlePassing) {
+TEST_P(MultiprocessMessagePipeTestWithPipeCount,
+ DISABLED_PlatformHandlePassing) {
#else
TEST_P(MultiprocessMessagePipeTestWithPipeCount, PlatformHandlePassing) {
#endif
diff --git a/third_party/mojo/src/mojo/edk/system/raw_channel.cc b/third_party/mojo/src/mojo/edk/system/raw_channel.cc
index 383a743..4cf7c02 100644
--- a/third_party/mojo/src/mojo/edk/system/raw_channel.cc
+++ b/third_party/mojo/src/mojo/edk/system/raw_channel.cc
@@ -87,7 +87,6 @@ void RawChannel::WriteBuffer::GetPlatformHandlesToSend(
if (serialized_platform_handle_size_ > 0) {
size_t serialization_data_offset =
transport_data->platform_handle_table_offset();
- DCHECK_GT(serialization_data_offset, 0u);
serialization_data_offset +=
platform_handles_offset_ * serialized_platform_handle_size_;
*serialization_data = static_cast<char*>(transport_data->buffer()) +
diff --git a/third_party/mojo/src/mojo/edk/system/slave_connection_manager.cc b/third_party/mojo/src/mojo/edk/system/slave_connection_manager.cc
index aad78a2..dfe69d4 100644
--- a/third_party/mojo/src/mojo/edk/system/slave_connection_manager.cc
+++ b/third_party/mojo/src/mojo/edk/system/slave_connection_manager.cc
@@ -147,7 +147,8 @@ void SlaveConnectionManager::AllowConnectOnPrivateThread(
DCHECK(!lock_.Try());
DCHECK_EQ(awaiting_ack_type_, NOT_AWAITING_ACK);
- DVLOG(1) << "Sending AllowConnect: connection ID " << connection_id;
+ DVLOG(1) << "Sending AllowConnect: connection ID "
+ << connection_id.ToString();
if (!raw_channel_->WriteMessage(make_scoped_ptr(new MessageInTransit(
MessageInTransit::kTypeConnectionManager,
MessageInTransit::kSubtypeConnectionManagerAllowConnect,
@@ -171,7 +172,8 @@ void SlaveConnectionManager::CancelConnectOnPrivateThread(
DCHECK(!lock_.Try());
DCHECK_EQ(awaiting_ack_type_, NOT_AWAITING_ACK);
- DVLOG(1) << "Sending CancelConnect: connection ID " << connection_id;
+ DVLOG(1) << "Sending CancelConnect: connection ID "
+ << connection_id.ToString();
if (!raw_channel_->WriteMessage(make_scoped_ptr(new MessageInTransit(
MessageInTransit::kTypeConnectionManager,
MessageInTransit::kSubtypeConnectionManagerCancelConnect,
@@ -199,7 +201,7 @@ void SlaveConnectionManager::ConnectOnPrivateThread(
DCHECK(!lock_.Try());
DCHECK_EQ(awaiting_ack_type_, NOT_AWAITING_ACK);
- DVLOG(1) << "Sending Connect: connection ID " << connection_id;
+ DVLOG(1) << "Sending Connect: connection ID " << connection_id.ToString();
if (!raw_channel_->WriteMessage(make_scoped_ptr(new MessageInTransit(
MessageInTransit::kTypeConnectionManager,
MessageInTransit::kSubtypeConnectionManagerConnect,
diff --git a/third_party/mojo/src/mojo/edk/system/unique_identifier.cc b/third_party/mojo/src/mojo/edk/system/unique_identifier.cc
index 11e482b..6e036c8 100644
--- a/third_party/mojo/src/mojo/edk/system/unique_identifier.cc
+++ b/third_party/mojo/src/mojo/edk/system/unique_identifier.cc
@@ -4,7 +4,9 @@
#include "mojo/edk/system/unique_identifier.h"
-#include <ostream>
+#include <stdint.h>
+
+#include <vector>
#include "base/strings/string_number_conversions.h"
#include "mojo/edk/embedder/platform_support.h"
@@ -12,12 +14,6 @@
namespace mojo {
namespace system {
-std::ostream& operator<<(std::ostream& out,
- const UniqueIdentifier& unique_identifier) {
- return out << base::HexEncode(unique_identifier.data_,
- sizeof(unique_identifier.data_));
-}
-
// static
UniqueIdentifier UniqueIdentifier::Generate(
embedder::PlatformSupport* platform_support) {
@@ -26,5 +22,24 @@ UniqueIdentifier UniqueIdentifier::Generate(
return rv;
}
+// static
+UniqueIdentifier UniqueIdentifier::FromString(const std::string& s,
+ bool* success) {
+ UniqueIdentifier rv;
+ std::vector<uint8_t> bytes;
+ if (base::HexStringToBytes(s, &bytes) && bytes.size() == sizeof(rv.data_)) {
+ memcpy(rv.data_, &bytes[0], sizeof(rv.data_));
+ *success = true;
+ } else {
+ *success = false;
+ }
+ return rv;
+}
+
+std::string UniqueIdentifier::ToString() const {
+ // TODO(vtl): Maybe we should base-64 encode instead?
+ return base::HexEncode(data_, sizeof(data_));
+}
+
} // namespace system
} // namespace mojo
diff --git a/third_party/mojo/src/mojo/edk/system/unique_identifier.h b/third_party/mojo/src/mojo/edk/system/unique_identifier.h
index c9cba88..1a13b36 100644
--- a/third_party/mojo/src/mojo/edk/system/unique_identifier.h
+++ b/third_party/mojo/src/mojo/edk/system/unique_identifier.h
@@ -8,7 +8,7 @@
#include <stdint.h>
#include <string.h>
-#include <iosfwd>
+#include <string>
#include "base/compiler_specific.h"
#include "base/containers/hash_tables.h"
@@ -40,11 +40,6 @@ class PlatformSupport;
namespace system {
-// Declare this before |UniqueIdentifier|, so that it can be friended.
-MOJO_SYSTEM_IMPL_EXPORT std::ostream& operator<<(
- std::ostream& out,
- const UniqueIdentifier& unique_identifier);
-
// |UniqueIdentifier| is a POD class whose value is used to uniquely identify
// things.
class MOJO_SYSTEM_IMPL_EXPORT UniqueIdentifier {
@@ -53,6 +48,17 @@ class MOJO_SYSTEM_IMPL_EXPORT UniqueIdentifier {
// probabilistically) for identifiers.
static UniqueIdentifier Generate(embedder::PlatformSupport* platform_support);
+ // This reconstitutes an identifier from its representation as a string
+ // (generated by |ToString()|, below). On success, |*success| is set to true;
+ // on failure, it is set to false (and the return value is undefined).
+ static UniqueIdentifier FromString(const std::string& s, bool* success);
+
+ // Yields a string representation of this identifier (which can be
+ // reconstituted using |FromString()|. The result will consist of printable,
+ // non-whitespace ASCII characters. It will *not* contain the following
+ // characters: ", ', or \.
+ std::string ToString() const;
+
bool operator==(const UniqueIdentifier& other) const {
return memcmp(data_, other.data_, sizeof(data_)) == 0;
}
@@ -65,9 +71,6 @@ class MOJO_SYSTEM_IMPL_EXPORT UniqueIdentifier {
private:
friend BASE_HASH_NAMESPACE::hash<mojo::system::UniqueIdentifier>;
- friend MOJO_SYSTEM_IMPL_EXPORT std::ostream& operator<<(
- std::ostream&,
- const UniqueIdentifier&);
explicit UniqueIdentifier() {}
diff --git a/third_party/mojo/src/mojo/edk/system/unique_identifier_unittest.cc b/third_party/mojo/src/mojo/edk/system/unique_identifier_unittest.cc
index 5241293..15b70b4 100644
--- a/third_party/mojo/src/mojo/edk/system/unique_identifier_unittest.cc
+++ b/third_party/mojo/src/mojo/edk/system/unique_identifier_unittest.cc
@@ -5,7 +5,7 @@
#include "mojo/edk/system/unique_identifier.h"
#include <set>
-#include <sstream>
+#include <string>
#include "base/containers/hash_tables.h"
#include "base/macros.h"
@@ -47,19 +47,66 @@ TEST_F(UniqueIdentifierTest, Basic) {
id2 = id1;
}
-TEST_F(UniqueIdentifierTest, Logging) {
- std::ostringstream oss1;
+TEST_F(UniqueIdentifierTest, ToString) {
UniqueIdentifier id1 = UniqueIdentifier::Generate(platform_support());
- oss1 << id1;
- EXPECT_FALSE(oss1.str().empty());
+ std::string id1_string = id1.ToString();
+ EXPECT_FALSE(id1_string.empty());
+
+ // The string should be printable, and not contain certain characters.
+ for (size_t i = 0; i < id1_string.size(); i++) {
+ char c = id1_string[i];
+ // Printable characters, not including space.
+ EXPECT_GT(c, ' ');
+ EXPECT_LE(c, '\x7e');
+ // Single and double quotes, and backslashes are disallowed.
+ EXPECT_NE(c, '\'');
+ EXPECT_NE(c, '"');
+ EXPECT_NE(c, '\\');
+ }
- std::ostringstream oss2;
UniqueIdentifier id2 = UniqueIdentifier::Generate(platform_support());
- oss2 << id2;
- EXPECT_FALSE(oss2.str().empty());
+ std::string id2_string = id2.ToString();
+ EXPECT_FALSE(id2_string.empty());
EXPECT_NE(id1, id2);
- EXPECT_NE(oss1.str(), oss2.str());
+ EXPECT_NE(id1_string, id2_string);
+}
+
+TEST_F(UniqueIdentifierTest, FromString) {
+ UniqueIdentifier id = UniqueIdentifier::Generate(platform_support());
+ std::string id_string = id.ToString();
+ EXPECT_FALSE(id_string.empty());
+
+ bool success = false;
+ UniqueIdentifier id_restored =
+ UniqueIdentifier::FromString(id_string, &success);
+ EXPECT_TRUE(success);
+ EXPECT_EQ(id, id_restored);
+}
+
+TEST_F(UniqueIdentifierTest, FromStringFailures) {
+ bool success = true;
+ UniqueIdentifier::FromString("", &success);
+ EXPECT_FALSE(success);
+
+ // That the cases below will fail requires *some* knowledge of the (private)
+ // encoding. So first check something that we know should succeed, to roughly
+ // confirm our knowledge.
+ success = false;
+ UniqueIdentifier::FromString("0123456789abcdef0123456789ABCDEF", &success);
+ EXPECT_TRUE(success);
+
+ success = true;
+ UniqueIdentifier::FromString("!@#$%^&*()_+-=/\\,.<>[]{};':\"|", &success);
+ EXPECT_FALSE(success);
+
+ success = true;
+ UniqueIdentifier::FromString("0123456789abcdef0123456789ABCDE", &success);
+ EXPECT_FALSE(success);
+
+ success = true;
+ UniqueIdentifier::FromString("0123456789abcdef0123456789ABCD", &success);
+ EXPECT_FALSE(success);
}
TEST_F(UniqueIdentifierTest, StdSet) {
diff --git a/third_party/mojo/src/mojo/edk/test/BUILD.gn b/third_party/mojo/src/mojo/edk/test/BUILD.gn
index 6f460bc..75821b2 100644
--- a/third_party/mojo/src/mojo/edk/test/BUILD.gn
+++ b/third_party/mojo/src/mojo/edk/test/BUILD.gn
@@ -3,6 +3,7 @@
# found in the LICENSE file.
import("../mojo_edk.gni")
+import("../../public/mojo.gni")
import("//testing/test.gni")
mojo_edk_source_set("test_support") {
@@ -91,6 +92,19 @@ group("public_tests") {
":mojo_public_utility_unittests",
":mojo_system_impl_private_unittests",
]
+
+ if (mojo_use_application_in_sdk) {
+ deps += [ ":mojo_public_application_unittests" ]
+ }
+}
+
+if (mojo_use_application_in_sdk) {
+ test("mojo_public_application_unittests") {
+ deps = [
+ ":run_all_unittests",
+ "../../public/cpp/application/tests",
+ ]
+ }
}
test("mojo_public_bindings_unittests") {
diff --git a/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.cc b/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.cc
index 6dd8b72..c107a02 100644
--- a/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.cc
+++ b/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.cc
@@ -26,6 +26,13 @@ MultiprocessTestHelper::~MultiprocessTestHelper() {
}
void MultiprocessTestHelper::StartChild(const std::string& test_child_name) {
+ StartChildWithExtraSwitch(test_child_name, std::string(), std::string());
+}
+
+void MultiprocessTestHelper::StartChildWithExtraSwitch(
+ const std::string& test_child_name,
+ const std::string& switch_string,
+ const std::string& switch_value) {
CHECK(platform_channel_pair_);
CHECK(!test_child_name.empty());
CHECK(!test_child_.IsValid());
@@ -38,6 +45,14 @@ void MultiprocessTestHelper::StartChild(const std::string& test_child_name) {
platform_channel_pair_->PrepareToPassClientHandleToChildProcess(
&command_line, &handle_passing_info);
+ if (!switch_string.empty()) {
+ CHECK(!command_line.HasSwitch(switch_string));
+ if (!switch_value.empty())
+ command_line.AppendSwitchASCII(switch_string, switch_value);
+ else
+ command_line.AppendSwitch(switch_string);
+ }
+
base::LaunchOptions options;
#if defined(OS_POSIX)
options.fds_to_remap = &handle_passing_info;
diff --git a/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.h b/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.h
index e40b309c..b2887ac 100644
--- a/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.h
+++ b/third_party/mojo/src/mojo/edk/test/multiprocess_test_helper.h
@@ -31,6 +31,12 @@ class MultiprocessTestHelper {
// declared using |MOJO_MULTIPROCESS_TEST_CHILD_MAIN()| or
// |MOJO_MULTIPROCESS_TEST_CHILD_TEST()| (below).
void StartChild(const std::string& test_child_name);
+ // Like |StartChild()|, but appends an extra switch (with ASCII value) to the
+ // command line. (The switch must not already be present in the default
+ // command line.)
+ void StartChildWithExtraSwitch(const std::string& test_child_name,
+ const std::string& switch_string,
+ const std::string& switch_value);
// Wait for the child process to terminate.
// Returns the exit code of the child process. Note that, though it's declared
// to be an |int|, the exit code is subject to mangling by the OS. E.g., we
diff --git a/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.cc b/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.cc
index 9f3b97d..fad9c82 100644
--- a/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.cc
+++ b/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.cc
@@ -10,17 +10,13 @@
namespace mojo {
namespace test {
-ScopedIPCSupport::ScopedIPCSupport(
- scoped_refptr<base::TaskRunner> io_thread_task_runner)
- : io_thread_task_runner_(io_thread_task_runner),
- event_(true, false) { // Manual reset.
- // Note: Run delegate methods on the I/O thread.
- embedder::InitIPCSupport(embedder::ProcessType::NONE, io_thread_task_runner,
- this, io_thread_task_runner,
- embedder::ScopedPlatformHandle());
+namespace internal {
+
+ScopedIPCSupportHelper::ScopedIPCSupportHelper()
+ : event_(true, false) { // Manual reset.
}
-ScopedIPCSupport::~ScopedIPCSupport() {
+ScopedIPCSupportHelper::~ScopedIPCSupportHelper() {
if (base::MessageLoop::current() &&
base::MessageLoop::current()->task_runner() == io_thread_task_runner_) {
embedder::ShutdownIPCSupportOnIOThread();
@@ -30,9 +26,90 @@ ScopedIPCSupport::~ScopedIPCSupport() {
}
}
-void ScopedIPCSupport::OnShutdownComplete() {
+void ScopedIPCSupportHelper::Init(
+ embedder::ProcessType process_type,
+ embedder::ProcessDelegate* process_delegate,
+ scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ embedder::ScopedPlatformHandle platform_handle) {
+ io_thread_task_runner_ = io_thread_task_runner;
+ // Note: Run delegate methods on the I/O thread.
+ embedder::InitIPCSupport(process_type, io_thread_task_runner_,
+ process_delegate, io_thread_task_runner_,
+ platform_handle.Pass());
+}
+
+void ScopedIPCSupportHelper::OnShutdownCompleteImpl() {
event_.Signal();
}
+} // namespace internal
+
+ScopedIPCSupport::ScopedIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner) {
+ helper_.Init(embedder::ProcessType::NONE, this, io_thread_task_runner.Pass(),
+ embedder::ScopedPlatformHandle());
+}
+
+ScopedIPCSupport::~ScopedIPCSupport() {
+}
+
+void ScopedIPCSupport::OnShutdownComplete() {
+ helper_.OnShutdownCompleteImpl();
+}
+
+ScopedMasterIPCSupport::ScopedMasterIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner) {
+ helper_.Init(embedder::ProcessType::MASTER, this,
+ io_thread_task_runner.Pass(), embedder::ScopedPlatformHandle());
+}
+
+ScopedMasterIPCSupport::ScopedMasterIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ base::Callback<void(embedder::SlaveInfo slave_info)> on_slave_disconnect)
+ : on_slave_disconnect_(on_slave_disconnect) {
+ helper_.Init(embedder::ProcessType::MASTER, this,
+ io_thread_task_runner.Pass(), embedder::ScopedPlatformHandle());
+}
+
+ScopedMasterIPCSupport::~ScopedMasterIPCSupport() {
+}
+
+void ScopedMasterIPCSupport::OnShutdownComplete() {
+ helper_.OnShutdownCompleteImpl();
+}
+
+void ScopedMasterIPCSupport::OnSlaveDisconnect(embedder::SlaveInfo slave_info) {
+ if (!on_slave_disconnect_.is_null())
+ on_slave_disconnect_.Run(slave_info);
+}
+
+ScopedSlaveIPCSupport::ScopedSlaveIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ embedder::ScopedPlatformHandle platform_handle) {
+ helper_.Init(embedder::ProcessType::SLAVE, this, io_thread_task_runner.Pass(),
+ platform_handle.Pass());
+}
+
+ScopedSlaveIPCSupport::ScopedSlaveIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ embedder::ScopedPlatformHandle platform_handle,
+ base::Closure on_master_disconnect)
+ : on_master_disconnect_(on_master_disconnect) {
+ helper_.Init(embedder::ProcessType::SLAVE, this, io_thread_task_runner.Pass(),
+ platform_handle.Pass());
+}
+
+ScopedSlaveIPCSupport::~ScopedSlaveIPCSupport() {
+}
+
+void ScopedSlaveIPCSupport::OnShutdownComplete() {
+ helper_.OnShutdownCompleteImpl();
+}
+
+void ScopedSlaveIPCSupport::OnMasterDisconnect() {
+ if (!on_master_disconnect_.is_null())
+ on_master_disconnect_.Run();
+}
+
} // namespace test
} // namespace mojo
diff --git a/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.h b/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.h
index 2569c4e..961bafa 100644
--- a/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.h
+++ b/third_party/mojo/src/mojo/edk/test/scoped_ipc_support.h
@@ -5,38 +5,111 @@
#ifndef MOJO_EDK_TEST_SCOPED_IPC_SUPPORT_H_
#define MOJO_EDK_TEST_SCOPED_IPC_SUPPORT_H_
+#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/waitable_event.h"
#include "base/task_runner.h"
+#include "mojo/edk/embedder/master_process_delegate.h"
#include "mojo/edk/embedder/process_delegate.h"
+#include "mojo/edk/embedder/process_type.h"
+#include "mojo/edk/embedder/scoped_platform_handle.h"
+#include "mojo/edk/embedder/slave_process_delegate.h"
namespace mojo {
namespace test {
+namespace internal {
+
+class ScopedIPCSupportHelper {
+ public:
+ ScopedIPCSupportHelper();
+ ~ScopedIPCSupportHelper();
+
+ void Init(embedder::ProcessType process_type,
+ embedder::ProcessDelegate* process_delegate,
+ scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ embedder::ScopedPlatformHandle platform_handle);
+
+ void OnShutdownCompleteImpl();
+
+ private:
+ scoped_refptr<base::TaskRunner> io_thread_task_runner_;
+
+ // Set after shut down.
+ base::WaitableEvent event_;
+
+ DISALLOW_COPY_AND_ASSIGN(ScopedIPCSupportHelper);
+};
+
+} // namespace internal
+
// A simple class that calls |mojo::embedder::InitIPCSupport()| (with
// |ProcessType::NONE|) on construction and |ShutdownIPCSupport()| on
// destruction (or |ShutdownIPCSupportOnIOThread()| if destroyed on the I/O
// thread).
-// TODO(vtl): Need master/slave versions.
class ScopedIPCSupport : public embedder::ProcessDelegate {
public:
- ScopedIPCSupport(scoped_refptr<base::TaskRunner> io_thread_task_runner);
+ explicit ScopedIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner);
~ScopedIPCSupport() override;
private:
- // ProcessDelegate| implementation:
+ // |ProcessDelegate| implementation:
// Note: Executed on the I/O thread.
void OnShutdownComplete() override;
- scoped_refptr<base::TaskRunner> io_thread_task_runner_;
-
- // Set after shut down.
- base::WaitableEvent event_;
+ internal::ScopedIPCSupportHelper helper_;
DISALLOW_COPY_AND_ASSIGN(ScopedIPCSupport);
};
+// Like |ScopedIPCSupport|, but with |ProcessType::MASTER|. It will (optionally)
+// call a callback (on the I/O thread) on receiving |OnSlaveDisconnect()|.
+class ScopedMasterIPCSupport : public embedder::MasterProcessDelegate {
+ public:
+ explicit ScopedMasterIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner);
+ ScopedMasterIPCSupport(
+ scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ base::Callback<void(embedder::SlaveInfo slave_info)> on_slave_disconnect);
+ ~ScopedMasterIPCSupport() override;
+
+ private:
+ // |MasterProcessDelegate| implementation:
+ // Note: Executed on the I/O thread.
+ void OnShutdownComplete() override;
+ void OnSlaveDisconnect(embedder::SlaveInfo slave_info) override;
+
+ internal::ScopedIPCSupportHelper helper_;
+ base::Callback<void(embedder::SlaveInfo slave_info)> on_slave_disconnect_;
+
+ DISALLOW_COPY_AND_ASSIGN(ScopedMasterIPCSupport);
+};
+
+// Like |ScopedIPCSupport|, but with |ProcessType::SLAVE|. It will (optionally)
+// call a callback (on the I/O thread) on receiving |OnMasterDisconnect()|.
+class ScopedSlaveIPCSupport : public embedder::SlaveProcessDelegate {
+ public:
+ ScopedSlaveIPCSupport(scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ embedder::ScopedPlatformHandle platform_handle);
+ ScopedSlaveIPCSupport(scoped_refptr<base::TaskRunner> io_thread_task_runner,
+ embedder::ScopedPlatformHandle platform_handle,
+ base::Closure on_master_disconnect);
+ ~ScopedSlaveIPCSupport() override;
+
+ private:
+ // |SlaveProcessDelegate| implementation:
+ // Note: Executed on the I/O thread.
+ void OnShutdownComplete() override;
+ void OnMasterDisconnect() override;
+
+ internal::ScopedIPCSupportHelper helper_;
+ base::Closure on_master_disconnect_;
+
+ DISALLOW_COPY_AND_ASSIGN(ScopedSlaveIPCSupport);
+};
+
} // namespace test
} // namespace mojo
diff --git a/third_party/mojo/src/mojo/public/BUILD.gn b/third_party/mojo/src/mojo/public/BUILD.gn
index e1e9e18..36018e2 100644
--- a/third_party/mojo/src/mojo/public/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/BUILD.gn
@@ -16,6 +16,10 @@ group("public") {
"interfaces/bindings/tests:test_interfaces",
]
+ if (mojo_use_application_in_sdk) {
+ deps += [ "cpp/application:standalone" ]
+ }
+
if (is_linux) {
deps += [ "python" ]
}
@@ -26,6 +30,10 @@ group("public") {
"java:bindings",
]
}
+
+ if (is_android && mojo_use_application_in_sdk) {
+ deps += [ "java:application" ]
+ }
}
group("sdk") {
@@ -37,6 +45,13 @@ group("sdk") {
"interfaces/bindings",
"js",
]
+
+ if (mojo_use_application_in_sdk) {
+ deps += [
+ "cpp/application:standalone",
+ "interfaces/application",
+ ]
+ }
}
static_library("libmojo_sdk") {
diff --git a/third_party/mojo/src/mojo/public/VERSION b/third_party/mojo/src/mojo/public/VERSION
index c314df0..6a5d5c0 100644
--- a/third_party/mojo/src/mojo/public/VERSION
+++ b/third_party/mojo/src/mojo/public/VERSION
@@ -1 +1 @@
-f84766d3b6420b7cf6a113d9d65d73cb5fe18d90 \ No newline at end of file
+1dc8a9a5db73d3718d99917fadf31f5fb2ebad4f \ No newline at end of file
diff --git a/third_party/mojo/src/mojo/public/c/environment/logger.h b/third_party/mojo/src/mojo/public/c/environment/logger.h
index c492a66..2a9b617 100644
--- a/third_party/mojo/src/mojo/public/c/environment/logger.h
+++ b/third_party/mojo/src/mojo/public/c/environment/logger.h
@@ -30,10 +30,17 @@ const MojoLogLevel MOJO_LOG_LEVEL_FATAL = 3;
// macros may be built). The functions are thread-safe, except for
// |SetMinimumLogLevel()| (see below).
struct MojoLogger {
- // Logs |message| at level |log_level| if |log_level| is at least the current
- // minimum log level. If |log_level| is |MOJO_LOG_LEVEL_FATAL| (or greater),
- // aborts the application/process.
- void (*LogMessage)(MojoLogLevel log_level, const char* message);
+ // Logs |message| (which must not be null) at level |log_level| if |log_level|
+ // is at least the current minimum log level. If |log_level| is
+ // |MOJO_LOG_LEVEL_FATAL| (or greater), aborts the application/process.
+ // |source_file| and |source_line| indicate the source file and (1-based) line
+ // number, respectively; they are optional: |source_file| may be null and
+ // |source_line| may be zero (if |source_file| is null, then |source_line| may
+ // be ignored).
+ void (*LogMessage)(MojoLogLevel log_level,
+ const char* source_file,
+ uint32_t source_line,
+ const char* message);
// Gets the minimum log level (see above), which will always be at most
// |MOJO_LOG_LEVEL_FATAL|. (Though |LogMessage()| will automatically avoid
diff --git a/third_party/mojo/src/mojo/public/c/gles2/BUILD.gn b/third_party/mojo/src/mojo/public/c/gles2/BUILD.gn
index b680bec..aab423e 100644
--- a/third_party/mojo/src/mojo/public/c/gles2/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/c/gles2/BUILD.gn
@@ -20,8 +20,20 @@ group("gles2") {
mojo_sdk_source_set("headers") {
sources = [
+ "chromium_miscellaneous.h",
+ "chromium_sub_image.h",
+ "chromium_sync_point.h",
+ "chromium_texture_mailbox.h",
"gles2.h",
+ "gles2_call_visitor_autogen.h",
+ "gles2_call_visitor_chromium_miscellaneous_autogen.h",
+ "gles2_call_visitor_chromium_sub_image_autogen.h",
+ "gles2_call_visitor_chromium_sync_point_autogen.h",
+ "gles2_call_visitor_chromium_texture_mailbox_autogen.h",
+ "gles2_call_visitor_occlusion_query_ext_autogen.h",
"gles2_export.h",
+ "gles2_types.h",
+ "occlusion_query_ext.h",
]
public_configs = [ ":gles2_config" ]
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h b/third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h
index f7323e8..cdca105 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h
@@ -115,10 +115,8 @@ class InterfacePtr {
//
// This method may only be called after the InterfacePtr has been bound to a
// message pipe.
- //
- // TODO(jamesr): Rename to WaitForIncomingResponse().
- bool WaitForIncomingMethodCall() {
- return internal_state_.WaitForIncomingMethodCall();
+ bool WaitForIncomingResponse() {
+ return internal_state_.WaitForIncomingResponse();
}
// Indicates whether the message pipe has encountered an error. If true,
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/lib/interface_ptr_internal.h b/third_party/mojo/src/mojo/public/cpp/bindings/lib/interface_ptr_internal.h
index cd3803fd..e88084f 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/lib/interface_ptr_internal.h
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/lib/interface_ptr_internal.h
@@ -91,7 +91,7 @@ class InterfacePtrState {
version_ = info.version();
}
- bool WaitForIncomingMethodCall() {
+ bool WaitForIncomingResponse() {
ConfigureProxyIfNecessary();
MOJO_DCHECK(router_);
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/tests/BUILD.gn b/third_party/mojo/src/mojo/public/cpp/bindings/tests/BUILD.gn
index 9ebd6f5..bb94bc2 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/tests/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/tests/BUILD.gn
@@ -4,6 +4,7 @@
import("../../../mojo_application.gni")
import("../../../mojo_sdk.gni")
+import("../../../mojo.gni")
mojo_sdk_source_set("tests") {
testonly = true
@@ -29,6 +30,7 @@ mojo_sdk_source_set("tests") {
"string_unittest.cc",
"struct_unittest.cc",
"type_conversion_unittest.cc",
+ "union_unittest.cc",
"validation_unittest.cc",
]
@@ -45,6 +47,7 @@ mojo_sdk_source_set("tests") {
"mojo/public/cpp/test_support:test_utils",
"mojo/public/cpp/utility",
"mojo/public/interfaces/bindings/tests:test_interfaces",
+ "mojo/public/interfaces/bindings/tests:test_interfaces_experimental",
]
}
@@ -56,3 +59,55 @@ mojo_sdk_source_set("mojo_public_bindings_test_utils") {
mojo_sdk_deps = [ "mojo/public/c/system" ]
}
+
+if (mojo_use_application_in_sdk) {
+ mojo_native_application("versioning_test_service") {
+ testonly = true
+
+ deps = [
+ ":versioning_test_service_source_set",
+ ]
+ }
+
+ mojo_sdk_source_set("versioning_test_service_source_set") {
+ testonly = true
+ visibility = [ ":*" ]
+
+ sources = [
+ "versioning_test_service.cc",
+ ]
+
+ mojo_sdk_deps = [
+ "mojo/public/cpp/application:standalone",
+ "mojo/public/cpp/bindings",
+ "mojo/public/cpp/system",
+ "mojo/public/interfaces/bindings/tests:versioning_test_service_interfaces",
+ ]
+ }
+
+ mojo_native_application("versioning_apptests") {
+ testonly = true
+
+ deps = [
+ ":versioning_apptest_source_set",
+ ]
+ data_deps = [ ":versioning_test_service" ]
+ }
+
+ mojo_sdk_source_set("versioning_apptest_source_set") {
+ testonly = true
+ visibility = [ ":*" ]
+
+ sources = [
+ "versioning_apptest.cc",
+ ]
+
+ mojo_sdk_deps = [
+ "mojo/public/cpp/application:standalone",
+ "mojo/public/cpp/application:test_support_standalone",
+ "mojo/public/cpp/bindings",
+ "mojo/public/cpp/system",
+ "mojo/public/interfaces/bindings/tests:versioning_test_client_interfaces",
+ ]
+ }
+}
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc b/third_party/mojo/src/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc
index 09e4812..57abf8f 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/tests/interface_ptr_unittest.cc
@@ -87,8 +87,8 @@ class MathCalculatorUI {
output_(0.0),
callback_(MakeRunnable(&MathCalculatorUI::Output, this)) {}
- bool WaitForIncomingMethodCall() {
- return calculator_.WaitForIncomingMethodCall();
+ bool WaitForIncomingResponse() {
+ return calculator_.WaitForIncomingResponse();
}
bool encountered_error() const { return calculator_.encountered_error(); }
@@ -232,13 +232,13 @@ TEST_F(InterfacePtrTest, EndToEnd_Synchronous) {
calculator_ui.Add(2.0);
EXPECT_EQ(0.0, calculator_ui.GetOutput());
calc_impl.WaitForIncomingMethodCall();
- calculator_ui.WaitForIncomingMethodCall();
+ calculator_ui.WaitForIncomingResponse();
EXPECT_EQ(2.0, calculator_ui.GetOutput());
calculator_ui.Multiply(5.0);
EXPECT_EQ(2.0, calculator_ui.GetOutput());
calc_impl.WaitForIncomingMethodCall();
- calculator_ui.WaitForIncomingMethodCall();
+ calculator_ui.WaitForIncomingResponse();
EXPECT_EQ(10.0, calculator_ui.GetOutput());
}
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/tests/union_unittest.cc b/third_party/mojo/src/mojo/public/cpp/bindings/tests/union_unittest.cc
index 3253232..e6e38de 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/tests/union_unittest.cc
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/tests/union_unittest.cc
@@ -4,6 +4,7 @@
#include <vector>
#include "mojo/public/cpp/bindings/array.h"
+#include "mojo/public/cpp/bindings/binding.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/bounds_checker.h"
@@ -11,6 +12,7 @@
#include "mojo/public/cpp/bindings/string.h"
#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/test_structs.mojom.h"
#include "mojo/public/interfaces/bindings/tests/test_unions.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -497,7 +499,8 @@ TEST(UnionTest, Validation_UnionsInStruct) {
Serialize_(small_struct.Pass(), &buf, &data);
void* raw_buf = buf.Leak();
- mojo::internal::BoundsChecker bounds_checker(data, size, 0);
+ mojo::internal::BoundsChecker bounds_checker(data,
+ static_cast<uint32_t>(size), 0);
EXPECT_TRUE(internal::SmallStruct_Data::Validate(raw_buf, &bounds_checker));
free(raw_buf);
}
@@ -517,7 +520,8 @@ TEST(UnionTest, Validation_PodUnionInStruct_Failure) {
data->pod_union.tag = static_cast<internal::PodUnion_Data::PodUnion_Tag>(100);
void* raw_buf = buf.Leak();
- mojo::internal::BoundsChecker bounds_checker(data, size, 0);
+ mojo::internal::BoundsChecker bounds_checker(data,
+ static_cast<uint32_t>(size), 0);
EXPECT_FALSE(internal::SmallStruct_Data::Validate(raw_buf, &bounds_checker));
free(raw_buf);
}
@@ -535,7 +539,8 @@ TEST(UnionTest, Validation_NullUnion_Failure) {
internal::SmallStructNonNullableUnion_Data::New(&buf);
void* raw_buf = buf.Leak();
- mojo::internal::BoundsChecker bounds_checker(data, size, 0);
+ mojo::internal::BoundsChecker bounds_checker(data,
+ static_cast<uint32_t>(size), 0);
EXPECT_FALSE(internal::SmallStructNonNullableUnion_Data::Validate(
raw_buf, &bounds_checker));
free(raw_buf);
@@ -553,7 +558,8 @@ TEST(UnionTest, Validation_NullableUnion) {
Serialize_(small_struct.Pass(), &buf, &data);
void* raw_buf = buf.Leak();
- mojo::internal::BoundsChecker bounds_checker(data, size, 0);
+ mojo::internal::BoundsChecker bounds_checker(data,
+ static_cast<uint32_t>(size), 0);
EXPECT_TRUE(internal::SmallStruct_Data::Validate(raw_buf, &bounds_checker));
free(raw_buf);
}
@@ -1043,5 +1049,90 @@ TEST(UnionTest, HandleInUnionValidationNull) {
free(raw_buf);
}
+class SmallCacheImpl : public SmallCache {
+ public:
+ SmallCacheImpl() : int_value_(0) {}
+ ~SmallCacheImpl() override {}
+ int64_t int_value() const { return int_value_; }
+
+ private:
+ void SetIntValue(int64_t int_value) override { int_value_ = int_value; }
+ void GetIntValue(const GetIntValueCallback& callback) override {
+ callback.Run(int_value_);
+ }
+
+ int64_t int_value_;
+};
+
+TEST(UnionTest, InterfaceInUnion) {
+ Environment env;
+ RunLoop run_loop;
+ SmallCacheImpl impl;
+ SmallCachePtr ptr;
+ Binding<SmallCache> bindings(&impl, GetProxy(&ptr));
+
+ HandleUnionPtr handle(HandleUnion::New());
+ handle->set_f_small_cache(ptr.Pass());
+
+ handle->get_f_small_cache()->SetIntValue(10);
+ run_loop.RunUntilIdle();
+ EXPECT_EQ(10, impl.int_value());
+}
+
+TEST(UnionTest, InterfaceInUnionSerialization) {
+ Environment env;
+ RunLoop run_loop;
+ SmallCacheImpl impl;
+ SmallCachePtr ptr;
+ Binding<SmallCache> bindings(&impl, GetProxy(&ptr));
+
+ HandleUnionPtr handle(HandleUnion::New());
+ handle->set_f_small_cache(ptr.Pass());
+ size_t size = GetSerializedSize_(handle, false);
+ EXPECT_EQ(16U, size);
+
+ mojo::internal::FixedBuffer buf(size);
+ internal::HandleUnion_Data* data = nullptr;
+ SerializeUnion_(handle.Pass(), &buf, &data, false);
+
+ std::vector<Handle> handles;
+ data->EncodePointersAndHandles(&handles);
+ EXPECT_EQ(1U, handles.size());
+ data->DecodePointersAndHandles(&handles);
+
+ HandleUnionPtr handle2(HandleUnion::New());
+ Deserialize_(data, &handle2);
+
+ handle2->get_f_small_cache()->SetIntValue(10);
+ run_loop.RunUntilIdle();
+ EXPECT_EQ(10, impl.int_value());
+}
+
+class UnionInterfaceImpl : public UnionInterface {
+ public:
+ UnionInterfaceImpl() {}
+ ~UnionInterfaceImpl() override {}
+
+ private:
+ void Echo(PodUnionPtr in, const EchoCallback& callback) override {
+ callback.Run(in.Pass());
+ }
+};
+
+TEST(UnionTest, UnionInInterface) {
+ Environment env;
+ RunLoop run_loop;
+ UnionInterfaceImpl impl;
+ UnionInterfacePtr ptr;
+ Binding<UnionInterface> bindings(&impl, GetProxy(&ptr));
+
+ PodUnionPtr pod(PodUnion::New());
+ pod->set_f_int16(16);
+
+ ptr->Echo(pod.Pass(),
+ [](PodUnionPtr out) { EXPECT_EQ(16, out->get_f_int16()); });
+ run_loop.RunUntilIdle();
+}
+
} // namespace test
} // namespace mojo
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_apptest.cc b/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_apptest.cc
index 4e1cf69..18cbea9 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_apptest.cc
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_apptest.cc
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "mojo/application/public/cpp/application_impl.h"
-#include "mojo/application/public/cpp/application_test_base.h"
+#include "mojo/public/cpp/application/application_impl.h"
+#include "mojo/public/cpp/application/application_test_base.h"
#include "mojo/public/cpp/system/macros.h"
#include "mojo/public/interfaces/bindings/tests/versioning_test_client.mojom.h"
@@ -45,7 +45,7 @@ TEST_F(VersioningApplicationTest, Struct) {
EXPECT_TRUE(employee->Equals(*returned_employee));
EXPECT_FALSE(returned_finger_print.is_null());
});
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
// Passing a struct of older version to the service side works.
EmployeePtr new_employee(Employee::New());
@@ -55,7 +55,7 @@ TEST_F(VersioningApplicationTest, Struct) {
database_->AddEmployee(new_employee.Clone(),
[](bool success) { EXPECT_TRUE(success); });
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
database_->QueryEmployee(
2, false, [&new_employee](EmployeePtr returned_employee,
@@ -63,13 +63,13 @@ TEST_F(VersioningApplicationTest, Struct) {
EXPECT_TRUE(new_employee->Equals(*returned_employee));
EXPECT_TRUE(returned_finger_print.is_null());
});
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
}
TEST_F(VersioningApplicationTest, QueryVersion) {
EXPECT_EQ(0u, database_.version());
database_.QueryVersion([](uint32_t version) { EXPECT_EQ(1u, version); });
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
EXPECT_EQ(1u, database_.version());
}
@@ -81,7 +81,7 @@ TEST_F(VersioningApplicationTest, RequireVersion) {
database_->QueryEmployee(3, false,
[](EmployeePtr returned_employee,
Array<uint8_t> returned_finger_print) {});
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
EXPECT_FALSE(database_.encountered_error());
// Requiring a version higher than what the service side implements will close
@@ -91,7 +91,7 @@ TEST_F(VersioningApplicationTest, RequireVersion) {
database_->QueryEmployee(1, false,
[](EmployeePtr returned_employee,
Array<uint8_t> returned_finger_print) {});
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
EXPECT_TRUE(database_.encountered_error());
}
@@ -107,12 +107,12 @@ TEST_F(VersioningApplicationTest, CallNonexistentMethod) {
// supports version 1.
database_->AttachFingerPrint(1, new_finger_print.Clone(),
[](bool success) { EXPECT_TRUE(success); });
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
// Calling a version 2 method (which the service side doesn't support) closes
// the pipe.
database_->ListEmployeeIds([](Array<uint64_t> ids) { EXPECT_TRUE(false); });
- database_.WaitForIncomingMethodCall();
+ database_.WaitForIncomingResponse();
EXPECT_TRUE(database_.encountered_error());
}
diff --git a/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_test_service.cc b/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_test_service.cc
index 97f76e9..e5d63a4 100644
--- a/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_test_service.cc
+++ b/third_party/mojo/src/mojo/public/cpp/bindings/tests/versioning_test_service.cc
@@ -5,10 +5,10 @@
#include <map>
#include "mojo/public/c/system/main.h"
-#include "mojo/application/public/cpp/application_connection.h"
-#include "mojo/application/public/cpp/application_delegate.h"
-#include "mojo/application/public/cpp/application_runner.h"
-#include "mojo/application/public/cpp/interface_factory.h"
+#include "mojo/public/cpp/application/application_connection.h"
+#include "mojo/public/cpp/application/application_delegate.h"
+#include "mojo/public/cpp/application/application_runner.h"
+#include "mojo/public/cpp/application/interface_factory.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/macros.h"
#include "mojo/public/interfaces/bindings/tests/versioning_test_service.mojom.h"
diff --git a/third_party/mojo/src/mojo/public/cpp/environment/lib/default_logger.cc b/third_party/mojo/src/mojo/public/cpp/environment/lib/default_logger.cc
index 05cafbd..ba787d1 100644
--- a/third_party/mojo/src/mojo/public/cpp/environment/lib/default_logger.cc
+++ b/third_party/mojo/src/mojo/public/cpp/environment/lib/default_logger.cc
@@ -38,12 +38,20 @@ const char* GetLogLevelString(MojoLogLevel log_level) {
return "FATAL";
}
-void LogMessage(MojoLogLevel log_level, const char* message) {
+void LogMessage(MojoLogLevel log_level,
+ const char* source_file,
+ uint32_t source_line,
+ 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 (source_file) {
+ fprintf(stderr, "%s: %s(%u): %s\n", GetLogLevelString(log_level),
+ source_file, static_cast<unsigned>(source_line), message);
+ } else {
+ fprintf(stderr, "%s: %s\n", GetLogLevelString(log_level), message);
+ }
if (log_level >= MOJO_LOG_LEVEL_FATAL)
abort();
}
diff --git a/third_party/mojo/src/mojo/public/cpp/environment/lib/logging.cc b/third_party/mojo/src/mojo/public/cpp/environment/lib/logging.cc
index 990626d..57f1892 100644
--- a/third_party/mojo/src/mojo/public/cpp/environment/lib/logging.cc
+++ b/third_party/mojo/src/mojo/public/cpp/environment/lib/logging.cc
@@ -30,15 +30,15 @@ const char* GetFilename(const char* s) {
} // 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 << "): ";
+// TODO(vtl): Maybe we should preserve the full path and strip it out at a
+// different level instead?
+LogMessage::LogMessage(MojoLogLevel log_level, const char* file, int line)
+ : log_level_(log_level), file_(GetFilename(file)), line_(line) {
}
LogMessage::~LogMessage() {
- Environment::GetDefaultLogger()->LogMessage(log_level_,
- stream_.str().c_str());
+ Environment::GetDefaultLogger()->LogMessage(
+ log_level_, file_, static_cast<uint32_t>(line_), stream_.str().c_str());
}
} // namespace internal
diff --git a/third_party/mojo/src/mojo/public/cpp/environment/logging.h b/third_party/mojo/src/mojo/public/cpp/environment/logging.h
index d0fdeaf..bfc5c13 100644
--- a/third_party/mojo/src/mojo/public/cpp/environment/logging.h
+++ b/third_party/mojo/src/mojo/public/cpp/environment/logging.h
@@ -19,7 +19,7 @@
#include "mojo/public/cpp/system/macros.h"
#define MOJO_LOG_STREAM(level) \
- ::mojo::internal::LogMessage(__FILE__, __LINE__, MOJO_LOG_LEVEL_##level) \
+ ::mojo::internal::LogMessage(MOJO_LOG_LEVEL_##level, __FILE__, __LINE__) \
.stream()
#define MOJO_LAZY_LOG_STREAM(level, condition) \
@@ -64,13 +64,15 @@ namespace internal {
class LogMessage {
public:
- LogMessage(const char* file, int line, MojoLogLevel log_level);
+ LogMessage(MojoLogLevel log_level, const char* file, int line);
~LogMessage();
std::ostream& stream() { return stream_; }
private:
const MojoLogLevel log_level_;
+ const char* const file_;
+ const int line_;
std::ostringstream stream_;
MOJO_DISALLOW_COPY_AND_ASSIGN(LogMessage);
diff --git a/third_party/mojo/src/mojo/public/cpp/environment/tests/logger_unittest.cc b/third_party/mojo/src/mojo/public/cpp/environment/tests/logger_unittest.cc
index 7aef2ee..8ca5538 100644
--- a/third_party/mojo/src/mojo/public/cpp/environment/tests/logger_unittest.cc
+++ b/third_party/mojo/src/mojo/public/cpp/environment/tests/logger_unittest.cc
@@ -10,22 +10,30 @@ namespace mojo {
namespace {
TEST(LoggerTest, Basic) {
+ const char kPath[] = "/fake/path/to/file.cc";
+
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");
+ logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE - 1, kPath, 123,
+ "Logged at VERBOSE-1 level");
+ logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE, kPath, 123,
+ "Logged at VERBOSE level");
+ logger->LogMessage(MOJO_LOG_LEVEL_INFO, kPath, 123, "Logged at INFO level");
+ logger->LogMessage(MOJO_LOG_LEVEL_WARNING, kPath, 123,
+ "Logged at WARNING level");
+ logger->LogMessage(MOJO_LOG_LEVEL_ERROR, kPath, 123, "Logged at ERROR level");
// This should kill us:
- EXPECT_DEATH_IF_SUPPORTED(
- { logger->LogMessage(MOJO_LOG_LEVEL_FATAL, "Logged at FATAL level"); },
- "");
+ EXPECT_DEATH_IF_SUPPORTED({
+ logger->LogMessage(MOJO_LOG_LEVEL_FATAL, kPath, 123,
+ "Logged at FATAL level");
+ }, "");
}
TEST(LoggerTest, LogLevels) {
+ const char kPath[] = "/fake/path/to/file.cc";
+
Environment environment;
const MojoLogger* const logger = Environment::GetDefaultLogger();
@@ -39,18 +47,43 @@ TEST(LoggerTest, LogLevels) {
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");
+ logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE - 1, kPath, 123,
+ "Logged at VERBOSE-1 level");
+ logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE, kPath, 123,
+ "Logged at VERBOSE level");
+ logger->LogMessage(MOJO_LOG_LEVEL_INFO, kPath, 123, "Logged at INFO level");
+ logger->LogMessage(MOJO_LOG_LEVEL_WARNING, kPath, 123,
+ "Logged at WARNING level");
+ logger->LogMessage(MOJO_LOG_LEVEL_ERROR, kPath, 123,
+ "Logged at ERROR level");
// This should kill us:
- EXPECT_DEATH_IF_SUPPORTED(
- { logger->LogMessage(MOJO_LOG_LEVEL_FATAL, "Logged at FATAL level"); },
- "");
+ EXPECT_DEATH_IF_SUPPORTED({
+ logger->LogMessage(MOJO_LOG_LEVEL_FATAL, kPath, 123,
+ "Logged at FATAL level");
+ }, "");
}
}
+TEST(LoggerTest, NoFile) {
+ Environment environment;
+ const MojoLogger* const logger = Environment::GetDefaultLogger();
+
+ logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE - 1, nullptr, 0,
+ "Logged at VERBOSE-1 level");
+ logger->LogMessage(MOJO_LOG_LEVEL_VERBOSE, nullptr, 0,
+ "Logged at VERBOSE level");
+ logger->LogMessage(MOJO_LOG_LEVEL_INFO, nullptr, 0, "Logged at INFO level");
+ logger->LogMessage(MOJO_LOG_LEVEL_WARNING, nullptr, 0,
+ "Logged at WARNING level");
+ logger->LogMessage(MOJO_LOG_LEVEL_ERROR, nullptr, 0, "Logged at ERROR level");
+
+ // This should kill us:
+ EXPECT_DEATH_IF_SUPPORTED({
+ logger->LogMessage(MOJO_LOG_LEVEL_FATAL, nullptr, 0,
+ "Logged at FATAL level");
+ }, "");
+}
+
} // namespace
} // namespace mojo
diff --git a/third_party/mojo/src/mojo/public/cpp/environment/tests/logging_unittest.cc b/third_party/mojo/src/mojo/public/cpp/environment/tests/logging_unittest.cc
index 25ebb34..489888c 100644
--- a/third_party/mojo/src/mojo/public/cpp/environment/tests/logging_unittest.cc
+++ b/third_party/mojo/src/mojo/public/cpp/environment/tests/logging_unittest.cc
@@ -12,13 +12,12 @@
#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 {
+// The current logging system strips the path, so we need our filename.
+const char kOurFilename[] = "logging_unittest.cc";
+
class PtrToMemberHelper {
public:
int member;
@@ -42,6 +41,8 @@ class LoggingTest : public testing::Test {
static void ResetMockLogger() {
log_message_was_called_ = false;
last_log_level_ = MOJO_LOG_LEVEL_INFO;
+ last_source_file_.clear();
+ last_source_line_ = 0;
last_message_.clear();
}
@@ -53,6 +54,8 @@ class LoggingTest : public testing::Test {
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_source_file() { return last_source_file_; }
+ static uint32_t last_source_line() { return last_source_line_; }
static const std::string& last_message() { return last_message_; }
static bool not_called_condition_was_called() {
return not_called_condition_was_called_;
@@ -62,9 +65,14 @@ class LoggingTest : public testing::Test {
// 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) {
+ static void MockLogMessage(MojoLogLevel log_level,
+ const char* source_file,
+ uint32_t source_line,
+ const char* message) {
log_message_was_called_ = true;
last_log_level_ = log_level;
+ last_source_file_ = source_file;
+ last_source_line_ = source_line;
last_message_ = message;
}
@@ -80,6 +88,8 @@ class LoggingTest : public testing::Test {
static MojoLogLevel minimum_log_level_;
static bool log_message_was_called_;
static MojoLogLevel last_log_level_;
+ static std::string last_source_file_;
+ static uint32_t last_source_line_;
static std::string last_message_;
static bool not_called_condition_was_called_;
@@ -102,114 +112,138 @@ bool LoggingTest::log_message_was_called_ = MOJO_LOG_LEVEL_INFO;
MojoLogLevel LoggingTest::last_log_level_ = MOJO_LOG_LEVEL_INFO;
// static
+std::string LoggingTest::last_source_file_;
+
+// static
+uint32_t LoggingTest::last_source_line_ = 0;
+
+// 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 "
+ internal::LogMessage(MOJO_LOG_LEVEL_INFO, "foo.cc", 123).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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage("./path/to/foo.cc", 123, MOJO_LOG_LEVEL_WARNING).stream()
+ internal::LogMessage(MOJO_LOG_LEVEL_WARNING, "./path/to/foo.cc", 123).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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage("/path/to/foo.cc", 123, MOJO_LOG_LEVEL_ERROR).stream()
+ internal::LogMessage(MOJO_LOG_LEVEL_ERROR, "/path/to/foo.cc", 123).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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage("path/to/foo.cc", 123, MOJO_LOG_LEVEL_FATAL).stream()
+ internal::LogMessage(MOJO_LOG_LEVEL_FATAL, "path/to/foo.cc", 123).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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage(".\\xy\\foo.cc", 123, MOJO_LOG_LEVEL_VERBOSE).stream()
+ internal::LogMessage(MOJO_LOG_LEVEL_VERBOSE, ".\\xy\\foo.cc", 123).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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage("xy\\foo.cc", 123, MOJO_LOG_LEVEL_VERBOSE - 1).stream()
+ internal::LogMessage(MOJO_LOG_LEVEL_VERBOSE - 1, "xy\\foo.cc", 123).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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage("C:\\xy\\foo.cc", 123, MOJO_LOG_LEVEL_VERBOSE - 9)
+ internal::LogMessage(MOJO_LOG_LEVEL_VERBOSE - 9, "C:\\xy\\foo.cc", 123)
.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());
+ EXPECT_EQ("foo.cc", last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("hello world", last_message());
ResetMockLogger();
- internal::LogMessage(__FILE__, 123, MOJO_LOG_LEVEL_INFO).stream() << "hello "
+ internal::LogMessage(MOJO_LOG_LEVEL_INFO, __FILE__, 123).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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(123u, last_source_line());
+ EXPECT_EQ("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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("hi 123", last_message());
ResetMockLogger();
@@ -273,14 +307,18 @@ TEST_F(LoggingTest, Log) {
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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("hello", last_message());
ResetMockLogger();
@@ -299,7 +337,9 @@ TEST_F(LoggingTest, Log) {
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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("hello", last_message());
}
TEST_F(LoggingTest, LogIf) {
@@ -335,7 +375,9 @@ TEST_F(LoggingTest, LogIf) {
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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("hello", last_message());
ResetMockLogger();
@@ -365,12 +407,9 @@ TEST_F(LoggingTest, Check) {
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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 4), last_source_line());
+ EXPECT_EQ("Check failed: helper.*member_ptr == 1. hello", last_message());
ResetMockLogger();
@@ -392,7 +431,9 @@ TEST_F(LoggingTest, Dlog) {
#else
EXPECT_TRUE(log_message_was_called());
EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level());
- EXPECT_EQ(ExpectedLogMessage(__LINE__ - 6, "hello"), last_message());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 7), last_source_line());
+ EXPECT_EQ("hello", last_message());
#endif
}
@@ -416,7 +457,9 @@ TEST_F(LoggingTest, DlogIf) {
#else
EXPECT_TRUE(log_message_was_called());
EXPECT_EQ(MOJO_LOG_LEVEL_INFO, last_log_level());
- EXPECT_EQ(ExpectedLogMessage(__LINE__ - 6, "hello"), last_message());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 7), last_source_line());
+ EXPECT_EQ("hello", last_message());
#endif
ResetMockLogger();
@@ -431,7 +474,9 @@ TEST_F(LoggingTest, DlogIf) {
#else
EXPECT_TRUE(log_message_was_called());
EXPECT_EQ(MOJO_LOG_LEVEL_WARNING, last_log_level());
- EXPECT_EQ(ExpectedLogMessage(__LINE__ - 6, "hello"), last_message());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 7), last_source_line());
+ EXPECT_EQ("hello", last_message());
#endif
}
@@ -458,13 +503,10 @@ TEST_F(LoggingTest, Dcheck) {
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());
+ EXPECT_EQ(kOurFilename, last_source_file());
+ EXPECT_EQ(static_cast<uint32_t>(__LINE__ - 9), last_source_line());
+ EXPECT_EQ("Check failed: DcheckTestHelper(&was_called). hello",
+ last_message());
#endif
ResetMockLogger();
diff --git a/third_party/mojo/src/mojo/public/dart/.gitignore b/third_party/mojo/src/mojo/public/dart/.gitignore
new file mode 100644
index 0000000..3b66ccd
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/dart/.gitignore
@@ -0,0 +1,2 @@
+packages/
+pubspec.lock
diff --git a/third_party/mojo/src/mojo/public/dart/BUILD.gn b/third_party/mojo/src/mojo/public/dart/BUILD.gn
index 711eee3..7305582 100644
--- a/third_party/mojo/src/mojo/public/dart/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/dart/BUILD.gn
@@ -2,32 +2,46 @@ import("../mojo_sdk.gni")
import("rules.gni")
dart_mojo_sdk_sources = [
- "application.dart",
- "bindings.dart",
- "core.dart",
- "src/application_connection.dart",
- "src/application.dart",
- "src/buffer.dart",
- "src/codec.dart",
- "src/data_pipe.dart",
- "src/drain_data.dart",
- "src/event_stream.dart",
- "src/handle.dart",
- "src/message.dart",
- "src/message_pipe.dart",
- "src/proxy.dart",
- "src/struct.dart",
- "src/stub.dart",
- "src/types.dart",
+ "lib/application.dart",
+ "lib/bindings.dart",
+ "lib/core.dart",
+ "lib/src/application_connection.dart",
+ "lib/src/application.dart",
+ "lib/src/buffer.dart",
+ "lib/src/codec.dart",
+ "lib/src/control_message.dart",
+ "lib/src/data_pipe.dart",
+ "lib/src/drain_data.dart",
+ "lib/src/event_stream.dart",
+ "lib/src/handle.dart",
+ "lib/src/message.dart",
+ "lib/src/message_pipe.dart",
+ "lib/src/proxy.dart",
+ "lib/src/struct.dart",
+ "lib/src/stub.dart",
+ "lib/src/types.dart",
]
-dart_package("dart") {
- # This base dir ensures that Dart's Mojo SDK can be imported with, e.g.,
- # import 'package:mojo/public/dart/core.dart' even when the Mojo SDK lives
- # somewhere else in the source tree.
- base_dir = rebase_path("../../$mojo_root", ".", ".")
- sources = dart_mojo_sdk_sources
+dartzip_package("dart") {
+ sources = dart_mojo_sdk_sources + [
+ "pubspec.yaml",
+ "README.md",
+ ]
+ uses_pub = true
+ package_name_override = "mojo"
deps = [
"../interfaces/application",
+ "../interfaces/bindings",
+ ]
+}
+
+dart_pkg("mojo") {
+ sources = dart_mojo_sdk_sources + [
+ "pubspec.yaml",
+ "README.md",
+ ]
+ deps = [
+ "../interfaces/application",
+ "../interfaces/bindings",
]
}
diff --git a/third_party/mojo/src/mojo/public/dart/README.md b/third_party/mojo/src/mojo/public/dart/README.md
index 6de696b..6252690 100644
--- a/third_party/mojo/src/mojo/public/dart/README.md
+++ b/third_party/mojo/src/mojo/public/dart/README.md
@@ -15,12 +15,12 @@ all make it to the right place.
### GN Template
Dart Mojo applications are built with the GN template
-'dart_packaged_application' defined in `//mojo/public/dart/rules.gni`.
+'dartzip_packaged_application' defined in `//mojo/public/dart/rules.gni`.
Here is an example:
```
-dart_packaged_application("foo") {
+dartzip_packaged_application("foo") {
output_name = "dart_foo"
uses_pub = true
sources = [
@@ -73,8 +73,8 @@ Dart packages. `pub get` also creates a `pubspec.lock` file that locks down
pub packages to specific versions. This `pubspec.lock` file must be checked in
in order to have hermetic builds.
-During the build, The `dart_packaged_application` rule looks for a "packages/"
-directory, and copies its contents into the zip file.
+During the build, The `dartzip_packaged_application` rule looks for a
+"packages/" directory, and copies its contents into the zip file.
### Generated bindings
diff --git a/third_party/mojo/src/mojo/public/dart/io.dart b/third_party/mojo/src/mojo/public/dart/io.dart
deleted file mode 100644
index 7596c74..0000000
--- a/third_party/mojo/src/mojo/public/dart/io.dart
+++ /dev/null
@@ -1,49 +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.
-
-library dart.io;
-
-import 'dart:async';
-import 'dart:collection' show HashMap,
- HashSet,
- Queue,
- ListQueue,
- LinkedList,
- LinkedListEntry,
- UnmodifiableMapView;
-import 'dart:convert';
-import 'dart:isolate';
-import 'dart:math';
-import 'dart:typed_data';
-
-
-part '../../../dart/sdk/lib/io/bytes_builder.dart';
-part '../../../dart/sdk/lib/io/common.dart';
-part '../../../dart/sdk/lib/io/crypto.dart';
-part '../../../dart/sdk/lib/io/data_transformer.dart';
-part '../../../dart/sdk/lib/io/directory.dart';
-part '../../../dart/sdk/lib/io/directory_impl.dart';
-part '../../../dart/sdk/lib/io/file.dart';
-part '../../../dart/sdk/lib/io/file_impl.dart';
-part '../../../dart/sdk/lib/io/file_system_entity.dart';
-part '../../../dart/sdk/lib/io/http.dart';
-part '../../../dart/sdk/lib/io/http_date.dart';
-part '../../../dart/sdk/lib/io/http_headers.dart';
-part '../../../dart/sdk/lib/io/http_impl.dart';
-part '../../../dart/sdk/lib/io/http_parser.dart';
-part '../../../dart/sdk/lib/io/http_session.dart';
-part '../../../dart/sdk/lib/io/io_sink.dart';
-part '../../../dart/sdk/lib/io/io_service.dart';
-part '../../../dart/sdk/lib/io/link.dart';
-part '../../../dart/sdk/lib/io/platform.dart';
-part '../../../dart/sdk/lib/io/platform_impl.dart';
-part '../../../dart/sdk/lib/io/process.dart';
-part '../../../dart/sdk/lib/io/service_object.dart';
-part '../../../dart/sdk/lib/io/socket.dart';
-part '../../../dart/sdk/lib/io/stdio.dart';
-part '../../../dart/sdk/lib/io/string_transformer.dart';
-part '../../../dart/sdk/lib/io/secure_socket.dart';
-part '../../../dart/sdk/lib/io/secure_server_socket.dart';
-part '../../../dart/sdk/lib/io/websocket.dart';
-part '../../../dart/sdk/lib/io/websocket_impl.dart';
diff --git a/third_party/mojo/src/mojo/public/dart/application.dart b/third_party/mojo/src/mojo/public/dart/lib/application.dart
index 37f923e..72cf84d 100644
--- a/third_party/mojo/src/mojo/public/dart/application.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/application.dart
@@ -8,8 +8,8 @@ import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
-import 'package:mojo/public/dart/bindings.dart' as bindings;
-import 'package:mojo/public/dart/core.dart' as core;
+import 'package:mojo/bindings.dart' as bindings;
+import 'package:mojo/core.dart' as core;
import 'package:mojom/mojo/application.mojom.dart' as application_mojom;
import 'package:mojom/mojo/service_provider.mojom.dart';
import 'package:mojom/mojo/shell.mojom.dart' as shell_mojom;
diff --git a/third_party/mojo/src/mojo/public/dart/bindings.dart b/third_party/mojo/src/mojo/public/dart/lib/bindings.dart
index e68afec..00e0c22 100644
--- a/third_party/mojo/src/mojo/public/dart/bindings.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/bindings.dart
@@ -8,8 +8,10 @@ import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
-import 'package:mojo/public/dart/core.dart' as core;
+import 'package:mojo/core.dart' as core;
+import 'package:mojom/mojo/interface_control_messages.mojom.dart' as icm;
+part 'src/control_message.dart';
part 'src/codec.dart';
part 'src/message.dart';
part 'src/proxy.dart';
diff --git a/third_party/mojo/src/mojo/public/dart/core.dart b/third_party/mojo/src/mojo/public/dart/lib/core.dart
index e72da3f..e72da3f 100644
--- a/third_party/mojo/src/mojo/public/dart/core.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/core.dart
diff --git a/third_party/mojo/src/mojo/public/dart/internal.dart b/third_party/mojo/src/mojo/public/dart/lib/internal.dart
index 4239df2..4239df2 100644
--- a/third_party/mojo/src/mojo/public/dart/internal.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/internal.dart
diff --git a/third_party/mojo/src/mojo/public/dart/lib/io.dart b/third_party/mojo/src/mojo/public/dart/lib/io.dart
new file mode 100644
index 0000000..bb8e64dc
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/dart/lib/io.dart
@@ -0,0 +1,49 @@
+// 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.
+
+library dart.io;
+
+import 'dart:async';
+import 'dart:collection' show HashMap,
+ HashSet,
+ Queue,
+ ListQueue,
+ LinkedList,
+ LinkedListEntry,
+ UnmodifiableMapView;
+import 'dart:convert';
+import 'dart:isolate';
+import 'dart:math';
+import 'dart:typed_data';
+
+
+part '../../../../dart/sdk/lib/io/bytes_builder.dart';
+part '../../../../dart/sdk/lib/io/common.dart';
+part '../../../../dart/sdk/lib/io/crypto.dart';
+part '../../../../dart/sdk/lib/io/data_transformer.dart';
+part '../../../../dart/sdk/lib/io/directory.dart';
+part '../../../../dart/sdk/lib/io/directory_impl.dart';
+part '../../../../dart/sdk/lib/io/file.dart';
+part '../../../../dart/sdk/lib/io/file_impl.dart';
+part '../../../../dart/sdk/lib/io/file_system_entity.dart';
+part '../../../../dart/sdk/lib/io/http.dart';
+part '../../../../dart/sdk/lib/io/http_date.dart';
+part '../../../../dart/sdk/lib/io/http_headers.dart';
+part '../../../../dart/sdk/lib/io/http_impl.dart';
+part '../../../../dart/sdk/lib/io/http_parser.dart';
+part '../../../../dart/sdk/lib/io/http_session.dart';
+part '../../../../dart/sdk/lib/io/io_sink.dart';
+part '../../../../dart/sdk/lib/io/io_service.dart';
+part '../../../../dart/sdk/lib/io/link.dart';
+part '../../../../dart/sdk/lib/io/platform.dart';
+part '../../../../dart/sdk/lib/io/platform_impl.dart';
+part '../../../../dart/sdk/lib/io/process.dart';
+part '../../../../dart/sdk/lib/io/service_object.dart';
+part '../../../../dart/sdk/lib/io/socket.dart';
+part '../../../../dart/sdk/lib/io/stdio.dart';
+part '../../../../dart/sdk/lib/io/string_transformer.dart';
+part '../../../../dart/sdk/lib/io/secure_socket.dart';
+part '../../../../dart/sdk/lib/io/secure_server_socket.dart';
+part '../../../../dart/sdk/lib/io/websocket.dart';
+part '../../../../dart/sdk/lib/io/websocket_impl.dart';
diff --git a/third_party/mojo/src/mojo/public/dart/src/application.dart b/third_party/mojo/src/mojo/public/dart/lib/src/application.dart
index f6ee473..f6ee473 100644
--- a/third_party/mojo/src/mojo/public/dart/src/application.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/application.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/application_connection.dart b/third_party/mojo/src/mojo/public/dart/lib/src/application_connection.dart
index 2e80fc1..2e80fc1 100644
--- a/third_party/mojo/src/mojo/public/dart/src/application_connection.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/application_connection.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/buffer.dart b/third_party/mojo/src/mojo/public/dart/lib/src/buffer.dart
index 5e153be..5e153be 100644
--- a/third_party/mojo/src/mojo/public/dart/src/buffer.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/buffer.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/codec.dart b/third_party/mojo/src/mojo/public/dart/lib/src/codec.dart
index 89e32c2..07bad35 100644
--- a/third_party/mojo/src/mojo/public/dart/src/codec.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/codec.dart
@@ -201,11 +201,10 @@ class Encoder {
void encodeInterface(
core.MojoEventStreamListener interface, int offset, bool nullable) {
- // Set the version field to 0 for now.
- encodeUint32(0, offset + kSerializedHandleSize);
-
if (interface == null) {
encodeInvalideHandle(offset, nullable);
+ // Set the version field to 0.
+ encodeUint32(0, offset + kSerializedHandleSize);
return;
}
if (interface is Stub) {
@@ -214,6 +213,8 @@ class Encoder {
interface.bind(pipe.endpoints[0]);
interface.listen();
encodeMessagePipeHandle(pipe.endpoints[1], offset, nullable);
+ // Set the version to the version in the stub.
+ encodeUint32(interface.version, offset + kSerializedHandleSize);
} else if (interface is Proxy) {
assert(interface.isBound);
if (!interface.isOpen) {
@@ -222,6 +223,8 @@ class Encoder {
interface.listen();
}
encodeMessagePipeHandle(interface.endpoint, offset, nullable);
+ // Set the version to the current version of the proxy.
+ encodeUint32(interface.version, offset + kSerializedHandleSize);
} else {
throw new MojoCodecError(
'Trying to encode an unknown MojoEventStreamListener');
@@ -594,9 +597,14 @@ class Decoder {
ProxyBase decodeServiceInterface(
int offset, bool nullable, Function clientFactory) {
- // Ignore the version field for now.
var endpoint = decodeMessagePipeHandle(offset, nullable);
- return endpoint.handle.isValid ? clientFactory(endpoint) : null;
+ var version = decodeUint32(offset + kSerializedHandleSize);
+ if (!endpoint.handle.isValid) {
+ return null;
+ }
+ ProxyBase client = clientFactory(endpoint);
+ client.impl._version = version;
+ return client;
}
Stub decodeInterfaceRequest(
diff --git a/third_party/mojo/src/mojo/public/dart/lib/src/control_message.dart b/third_party/mojo/src/mojo/public/dart/lib/src/control_message.dart
new file mode 100644
index 0000000..de71a980
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/control_message.dart
@@ -0,0 +1,61 @@
+// 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.
+
+part of bindings;
+
+// Handles InterfaceControlMessages for a stub.
+class ControlMessageHandler {
+ static bool isControlMessage(ServiceMessage message) =>
+ _isRun(message) || _isRunOrClose(message);
+
+ static bool _isRun(ServiceMessage message) =>
+ (message.header.type == icm.kRunMessageId);
+
+ static bool _isRunOrClose(ServiceMessage message) =>
+ (message.header.type == icm.kRunOrClosePipeMessageId);
+
+ static Future<Message> handleMessage(Stub stub,
+ int interface_version,
+ ServiceMessage message) {
+ assert(isControlMessage(message));
+ if (_isRun(message)) {
+ return _handleRun(stub, interface_version, message);
+ } else {
+ assert(_isRunOrClose(message));
+ return _handleRunOrClose(stub, interface_version, message);
+ }
+ }
+
+ static Future<Message> _handleRun(Stub stub,
+ int interface_version,
+ ServiceMessage message) {
+ // Construct RunMessage response.
+ var response = new icm.RunResponseMessageParams();
+ response.reserved0 = 16;
+ response.reserved1 = 0;
+ response.queryVersionResult = new icm.QueryVersionResult();
+ response.queryVersionResult.version = interface_version;
+ // Return response.
+ return new Future.value(
+ stub.buildResponseWithId(response,
+ icm.kRunMessageId,
+ message.header.requestId,
+ MessageHeader.kMessageIsResponse));
+ }
+
+ static Future<Message> _handleRunOrClose(Stub stub,
+ int interface_version,
+ ServiceMessage message) {
+ // Deserialize message.
+ var params = icm.RunOrClosePipeMessageParams.deserialize(message.payload);
+ // Grab required version.
+ var requiredVersion = params.requireVersion.version;
+ if (interface_version >= requiredVersion) {
+ // Stub meets the requirements.
+ return;
+ }
+ // Stub does not implement required version. Close the pipe immediately.
+ stub.close(immediate: true);
+ }
+}
diff --git a/third_party/mojo/src/mojo/public/dart/src/data_pipe.dart b/third_party/mojo/src/mojo/public/dart/lib/src/data_pipe.dart
index 884bbcb..884bbcb 100644
--- a/third_party/mojo/src/mojo/public/dart/src/data_pipe.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/data_pipe.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/drain_data.dart b/third_party/mojo/src/mojo/public/dart/lib/src/drain_data.dart
index b5929e5..b5929e5 100644
--- a/third_party/mojo/src/mojo/public/dart/src/drain_data.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/drain_data.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/event_stream.dart b/third_party/mojo/src/mojo/public/dart/lib/src/event_stream.dart
index febfc9d..febfc9d 100644
--- a/third_party/mojo/src/mojo/public/dart/src/event_stream.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/event_stream.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/handle.dart b/third_party/mojo/src/mojo/public/dart/lib/src/handle.dart
index e7ac3eb..e7ac3eb 100644
--- a/third_party/mojo/src/mojo/public/dart/src/handle.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/handle.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/handle_watcher.dart b/third_party/mojo/src/mojo/public/dart/lib/src/handle_watcher.dart
index 4aeeaff..4aeeaff 100644
--- a/third_party/mojo/src/mojo/public/dart/src/handle_watcher.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/handle_watcher.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/message.dart b/third_party/mojo/src/mojo/public/dart/lib/src/message.dart
index 559c345..559c345 100644
--- a/third_party/mojo/src/mojo/public/dart/src/message.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/message.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/message_pipe.dart b/third_party/mojo/src/mojo/public/dart/lib/src/message_pipe.dart
index 29ae078..29ae078 100644
--- a/third_party/mojo/src/mojo/public/dart/src/message_pipe.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/message_pipe.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/natives.dart b/third_party/mojo/src/mojo/public/dart/lib/src/natives.dart
index a46ddd6..a46ddd6 100644
--- a/third_party/mojo/src/mojo/public/dart/src/natives.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/natives.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/proxy.dart b/third_party/mojo/src/mojo/public/dart/lib/src/proxy.dart
index 863e734..528e13a 100644
--- a/third_party/mojo/src/mojo/public/dart/src/proxy.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/proxy.dart
@@ -13,6 +13,10 @@ class ProxyCloseException {
abstract class Proxy extends core.MojoEventStreamListener {
Map<int, Completer> _completerMap;
int _nextId = 0;
+ int _version = 0;
+ /// Version of this interface that the remote side supports. Updated when a
+ /// call to [queryVersion] or [requireVersion] is made.
+ int get version => _version;
Proxy.fromEndpoint(core.MojoMessagePipeEndpoint endpoint)
: _completerMap = {},
@@ -39,6 +43,10 @@ abstract class Proxy extends core.MojoEventStreamListener {
result = endpoint.read(bytes, result.bytesRead, handles);
assert(result.status.isOk || result.status.isResourceExhausted);
var message = new ServiceMessage.fromMessage(new Message(bytes, handles));
+ if (ControlMessageHandler.isControlMessage(message)) {
+ _handleControlMessageResponse(message);
+ return;
+ }
handleResponse(message);
}
@@ -96,6 +104,63 @@ abstract class Proxy extends core.MojoEventStreamListener {
var superString = super.toString();
return "Proxy(${superString})";
}
+
+ /// Queries the max version that the remote side supports.
+ /// Updates [version].
+ Future<int> queryVersion() async {
+ var params = new icm.RunMessageParams();
+ params.reserved0 = 16;
+ params.reserved1 = 0;
+ params.queryVersion = new icm.QueryVersion();
+ var response = await
+ sendMessageWithRequestId(params,
+ icm.kRunMessageId,
+ -1,
+ MessageHeader.kMessageExpectsResponse);
+ _version = response.queryVersionResult.version;
+ return _version;
+ }
+
+ /// If the remote side doesn't support the [requiredVersion], it will close
+ /// its end of the message pipe asynchronously. This does nothing if it's
+ /// already known that the remote side supports [requiredVersion].
+ /// Updates [version].
+ void requireVersion(int requiredVersion) {
+ if (requiredVersion <= _version) {
+ // Already supported.
+ return;
+ }
+
+ // If the remote end doesn't close the pipe, we know that it supports
+ // required version.
+ _version = requiredVersion;
+
+ var params = new icm.RunOrClosePipeMessageParams();
+ params.reserved0 = 16;
+ params.reserved1 = 0;
+ params.requireVersion = new icm.RequireVersion();
+ params.requireVersion.version = requiredVersion;
+ // TODO(johnmccutchan): We've set _version above but if this sendMessage
+ // throws an exception we may not have sent the RunOrClose message. Should
+ // we reset _version in that case?
+ sendMessage(params, icm.kRunOrClosePipeMessageId);
+ }
+
+ _handleControlMessageResponse(ServiceMessage message) {
+ // We only expect to see Run messages.
+ assert(message.header.type == icm.kRunMessageId);
+ var response = icm.RunResponseMessageParams.deserialize(message.payload);
+ if (!message.header.hasRequestId) {
+ throw 'Expected a message with a valid request Id.';
+ }
+ Completer c = completerMap[message.header.requestId];
+ if (c == null) {
+ throw 'Message had unknown request Id: ${message.header.requestId}';
+ }
+ completerMap.remove(message.header.requestId);
+ assert(!c.isCompleted);
+ c.complete(response);
+ }
}
// Generated Proxy classes implement this interface.
diff --git a/third_party/mojo/src/mojo/public/dart/src/struct.dart b/third_party/mojo/src/mojo/public/dart/lib/src/struct.dart
index d4ac365..d4ac365 100644
--- a/third_party/mojo/src/mojo/public/dart/src/struct.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/struct.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/stub.dart b/third_party/mojo/src/mojo/public/dart/lib/src/stub.dart
index 87298bf..babba68 100644
--- a/third_party/mojo/src/mojo/public/dart/src/stub.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/stub.dart
@@ -125,4 +125,6 @@ abstract class Stub extends core.MojoEventStreamListener {
var superString = super.toString();
return "Stub(${superString})";
}
+
+ int get version;
}
diff --git a/third_party/mojo/src/mojo/public/dart/src/timer_queue.dart b/third_party/mojo/src/mojo/public/dart/lib/src/timer_queue.dart
index 01c2493..01c2493 100644
--- a/third_party/mojo/src/mojo/public/dart/src/timer_queue.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/timer_queue.dart
diff --git a/third_party/mojo/src/mojo/public/dart/src/types.dart b/third_party/mojo/src/mojo/public/dart/lib/src/types.dart
index 8c6e4f4..8c6e4f4 100644
--- a/third_party/mojo/src/mojo/public/dart/src/types.dart
+++ b/third_party/mojo/src/mojo/public/dart/lib/src/types.dart
diff --git a/third_party/mojo/src/mojo/public/dart/pubspec.yaml b/third_party/mojo/src/mojo/public/dart/pubspec.yaml
new file mode 100644
index 0000000..920d2e9
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/dart/pubspec.yaml
@@ -0,0 +1,4 @@
+name: mojo
+version: 0.0.6
+dependencies:
+ mojom: any
diff --git a/third_party/mojo/src/mojo/public/dart/rules.gni b/third_party/mojo/src/mojo/public/dart/rules.gni
index 930a896..03b17b18 100644
--- a/third_party/mojo/src/mojo/public/dart/rules.gni
+++ b/third_party/mojo/src/mojo/public/dart/rules.gni
@@ -2,11 +2,12 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-# Rules to generate python packaged applications for Dart
+# Rules to generate zipped applications for Dart.
+# Rules to generate dart-pkg and dart-pkg/packages.
import("//build/module_args/mojo.gni")
-template("dart_package") {
+template("dartzip_package") {
package_target_name = "$target_name"
package_output = "$target_out_dir/$target_name.dartzip"
@@ -16,6 +17,11 @@ template("dart_package") {
target_dir = get_label_info(":$target_name", "dir")
script = rebase_path("mojo/public/tools/gn/zip.py", ".", mojo_sdk_root)
+ package_name = "$package_target_name"
+ if (defined(invoker.package_name_override)) {
+ package_name = invoker.package_name_override
+ }
+
# Get a list of the files in packages/ as inputs.
list_packages_contents_script =
rebase_path("mojo/public/tools/dart_list_packages_contents.py",
@@ -26,6 +32,8 @@ template("dart_package") {
[
"--target-directory",
rebase_target_dir,
+ "--package-name",
+ package_name,
],
"list lines",
[ target_dir + "/pubspec.lock" ])
@@ -36,7 +44,7 @@ template("dart_package") {
outputs = [
output,
]
- rebase_base_dir = rebase_target_dir + "/packages"
+ rebase_base_dir = rebase_target_dir
rebase_inputs = rebase_path(inputs, root_build_dir)
rebase_output = rebase_path(output, root_build_dir)
args = [
@@ -48,7 +56,8 @@ template("dart_package") {
}
action("${package_target_name}_package") {
- script = rebase_path("mojo/public/tools/gn/zip.py", ".", mojo_sdk_root)
+ script =
+ rebase_path("mojo/public/tools/dart_package.py", ".", mojo_sdk_root)
inputs = invoker.sources
@@ -86,6 +95,7 @@ template("dart_package") {
rebase_inputs = rebase_path(inputs, root_build_dir)
rebase_zip_inputs = rebase_path(zip_inputs, root_build_dir)
rebase_output = rebase_path(output, root_build_dir)
+
args = [
"--base-dir=$rebase_base_dir",
"--inputs=$rebase_inputs",
@@ -107,7 +117,7 @@ template("dart_package") {
rebase_path("$target_gen_dir/${package_target_name}_analyze.stamp"),
"--no-hints",
"--url-mapping=dart:mojo.io,/" +
- rebase_path("mojo/public/dart/io.dart", "/", mojo_sdk_root),
+ rebase_path("mojo/public/dart/lib/io.dart", "/", mojo_sdk_root),
]
deps = [
@@ -131,8 +141,8 @@ template("dart_package") {
# files should be named main.dart and contain a main function as the
# entry point. Dependencies of dart_packaged_application targets should be
# either mojom targets (and specified using the mojom_deps variable) or
-# dart_package targets.
-template("dart_packaged_application") {
+# dartzip_package targets.
+template("dartzip_packaged_application") {
package_name = "${target_name}_package"
package_output = "$target_out_dir/$package_name.dartzip"
@@ -142,7 +152,7 @@ template("dart_packaged_application") {
mojo_output = "$root_out_dir/" + target_name + ".mojo"
}
- dart_package(package_name) {
+ dartzip_package(package_name) {
sources = invoker.sources
if (defined(invoker.deps)) {
deps = invoker.deps
@@ -198,3 +208,93 @@ template("dart_packaged_application") {
]
}
}
+
+# Creates a gen/dart-pkg/package_name directory containing symlinks to package
+# sources. Also copies any mojom dependencies into lib/mojom.
+#
+# sources
+# List of sources to include in the package.
+#
+# deps (optional)
+# Note: this can only contain mojom targets.
+#
+# datadeps (optional)
+#
+# sdk_ext_directory (optional)
+# Directory containing sdk-ext .dart sources.
+#
+template("dart_pkg") {
+ pubspec_yaml_path = rebase_path("pubspec.yaml")
+ dart_package_name_script =
+ rebase_path("mojo/public/tools/dart_package_name.py", ".", mojo_sdk_root)
+ package_name = exec_script(dart_package_name_script,
+ [
+ "--pubspec",
+ pubspec_yaml_path,
+ ],
+ "trim string",
+ [ pubspec_yaml_path ])
+
+ pkg_directory = rebase_path("$root_gen_dir/dart-pkg")
+ package_root = rebase_path("$root_gen_dir/dart-pkg/packages")
+ stamp_file = "$root_gen_dir/dart-pkg/${package_name}.stamp"
+
+ assert(defined(invoker.sources))
+
+ action(target_name) {
+ deps = []
+ if (defined(invoker.deps)) {
+ deps += invoker.deps
+ }
+
+ datadeps = []
+ if (defined(invoker.datadeps)) {
+ datadeps += invoker.datadeps
+ }
+
+ list_mojoms_script =
+ rebase_path("mojo/public/tools/dart_list_mojoms.py", ".", mojo_sdk_root)
+ mojom_sources = []
+ foreach(d, deps) {
+ root_prefix = rebase_path(".", "", mojo_sdk_root)
+ source_directory = rebase_path(get_label_info(d, "dir"))
+ mojom_sources += exec_script(list_mojoms_script,
+ [
+ source_directory,
+ root_prefix,
+ ],
+ "list lines")
+ }
+
+ sdk_ext_directory = []
+ if (defined(invoker.sdk_ext_directory)) {
+ sdk_ext_directory += [ invoker.sdk_ext_directory ]
+ }
+
+ script = rebase_path("mojo/public/tools/dart_pkg.py", ".", mojo_sdk_root)
+ outputs = [
+ stamp_file,
+ ]
+
+ inputs = [
+ list_mojoms_script,
+ script,
+ ] + rebase_path(invoker.sources)
+
+ args = [
+ "--package-name",
+ package_name,
+ "--gen-directory",
+ rebase_path("$root_gen_dir/dart-gen"),
+ "--pkg-directory",
+ pkg_directory,
+ "--package-root",
+ package_root,
+ "--stamp-file",
+ rebase_path(stamp_file),
+ "--package-sources",
+ ] + rebase_path(invoker.sources) + [ "--mojom-sources" ] +
+ rebase_path(mojom_sources, "", mojo_sdk_root) +
+ [ "--sdk-ext-directories" ] + rebase_path(sdk_ext_directory)
+ }
+}
diff --git a/third_party/mojo/src/mojo/public/go/bindings/decoder.go b/third_party/mojo/src/mojo/public/go/bindings/decoder.go
index 9711e23..dac5110 100644
--- a/third_party/mojo/src/mojo/public/go/bindings/decoder.go
+++ b/third_party/mojo/src/mojo/public/go/bindings/decoder.go
@@ -149,6 +149,21 @@ func (d *Decoder) StartStruct() (DataHeader, error) {
return header, nil
}
+// StartUnion starts decoding a union and reads its header.
+// Returns the read data header. The caller should check if it is valid.
+// Note: it doesn't read the data field.
+func (d *Decoder) StartUnion() (DataHeader, error) {
+ header, err := d.readDataHeader()
+ if err != nil {
+ return DataHeader{}, err
+ }
+
+ if err := d.pushState(header, 0); err != nil {
+ return DataHeader{}, err
+ }
+ return header, nil
+}
+
func (d *Decoder) readDataHeader() (DataHeader, error) {
if err := d.claimData(dataHeaderSize); err != nil {
return DataHeader{}, err
diff --git a/third_party/mojo/src/mojo/public/go/bindings/encoder.go b/third_party/mojo/src/mojo/public/go/bindings/encoder.go
index 822aaa4..918c883 100644
--- a/third_party/mojo/src/mojo/public/go/bindings/encoder.go
+++ b/third_party/mojo/src/mojo/public/go/bindings/encoder.go
@@ -163,6 +163,12 @@ func (e *Encoder) StartStruct(size, version uint32) {
e.pushState(header, 0)
}
+// StartUnion starts encoding a union and writes its data header.
+func (e *Encoder) StartUnion(tag uint32) {
+ header := DataHeader{uint32(16), tag}
+ e.pushState(header, 0)
+}
+
func (e *Encoder) writeDataHeader(header DataHeader) {
binary.LittleEndian.PutUint32(e.buf[e.state().offset:], header.Size)
binary.LittleEndian.PutUint32(e.buf[e.state().offset+4:], header.ElementsOrVersion)
@@ -285,6 +291,22 @@ func (e *Encoder) WriteFloat64(value float64) error {
return e.WriteUint64(math.Float64bits(value))
}
+// WriteNullUnion writes a null union.
+func (e *Encoder) WriteNullUnion() error {
+ if err := ensureElementBitSizeAndCapacity(e.state(), 128); err != nil {
+ return err
+ }
+ e.state().alignOffsetToBytes()
+ e.state().offset = align(e.state().offset, 16)
+ binary.LittleEndian.PutUint64(e.buf[e.state().offset:], 0)
+ e.state().skipBytes(8)
+ binary.LittleEndian.PutUint64(e.buf[e.state().offset:], 0)
+ e.state().skipBytes(8)
+ e.state().elementsProcessed++
+
+ return nil
+}
+
// WriteNullPointer writes a null pointer.
func (e *Encoder) WriteNullPointer() error {
return e.WriteUint64(0)
diff --git a/third_party/mojo/src/mojo/public/interfaces/bindings/tests/BUILD.gn b/third_party/mojo/src/mojo/public/interfaces/bindings/tests/BUILD.gn
index 5cdbda1..9bf206c 100644
--- a/third_party/mojo/src/mojo/public/interfaces/bindings/tests/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/interfaces/bindings/tests/BUILD.gn
@@ -23,15 +23,24 @@ mojom("test_interfaces") {
]
}
-mojom("versioning_test_service_interfaces") {
+mojom("test_interfaces_experimental") {
testonly = true
sources = [
+ "test_unions.mojom",
+ ]
+}
+
+mojom("versioning_test_service_interfaces") {
+ # FIXME: Dart packaged applications cannot depend on testonly mojoms.
+ # testonly = true
+ sources = [
"versioning_test_service.mojom",
]
}
mojom("versioning_test_client_interfaces") {
- testonly = true
+ # FIXME: Dart packaged applications cannot depend on testonly mojoms.
+ # testonly = true
sources = [
"versioning_test_client.mojom",
]
diff --git a/third_party/mojo/src/mojo/public/interfaces/bindings/tests/test_unions.mojom b/third_party/mojo/src/mojo/public/interfaces/bindings/tests/test_unions.mojom
index 4e7a540d..6c573bc 100644
--- a/third_party/mojo/src/mojo/public/interfaces/bindings/tests/test_unions.mojom
+++ b/third_party/mojo/src/mojo/public/interfaces/bindings/tests/test_unions.mojom
@@ -40,6 +40,11 @@ union HandleUnion {
handle<data_pipe_consumer> f_data_pipe_consumer;
handle<data_pipe_producer> f_data_pipe_producer;
handle<shared_buffer> f_shared_buffer;
+ SmallCache f_small_cache;
+};
+
+struct HandleStruct {
+ SmallCache f_small_cache;
};
struct DummyStruct {
@@ -50,8 +55,10 @@ struct SmallStruct {
DummyStruct? dummy_struct;
PodUnion? pod_union;
array<PodUnion>? pod_union_array;
+ array<PodUnion?>? nullable_pod_union_array;
array<DummyStruct>? s_array;
map<string, PodUnion>? pod_union_map;
+ map<string, PodUnion?>? nullable_pod_union_map;
};
struct SmallStructNonNullableUnion {
@@ -61,3 +68,12 @@ struct SmallStructNonNullableUnion {
struct SmallObjStruct {
ObjectUnion obj_union;
};
+
+interface SmallCache {
+ SetIntValue(int64 int_value);
+ GetIntValue() => (int64 int_value);
+};
+
+interface UnionInterface {
+ Echo(PodUnion in) => (PodUnion out);
+};
diff --git a/third_party/mojo/src/mojo/public/java/BUILD.gn b/third_party/mojo/src/mojo/public/java/BUILD.gn
index 2bb5ff1..6c9c308 100644
--- a/third_party/mojo/src/mojo/public/java/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/java/BUILD.gn
@@ -3,6 +3,7 @@
# found in the LICENSE file.
import("//build/config/android/rules.gni")
+import("../mojo.gni")
android_library("system") {
java_files = [
@@ -30,6 +31,7 @@ android_library("bindings") {
"bindings/src/org/chromium/mojo/bindings/Callbacks.java",
"bindings/src/org/chromium/mojo/bindings/ConnectionErrorHandler.java",
"bindings/src/org/chromium/mojo/bindings/Connector.java",
+ "bindings/src/org/chromium/mojo/bindings/DataHeader.java",
"bindings/src/org/chromium/mojo/bindings/Decoder.java",
"bindings/src/org/chromium/mojo/bindings/DelegatingConnectionErrorHandler.java",
"bindings/src/org/chromium/mojo/bindings/DeserializationException.java",
@@ -49,6 +51,7 @@ android_library("bindings") {
"bindings/src/org/chromium/mojo/bindings/ServiceMessage.java",
"bindings/src/org/chromium/mojo/bindings/SideEffectFreeCloseable.java",
"bindings/src/org/chromium/mojo/bindings/Struct.java",
+ "bindings/src/org/chromium/mojo/bindings/Union.java",
]
deps = [
@@ -57,3 +60,21 @@ android_library("bindings") {
srcjar_deps = [ "../interfaces/bindings:bindings_java_sources" ]
}
+
+if (mojo_use_application_in_sdk) {
+ android_library("application") {
+ java_files = [
+ "application/src/org/chromium/mojo/application/ApplicationConnection.java",
+ "application/src/org/chromium/mojo/application/ApplicationDelegate.java",
+ "application/src/org/chromium/mojo/application/ApplicationImpl.java",
+ "application/src/org/chromium/mojo/application/ApplicationRunner.java",
+ "application/src/org/chromium/mojo/application/ServiceFactoryBinder.java",
+ "application/src/org/chromium/mojo/application/ShellHelper.java",
+ ]
+ deps = [
+ ":bindings",
+ ":system",
+ "../interfaces/application:application_java",
+ ]
+ }
+}
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/BindingsHelper.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/BindingsHelper.java
index 169edcb..6146316 100644
--- a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/BindingsHelper.java
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/BindingsHelper.java
@@ -4,7 +4,6 @@
package org.chromium.mojo.bindings;
-import org.chromium.mojo.bindings.Struct.DataHeader;
import org.chromium.mojo.system.AsyncWaiter;
import org.chromium.mojo.system.Handle;
@@ -36,6 +35,11 @@ public class BindingsHelper {
public static final int POINTER_SIZE = 8;
/**
+ * The size, in bytes, of a serialized union.
+ */
+ public static final int UNION_SIZE = 16;
+
+ /**
* The header for a serialized map element.
*/
public static final DataHeader MAP_STRUCT_HEADER = new DataHeader(24, 0);
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/DataHeader.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/DataHeader.java
new file mode 100644
index 0000000..96acec9
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/DataHeader.java
@@ -0,0 +1,70 @@
+// 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.
+
+package org.chromium.mojo.bindings;
+
+/**
+ * The header for a mojo complex element.
+ */
+public final class DataHeader {
+ /**
+ * The size of a serialized header, in bytes.
+ */
+ public static final int HEADER_SIZE = 8;
+
+ /**
+ * The offset of the size field.
+ */
+ public static final int SIZE_OFFSET = 0;
+
+ /**
+ * The offset of the number of fields field.
+ */
+ public static final int ELEMENTS_OR_VERSION_OFFSET = 4;
+
+ /**
+ * The size of the object owning this header.
+ */
+ public final int size;
+
+ /**
+ * Number of element (for an array) or version (for a struct) of the object owning this
+ * header.
+ */
+ public final int elementsOrVersion;
+
+ /**
+ * Constructor.
+ */
+ public DataHeader(int size, int elementsOrVersion) {
+ super();
+ this.size = size;
+ this.elementsOrVersion = elementsOrVersion;
+ }
+
+ /**
+ * @see Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + elementsOrVersion;
+ result = prime * result + size;
+ return result;
+ }
+
+ /**
+ * @see Object#equals(Object)
+ */
+ @Override
+ public boolean equals(Object object) {
+ if (object == this) return true;
+ if (object == null) return false;
+ if (getClass() != object.getClass()) return false;
+
+ DataHeader other = (DataHeader) object;
+ return (elementsOrVersion == other.elementsOrVersion && size == other.size);
+ }
+} \ No newline at end of file
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Decoder.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Decoder.java
index 81cbc98..868eab6 100644
--- a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Decoder.java
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Decoder.java
@@ -5,7 +5,6 @@
package org.chromium.mojo.bindings;
import org.chromium.mojo.bindings.Interface.Proxy;
-import org.chromium.mojo.bindings.Struct.DataHeader;
import org.chromium.mojo.system.DataPipe;
import org.chromium.mojo.system.Handle;
import org.chromium.mojo.system.InvalidHandle;
@@ -114,26 +113,60 @@ public class Decoder {
}
/**
- * Deserializes a {@link DataHeader} at the given offset.
+ * Deserializes a {@link DataHeader} at the current position.
*/
public DataHeader readDataHeader() {
// Claim the memory for the header.
mValidator.claimMemory(mBaseOffset, mBaseOffset + DataHeader.HEADER_SIZE);
- int size = readInt(DataHeader.SIZE_OFFSET);
- int elementsOrVersion = readInt(DataHeader.ELEMENTS_OR_VERSION_OFFSET);
+ DataHeader result = readDataHeaderAtOffset(0, false);
+ // Claim the rest of the memory.
+ mValidator.claimMemory(mBaseOffset + DataHeader.HEADER_SIZE, mBaseOffset + result.size);
+ return result;
+ }
+
+ /**
+ * Deserializes a {@link DataHeader} for an union at the given offset.
+ */
+ public DataHeader readDataHeaderForUnion(int offset) {
+ DataHeader result = readDataHeaderAtOffset(offset, true);
+ if (result.size == 0) {
+ if (result.elementsOrVersion != 0) {
+ throw new DeserializationException(
+ "Unexpected version tag for a null union. Expecting 0, found: "
+ + result.elementsOrVersion);
+ }
+ } else if (result.size != BindingsHelper.UNION_SIZE) {
+ throw new DeserializationException(
+ "Unexpected size of an union. The size must be 0 for a null union, or 16 for "
+ + "a non-null union.");
+ }
+ return result;
+ }
+
+ /**
+ * @returns a decoder suitable to decode an union defined as the root object of a message.
+ */
+ public Decoder decoderForSerializedUnion() {
+ mValidator.claimMemory(0, BindingsHelper.UNION_SIZE);
+ return this;
+ }
+
+ /**
+ * Deserializes a {@link DataHeader} at the given offset.
+ */
+ private DataHeader readDataHeaderAtOffset(int offset, boolean isUnion) {
+ int size = readInt(offset + DataHeader.SIZE_OFFSET);
+ int elementsOrVersion = readInt(offset + DataHeader.ELEMENTS_OR_VERSION_OFFSET);
if (size < 0) {
throw new DeserializationException(
"Negative size. Unsigned integers are not valid for java.");
}
- if (elementsOrVersion < 0) {
+ if (elementsOrVersion < 0 && (!isUnion || elementsOrVersion != -1)) {
throw new DeserializationException(
"Negative elements or version. Unsigned integers are not valid for java.");
}
- // Claim the remaining memory.
- mValidator.claimMemory(mBaseOffset + DataHeader.HEADER_SIZE, mBaseOffset + size);
- DataHeader res = new DataHeader(size, elementsOrVersion);
- return res;
+ return new DataHeader(size, elementsOrVersion);
}
public DataHeader readAndValidateDataHeader(DataHeader[] versionArray) {
@@ -163,10 +196,18 @@ public class Decoder {
/**
* Deserializes a {@link DataHeader} at the given offset and checks if it is correct for an
- * array where element have the given size.
+ * array where elements are pointers.
*/
public DataHeader readDataHeaderForPointerArray(int expectedLength) {
- return readDataHeaderForArray(8, expectedLength);
+ return readDataHeaderForArray(BindingsHelper.POINTER_SIZE, expectedLength);
+ }
+
+ /**
+ * Deserializes a {@link DataHeader} at the given offset and checks if it is correct for an
+ * array where elements are unions.
+ */
+ public DataHeader readDataHeaderForUnionArray(int expectedLength) {
+ return readDataHeaderForArray(BindingsHelper.UNION_SIZE, expectedLength);
}
/**
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Encoder.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Encoder.java
index c820ac5..4f95351 100644
--- a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Encoder.java
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Encoder.java
@@ -5,7 +5,6 @@
package org.chromium.mojo.bindings;
import org.chromium.mojo.bindings.Interface.AbstractProxy.HandlerImpl;
-import org.chromium.mojo.bindings.Struct.DataHeader;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.Handle;
import org.chromium.mojo.system.MessagePipeHandle;
@@ -50,8 +49,8 @@ public class Encoder {
public int dataEnd;
/**
- * @param core the |Core| implementation used to generate handles. Only used if the |Struct|
- * being encoded contains interfaces, can be |null| otherwise.
+ * @param core the |Core| implementation used to generate handles. Only used if the data
+ * structure being encoded contains interfaces, can be |null| otherwise.
* @param bufferSize A hint on the size of the message. Used to build the initial byte
* buffer.
*/
@@ -119,8 +118,8 @@ public class Encoder {
/**
* Constructor.
*
- * @param core the |Core| implementation used to generate handles. Only used if the |Struct|
- * being encoded contains interfaces, can be |null| otherwise.
+ * @param core the |Core| implementation used to generate handles. Only used if the data
+ * structure being encoded contains interfaces, can be |null| otherwise.
* @param sizeHint A hint on the size of the message. Used to build the initial byte buffer.
*/
public Encoder(Core core, int sizeHint) {
@@ -220,6 +219,22 @@ public class Encoder {
}
/**
+ * Encode a {@link Union} at the given offset.
+ */
+ public void encode(Union v, int offset, boolean nullable) {
+ if (v == null && !nullable) {
+ throw new SerializationException(
+ "Trying to encode a null pointer for a non-nullable type.");
+ }
+ if (v == null) {
+ encode(0L, offset);
+ encode(0L, offset + DataHeader.HEADER_SIZE);
+ return;
+ }
+ v.encode(this, offset);
+ }
+
+ /**
* Encodes a String.
*/
public void encode(String v, int offset, boolean nullable) {
@@ -300,6 +315,13 @@ public class Encoder {
}
/**
+ * Returns an {@link Encoder} suitable for encoding an array of union of the given length.
+ */
+ public Encoder encodeUnionArray(int length, int offset, int expectedLength) {
+ return encoderForArray(BindingsHelper.UNION_SIZE, length, offset, expectedLength);
+ }
+
+ /**
* Encodes an array of booleans.
*/
public void encode(boolean[] v, int offset, int arrayNullability, int expectedLength) {
@@ -432,6 +454,17 @@ public class Encoder {
}
/**
+ * Encodes a pointer to the next unclaimed memory and returns an encoder suitable to encode an
+ * union at this location.
+ */
+ public Encoder encoderForUnionPointer(int offset) {
+ encodePointerToNextUnclaimedData(offset);
+ Encoder result = new Encoder(mEncoderState);
+ result.mEncoderState.claimMemory(16);
+ return result;
+ }
+
+ /**
* Encodes an array of {@link InterfaceRequest}.
*/
public <I extends Interface> void encode(InterfaceRequest<I>[] v, int offset,
@@ -471,6 +504,13 @@ public class Encoder {
mEncoderState.byteBuffer.putInt(mBaseOffset + offset, -1);
}
+ /**
+ * Claim the given amount of memory at the end of the buffer, resizing it if needed.
+ */
+ void claimMemory(int size) {
+ mEncoderState.claimMemory(BindingsHelper.align(size));
+ }
+
private void encodePointerToNextUnclaimedData(int offset) {
encode((long) mEncoderState.dataEnd - (mBaseOffset + offset), offset);
}
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/MessageHeader.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/MessageHeader.java
index a908698..d4d6b83 100644
--- a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/MessageHeader.java
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/MessageHeader.java
@@ -4,8 +4,6 @@
package org.chromium.mojo.bindings;
-import org.chromium.mojo.bindings.Struct.DataHeader;
-
import java.nio.ByteBuffer;
/**
@@ -182,12 +180,9 @@ public class MessageHeader {
*/
@Override
public boolean equals(Object object) {
- if (object == this)
- return true;
- if (object == null)
- return false;
- if (getClass() != object.getClass())
- return false;
+ if (object == this) return true;
+ if (object == null) return false;
+ if (getClass() != object.getClass()) return false;
MessageHeader other = (MessageHeader) object;
return (BindingsHelper.equals(mDataHeader, other.mDataHeader)
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Struct.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Struct.java
index 16ae801..85cc97c 100644
--- a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Struct.java
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Struct.java
@@ -10,79 +10,10 @@ import org.chromium.mojo.system.Core;
* Base class for all mojo structs.
*/
public abstract class Struct {
-
/**
- * The header for a mojo complex element.
+ * The base size of the encoded struct.
*/
- public static final class DataHeader {
- /**
- * The size of a serialized header, in bytes.
- */
- public static final int HEADER_SIZE = 8;
-
- /**
- * The offset of the size field.
- */
- public static final int SIZE_OFFSET = 0;
-
- /**
- * The offset of the number of fields field.
- */
- public static final int ELEMENTS_OR_VERSION_OFFSET = 4;
-
- /**
- * The size of the object owning this header.
- */
- public final int size;
-
- /**
- * Number of element (for an array) or version (for a struct) of the object owning this
- * header.
- */
- public final int elementsOrVersion;
-
- /**
- * Constructor.
- */
- public DataHeader(int size, int elementsOrVersion) {
- super();
- this.size = size;
- this.elementsOrVersion = elementsOrVersion;
- }
-
- /**
- * @see Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + elementsOrVersion;
- result = prime * result + size;
- return result;
- }
-
- /**
- * @see Object#equals(Object)
- */
- @Override
- public boolean equals(Object object) {
- if (object == this)
- return true;
- if (object == null)
- return false;
- if (getClass() != object.getClass())
- return false;
-
- DataHeader other = (DataHeader) object;
- return (elementsOrVersion == other.elementsOrVersion && size == other.size);
- }
- }
-
- /**
- * The base size of the struct.
- */
- protected final int mEncodedBaseSize;
+ private final int mEncodedBaseSize;
/**
* The version of the struct.
@@ -108,8 +39,8 @@ public abstract class Struct {
/**
* Returns the serialization of the struct. This method can close Handles.
*
- * @param core the |Core| implementation used to generate handles. Only used if the |Struct|
- * being encoded contains interfaces, can be |null| otherwise.
+ * @param core the |Core| implementation used to generate handles. Only used if the data
+ * structure being encoded contains interfaces, can be |null| otherwise.
*/
public Message serialize(Core core) {
Encoder encoder = new Encoder(core, mEncodedBaseSize);
@@ -132,7 +63,7 @@ public abstract class Struct {
}
/**
- * Use the given encoder to serialize this struct.
+ * Use the given encoder to serialize this data structure.
*/
protected abstract void encode(Encoder encoder);
}
diff --git a/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Union.java b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Union.java
new file mode 100644
index 0000000..90b40ea
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/Union.java
@@ -0,0 +1,30 @@
+// 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.
+
+package org.chromium.mojo.bindings;
+
+import org.chromium.mojo.system.Core;
+
+/**
+ * Base class for all mojo unions.
+ */
+public abstract class Union {
+ /**
+ * Returns the serialization of the union. This method can close Handles.
+ *
+ * @param core the |Core| implementation used to generate handles. Only used if the data
+ * structure being encoded contains interfaces, can be |null| otherwise.
+ */
+ public Message serialize(Core core) {
+ Encoder encoder = new Encoder(core, BindingsHelper.UNION_SIZE);
+ encoder.claimMemory(16);
+ encode(encoder, 0);
+ return encoder.getMessage();
+ }
+
+ /**
+ * Serializes this data structure using the given encoder.
+ */
+ protected abstract void encode(Encoder encoder, int offset);
+}
diff --git a/third_party/mojo/src/mojo/public/mojo.gni b/third_party/mojo/src/mojo/public/mojo.gni
index f2631a0..c8c3055 100644
--- a/third_party/mojo/src/mojo/public/mojo.gni
+++ b/third_party/mojo/src/mojo/public/mojo.gni
@@ -27,6 +27,13 @@ if (defined(mojo_disable_dart_apptest_framework) &&
mojo_use_dart_apptest_framework = false
}
+# Embedder uses Mojo application code.
+mojo_use_application_in_sdk = true
+if (defined(mojo_disable_application_in_sdk) &&
+ mojo_disable_application_in_sdk) {
+ mojo_use_application_in_sdk = false
+}
+
# The absolute path to the directory containing the mojo public SDK (i.e., the
# directory containing mojo/public). The build files within the Mojo public
# SDK use this variable to allow themselves to be parameterized by the location
diff --git a/third_party/mojo/src/mojo/public/tools/BUILD.gn b/third_party/mojo/src/mojo/public/tools/BUILD.gn
index 9850a17..2368ae9 100644
--- a/third_party/mojo/src/mojo/public/tools/BUILD.gn
+++ b/third_party/mojo/src/mojo/public/tools/BUILD.gn
@@ -86,7 +86,7 @@ if (mojo_use_prebuilt_network_service) {
# This rule can be seen as a sort of adapter. This takes a dart framework
# loaded from Google Storage and then puts it in a rule which the
-# "dart_package" template in mojo/public/dart/rules.gni can introspect on,
+# "dartzip_package" template in mojo/public/dart/rules.gni can introspect on,
# accessing the 'label' and 'target_out_dir' variables.
if (mojo_use_dart_apptest_framework) {
copy("dart_apptest_framework") {
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_definition.tmpl
index 487d2a5..087499a 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_definition.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_definition.tmpl
@@ -62,8 +62,12 @@ void {{class_name}}::EncodePointersAndHandles(
case {{enum_name}}::{{field.name|upper}}: {
{%- if field.kind|is_object_kind %}
mojo::internal::Encode(&data.f_{{field.name}}, handles);
-{%- elif field.kind|is_any_handle_kind or field.kind|is_interface_kind %}
+{%- elif field.kind|is_any_handle_kind %}
mojo::internal::EncodeHandle(&data.f_{{field.name}}, handles);
+{%- elif field.kind|is_interface_kind %}
+ mojo::internal::EncodeHandle(
+ reinterpret_cast<mojo::internal::Interface_Data*>(
+ &data.f_{{field.name}}), handles);
{%- endif %}
return;
}
@@ -78,8 +82,12 @@ void {{class_name}}::DecodePointersAndHandles(
case {{enum_name}}::{{field.name|upper}}: {
{%- if field.kind|is_object_kind %}
mojo::internal::Decode(&data.f_{{field.name}}, handles);
-{%- elif field.kind|is_any_handle_kind or field.kind|is_interface_kind %}
+{%- elif field.kind|is_any_handle_kind %}
mojo::internal::DecodeHandle(&data.f_{{field.name}}, handles);
+{%- elif field.kind|is_interface_kind %}
+ mojo::internal::DecodeHandle(
+ reinterpret_cast<mojo::internal::Interface_Data*>(
+ &data.f_{{field.name}}), handles);
{%- endif %}
return;
}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl
index c9cc307..f07c487 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/union_serialization_definition.tmpl
@@ -70,6 +70,12 @@ void SerializeUnion_({{union.name}}Ptr input, mojo::internal::Buffer* buf,
{% elif field.kind|is_any_handle_kind %}
result->data.f_{{field.name}} =
input_acc.data()->{{field.name}}->release().value();
+{% elif field.kind|is_interface_kind %}
+ mojo::internal::Interface_Data* {{field.name}} =
+ reinterpret_cast<mojo::internal::Interface_Data*>(
+ &result->data.f_{{field.name}});
+ mojo::internal::InterfacePointerToData(
+ input_acc.data()->{{field.name}}->Pass(), {{field.name}});
{% else %}
result->data.f_{{field.name}} = input_acc.data()->{{field.name}};
{%- endif %}
@@ -100,6 +106,14 @@ void Deserialize_(internal::{{union.name}}_Data* input,
{{field.kind|cpp_wrapper_type}}* {{field.name}} =
reinterpret_cast<{{field.kind|cpp_wrapper_type}}*>(&input->data.f_{{field.name}});
result->set_{{field.name}}({{field.name}}->Pass());
+{% elif field.kind|is_interface_kind %}
+ {{field.kind|cpp_wrapper_type}} {{field.name}}_out;
+ mojo::internal::Interface_Data* {{field.name}}_in =
+ reinterpret_cast<mojo::internal::Interface_Data*>(
+ &input->data.f_{{field.name}});
+ mojo::internal::InterfaceDataToPointer(
+ {{field.name}}_in, &{{field.name}}_out);
+ result->set_{{field.name}}({{field.name}}_out.Pass());
{% elif field.kind|is_enum_kind %}
result->set_{{field.name}}(static_cast<{{field.kind|cpp_wrapper_type}}>(input->data.f_{{field.name}}));
{% else %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl
index 2f931bf..5e43c43 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_declaration.tmpl
@@ -39,7 +39,8 @@ class {{union.name}} {
Union_() {}
~Union_() {}
{% for field in union.fields %}
-{% if field.kind|is_object_kind or field.kind|is_any_handle_kind -%}
+{% if field.kind|is_object_kind or field.kind|is_any_handle_kind
+ or field.kind|is_interface_kind -%}
{{field.kind|cpp_wrapper_type}}* {{field.name}};
{% else -%}
{{field.kind|cpp_wrapper_type}} {{field.name}};
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl
index cb4e785..0f19a15 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/cpp_templates/wrapper_union_class_definition.tmpl
@@ -43,7 +43,8 @@ bool {{union.name}}::Equals(const {{union.name}}& other) const {
switch (tag_) {
{% for field in union.fields %}
case Tag::{{field.name|upper}}:
-{% if field.kind|is_object_kind or field.kind|is_any_handle_kind %}
+{% if field.kind|is_object_kind or field.kind|is_any_handle_kind
+ or field.kind|is_interface_kind %}
return mojo::internal::ValueTraits<{{field.kind|cpp_wrapper_type}}>::Equals(*(data_.{{field.name}}), *(other.data_.{{field.name}}));
{%- else %}
return mojo::internal::ValueTraits<{{field.kind|cpp_wrapper_type}}>::Equals(data_.{{field.name}}, other.data_.{{field.name}});
@@ -61,7 +62,8 @@ bool {{union.name}}::is_{{field.name}}() const {
{{field.kind|cpp_union_getter_return_type}} {{union.name}}::get_{{field.name}}() const {
MOJO_DCHECK(tag_ == Tag::{{field.name|upper}});
-{% if field.kind|is_object_kind or field.kind|is_any_handle_kind %}
+{% if field.kind|is_object_kind or field.kind|is_any_handle_kind
+ or field.kind|is_interface_kind %}
return *(data_.{{field.name}});
{%- else %}
return data_.{{field.name}};
@@ -72,7 +74,7 @@ void {{union.name}}::set_{{field.name}}({{field.kind|cpp_const_wrapper_type}} {{
SwitchActive(Tag::{{field.name|upper}});
{% if field.kind|is_string_kind %}
*(data_.{{field.name}}) = {{field.name}};
-{% elif field.kind|is_object_kind %}
+{% elif field.kind|is_object_kind or field.kind|is_interface_kind %}
*(data_.{{field.name}}) = {{field.name}}.Pass();
{% elif field.kind|is_any_handle_kind %}
data_.{{field.name}}->reset({{field.name}}.release());
@@ -95,7 +97,8 @@ void {{union.name}}::SetActive(Tag new_active) {
switch (new_active) {
{% for field in union.fields %}
case Tag::{{field.name|upper}}:
-{% if field.kind|is_object_kind or field.kind|is_any_handle_kind %}
+{% if field.kind|is_object_kind or field.kind|is_any_handle_kind
+ or field.kind|is_interface_kind %}
data_.{{field.name}} = new {{field.kind|cpp_wrapper_type}}();
{%- endif %}
break;
@@ -109,7 +112,8 @@ void {{union.name}}::DestroyActive() {
switch (tag_) {
{% for field in union.fields %}
case Tag::{{field.name|upper}}:
-{% if field.kind|is_object_kind or field.kind|is_any_handle_kind %}
+{% if field.kind|is_object_kind or field.kind|is_any_handle_kind
+ or field.kind|is_interface_kind %}
delete data_.{{field.name}};
{%- endif %}
break;
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl
index 0fbcb49..6e3cae4 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/interface_definition.tmpl
@@ -160,6 +160,14 @@ class {{interface|name}}Proxy implements bindings.ProxyBase {
Future close({bool immediate: false}) => impl.close(immediate: immediate);
+ int get version => impl.version;
+
+ Future<int> queryVersion() => impl.queryVersion();
+
+ void requireVersion(int requiredVersion) {
+ impl.requireVersion(requiredVersion);
+ }
+
String toString() {
return "{{interface|name}}Proxy($impl)";
}
@@ -202,6 +210,11 @@ class {{interface|name}}Stub extends bindings.Stub {
{%- endfor %}
Future<bindings.Message> handleMessage(bindings.ServiceMessage message) {
+ if (bindings.ControlMessageHandler.isControlMessage(message)) {
+ return bindings.ControlMessageHandler.handleMessage(this,
+ {{interface.version}},
+ message);
+ }
assert(_impl != null);
switch (message.header.type) {
{%- for method in interface.methods %}
@@ -241,7 +254,7 @@ class {{interface|name}}Stub extends bindings.Stub {
}
{{interface|name}} get impl => _impl;
- set impl({{interface|name}} d) {
+ set impl({{interface|name}} d) {
assert(_impl == null);
_impl = d;
}
@@ -250,4 +263,6 @@ class {{interface|name}}Stub extends bindings.Stub {
var superString = super.toString();
return "{{interface|name}}Stub($superString)";
}
+
+ int get version => {{interface.version}};
}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl
index d6b869e..4eb9ad4 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/module.lib.tmpl
@@ -6,8 +6,8 @@ library {{module.name}};
import 'dart:async';
-import 'package:mojo/public/dart/bindings.dart' as bindings;
-import 'package:mojo/public/dart/core.dart' as core;
+import 'package:mojo/bindings.dart' as bindings;
+import 'package:mojo/core.dart' as core;
{%- for import in imports %}
import 'package:{{import.rebased_path}}.dart' as {{import.unique_name}};
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl
index 9f62100..226a060 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/dart_templates/struct_definition.tmpl
@@ -33,9 +33,12 @@ encoder{{level}}.{{kind|encode_method(variable, offset, bit)}};
{%- macro decode(variable, kind, offset, bit, level=0) %}
-{%- if kind|is_struct_kind or kind|is_pointer_array_kind or kind|is_map_kind %}
+{%- if kind|is_struct_kind or
+ kind|is_union_kind or
+ kind|is_pointer_array_kind or
+ kind|is_map_kind %}
var decoder{{level+1}} = decoder{{level}}.decodePointer({{offset}}, {{kind|is_nullable_kind|dart_true_false}});
-{%- if kind|is_struct_kind %}
+{%- if kind|is_struct_kind or kind|is_union_kind %}
{{variable}} = {{kind|dart_type}}.decode(decoder{{level+1}});
{%- else %}{# kind|is_pointer_array_kind or is_map_kind #}
{%- if kind|is_nullable_kind %}
@@ -117,9 +120,12 @@ class {{struct|name}} extends bindings.Struct {
// Scan in reverse order to optimize for more recent versions.
for (int i = kVersions.length - 1; i >= 0; --i) {
if (mainDataHeader.version >= kVersions[i].version) {
- if (mainDataHeader.size != kVersions[i].size)
- throw new bindings.MojoCodecError(
- 'Header doesn\'t correspond to any known version.');
+ if (mainDataHeader.size == kVersions[i].size) {
+ // Found a match.
+ break;
+ }
+ throw new bindings.MojoCodecError(
+ 'Header size doesn\'t correspond to known version size.');
}
}
} else if (mainDataHeader.size < kVersions.last.size) {
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/encoding_macros.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/encoding_macros.tmpl
new file mode 100644
index 0000000..31e5c63
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/encoding_macros.tmpl
@@ -0,0 +1,192 @@
+{% macro encode(value, kind, level=0) %}
+{% if kind|is_nullable %}
+if {{value}} == nil {
+{% if kind|is_interface %}
+ encoder.WriteInvalidInterface()
+{% elif kind|is_handle %}
+ encoder.WriteInvalidHandle()
+{% elif kind|is_union %}
+ encoder.WriteNullUnion()
+{% else %}
+ encoder.WriteNullPointer()
+{% endif %}
+} else {
+ {{encodeNonNullable('(*'~value~')', kind, level)|tab_indent()}}
+}
+{% else -%}
+{{encodeNonNullable(value, kind, level)}}
+{%- endif %}
+{% endmacro %}
+
+
+
+{% macro encodeNonNullable(value, kind, level=0) %}
+{% if kind|is_pointer %}
+if err := encoder.WritePointer(); err != nil {
+ return err
+}
+{% endif %}
+{% if kind|is_struct or kind|is_union %}
+if err := {{value}}.Encode(encoder); err != nil {
+ return err
+}
+{% elif kind|is_array %}
+encoder.StartArray(uint32(len({{value}})), {{kind.kind|bit_size}})
+for _, elem{{level}} := range {{value}} {
+ {{encode('elem'~level, kind.kind, level+1)|tab_indent()}}
+}
+if err := encoder.Finish(); err != nil {
+ return err
+}
+{% elif kind|is_map %}
+encoder.StartMap()
+{
+ var keys{{level}} {{kind.key_kind|array|go_type}}
+ var values{{level}} {{kind.value_kind|array|go_type}}
+ for key{{level}}, value{{level}} := range {{value}} {
+ keys{{level}} = append(keys{{level}}, key{{level}})
+ values{{level}} = append(values{{level}}, value{{level}})
+ }
+ {{encode('keys'~level, kind.key_kind|array, level+1)|tab_indent()}}
+ {{encode('values'~level, kind.value_kind|array, level+1)|tab_indent()}}
+}
+if err := encoder.Finish(); err != nil {
+ return err
+}
+{% elif kind|is_enum %}
+if err := encoder.WriteInt32(int32({{value}})); err != nil {
+ return err
+}
+{% elif kind|is_interface %}
+if err := encoder.WriteInterface({{value}}.PassMessagePipe()); err != nil {
+ return err
+}
+{% elif kind|is_interface_request %}
+if err := encoder.WriteHandle({{value}}.PassMessagePipe()); err != nil {
+ return err
+}
+{% else %}
+if err := encoder.Write{{kind|encode_suffix}}({{value}}); err != nil {
+ return err
+}
+{% endif %}
+{% endmacro %}
+
+
+
+{% macro decode(value, kind, level=0) %}
+{% if kind|is_pointer %}
+pointer{{level}}, err := decoder.ReadPointer()
+if err != nil {
+ return err
+}
+if pointer{{level}} == 0 {
+{% if kind|is_nullable %}
+ {{value}} = nil
+} else {
+ {{value}} = new({{kind|go_type(False)}})
+ {{decodePointerValue('(*'~value~')', kind, level)|tab_indent()}}
+}
+{% else %}
+ return &bindings.ValidationError{bindings.UnexpectedNullPointer, "unexpected null pointer"}
+} else {
+ {{decodePointerValue(value, kind, level)|tab_indent()}}
+}
+{% endif %}
+{% elif kind|is_handle or kind|is_interface %}
+handle{{level}}, err := decoder.Read{{kind|decode_suffix}}()
+if err != nil {
+ return err
+}
+if handle{{level}}.IsValid() {
+{% if kind|is_interface or kind|is_interface_request %}
+ handleOwner := bindings.NewMessagePipeHandleOwner(handle{{level}})
+ {{value}} = {% if kind|is_nullable %}&{% endif %}{{kind|go_type(False)}}{handleOwner}
+{% else %}
+ {{value}} = {% if kind|is_nullable %}&{% endif %}handle{{level}}
+{% endif %}
+} else {
+{% if kind|is_nullable %}
+ {{value}} = nil
+{% else %}
+ return &bindings.ValidationError{bindings.UnexpectedInvalidHandle, "unexpected invalid handle"}
+{% endif %}
+}
+{% elif kind|is_enum %}
+value{{level}}, err := decoder.Read{{kind|decode_suffix}}()
+if err != nil {
+ return err
+}
+{{value}} = {% if kind|is_nullable %}&{% endif %}{{kind|go_type(False)}}(value{{level}})
+{% else %}
+value{{level}}, err := decoder.Read{{kind|decode_suffix}}()
+if err != nil {
+ return err
+}
+{{value}} = {% if kind|is_nullable %}&{% endif %}value{{level}}
+{% endif %}
+{% endmacro %}
+
+
+
+{% macro decodePointerValue(value, kind, level=0) %}
+{% if kind|is_struct %}
+if err := {{value}}.Decode(decoder); err != nil {
+ return err
+}
+{% elif kind|is_union %}
+// TODO(azani): Implement union decoding.
+{% elif kind|is_array %}
+len{{level}}, err := decoder.StartArray({{kind.kind|bit_size}})
+if err != nil {
+ return err
+}
+{% if kind.length %}
+if len{{level}} != {{kind.length}} {
+ return &bindings.ValidationError{bindings.UnexpectedArrayHeader,
+ fmt.Sprintf("invalid array length: expected %d, got %d", {{kind.length}}, len{{level}}),
+ }
+}
+{% else %}
+{{value}} = make({{kind|go_type(False)}}, len{{level}})
+{% endif %}
+for i{{level}} := uint32(0); i{{level}} < len{{level}}; i{{level}}++ {
+ {{decode(value~'[i'~level~']', kind.kind, level+1)|tab_indent()}}
+}
+if err := decoder.Finish(); err != nil {
+ return err
+}
+{% elif kind|is_map %}
+if err := decoder.StartMap(); err != nil {
+ return err
+}
+var keys{{level}} {{kind.key_kind|array|go_type}}
+{
+ {{decode('keys'~level, kind.key_kind|array, level+1)|tab_indent()}}
+}
+var values{{level}} {{kind.value_kind|array|go_type}}
+{
+ {{decode('values'~level, kind.value_kind|array, level+1)|tab_indent()}}
+}
+if len(keys{{level}}) != len(values{{level}}) {
+ return &bindings.ValidationError{bindings.DifferentSizedArraysInMap,
+ fmt.Sprintf("Number of keys %d is different from number of values %d", len(keys{{level}}), len(values{{level}})),
+ }
+}
+if err := decoder.Finish(); err != nil {
+ return err
+}
+len{{level}} := len(keys{{level}})
+map{{level}} := make({{kind|go_type(False)}})
+for i{{level}} := 0; i{{level}} < len{{level}}; i{{level}}++ {
+ map{{level}}[keys{{level}}[i{{level}}]] = values{{level}}[i{{level}}]
+}
+{{value}} = map{{level}}
+{% else %}
+value{{level}}, err := decoder.Read{{kind|decode_suffix}}()
+if err != nil {
+ return err
+}
+{{value}} = value{{level}}
+{% endif %}
+{% endmacro %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/source.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/source.tmpl
index 820f113..e864d67 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/source.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/source.tmpl
@@ -19,6 +19,7 @@ import (
{% import "enum.tmpl" as enum_macros %}
{% import "interface.tmpl" as interface_macros %}
{% import "struct.tmpl" as struct_macros %}
+{% import "union.tmpl" as union_macros %}
{#- Enum definitions #}
{% for enum in enums %}
@@ -34,3 +35,8 @@ import (
{% for struct in structs %}
{{struct_macros.define(struct)}}
{%- endfor %}
+
+{#- Union definitions #}
+{% for union in unions %}
+{{union_macros.define(union)}}
+{%- endfor %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/struct.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/struct.tmpl
index f523ba6..444ffdb 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/struct.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/struct.tmpl
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+{% import "encoding_macros.tmpl" as encoding_macros %}
+
{% macro define(struct, exported=True) %}
type {{struct|name(exported)}} struct {
{% for field in struct.fields %}
@@ -14,7 +16,7 @@ func (s *{{struct|name(exported)}}) Encode(encoder *bindings.Encoder) error {
encoder.StartStruct({{struct.versions[-1].num_bytes - HEADER_SIZE}}, {{struct.versions[-1].version}})
{% for byte in struct.bytes %}
{% for packed_field in byte.packed_fields %}
- {{encode('s.'~packed_field.field|name(exported), packed_field.field.kind)|tab_indent()}}
+ {{encoding_macros.encode('s.'~packed_field.field|name(exported), packed_field.field.kind)|tab_indent()}}
{% endfor %}
{% endfor %}
if err := encoder.Finish(); err != nil {
@@ -51,7 +53,7 @@ func (s *{{struct|name(exported)}}) Decode(decoder *bindings.Decoder) error {
{% for byte in struct.bytes %}
{% for packed_field in byte.packed_fields %}
if header.ElementsOrVersion >= {{packed_field.min_version}} {
- {{decode('s.'~packed_field.field|name(exported), packed_field.field.kind)|tab_indent(2)}}
+ {{encoding_macros.decode('s.'~packed_field.field|name(exported), packed_field.field.kind)|tab_indent(2)}}
}
{% endfor %}
{% endfor %}
@@ -62,194 +64,3 @@ func (s *{{struct|name(exported)}}) Decode(decoder *bindings.Decoder) error {
}
{% endmacro %}
-
-
-
-{% macro encode(value, kind, level=0) %}
-{% if kind|is_nullable %}
-if {{value}} == nil {
-{% if kind|is_interface %}
- encoder.WriteInvalidInterface()
-{% elif kind|is_handle %}
- encoder.WriteInvalidHandle()
-{% else %}
- encoder.WriteNullPointer()
-{% endif %}
-} else {
- {{encodeNonNullable('(*'~value~')', kind, level)|tab_indent()}}
-}
-{% else -%}
-{{encodeNonNullable(value, kind, level)}}
-{%- endif %}
-{% endmacro %}
-
-
-
-{% macro encodeNonNullable(value, kind, level=0) %}
-{% if kind|is_pointer %}
-if err := encoder.WritePointer(); err != nil {
- return err
-}
-{% endif %}
-{% if kind|is_struct %}
-if err := {{value}}.Encode(encoder); err != nil {
- return err
-}
-{% elif kind|is_array %}
-encoder.StartArray(uint32(len({{value}})), {{kind.kind|bit_size}})
-for _, elem{{level}} := range {{value}} {
- {{encode('elem'~level, kind.kind, level+1)|tab_indent()}}
-}
-if err := encoder.Finish(); err != nil {
- return err
-}
-{% elif kind|is_map %}
-encoder.StartMap()
-{
- var keys{{level}} {{kind.key_kind|array|go_type}}
- var values{{level}} {{kind.value_kind|array|go_type}}
- for key{{level}}, value{{level}} := range {{value}} {
- keys{{level}} = append(keys{{level}}, key{{level}})
- values{{level}} = append(values{{level}}, value{{level}})
- }
- {{encode('keys'~level, kind.key_kind|array, level+1)|tab_indent()}}
- {{encode('values'~level, kind.value_kind|array, level+1)|tab_indent()}}
-}
-if err := encoder.Finish(); err != nil {
- return err
-}
-{% elif kind|is_enum %}
-if err := encoder.WriteInt32(int32({{value}})); err != nil {
- return err
-}
-{% elif kind|is_interface %}
-if err := encoder.WriteInterface({{value}}.PassMessagePipe()); err != nil {
- return err
-}
-{% elif kind|is_interface_request %}
-if err := encoder.WriteHandle({{value}}.PassMessagePipe()); err != nil {
- return err
-}
-{% else %}
-if err := encoder.Write{{kind|encode_suffix}}({{value}}); err != nil {
- return err
-}
-{% endif %}
-{% endmacro %}
-
-
-
-{% macro decode(value, kind, level=0) %}
-{% if kind|is_pointer %}
-pointer{{level}}, err := decoder.ReadPointer()
-if err != nil {
- return err
-}
-if pointer{{level}} == 0 {
-{% if kind|is_nullable %}
- {{value}} = nil
-} else {
- {{value}} = new({{kind|go_type(False)}})
- {{decodePointerValue('(*'~value~')', kind, level)|tab_indent()}}
-}
-{% else %}
- return &bindings.ValidationError{bindings.UnexpectedNullPointer, "unexpected null pointer"}
-} else {
- {{decodePointerValue(value, kind, level)|tab_indent()}}
-}
-{% endif %}
-{% elif kind|is_handle or kind|is_interface %}
-handle{{level}}, err := decoder.Read{{kind|decode_suffix}}()
-if err != nil {
- return err
-}
-if handle{{level}}.IsValid() {
-{% if kind|is_interface or kind|is_interface_request %}
- handleOwner := bindings.NewMessagePipeHandleOwner(handle{{level}})
- {{value}} = {% if kind|is_nullable %}&{% endif %}{{kind|go_type(False)}}{handleOwner}
-{% else %}
- {{value}} = {% if kind|is_nullable %}&{% endif %}handle{{level}}
-{% endif %}
-} else {
-{% if kind|is_nullable %}
- {{value}} = nil
-{% else %}
- return &bindings.ValidationError{bindings.UnexpectedInvalidHandle, "unexpected invalid handle"}
-{% endif %}
-}
-{% elif kind|is_enum %}
-value{{level}}, err := decoder.Read{{kind|decode_suffix}}()
-if err != nil {
- return err
-}
-{{value}} = {% if kind|is_nullable %}&{% endif %}{{kind|go_type(False)}}(value{{level}})
-{% else %}
-value{{level}}, err := decoder.Read{{kind|decode_suffix}}()
-if err != nil {
- return err
-}
-{{value}} = {% if kind|is_nullable %}&{% endif %}value{{level}}
-{% endif %}
-{% endmacro %}
-
-
-
-{% macro decodePointerValue(value, kind, level=0) %}
-{% if kind|is_struct %}
-if err := {{value}}.Decode(decoder); err != nil {
- return err
-}
-{% elif kind|is_array %}
-len{{level}}, err := decoder.StartArray({{kind.kind|bit_size}})
-if err != nil {
- return err
-}
-{% if kind.length %}
-if len{{level}} != {{kind.length}} {
- return &bindings.ValidationError{bindings.UnexpectedArrayHeader,
- fmt.Sprintf("invalid array length: expected %d, got %d", {{kind.length}}, len{{level}}),
- }
-}
-{% else %}
-{{value}} = make({{kind|go_type(False)}}, len{{level}})
-{% endif %}
-for i{{level}} := uint32(0); i{{level}} < len{{level}}; i{{level}}++ {
- {{decode(value~'[i'~level~']', kind.kind, level+1)|tab_indent()}}
-}
-if err := decoder.Finish(); err != nil {
- return err
-}
-{% elif kind|is_map %}
-if err := decoder.StartMap(); err != nil {
- return err
-}
-var keys{{level}} {{kind.key_kind|array|go_type}}
-{
- {{decode('keys'~level, kind.key_kind|array, level+1)|tab_indent()}}
-}
-var values{{level}} {{kind.value_kind|array|go_type}}
-{
- {{decode('values'~level, kind.value_kind|array, level+1)|tab_indent()}}
-}
-if len(keys{{level}}) != len(values{{level}}) {
- return &bindings.ValidationError{bindings.DifferentSizedArraysInMap,
- fmt.Sprintf("Number of keys %d is different from number of values %d", len(keys{{level}}), len(values{{level}})),
- }
-}
-if err := decoder.Finish(); err != nil {
- return err
-}
-len{{level}} := len(keys{{level}})
-map{{level}} := make({{kind|go_type(False)}})
-for i{{level}} := 0; i{{level}} < len{{level}}; i{{level}}++ {
- map{{level}}[keys{{level}}[i{{level}}]] = values{{level}}[i{{level}}]
-}
-{{value}} = map{{level}}
-{% else %}
-value{{level}}, err := decoder.Read{{kind|decode_suffix}}()
-if err != nil {
- return err
-}
-{{value}} = value{{level}}
-{% endif %}
-{% endmacro %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/union.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/union.tmpl
new file mode 100644
index 0000000..ccb8d5d
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/go_templates/union.tmpl
@@ -0,0 +1,66 @@
+// 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.
+
+{% import "encoding_macros.tmpl" as encoding_macros %}
+
+
+{% macro define(union, exported=True) %}
+type {{union|name(exported)}} interface {
+ Tag() uint32
+ Interface() interface{}
+ __Reflect(__{{union|name(exported)}}Reflect)
+ Encode(encoder *bindings.Encoder) error
+}
+
+type __{{union|name(exported)}}Reflect struct {
+{% for field in union.fields %}
+ {{field|name(exported)}} {{field.kind|go_type}}
+{% endfor %}
+}
+
+func Decode{{union|name(exported)}}(decoder *bindings.Decoder) ({{union|name(exported)}}, error) {
+ header, err := decoder.StartUnion()
+ if err != nil {
+ return nil, err
+ }
+
+ if header.Size == 0 {
+ return nil, nil
+ }
+
+ switch header.ElementsOrVersion {
+{% for field in union.fields %}
+ case {{field.ordinal}}:
+ var value {{union|name(exported)}}{{field|name(exported)}}
+ value.decodeInternal(decoder)
+ decoder.Finish()
+ return &value, nil
+{% endfor %}
+ }
+
+ return nil, fmt.Errorf("Unknown tag %d in {{union|name(exported)}}", header.ElementsOrVersion);
+}
+
+{% for field in union.fields %}
+{%- set struct_name = union|name(exported) + field|name(exported) %}
+type {{struct_name}} struct { Value {{field.kind|go_type}} }
+func (u *{{struct_name}}) Tag() uint32 { return {{field.ordinal}} }
+func (u *{{struct_name}}) Interface() interface{} { return u.Value }
+func (u *{{struct_name}}) __Reflect(__{{union|name(exported)}}Reflect) {}
+
+func (u *{{struct_name}}) Encode(encoder *bindings.Encoder) error {
+ encoder.StartUnion(u.Tag())
+ {{encoding_macros.encode('u.Value', field.kind)|tab_indent()}}
+ encoder.Finish()
+ return nil
+}
+
+func (u *{{struct_name}}) decodeInternal(decoder *bindings.Decoder) error {
+ {{encoding_macros.decode('u.Value', field.kind)|tab_indent()}}
+ return nil
+}
+
+{% endfor %}
+
+{% endmacro %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/data_types_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/data_types_definition.tmpl
new file mode 100644
index 0000000..5c686f3
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/data_types_definition.tmpl
@@ -0,0 +1,367 @@
+{% from "constant_definition.tmpl" import constant_def %}
+{% from "enum_definition.tmpl" import enum_def %}
+
+{%- macro equality(kind, v1, v2, ne=False) -%}
+{%- if kind|is_reference_kind -%}
+{%- if kind|is_array_kind -%}
+{%- if kind.kind|is_reference_kind -%}
+{% if ne %}!{% endif %}java.util.Arrays.deepEquals({{v1}}, {{v2}})
+{%- else -%}
+{% if ne %}!{% endif %}java.util.Arrays.equals({{v1}}, {{v2}})
+{%- endif -%}
+{%- else -%}
+{% if ne %}!{% endif %}org.chromium.mojo.bindings.BindingsHelper.equals({{v1}}, {{v2}})
+{%- endif -%}
+{%- else -%}
+{{v1}} {% if ne %}!={% else %}=={% endif %} {{v2}}
+{%- endif -%}
+{%- endmacro -%}
+
+{%- macro hash(kind, v) -%}
+{%- if kind|is_array_kind -%}
+{%- if kind.kind|is_reference_kind -%}
+java.util.Arrays.deepHashCode({{v}})
+{%- else -%}
+java.util.Arrays.hashCode({{v}})
+{%- endif -%}
+{%- else -%}
+org.chromium.mojo.bindings.BindingsHelper.hashCode({{v}})
+{%- endif -%}
+{%- endmacro -%}
+
+{%- macro array_element_size(kind) -%}
+{%- if kind|is_union_kind %}
+org.chromium.mojo.bindings.BindingsHelper.UNION_SIZE
+{%- else -%}
+org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE
+{%- endif -%}
+{%- endmacro -%}
+
+{% macro encode(variable, kind, offset, bit, level=0, check_for_null=True) %}
+{% if kind|is_pointer_array_kind or kind|is_union_array_kind %}
+{% set sub_kind = kind.kind %}
+{% if check_for_null %}
+if ({{variable}} == null) {
+ encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
+} else {
+{% else %}
+{
+{% endif %}
+{% if kind|is_pointer_array_kind %}
+{% set encodePointer = 'encodePointerArray' %}
+{% else %}
+{% set encodePointer = 'encodeUnionArray' %}
+{% endif %}
+ org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.{{encodePointer}}({{variable}}.length, {{offset}}, {{kind|array_expected_length}});
+ for (int i{{level}} = 0; i{{level}} < {{variable}}.length; ++i{{level}}) {
+ {{encode(variable~'[i'~level~']', sub_kind, 'org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + ' ~ array_element_size(sub_kind) ~ ' * i'~level, 0, level+1)|indent(8)}}
+ }
+}
+{% elif kind|is_map_kind %}
+if ({{variable}} == null) {
+ encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
+} else {
+ org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.encoderForMap({{offset}});
+ int size{{level}} = {{variable}}.size();
+ {{kind.key_kind|java_type}}[] keys{{level}} = {{kind.key_kind|array|new_array('size'~level)}};
+ {{kind.value_kind|java_type}}[] values{{level}} = {{kind.value_kind|array|new_array('size'~level)}};
+ int index{{level}} = 0;
+ for (java.util.Map.Entry<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}> entry{{level}} : {{variable}}.entrySet()) {
+ keys{{level}}[index{{level}}] = entry{{level}}.getKey();
+ values{{level}}[index{{level}}] = entry{{level}}.getValue();
+ ++index{{level}};
+ }
+ {{encode('keys'~level, kind.key_kind|array, 'org.chromium.mojo.bindings.DataHeader.HEADER_SIZE', 0, level+1, False)|indent(4)}}
+ {{encode('values'~level, kind.value_kind|array, 'org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1, False)|indent(4)}}
+}
+{% else %}
+encoder{{level}}.{{kind|encode_method(variable, offset, bit)}};
+{% endif %}
+{% endmacro %}
+
+{% macro decode(variable, kind, offset, bit, level=0) %}
+{% if kind|is_struct_kind or
+ kind|is_pointer_array_kind or
+ kind|is_union_array_kind or
+ kind|is_map_kind %}
+org.chromium.mojo.bindings.Decoder decoder{{level+1}} = decoder{{level}}.readPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
+{% if kind|is_struct_kind %}
+{{variable}} = {{kind|java_type}}.decode(decoder{{level+1}});
+{% else %}{# kind|is_pointer_array_kind or is_map_kind #}
+{% if kind|is_nullable_kind %}
+if (decoder{{level+1}} == null) {
+ {{variable}} = null;
+} else {
+{% else %}
+{
+{% endif %}
+{% if kind|is_map_kind %}
+ decoder{{level+1}}.readDataHeaderForMap();
+ {{kind.key_kind|java_type}}[] keys{{level}};
+ {{kind.value_kind|java_type}}[] values{{level}};
+ {
+ {{decode('keys'~level, kind.key_kind|array, 'org.chromium.mojo.bindings.DataHeader.HEADER_SIZE', 0, level+1)|indent(8)}}
+ }
+ {
+ {{decode('values'~level, kind.value_kind|array('keys'~level~'.length'), 'org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1)|indent(8)}}
+ }
+ {{variable}} = new java.util.HashMap<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}>();
+ for (int index{{level}} = 0; index{{level}} < keys{{level}}.length; ++index{{level}}) {
+ {{variable}}.put(keys{{level}}[index{{level}}], values{{level}}[index{{level}}]);
+ }
+{% else %}
+ org.chromium.mojo.bindings.DataHeader si{{level+1}} = decoder{{level+1}}.readDataHeaderForPointerArray({{kind|array_expected_length}});
+ {{variable}} = {{kind|new_array('si'~(level+1)~'.elementsOrVersion')}};
+ for (int i{{level+1}} = 0; i{{level+1}} < si{{level+1}}.elementsOrVersion; ++i{{level+1}}) {
+ {{decode(variable~'[i'~(level+1)~']', kind.kind, 'org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + ' ~ array_element_size(kind.kind) ~' * i'~(level+1), 0, level+1)|indent(8)}}
+ }
+{% endif %}
+}
+{% endif %}
+{% elif kind|is_union_kind %}
+{{variable}} = {{kind|java_type}}.decode(decoder{{level}}, {{offset}});
+{% else %}
+{{variable}} = decoder{{level}}.{{kind|decode_method(offset, bit)}};
+{% endif %}
+{% endmacro %}
+
+{% macro struct_def(struct, inner_class=False) %}
+{{'static' if inner_class else 'public'}} final class {{struct|name}} extends org.chromium.mojo.bindings.Struct {
+
+ private static final int STRUCT_SIZE = {{struct.versions[-1].num_bytes}};
+ private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {
+{%- for version in struct.versions -%}
+ new org.chromium.mojo.bindings.DataHeader({{version.num_bytes}}, {{version.version}}){% if not loop.last %}, {% endif -%}
+{%- endfor -%}
+ };
+ private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[{{struct.versions|length - 1}}];
+{% for constant in struct.constants %}
+
+ {{constant_def(constant)|indent(4)}}
+{% endfor %}
+{% for enum in struct.enums %}
+
+ {{enum_def(enum, false)|indent(4)}}
+{% endfor %}
+{% if struct.fields %}
+
+{% for field in struct.fields %}
+ public {{field.kind|java_type}} {{field|name}};
+{% endfor %}
+{% endif %}
+
+ private {{struct|name}}(int version) {
+ super(STRUCT_SIZE, version);
+{% for field in struct.fields %}
+{% if field.default %}
+ {{field|name}} = {{field|default_value}};
+{% elif field.kind|is_any_handle_kind and not field.kind|is_interface_request_kind %}
+ {{field|name}} = org.chromium.mojo.system.InvalidHandle.INSTANCE;
+{% endif %}
+{% endfor %}
+ }
+
+ public {{struct|name}}() {
+ this({{struct.versions[-1].version}});
+ }
+
+ public static {{struct|name}} deserialize(org.chromium.mojo.bindings.Message message) {
+ return decode(new org.chromium.mojo.bindings.Decoder(message));
+ }
+
+ @SuppressWarnings("unchecked")
+ public static {{struct|name}} decode(org.chromium.mojo.bindings.Decoder decoder0) {
+ if (decoder0 == null) {
+ return null;
+ }
+ org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
+ {{struct|name}} result = new {{struct|name}}(mainDataHeader.elementsOrVersion);
+{% for byte in struct.bytes %}
+{% for packed_field in byte.packed_fields %}
+ if (mainDataHeader.elementsOrVersion >= {{packed_field.min_version}}) {
+ {{decode('result.' ~ packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(12)}}
+ }
+{% endfor %}
+{% endfor %}
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
+{% if not struct.bytes %}
+ encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
+{% else %}
+ org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
+{% endif %}
+{% for byte in struct.bytes %}
+{% for packed_field in byte.packed_fields %}
+ {{encode(packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(8)}}
+{% endfor %}
+{% endfor %}
+ }
+
+ /**
+ * @see Object#equals(Object)
+ */
+ @Override
+ public boolean equals(Object object) {
+ if (object == this)
+ return true;
+ if (object == null)
+ return false;
+ if (getClass() != object.getClass())
+ return false;
+{% if struct.fields|length %}
+ {{struct|name}} other = ({{struct|name}}) object;
+{% for field in struct.fields %}
+ if ({{equality(field.kind, field|name, 'other.'~field|name, True)}})
+ return false;
+{% endfor %}
+{% endif %}
+ return true;
+ }
+
+ /**
+ * @see Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = prime + getClass().hashCode();
+{% for field in struct.fields %}
+ result = prime * result + {{hash(field.kind, field|name)}};
+{% endfor %}
+ return result;
+ }
+}
+{% endmacro %}
+
+
+{% macro union_def(union) %}
+public final class {{union|name}} extends org.chromium.mojo.bindings.Union {
+
+ public static final class Tag {
+{% for field in union.fields %}
+ public static final int {{field|ucc}} = {{field.ordinal}};
+{% endfor %}
+ };
+
+ private int mTag_ = -1;
+{% for field in union.fields %}
+ private {{field.kind|java_type}} m{{field|ucc}};
+{% endfor %}
+
+ public int which() {
+ return mTag_;
+ }
+
+ public boolean isUnknown() {
+ return mTag_ == -1;
+ }
+{% for field in union.fields %}
+
+ public void set{{field|ucc}}({{field.kind|java_type}} {{field|name}}) {
+ mTag_ = {{field.ordinal}};
+ m{{field|ucc}} = {{field|name}};
+ }
+
+ public {{field.kind|java_type}} get{{field|ucc}}() {
+ assert mTag_ == {{field.ordinal}};
+ return m{{field|ucc}};
+ }
+{% endfor %}
+
+
+ @Override
+ protected final void encode(org.chromium.mojo.bindings.Encoder encoder0, int offset) {
+ encoder0.encode(org.chromium.mojo.bindings.BindingsHelper.UNION_SIZE, offset);
+ encoder0.encode(mTag_, offset + 4);
+ switch (mTag_) {
+{% for field in union.fields %}
+ case {{field.ordinal}}: {
+{% if field.kind|is_union_kind %}
+ if (m{{field|ucc}} == null) {
+ encoder0.encodeNullPointer(offset + 8, {{field.kind|is_nullable_kind|java_true_false}});
+ } else {
+ m{{field|ucc}}.encode(encoder0.encoderForUnionPointer(offset + 8), 0);
+ }
+{% else %}
+ {{encode('m' ~ field|ucc, field.kind, 'offset + 8', 0)|indent(16)}}
+{% endif %}
+ break;
+ }
+{% endfor %}
+ }
+ }
+
+ public static {{union|name}} deserialize(org.chromium.mojo.bindings.Message message) {
+ return decode(new org.chromium.mojo.bindings.Decoder(message).decoderForSerializedUnion(), 0);
+ }
+
+ public static final {{union|name}} decode(org.chromium.mojo.bindings.Decoder decoder0, int offset) {
+ org.chromium.mojo.bindings.DataHeader dataHeader = decoder0.readDataHeaderForUnion(offset);
+ if (dataHeader.size == 0) {
+ return null;
+ }
+ {{union|name}} result = new {{union|name}}();
+ switch (dataHeader.elementsOrVersion) {
+{% for field in union.fields %}
+ case {{field.ordinal}}: {
+{% if field.kind|is_union_kind %}
+ org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(offset + org.chromium.mojo.bindings.DataHeader.HEADER_SIZE, {{field.kind|is_nullable_kind|java_true_false}});
+ if (decoder1 != null) {
+ result.m{{field|ucc}} = {{field.kind|name}}.decode(decoder1, 0);
+ }
+{% else %}
+ {{decode('result.m'~field|ucc, field.kind, 'offset + org.chromium.mojo.bindings.DataHeader.HEADER_SIZE', 0)|indent(16)}}
+{% endif %}
+ result.mTag_ = {{field.ordinal}};
+ break;
+ }
+{% endfor %}
+ }
+ return result;
+ }
+
+ /**
+ * @see Object#equals(Object)
+ */
+ @Override
+ public boolean equals(Object object) {
+ if (object == this)
+ return true;
+ if (object == null)
+ return false;
+ if (getClass() != object.getClass())
+ return false;
+ {{union|name}} other = ({{union|name}}) object;
+ if (mTag_ != other.mTag_)
+ return false;
+ switch (mTag_) {
+{% for field in union.fields %}
+ case {{field.ordinal}}:
+ return {{equality(field.kind, 'm'~field|ucc, 'other.m'~field|ucc)}};
+{% endfor %}
+ }
+ return false;
+ }
+
+ /**
+ * @see Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = prime + getClass().hashCode();
+ result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(mTag_);
+ switch (mTag_) {
+{% for field in union.fields %}
+ case {{field.ordinal}}:
+ result = prime * result + {{hash(field.kind, 'm'~field|ucc)}};
+{% endfor %}
+ }
+ return result;
+ }
+}
+{% endmacro %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl
index be9b7d3..39c17cc 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/interface_definition.tmpl
@@ -1,6 +1,6 @@
{% from "constant_definition.tmpl" import constant_def %}
{% from "enum_definition.tmpl" import enum_def %}
-{% from "struct_definition.tmpl" import struct_def %}
+{% from "data_types_definition.tmpl" import struct_def %}
{%- macro declare_params(parameters, boxed=false) %}
{%- for param in parameters -%}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl
index 232ec26..e28ba19 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct.java.tmpl
@@ -1,4 +1,4 @@
-{% from "struct_definition.tmpl" import struct_def %}
+{% from "data_types_definition.tmpl" import struct_def %}
{% include "header.java.tmpl" %}
{{ struct_def(struct) }}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl
deleted file mode 100644
index 76c07fd..0000000
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl
+++ /dev/null
@@ -1,220 +0,0 @@
-{% from "constant_definition.tmpl" import constant_def %}
-{% from "enum_definition.tmpl" import enum_def %}
-
-{%- macro inequality(kind, v1, v2) -%}
-{%- if kind|is_reference_kind -%}
-{%- if kind|is_array_kind -%}
-{%- if kind.kind|is_reference_kind -%}
-!java.util.Arrays.deepEquals({{v1}}, {{v2}})
-{%- else -%}
-!java.util.Arrays.equals({{v1}}, {{v2}})
-{%- endif -%}
-{%- else -%}
-!org.chromium.mojo.bindings.BindingsHelper.equals({{v1}}, {{v2}})
-{%- endif -%}
-{%- else -%}
-{{v1}} != {{v2}}
-{%- endif -%}
-{%- endmacro -%}
-
-{%- macro hash(kind, v) -%}
-{%- if kind|is_array_kind -%}
-{%- if kind.kind|is_reference_kind -%}
-java.util.Arrays.deepHashCode({{v}})
-{%- else -%}
-java.util.Arrays.hashCode({{v}})
-{%- endif -%}
-{%- else -%}
-org.chromium.mojo.bindings.BindingsHelper.hashCode({{v}})
-{%- endif -%}
-{%- endmacro -%}
-
-{% macro encode(variable, kind, offset, bit, level=0, check_for_null=True) %}
-{% if kind|is_pointer_array_kind %}
-{% set sub_kind = kind.kind %}
-{% if check_for_null %}
-if ({{variable}} == null) {
- encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
-} else {
-{% else %}
-{
-{% endif %}
- org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.encodePointerArray({{variable}}.length, {{offset}}, {{kind|array_expected_length}});
- for (int i{{level}} = 0; i{{level}} < {{variable}}.length; ++i{{level}}) {
- {{encode(variable~'[i'~level~']', sub_kind, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i'~level, 0, level+1)|indent(8)}}
- }
-}
-{% elif kind|is_map_kind %}
-if ({{variable}} == null) {
- encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
-} else {
- org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.encoderForMap({{offset}});
- int size{{level}} = {{variable}}.size();
- {{kind.key_kind|java_type}}[] keys{{level}} = {{kind.key_kind|array|new_array('size'~level)}};
- {{kind.value_kind|java_type}}[] values{{level}} = {{kind.value_kind|array|new_array('size'~level)}};
- int index{{level}} = 0;
- for (java.util.Map.Entry<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}> entry{{level}} : {{variable}}.entrySet()) {
- keys{{level}}[index{{level}}] = entry{{level}}.getKey();
- values{{level}}[index{{level}}] = entry{{level}}.getValue();
- ++index{{level}};
- }
- {{encode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1, False)|indent(4)}}
- {{encode('values'~level, kind.value_kind|array, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1, False)|indent(4)}}
-}
-{% else %}
-encoder{{level}}.{{kind|encode_method(variable, offset, bit)}};
-{% endif %}
-{% endmacro %}
-
-{% macro decode(variable, kind, offset, bit, level=0) %}
-{% if kind|is_struct_kind or kind|is_pointer_array_kind or kind|is_map_kind %}
-org.chromium.mojo.bindings.Decoder decoder{{level+1}} = decoder{{level}}.readPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
-{% if kind|is_struct_kind %}
-{{variable}} = {{kind|java_type}}.decode(decoder{{level+1}});
-{% else %}{# kind|is_pointer_array_kind or is_map_kind #}
-{% if kind|is_nullable_kind %}
-if (decoder{{level+1}} == null) {
- {{variable}} = null;
-} else {
-{% else %}
-{
-{% endif %}
-{% if kind|is_map_kind %}
- decoder{{level+1}}.readDataHeaderForMap();
- {{kind.key_kind|java_type}}[] keys{{level}};
- {{kind.value_kind|java_type}}[] values{{level}};
- {
- {{decode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1)|indent(8)}}
- }
- {
- {{decode('values'~level, kind.value_kind|array('keys'~level~'.length'), 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1)|indent(8)}}
- }
- {{variable}} = new java.util.HashMap<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}>();
- for (int index{{level}} = 0; index{{level}} < keys{{level}}.length; ++index{{level}}) {
- {{variable}}.put(keys{{level}}[index{{level}}], values{{level}}[index{{level}}]);
- }
-{% else %}
- DataHeader si{{level+1}} = decoder{{level+1}}.readDataHeaderForPointerArray({{kind|array_expected_length}});
- {{variable}} = {{kind|new_array('si'~(level+1)~'.elementsOrVersion')}};
- for (int i{{level+1}} = 0; i{{level+1}} < si{{level+1}}.elementsOrVersion; ++i{{level+1}}) {
- {{decode(variable~'[i'~(level+1)~']', kind.kind, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i'~(level+1), 0, level+1)|indent(8)}}
- }
-{% endif %}
-}
-{% endif %}
-{% else %}
-{{variable}} = decoder{{level}}.{{kind|decode_method(offset, bit)}};
-{% endif %}
-{% endmacro %}
-
-{% macro struct_def(struct, inner_class=False) %}
-{{'static' if inner_class else 'public'}} final class {{struct|name}} extends org.chromium.mojo.bindings.Struct {
-
- private static final int STRUCT_SIZE = {{struct.versions[-1].num_bytes}};
- private static final DataHeader[] VERSION_ARRAY = new DataHeader[] {
-{%- for version in struct.versions -%}
- new DataHeader({{version.num_bytes}}, {{version.version}}){% if not loop.last %}, {% endif -%}
-{%- endfor -%}
- };
- private static final DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[{{struct.versions|length - 1}}];
-{% for constant in struct.constants %}
-
- {{constant_def(constant)|indent(4)}}
-{% endfor %}
-{% for enum in struct.enums %}
-
- {{enum_def(enum, false)|indent(4)}}
-{% endfor %}
-{% if struct.fields %}
-
-{% for field in struct.fields %}
- public {{field.kind|java_type}} {{field|name}};
-{% endfor %}
-{% endif %}
-
- private {{struct|name}}(int version) {
- super(STRUCT_SIZE, version);
-{% for field in struct.fields %}
-{% if field.default %}
- {{field|name}} = {{field|default_value}};
-{% elif field.kind|is_any_handle_kind and not field.kind|is_interface_request_kind %}
- {{field|name}} = org.chromium.mojo.system.InvalidHandle.INSTANCE;
-{% endif %}
-{% endfor %}
- }
-
- public {{struct|name}}() {
- this({{struct.versions[-1].version}});
- }
-
- public static {{struct|name}} deserialize(org.chromium.mojo.bindings.Message message) {
- return decode(new org.chromium.mojo.bindings.Decoder(message));
- }
-
- @SuppressWarnings("unchecked")
- public static {{struct|name}} decode(org.chromium.mojo.bindings.Decoder decoder0) {
- if (decoder0 == null) {
- return null;
- }
- DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
- {{struct|name}} result = new {{struct|name}}(mainDataHeader.elementsOrVersion);
-{% for byte in struct.bytes %}
-{% for packed_field in byte.packed_fields %}
- if (mainDataHeader.elementsOrVersion >= {{packed_field.min_version}}) {
- {{decode('result.' ~ packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(12)}}
- }
-{% endfor %}
-{% endfor %}
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
-{% if not struct.bytes %}
- encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
-{% else %}
- org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
-{% endif %}
-{% for byte in struct.bytes %}
-{% for packed_field in byte.packed_fields %}
- {{encode(packed_field.field|name, packed_field.field.kind, 8+packed_field.offset, packed_field.bit)|indent(8)}}
-{% endfor %}
-{% endfor %}
- }
-
- /**
- * @see Object#equals(Object)
- */
- @Override
- public boolean equals(Object object) {
- if (object == this)
- return true;
- if (object == null)
- return false;
- if (getClass() != object.getClass())
- return false;
-{% if struct.fields|length %}
- {{struct|name}} other = ({{struct|name}}) object;
-{% for field in struct.fields %}
- if ({{inequality(field.kind, field|name, 'other.'~field|name)}})
- return false;
-{% endfor %}
-{% endif %}
- return true;
- }
-
- /**
- * @see Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = prime + getClass().hashCode();
-{% for field in struct.fields %}
- result = prime * result + {{hash(field.kind, field|name)}};
-{% endfor %}
- return result;
- }
-}
-{% endmacro %}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/union.java.tmpl b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/union.java.tmpl
new file mode 100644
index 0000000..b8cd4aa
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/java_templates/union.java.tmpl
@@ -0,0 +1,4 @@
+{% from "data_types_definition.tmpl" import union_def %}
+{% include "header.java.tmpl" %}
+
+{{ union_def(union) }}
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_cpp_generator.py b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_cpp_generator.py
index 70dc94b..f321c44 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_cpp_generator.py
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_cpp_generator.py
@@ -230,6 +230,8 @@ def GetCppFieldType(kind):
def GetCppUnionFieldType(kind):
if mojom.IsAnyHandleKind(kind):
return "MojoHandle"
+ if mojom.IsInterfaceKind(kind):
+ return "uint64_t"
if mojom.IsEnumKind(kind):
return "int32_t"
if mojom.IsUnionKind(kind):
@@ -240,7 +242,7 @@ def GetCppUnionFieldType(kind):
def GetUnionGetterReturnType(kind):
if (mojom.IsStructKind(kind) or mojom.IsUnionKind(kind) or
mojom.IsArrayKind(kind) or mojom.IsMapKind(kind) or
- mojom.IsAnyHandleKind(kind)):
+ mojom.IsAnyHandleKind(kind) or mojom.IsInterfaceKind(kind)):
return "%s&" % GetCppWrapperType(kind)
return GetCppResultWrapperType(kind)
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_dart_generator.py b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_dart_generator.py
index 2004010..11e300c 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_dart_generator.py
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_dart_generator.py
@@ -149,7 +149,7 @@ def DartDefaultValue(field):
def DartDeclType(kind):
if kind in mojom.PRIMITIVES:
return _kind_to_dart_decl_type[kind]
- if mojom.IsStructKind(kind):
+ if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind):
return GetDartType(kind)
if mojom.IsArrayKind(kind):
array_type = DartDeclType(kind.kind)
@@ -191,7 +191,7 @@ def ConstantStyle(name):
def GetNameForElement(element):
if (mojom.IsEnumKind(element) or mojom.IsInterfaceKind(element) or
- mojom.IsStructKind(element)):
+ mojom.IsStructKind(element) or mojom.IsUnionKind(element)):
return UpperCamelCase(element.name)
if mojom.IsInterfaceRequestKind(element):
return GetNameForElement(element.kind)
@@ -291,6 +291,8 @@ def EncodeMethod(kind, variable, offset, bit):
def _EncodeMethodName(kind):
if mojom.IsStructKind(kind):
return 'encodeStruct'
+ if mojom.IsUnionKind(kind):
+ return 'encodeUnion'
if mojom.IsArrayKind(kind):
return _EncodeMethodName(kind.kind) + 'Array'
if mojom.IsEnumKind(kind):
@@ -375,6 +377,7 @@ class Generator(generator.Generator):
'is_nullable_kind': mojom.IsNullableKind,
'is_pointer_array_kind': IsPointerArrayKind,
'is_struct_kind': mojom.IsStructKind,
+ 'is_union_kind': mojom.IsUnionKind,
'dart_true_false': GetDartTrueFalse,
'dart_type': DartDeclType,
'name': GetNameForElement,
@@ -398,10 +401,13 @@ class Generator(generator.Generator):
def GenerateLibModule(self, args):
return self.GetParameters(args)
+
def GenerateFiles(self, args):
elements = self.module.namespace.split('.')
elements.append("%s.dart" % self.module.name)
- path = os.path.join("dart-gen", "mojom", *elements)
+ path = os.path.join("dart-pkg", "mojom/lib", *elements)
+ self.Write(self.GenerateLibModule(args), path)
+ path = os.path.join("dart-gen", "mojom/lib", *elements)
self.Write(self.GenerateLibModule(args), path)
link = self.MatchMojomFilePath("%s.dart" % self.module.name)
if os.path.exists(os.path.join(self.output_dir, link)):
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_go_generator.py b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_go_generator.py
index 1df4eb5..e20e9e4 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_go_generator.py
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_go_generator.py
@@ -60,8 +60,12 @@ _kind_infos = {
_imports = {}
def GetBitSize(kind):
+ if isinstance(kind, (mojom.Union)):
+ return 128
if isinstance(kind, (mojom.Array, mojom.Map, mojom.Struct, mojom.Interface)):
return 64
+ if mojom.IsUnionKind(kind):
+ return 2*64
if isinstance(kind, (mojom.InterfaceRequest)):
kind = mojom.MSGPIPE
if isinstance(kind, mojom.Enum):
@@ -78,7 +82,7 @@ def GetGoType(kind, nullable = True):
# Returns go type corresponding to provided kind. Ignores nullability of
# top-level kind.
def GetNonNullableGoType(kind):
- if mojom.IsStructKind(kind):
+ if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind):
return '%s' % GetFullName(kind)
if mojom.IsArrayKind(kind):
if kind.length:
@@ -140,7 +144,8 @@ def GetNameForNestedElement(element):
return GetFullName(element)
def GetNameForElement(element, exported=True):
- if (mojom.IsInterfaceKind(element) or mojom.IsStructKind(element)):
+ if (mojom.IsInterfaceKind(element) or mojom.IsStructKind(element)
+ or mojom.IsUnionKind(element)):
return GetFullName(element, exported)
if isinstance(element, (mojom.EnumField,
mojom.Field,
@@ -228,6 +233,7 @@ def AddImport(module, element):
name += '_'
_imports[path] = name
+
class Generator(generator.Generator):
go_filters = {
'array': lambda kind: mojom.Array(kind),
@@ -246,6 +252,7 @@ class Generator(generator.Generator):
'is_nullable': mojom.IsNullableKind,
'is_pointer': mojom.IsObjectKind,
'is_struct': mojom.IsStructKind,
+ 'is_union': mojom.IsUnionKind,
'name': GetNameForElement,
'tab_indent': lambda s, size = 1: ('\n' + '\t' * size).join(s.splitlines())
}
@@ -257,6 +264,7 @@ class Generator(generator.Generator):
'interfaces': self.GetInterfaces(),
'package': GetPackageName(self.module),
'structs': self.GetStructs(),
+ 'unions': self.GetUnions(),
}
@UseJinja('go_templates/source.tmpl', filters=go_filters)
@@ -299,6 +307,10 @@ class Generator(generator.Generator):
if len(all_structs) > 0:
_imports['sort'] = 'sort'
+ for union in self.module.unions:
+ for field in union.fields:
+ AddImport(self.module, field.kind)
+
for struct in all_structs:
for field in struct.fields:
AddImport(self.module, field.kind)
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_java_generator.py b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_java_generator.py
index 78079f3..554db74 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_java_generator.py
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_java_generator.py
@@ -116,7 +116,7 @@ def ConstantStyle(name):
def GetNameForElement(element):
if (mojom.IsEnumKind(element) or mojom.IsInterfaceKind(element) or
- mojom.IsStructKind(element)):
+ mojom.IsStructKind(element) or mojom.IsUnionKind(element)):
return UpperCamelCase(element.name)
if mojom.IsInterfaceRequestKind(element):
return GetNameForElement(element.kind)
@@ -243,7 +243,9 @@ def GetBoxedJavaType(context, kind, with_generics=True):
def GetJavaType(context, kind, boxed=False, with_generics=True):
if boxed:
return GetBoxedJavaType(context, kind)
- if mojom.IsStructKind(kind) or mojom.IsInterfaceKind(kind):
+ if (mojom.IsStructKind(kind) or
+ mojom.IsInterfaceKind(kind) or
+ mojom.IsUnionKind(kind)):
return GetNameForKind(context, kind)
if mojom.IsInterfaceRequestKind(kind):
return ('org.chromium.mojo.bindings.InterfaceRequest<%s>' %
@@ -344,7 +346,13 @@ def IsPointerArrayKind(kind):
if not mojom.IsArrayKind(kind):
return False
sub_kind = kind.kind
- return mojom.IsObjectKind(sub_kind)
+ return mojom.IsObjectKind(sub_kind) and not mojom.IsUnionKind(sub_kind)
+
+def IsUnionArrayKind(kind):
+ if not mojom.IsArrayKind(kind):
+ return False
+ sub_kind = kind.kind
+ return mojom.IsUnionKind(sub_kind)
def GetConstantsMainEntityName(module):
if module.attributes and 'JavaConstantsClassName' in module.attributes:
@@ -406,11 +414,14 @@ class Generator(generator.Generator):
'is_pointer_array_kind': IsPointerArrayKind,
'is_reference_kind': mojom.IsReferenceKind,
'is_struct_kind': mojom.IsStructKind,
+ 'is_union_array_kind': IsUnionArrayKind,
+ 'is_union_kind': mojom.IsUnionKind,
'java_true_false': GetJavaTrueFalse,
'java_type': GetJavaType,
'method_ordinal_name': GetMethodOrdinalName,
'name': GetNameForElement,
'new_array': NewArray,
+ 'ucc': lambda x: UpperCamelCase(x.name),
}
def GetJinjaExports(self):
@@ -435,6 +446,12 @@ class Generator(generator.Generator):
exports.update({'struct': struct})
return exports
+ @UseJinja('java_templates/union.java.tmpl', filters=java_filters)
+ def GenerateUnionSource(self, union):
+ exports = self.GetJinjaExports()
+ exports.update({'union': union})
+ return exports
+
@UseJinja('java_templates/interface.java.tmpl', filters=java_filters)
def GenerateInterfaceSource(self, interface):
return self.GetJinjaExportsForInterface(interface)
@@ -459,6 +476,10 @@ class Generator(generator.Generator):
self.Write(self.GenerateStructSource(struct),
'%s.java' % GetNameForElement(struct))
+ for union in self.module.unions:
+ self.Write(self.GenerateUnionSource(union),
+ '%s.java' % GetNameForElement(union))
+
for enum in self.module.enums:
self.Write(self.GenerateEnumSource(enum),
'%s.java' % GetNameForElement(enum))
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_python_generator.py b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_python_generator.py
index 6fc5b97..1f726b6 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_python_generator.py
+++ b/third_party/mojo/src/mojo/public/tools/bindings/generators/mojom_python_generator.py
@@ -81,7 +81,8 @@ def FieldStyle(name):
def GetNameForElement(element):
if (mojom.IsEnumKind(element) or mojom.IsInterfaceKind(element) or
- mojom.IsStructKind(element) or isinstance(element, mojom.Method)):
+ mojom.IsStructKind(element) or mojom.IsUnionKind(element) or
+ isinstance(element, mojom.Method)):
return UpperCamelCase(element.name)
if isinstance(element, mojom.EnumValue):
return (GetNameForElement(element.enum) + '.' +
@@ -145,7 +146,7 @@ def GetFieldType(kind, field=None):
arguments.append('nullable=True')
return '_descriptor.MapType(%s)' % ', '.join(arguments)
- if mojom.IsStructKind(kind):
+ if mojom.IsStructKind(kind) or mojom.IsUnionKind(kind):
arguments = [ 'lambda: %s' % GetFullyQualifiedName(kind) ]
if mojom.IsNullableKind(kind):
arguments.append('nullable=True')
diff --git a/third_party/mojo/src/mojo/public/tools/bindings/mojom.gni b/third_party/mojo/src/mojo/public/tools/bindings/mojom.gni
index 51c28de..aad33c7 100644
--- a/third_party/mojo/src/mojo/public/tools/bindings/mojom.gni
+++ b/third_party/mojo/src/mojo/public/tools/bindings/mojom.gni
@@ -85,20 +85,23 @@ template("mojom") {
"$generator_root/generators/dart_templates/module.lib.tmpl",
"$generator_root/generators/dart_templates/module_definition.tmpl",
"$generator_root/generators/dart_templates/struct_definition.tmpl",
+ "$generator_root/generators/go_templates/encoding_macros.tmpl",
"$generator_root/generators/go_templates/enum.tmpl",
"$generator_root/generators/go_templates/interface.tmpl",
"$generator_root/generators/go_templates/source.tmpl",
"$generator_root/generators/go_templates/struct.tmpl",
+ "$generator_root/generators/go_templates/union.tmpl",
"$generator_root/generators/java_templates/constant_definition.tmpl",
"$generator_root/generators/java_templates/constants.java.tmpl",
- "$generator_root/generators/java_templates/enum.java.tmpl",
+ "$generator_root/generators/java_templates/data_types_definition.tmpl",
"$generator_root/generators/java_templates/enum_definition.tmpl",
+ "$generator_root/generators/java_templates/enum.java.tmpl",
"$generator_root/generators/java_templates/header.java.tmpl",
- "$generator_root/generators/java_templates/interface.java.tmpl",
"$generator_root/generators/java_templates/interface_definition.tmpl",
"$generator_root/generators/java_templates/interface_internal.java.tmpl",
+ "$generator_root/generators/java_templates/interface.java.tmpl",
"$generator_root/generators/java_templates/struct.java.tmpl",
- "$generator_root/generators/java_templates/struct_definition.tmpl",
+ "$generator_root/generators/java_templates/union.java.tmpl",
"$generator_root/generators/js_templates/enum_definition.tmpl",
"$generator_root/generators/js_templates/interface_definition.tmpl",
"$generator_root/generators/js_templates/module.amd.tmpl",
@@ -221,7 +224,7 @@ template("mojom") {
deps = []
if (defined(invoker.sources)) {
- deps += [ ":$generator_target_name" ]
+ public_deps += [ ":$generator_target_name" ]
}
deps += rebased_mojo_sdk_deps
if (defined(invoker.deps)) {
@@ -262,13 +265,14 @@ template("mojom") {
action("${target_name}_python") {
script = rebase_path("mojo/public/tools/gn/zip.py", ".", mojo_root)
+ deps = []
+ zip_inputs = []
+
if (defined(invoker.sources)) {
inputs = process_file_template(invoker.sources, generator_python_outputs)
+ deps += [ ":$generator_target_name" ]
}
- deps = []
- zip_inputs = []
-
foreach(d, all_deps) {
# Resolve the name, so that a target //mojo/something becomes
# //mojo/something:something and we can append "_python" to get the python
@@ -304,13 +308,14 @@ template("mojom") {
action("${target_name}_dart") {
script = rebase_path("mojo/public/tools/gn/zip.py", ".", mojo_root)
+ deps = []
+ zip_inputs = []
+
if (defined(invoker.sources)) {
inputs = process_file_template(invoker.sources, generator_dart_outputs)
+ deps += [ ":$generator_target_name" ]
}
- deps = []
- zip_inputs = []
-
foreach(d, all_deps) {
# Resolve the name, so that a target //mojo/something becomes
# //mojo/something:something and we can append "_dart" to get the dart
diff --git a/third_party/mojo/src/mojo/public/tools/dart_analyze.py b/third_party/mojo/src/mojo/public/tools/dart_analyze.py
index b90cbef..6e7dfc4 100755
--- a/third_party/mojo/src/mojo/public/tools/dart_analyze.py
+++ b/third_party/mojo/src/mojo/public/tools/dart_analyze.py
@@ -31,6 +31,9 @@ _IGNORED_PATTERNS = [
re.compile(r'.*is a part and can not|^Only libraries can be analyzed'),
# TODO: Remove this once dev SDK includes Uri.directory constructor.
re.compile(r'.*The class \'Uri\' does not have a constructor \'directory\''),
+ # TODO: Remove this once Sky no longer generates this warning.
+ # dartbug.com/22836
+ re.compile(r'.*cannot both be unnamed'),
]
def _success(stamp_file):
@@ -66,7 +69,7 @@ def main(args):
cmd.extend(dart_files)
cmd.extend(args)
- cmd.append("--package-root=%s" % temp_dir)
+ cmd.append("--package-root=%s/packages" % temp_dir)
cmd.append("--fatal-warnings")
errors = 0
diff --git a/third_party/mojo/src/mojo/public/tools/dart_list_mojoms.py b/third_party/mojo/src/mojo/public/tools/dart_list_mojoms.py
new file mode 100755
index 0000000..1ef886c
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/dart_list_mojoms.py
@@ -0,0 +1,38 @@
+#!/usr/bin/python
+# 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.
+
+# This script scans a directory tree for any .mojom files and outputs a list.
+
+import argparse
+import os
+import sys
+
+def main(args):
+ parser = argparse.ArgumentParser(
+ description='Prints list of generated dart binding source files.')
+ parser.add_argument('source_directory',
+ metavar='source_directory',
+ help='Path to source directory tree containing .mojom'
+ ' files')
+ parser.add_argument('relative_directory_root',
+ metavar='relative_directory_root',
+ help='Path to directory which all outputted paths will'
+ 'be relative to.')
+ args = parser.parse_args()
+ # Directory to start searching for .mojom files.
+ source_directory = args.source_directory
+ # Prefix to chop off output.
+ root_prefix = os.path.abspath(args.relative_directory_root)
+ for dirname, _, filenames in os.walk(source_directory):
+ # filter for .mojom files.
+ filenames = [f for f in filenames if f.endswith('.mojom')]
+ for f in filenames:
+ path = os.path.abspath(os.path.join(dirname, f))
+ path = os.path.relpath(path, root_prefix)
+ print(path)
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
+
diff --git a/third_party/mojo/src/mojo/public/tools/dart_list_packages_contents.py b/third_party/mojo/src/mojo/public/tools/dart_list_packages_contents.py
index b8fbbdc..f6e0d4a 100755
--- a/third_party/mojo/src/mojo/public/tools/dart_list_packages_contents.py
+++ b/third_party/mojo/src/mojo/public/tools/dart_list_packages_contents.py
@@ -10,11 +10,15 @@ import argparse
import os
import sys
-def main(target_directory):
+def main(target_directory, package_name):
os.chdir(target_directory)
+ self_path = 'packages/' + package_name
for root, _, files in os.walk("packages", followlinks=True):
for f in files:
- print os.path.join(root, f)
+ path = os.path.join(root, f)
+ # Skip the contents of our own packages/package_name symlink.
+ if not path.startswith(self_path):
+ print os.path.join(root, f)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
@@ -27,5 +31,12 @@ if __name__ == '__main__':
required=True,
help="The target directory, specified relative to this "
"directory.")
+ parser.add_argument("--package-name",
+ dest="package_name",
+ metavar="<package-name>",
+ type=str,
+ required=True,
+ help="The name of the package whose packages/ is being "
+ "dumped.")
args = parser.parse_args()
- sys.exit(main(args.target_directory))
+ sys.exit(main(args.target_directory, args.package_name))
diff --git a/third_party/mojo/src/mojo/public/tools/dart_package.py b/third_party/mojo/src/mojo/public/tools/dart_package.py
new file mode 100755
index 0000000..083a6d5
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/dart_package.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python
+#
+# 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.
+
+"""Archives a set of dart packages"""
+
+import ast
+import optparse
+import os
+import sys
+import zipfile
+
+def IsPackagesPath(path):
+ return path.startswith('packages/')
+
+def IsMojomPath(path):
+ return path.startswith('mojom/lib/')
+
+def IsMojomDartFile(path):
+ return path.endswith('.mojom.dart')
+
+# Strips off mojom/lib/ returning module/interface.mojom.dart
+def MojomDartRelativePath(path):
+ assert IsMojomPath(path)
+ assert IsMojomDartFile(path)
+ return os.path.relpath(path, 'mojom/lib/')
+
+# Line is a line from pubspec.yaml
+def PackageName(line):
+ assert line.startswith("name:")
+ return line.split(":")[1].strip()
+
+# pubspec_contents is the contents of a pubspec.yaml file, returns the package
+# name.
+def FindPackageName(pubspec_contents):
+ for line in pubspec_contents.splitlines():
+ if line.startswith("name:"):
+ return PackageName(line)
+
+# Returns true if path is in lib/.
+def IsPathInLib(path):
+ return path.startswith("lib/")
+
+# Strips off lib/
+def PackageRelativePath(path):
+ return os.path.relpath(path, "lib/")
+
+def DoZip(inputs, zip_inputs, output, base_dir):
+ files = []
+ with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as outfile:
+ # Loose file inputs (package source files)
+ for f in inputs:
+ file_name = os.path.relpath(f, base_dir)
+ # We should never see a packages/ path here.
+ assert not IsPackagesPath(file_name)
+ # We should never see a .mojom.dart path here.
+ files.append(file_name)
+ outfile.write(f, file_name)
+ # zip file inputs (other packages)
+ for zf_name in zip_inputs:
+ with zipfile.ZipFile(zf_name, 'r') as zf:
+ # Attempt to sniff package_name. If this fails, we are processing a zip
+ # file with mojom.dart bindings or a packages/ dump.
+ package_name = None
+ try:
+ with zf.open("pubspec.yaml") as pubspec_file:
+ package_name = FindPackageName(pubspec_file.read())
+ except KeyError:
+ pass
+
+ # Iterate over all files in zip file.
+ for f in zf.namelist():
+
+ # Copy any direct mojom dependencies into mojom/
+ if IsMojomPath(f):
+ mojom_dep_copy = os.path.join("lib/mojom/",
+ MojomDartRelativePath(f))
+ if mojom_dep_copy not in files:
+ files.append(mojom_dep_copy)
+ with zf.open(f) as zff:
+ outfile.writestr(mojom_dep_copy, zff.read())
+
+ # Rewrite output file name, if it isn't a packages/ path.
+ output_name = None
+ if not IsPackagesPath(f):
+ if IsMojomDartFile(f) and IsMojomPath(f):
+ # Place mojom/lib/*.mojom.dart files into packages/mojom/
+ output_name = os.path.join("packages/mojom/",
+ MojomDartRelativePath(f))
+ else:
+ # We are processing a package, it must have a package name.
+ assert not (package_name is None)
+ package_path = os.path.join("packages/", package_name)
+ if IsPathInLib(f):
+ output_name = os.path.join(package_path, PackageRelativePath(f))
+ else:
+ output_name = f;
+
+ if output_name is None:
+ continue
+
+ if output_name not in files:
+ files.append(output_name)
+ with zf.open(f) as zff:
+ outfile.writestr(output_name, zff.read())
+
+
+def main():
+ parser = optparse.OptionParser()
+
+ parser.add_option('--inputs', help='List of files to archive.')
+ parser.add_option('--link-inputs',
+ help='List of files to archive. Symbolic links are resolved.')
+ parser.add_option('--zip-inputs', help='List of zip files to re-archive.')
+ parser.add_option('--output', help='Path to output archive.')
+ parser.add_option('--base-dir',
+ help='If provided, the paths in the archive will be '
+ 'relative to this directory', default='.')
+ options, _ = parser.parse_args()
+
+ inputs = []
+ if (options.inputs):
+ inputs = ast.literal_eval(options.inputs)
+ zip_inputs = []
+ if options.zip_inputs:
+ zip_inputs = ast.literal_eval(options.zip_inputs)
+ output = options.output
+ base_dir = options.base_dir
+
+ DoZip(inputs, zip_inputs, output, base_dir)
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/third_party/mojo/src/mojo/public/tools/dart_package_name.py b/third_party/mojo/src/mojo/public/tools/dart_package_name.py
new file mode 100755
index 0000000..5817945
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/dart_package_name.py
@@ -0,0 +1,38 @@
+#!/usr/bin/python
+# 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.
+
+"""This script outputs the package name specified in the pubspec.yaml"""
+
+import argparse
+import os
+import sys
+
+# TODO(johnmccutchan): Use the yaml package to parse.
+def PackageName(line):
+ assert line.startswith("name:")
+ return line.split(":")[1].strip()
+
+def main(pubspec_file):
+ source_file = open(pubspec_file, "r")
+ for line in source_file:
+ if line.startswith("name:"):
+ print(PackageName(line))
+ return 0
+ source_file.close()
+ # Couldn't find it.
+ return -1
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(
+ description="This script outputs the package name specified in the"
+ "pubspec.yaml")
+ parser.add_argument("--pubspec",
+ dest="pubspec_file",
+ metavar="<pubspec-file>",
+ type=str,
+ required=True,
+ help="Path to pubspec file")
+ args = parser.parse_args()
+ sys.exit(main(args.pubspec_file))
diff --git a/third_party/mojo/src/mojo/public/tools/dart_pkg.py b/third_party/mojo/src/mojo/public/tools/dart_pkg.py
new file mode 100755
index 0000000..5872514
--- /dev/null
+++ b/third_party/mojo/src/mojo/public/tools/dart_pkg.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python
+#
+# 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.
+
+"""Utility for dart_pkg and dart_pkg_app rules"""
+
+import argparse
+import errno
+import os
+import shutil
+import sys
+
+# Disable lint check for finding modules:
+# pylint: disable=F0401
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
+ "bindings/pylib"))
+
+from mojom.parse.parser import Parse
+from mojom.parse.translate import Translate
+
+USE_LINKS = sys.platform != "win32"
+
+
+def mojom_dart_filter(path):
+ if os.path.isdir(path):
+ return True
+ # Don't include all .dart, just .mojom.dart.
+ return path.endswith('.mojom.dart')
+
+
+def dart_filter(path):
+ if os.path.isdir(path):
+ return True
+ _, ext = os.path.splitext(path)
+ # .dart includes '.mojom.dart'
+ return ext == '.dart'
+
+
+def mojom_filter(path):
+ if os.path.isdir(path):
+ return True
+ _, ext = os.path.splitext(path)
+ return ext == '.mojom'
+
+
+def ensure_dir_exists(path):
+ if not os.path.exists(path):
+ os.makedirs(path)
+
+
+def has_pubspec_yaml(paths):
+ for path in paths:
+ _, filename = os.path.split(path)
+ if 'pubspec.yaml' == filename:
+ return True
+ return False
+
+
+def link(from_root, to_root):
+ ensure_dir_exists(os.path.dirname(to_root))
+ if os.path.exists(to_root):
+ os.unlink(to_root)
+ try:
+ os.symlink(from_root, to_root)
+ except OSError as e:
+ if e.errno == errno.EEXIST:
+ pass
+
+
+def copy(from_root, to_root, filter_func=None):
+ if not os.path.exists(from_root):
+ return
+ if os.path.isfile(from_root):
+ ensure_dir_exists(os.path.dirname(to_root))
+ shutil.copy(from_root, to_root)
+ return
+
+ ensure_dir_exists(to_root)
+
+ for root, dirs, files in os.walk(from_root):
+ # filter_func expects paths not names, so wrap it to make them absolute.
+ wrapped_filter = None
+ if filter_func:
+ wrapped_filter = lambda name: filter_func(os.path.join(root, name))
+
+ for name in filter(wrapped_filter, files):
+ from_path = os.path.join(root, name)
+ root_rel_path = os.path.relpath(from_path, from_root)
+ to_path = os.path.join(to_root, root_rel_path)
+ to_dir = os.path.dirname(to_path)
+ if not os.path.exists(to_dir):
+ os.makedirs(to_dir)
+ shutil.copy(from_path, to_path)
+
+ dirs[:] = filter(wrapped_filter, dirs)
+
+
+def copy_or_link(from_root, to_root, filter_func=None):
+ if USE_LINKS:
+ link(from_root, to_root)
+ else:
+ copy(from_root, to_root, filter_func)
+
+
+def list_files(from_root, filter_func=None):
+ file_list = []
+ for root, dirs, files in os.walk(from_root):
+ # filter_func expects paths not names, so wrap it to make them absolute.
+ wrapped_filter = None
+ if filter_func:
+ wrapped_filter = lambda name: filter_func(os.path.join(root, name))
+ for name in filter(wrapped_filter, files):
+ path = os.path.join(root, name)
+ file_list.append(path)
+ dirs[:] = filter(wrapped_filter, dirs)
+ return file_list
+
+
+def remove_broken_symlink(path):
+ try:
+ link_path = os.readlink(path)
+ except OSError as e:
+ # Path was not a symlink.
+ if e.errno == errno.EINVAL:
+ pass
+ else:
+ if not os.path.exists(link_path):
+ os.unlink(path)
+
+
+def remove_broken_symlinks(root_dir):
+ for current_dir, _, child_files in os.walk(root_dir):
+ for filename in child_files:
+ path = os.path.join(current_dir, filename)
+ remove_broken_symlink(path)
+
+
+def mojom_path(filename):
+ with open(filename) as f:
+ source = f.read()
+ tree = Parse(source, filename)
+ _, name = os.path.split(filename)
+ mojom = Translate(tree, name)
+ elements = mojom['namespace'].split('.')
+ elements.append("%s" % mojom['name'])
+ return os.path.join(*elements)
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Generate a dart-pkg')
+ parser.add_argument('--package-name',
+ action='store',
+ type=str,
+ metavar='package_name',
+ help='Name of package',
+ required=True)
+ parser.add_argument('--gen-directory',
+ metavar='gen_directory',
+ help="dart-gen directory",
+ required=True)
+ parser.add_argument('--pkg-directory',
+ metavar='pkg_directory',
+ help='Directory where dart_pkg should go',
+ required=True)
+ parser.add_argument('--package-root',
+ metavar='package_root',
+ help='packages/ directory',
+ required=True)
+ parser.add_argument('--stamp-file',
+ metavar='stamp_file',
+ help='timestamp file',
+ required=True)
+ parser.add_argument('--package-sources',
+ metavar='package_sources',
+ help='Package sources',
+ nargs='+')
+ parser.add_argument('--mojom-sources',
+ metavar='mojom_sources',
+ help='.mojom and .mojom.dart sources',
+ nargs='*',
+ default=[])
+ parser.add_argument('--sdk-ext-directories',
+ metavar='sdk_ext_directories',
+ help='Directory containing .dart sources',
+ nargs='*',
+ default=[])
+ args = parser.parse_args()
+
+ # We must have a pubspec.yaml.
+ assert has_pubspec_yaml(args.package_sources)
+
+ # Copy or symlink package sources into pkg directory.
+ target_dir = os.path.join(args.pkg_directory, args.package_name)
+ common_source_prefix = os.path.commonprefix(args.package_sources)
+ for source in args.package_sources:
+ relative_source = os.path.relpath(source, common_source_prefix)
+ target = os.path.join(target_dir, relative_source)
+ copy_or_link(source, target)
+
+ # Copy sdk-ext sources into pkg directory
+ sdk_ext_dir = os.path.join(target_dir, 'sdk_ext')
+ for directory in args.sdk_ext_directories:
+ sdk_ext_sources = list_files(directory, dart_filter)
+ common_prefix = os.path.commonprefix(sdk_ext_sources)
+ for source in sdk_ext_sources:
+ relative_source = os.path.relpath(source, common_prefix)
+ target = os.path.join(sdk_ext_dir, relative_source)
+ copy_or_link(source, target)
+
+ lib_path = os.path.join(target_dir, "lib")
+ lib_mojom_path = os.path.join(lib_path, "mojom")
+
+ # Copy mojom sources
+ for mojom_source_path in args.mojom_sources:
+ path = mojom_path(mojom_source_path)
+ copy(mojom_source_path, os.path.join(lib_mojom_path, path))
+
+ # Copy generated mojom.dart files.
+ generated_mojom_lib_path = os.path.join(args.gen_directory, "mojom/lib")
+ for mojom_source_path in args.mojom_sources:
+ path = mojom_path(mojom_source_path)
+ source_path = '%s.dart' % os.path.join(generated_mojom_lib_path, path)
+ target_path = '%s.dart' % os.path.join(lib_mojom_path, path)
+ copy(source_path, target_path)
+
+ # Symlink packages/
+ package_path = os.path.join(args.package_root, args.package_name)
+ link(lib_path, package_path)
+
+ # Remove any broken symlinks in target_dir and package root.
+ remove_broken_symlinks(target_dir)
+ remove_broken_symlinks(args.package_root)
+
+ # Write stamp file.
+ with open(args.stamp_file, 'w'):
+ pass
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/third_party/mojo/src/mojo/public/tools/download_network_service.py b/third_party/mojo/src/mojo/public/tools/download_network_service.py
index 43b1172..05c28ba 100755
--- a/third_party/mojo/src/mojo/public/tools/download_network_service.py
+++ b/third_party/mojo/src/mojo/public/tools/download_network_service.py
@@ -15,10 +15,6 @@ _CURRENT_PATH = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(_CURRENT_PATH, "pylib"))
import gs
-if not sys.platform.startswith("linux"):
- print "Not supported for your platform"
- sys.exit(0)
-
script_dir = os.path.dirname(os.path.realpath(__file__))
diff --git a/third_party/mojo/src/mojo/public/tools/git/dart_pub_get.py b/third_party/mojo/src/mojo/public/tools/git/dart_pub_get.py
index a984de9..f2b0ddc 100755
--- a/third_party/mojo/src/mojo/public/tools/git/dart_pub_get.py
+++ b/third_party/mojo/src/mojo/public/tools/git/dart_pub_get.py
@@ -24,10 +24,16 @@ def pub_get(dart_sdk_path, target_directory):
# simultaneous builds in different repos stomping on each other.
env = os.environ.copy()
env["PUB_CACHE"] = os.path.join(os.getcwd(), "dart-pub-cache")
- subprocess.check_output(cmd, shell=False,
- stderr=subprocess.STDOUT,
- cwd=target_directory,
- env=env)
+ try:
+ subprocess.check_output(cmd, shell=False,
+ stderr=subprocess.STDOUT,
+ cwd=target_directory,
+ env=env)
+ except subprocess.CalledProcessError as e:
+ print('Error running pub get in %s' % target_directory)
+ print(e.output)
+ raise e
+
def main(repository_root, dart_sdk_path, dirs_to_ignore):