diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 927f4c74a5..4acdf940ce 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -715,6 +715,21 @@ FILE: ../../../flutter/shell/platform/embedder/platform_view_embedder.cc FILE: ../../../flutter/shell/platform/embedder/platform_view_embedder.h FILE: ../../../flutter/shell/platform/embedder/vsync_waiter_embedder.cc FILE: ../../../flutter/shell/platform/embedder/vsync_waiter_embedder.h +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc +FILE: ../../../flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/files.cc FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/files.h FILE: ../../../flutter/shell/platform/fuchsia/runtime/dart/utils/handle_exception.cc diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn new file mode 100644 index 0000000000..96ee6bc04f --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/BUILD.gn @@ -0,0 +1,32 @@ +# Copyright 2013 The Flutter 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("//build/fuchsia/sdk.gni") + +config("sdk_ext_config") { + include_dirs = [ "../.." ] +} + +group("fuchsia") { + public_deps = [ + ":sdk_ext", + ] +} + +source_set("sdk_ext") { + sources = [ + "sdk_ext/fuchsia.cc", + "sdk_ext/fuchsia.h", + ] + + deps = [ + "$flutter_root/fml", + "$fuchsia_sdk_root/fidl:fuchsia.sys", + "$fuchsia_sdk_root/pkg:async-cpp", + "../zircon", + "//third_party/tonic", + ] + + public_configs = [ ":sdk_ext_config" ] +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/README.md b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/README.md new file mode 100644 index 0000000000..d22670fbde --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/README.md @@ -0,0 +1,4 @@ +dart:fuchsia +=========== + +These are the Dart bindings for the Fuchsia application model. diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/analysis_options.yaml b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/analysis_options.yaml new file mode 100644 index 0000000000..d226629fdd --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/analysis_options.yaml @@ -0,0 +1,5 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +include: ../../analysis_options.yaml diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart new file mode 100644 index 0000000000..b04fe363d8 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter 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 fuchsia; + +import 'dart:io'; +import 'dart:isolate'; +import 'dart:zircon'; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +// TODO: refactors this incomingServices instead +@pragma('vm:entry-point') +Handle _environment; + +@pragma('vm:entry-point') +Handle _outgoingServices; + +class MxStartupInfo { + // TODO: refactor Handle to a Channel + static Handle takeEnvironment() { + if (_outgoingServices == null && Platform.isFuchsia) { + throw Exception( + 'Attempting to call takeEnvironment more than once per process'); + } + Handle handle = _environment; + _environment = null; + return handle; + } + + // TODO: refactor Handle to a Channel + static Handle takeOutgoingServices() { + if (_outgoingServices == null && Platform.isFuchsia) { + throw Exception( + 'Attempting to call takeOutgoingServices more than once per process'); + } + Handle handle = _outgoingServices; + _outgoingServices = null; + return handle; + } +} + +void _setReturnCode(int returnCode) native 'SetReturnCode'; + +void exit(int returnCode) { + _setReturnCode(returnCode); + Isolate.current.kill(priority: Isolate.immediate); +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/pubspec.yaml b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/pubspec.yaml new file mode 100644 index 0000000000..5e8ae01a4e --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/pubspec.yaml @@ -0,0 +1,3 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext.gni b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext.gni new file mode 100644 index 0000000000..906f83e7a6 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext.gni @@ -0,0 +1,7 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +fuchsia_sdk_ext_lib = "//topaz/public/dart-pkg/fuchsia/lib/fuchsia.dart" + +fuchsia_sdk_ext_files = [ fuchsia_sdk_ext_lib ] diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc new file mode 100644 index 0000000000..ea6c4cb382 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc @@ -0,0 +1,134 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "dart-pkg/fuchsia/sdk_ext/fuchsia.h" + +#include + +#include +#include + +#include +#include + +#include "dart-pkg/zircon/sdk_ext/handle.h" +#include "dart-pkg/zircon/sdk_ext/natives.h" +#include "dart-pkg/zircon/sdk_ext/system.h" +#include "flutter/fml/arraysize.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" +#include "third_party/tonic/dart_class_provider.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_invoke.h" +#include "third_party/tonic/typed_data/uint8_list.h" + +using tonic::ToDart; + +namespace fuchsia { +namespace dart { +namespace { + +static tonic::DartLibraryNatives* g_natives; + +tonic::DartLibraryNatives* InitNatives() { + tonic::DartLibraryNatives* natives = new tonic::DartLibraryNatives(); + + return natives; +} + +#define REGISTER_FUNCTION(name, count) {"" #name, name, count}, +#define DECLARE_FUNCTION(name, count) \ + extern void name(Dart_NativeArguments args); + +#define FIDL_NATIVE_LIST(V) V(SetReturnCode, 1) + +FIDL_NATIVE_LIST(DECLARE_FUNCTION); + +static struct NativeEntries { + const char* name; + Dart_NativeFunction function; + int argument_count; +} Entries[] = {FIDL_NATIVE_LIST(REGISTER_FUNCTION)}; + +Dart_NativeFunction NativeLookup(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + const char* function_name = nullptr; + Dart_Handle result = Dart_StringToCString(name, &function_name); + if (Dart_IsError(result)) { + Dart_PropagateError(result); + } + FML_DCHECK(function_name != nullptr); + FML_DCHECK(auto_setup_scope != nullptr); + *auto_setup_scope = true; + size_t num_entries = arraysize(Entries); + for (size_t i = 0; i < num_entries; ++i) { + const struct NativeEntries& entry = Entries[i]; + if (!strcmp(function_name, entry.name) && + (entry.argument_count == argument_count)) { + return entry.function; + } + } + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); +} + +const uint8_t* NativeSymbol(Dart_NativeFunction native_function) { + size_t num_entries = arraysize(Entries); + for (size_t i = 0; i < num_entries; ++i) { + const struct NativeEntries& entry = Entries[i]; + if (entry.function == native_function) { + return reinterpret_cast(entry.name); + } + } + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetSymbol(native_function); +} + +void SetReturnCode(Dart_NativeArguments arguments) { + int64_t return_code; + Dart_Handle status = + Dart_GetNativeIntegerArgument(arguments, 0, &return_code); + if (!tonic::LogIfError(status)) { + tonic::DartState::Current()->SetReturnCode(return_code); + } +} + +} // namespace + +void Initialize(fidl::InterfaceHandle environment, + zx::channel directory_request) { + zircon::dart::Initialize(); + + Dart_Handle library = Dart_LookupLibrary(ToDart("dart:fuchsia")); + FML_CHECK(!tonic::LogIfError(library)); + Dart_Handle result = Dart_SetNativeResolver( + library, fuchsia::dart::NativeLookup, fuchsia::dart::NativeSymbol); + FML_CHECK(!tonic::LogIfError(result)); + + auto dart_state = tonic::DartState::Current(); + std::unique_ptr fuchsia_class_provider( + new tonic::DartClassProvider(dart_state, "dart:fuchsia")); + dart_state->class_library().add_provider("fuchsia", + std::move(fuchsia_class_provider)); + + result = Dart_SetField( + library, ToDart("_environment"), + ToDart(zircon::dart::Handle::Create(environment.TakeChannel()))); + FML_CHECK(!tonic::LogIfError(result)); + + if (directory_request) { + result = Dart_SetField( + library, ToDart("_outgoingServices"), + ToDart(zircon::dart::Handle::Create(std::move(directory_request)))); + FML_CHECK(!tonic::LogIfError(result)); + } +} + +} // namespace dart +} // namespace fuchsia diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h new file mode 100644 index 0000000000..e516ffc6da --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.h @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_ + +#include + +namespace fuchsia { +namespace dart { + +void Initialize(fidl::InterfaceHandle environment, + zx::channel directory_request); + +} // namespace dart +} // namespace fuchsia + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_FUCHSIA_SDK_EXT_FUCHSIA_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn new file mode 100644 index 0000000000..dc43d91abb --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/BUILD.gn @@ -0,0 +1,33 @@ +# Copyright 2013 The Flutter 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("//build/fuchsia/sdk.gni") + +config("zircon_config") { + include_dirs = [ "." ] +} + +source_set("zircon") { + public_configs = [ ":zircon_config" ] + + sources = [ + "sdk_ext/handle.cc", + "sdk_ext/handle.h", + "sdk_ext/handle_waiter.cc", + "sdk_ext/handle_waiter.h", + "sdk_ext/natives.cc", + "sdk_ext/natives.h", + "sdk_ext/system.cc", + "sdk_ext/system.h", + ] + + deps = [ + "$fuchsia_sdk_root/pkg:async-cpp", + "$fuchsia_sdk_root/pkg:async-loop-cpp", + "$fuchsia_sdk_root/pkg:fdio", + "$fuchsia_sdk_root/pkg:zx", + "//flutter/fml", + "//third_party/tonic", + ] +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/README.md b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/README.md new file mode 100644 index 0000000000..c2a7fe7d57 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/README.md @@ -0,0 +1,10 @@ +dart:zircon +=========== + +These are the Dart bindings for the Zircon [kernel +interface](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/) + +This package exposes a `System` object with methods for may Zircon system +calls, a `Handle` type representing a Zircon handle and a `HandleWaiter` type +representing a wait on a handle. `Handle`s are returned by various methods on +`System` and `HandleWaiter`s are returned by `handle.asyncWait(...)`. diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/analysis_options.yaml b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/analysis_options.yaml new file mode 100644 index 0000000000..d226629fdd --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/analysis_options.yaml @@ -0,0 +1,5 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +include: ../../analysis_options.yaml diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart new file mode 100644 index 0000000000..9702a4839f --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle.dart @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter 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 zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +@pragma('vm:entry-point') +class Handle extends NativeFieldWrapperClass2 { + // No public constructor - this can only be created from native code. + @pragma('vm:entry-point') + Handle._(); + + // Create an invalid handle object. + factory Handle.invalid() { + return _createInvalid(); + } + static Handle _createInvalid() native 'Handle_CreateInvalid'; + + int get _handle native 'Handle_handle'; + + @override + String toString() => 'Handle($_handle)'; + + @override + bool operator ==(Object other) => + (other is Handle) && (_handle == other._handle); + + @override + int get hashCode => _handle.hashCode; + + // Common handle operations. + bool get isValid native 'Handle_is_valid'; + int close() native 'Handle_Close'; + HandleWaiter asyncWait(int signals, AsyncWaitCallback callback) + native 'Handle_AsyncWait'; + + Handle duplicate(int rights) native 'Handle_Duplicate'; +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart new file mode 100644 index 0000000000..e233f42ca4 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_waiter.dart @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter 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 zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +typedef AsyncWaitCallback = void Function(int status, int pending); + +@pragma('vm:entry-point') +class HandleWaiter extends NativeFieldWrapperClass2 { + // Private constructor. + @pragma('vm:entry-point') + HandleWaiter._(); + + void cancel() native 'HandleWaiter_Cancel'; +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart new file mode 100644 index 0000000000..50bbc60d9b --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/src/system.dart @@ -0,0 +1,161 @@ +// Copyright 2013 The Flutter 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 zircon; + +// ignore_for_file: native_function_body_in_non_sdk_code +// ignore_for_file: public_member_api_docs + +@pragma('vm:entry-point') +class _Namespace { // ignore: unused_element + // No public constructor - this only has static methods. + _Namespace._(); + + // Library private variable set by the embedder used to cache the + // namespace (as an fdio_ns_t*). + @pragma('vm:entry-point') + static int _namespace; // ignore: unused_field +} + +/// An exception representing an error returned as an zx_status_t. +class ZxStatusException implements Exception { + final String message; + final int status; + + ZxStatusException(this.status, [this.message]); + + @override + String toString() { + if (message == null) + return 'ZxStatusException: status = $status'; + else + return 'ZxStatusException: status = $status, "$message"'; + } +} + +class _Result { + final int status; + const _Result(this.status); +} + +@pragma('vm:entry-point') +class HandleResult extends _Result { + final Handle handle; + @pragma('vm:entry-point') + const HandleResult(final int status, [this.handle]) : super(status); + @override + String toString() => 'HandleResult(status=$status, handle=$handle)'; +} + +@pragma('vm:entry-point') +class HandlePairResult extends _Result { + final Handle first; + final Handle second; + @pragma('vm:entry-point') + const HandlePairResult(final int status, [this.first, this.second]) + : super(status); + @override + String toString() => + 'HandlePairResult(status=$status, first=$first, second=$second)'; +} + +@pragma('vm:entry-point') +class ReadResult extends _Result { + final ByteData bytes; + final int numBytes; + final List handles; + @pragma('vm:entry-point') + const ReadResult(final int status, [this.bytes, this.numBytes, this.handles]) + : super(status); + Uint8List bytesAsUint8List() => + bytes.buffer.asUint8List(bytes.offsetInBytes, numBytes); + String bytesAsUTF8String() => utf8.decode(bytesAsUint8List()); + @override + String toString() => + 'ReadResult(status=$status, bytes=$bytes, numBytes=$numBytes, handles=$handles)'; +} + +@pragma('vm:entry-point') +class WriteResult extends _Result { + final int numBytes; + @pragma('vm:entry-point') + const WriteResult(final int status, [this.numBytes]) : super(status); + @override + String toString() => 'WriteResult(status=$status, numBytes=$numBytes)'; +} + +@pragma('vm:entry-point') +class GetSizeResult extends _Result { + final int size; + @pragma('vm:entry-point') + const GetSizeResult(final int status, [this.size]) : super(status); + @override + String toString() => 'GetSizeResult(status=$status, size=$size)'; +} + +@pragma('vm:entry-point') +class FromFileResult extends _Result { + final Handle handle; + final int numBytes; + @pragma('vm:entry-point') + const FromFileResult(final int status, [this.handle, this.numBytes]) + : super(status); + @override + String toString() => + 'FromFileResult(status=$status, handle=$handle, numBytes=$numBytes)'; +} + +@pragma('vm:entry-point') +class MapResult extends _Result { + final Uint8List data; + @pragma('vm:entry-point') + const MapResult(final int status, [this.data]) : super(status); + @override + String toString() => 'MapResult(status=$status, data=$data)'; +} + +@pragma('vm:entry-point') +class System extends NativeFieldWrapperClass2 { + // No public constructor - this only has static methods. + System._(); + + // Channel operations. + static HandlePairResult channelCreate([int options = 0]) + native 'System_ChannelCreate'; + static HandleResult channelFromFile(String path) + native 'System_ChannelFromFile'; + static int reboot() + native 'System_Reboot'; + static int channelWrite(Handle channel, ByteData data, List handles) + native 'System_ChannelWrite'; + static ReadResult channelQueryAndRead(Handle channel) + native 'System_ChannelQueryAndRead'; + + // Eventpair operations. + static HandlePairResult eventpairCreate([int options = 0]) + native 'System_EventpairCreate'; + + // Socket operations. + static HandlePairResult socketCreate([int options = 0]) + native 'System_SocketCreate'; + static WriteResult socketWrite(Handle socket, ByteData data, int options) + native 'System_SocketWrite'; + static ReadResult socketRead(Handle socket, int size) + native 'System_SocketRead'; + + // Vmo operations. + static HandleResult vmoCreate(int size, [int options = 0]) + native 'System_VmoCreate'; + static FromFileResult vmoFromFile(String path) native 'System_VmoFromFile'; + static GetSizeResult vmoGetSize(Handle vmo) native 'System_VmoGetSize'; + static int vmoSetSize(Handle vmo, int size) native 'System_VmoSetSize'; + static int vmoWrite(Handle vmo, int offset, ByteData bytes) + native 'System_VmoWrite'; + static ReadResult vmoRead(Handle vmo, int offset, int size) + native 'System_VmoRead'; + static MapResult vmoMap(Handle vmo) native 'System_VmoMap'; + + // Time operations. + static int clockGet(int clockId) native 'System_ClockGet'; +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart new file mode 100644 index 0000000000..5e80671ffb --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/lib/zircon.dart @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter 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 zircon; + +import 'dart:convert' show utf8; +import 'dart:nativewrappers'; +import 'dart:typed_data'; + +part 'src/handle.dart'; +part 'src/handle_waiter.dart'; +part 'src/system.dart'; diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml new file mode 100644 index 0000000000..5e8ae01a4e --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/pubspec.yaml @@ -0,0 +1,3 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc new file mode 100644 index 0000000000..75571d06b6 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc @@ -0,0 +1,122 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "handle.h" + +#include + +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" + +using tonic::ToDart; + +namespace zircon { +namespace dart { + +IMPLEMENT_WRAPPERTYPEINFO(zircon, Handle); + +Handle::Handle(zx_handle_t handle) : handle_(handle) {} + +Handle::~Handle() { + if (is_valid()) { + zx_status_t status = Close(); + FML_DCHECK(status == ZX_OK); + } +} + +fml::RefPtr Handle::Create(zx_handle_t handle) { + return fml::MakeRefCounted(handle); +} + +Dart_Handle Handle::CreateInvalid() { + return ToDart(Create(ZX_HANDLE_INVALID)); +} + +zx_handle_t Handle::ReleaseHandle() { + FML_DCHECK(is_valid()); + + zx_handle_t handle = handle_; + handle_ = ZX_HANDLE_INVALID; + while (waiters_.size()) { + // HandleWaiter::Cancel calls Handle::ReleaseWaiter which removes the + // HandleWaiter from waiters_. + FML_DCHECK(waiters_.back()->is_pending()); + waiters_.back()->Cancel(); + } + + FML_DCHECK(!is_valid()); + + return handle; +} + +zx_status_t Handle::Close() { + if (is_valid()) { + zx_handle_t handle = ReleaseHandle(); + return zx_handle_close(handle); + } + return ZX_ERR_BAD_HANDLE; +} + +fml::RefPtr Handle::AsyncWait(zx_signals_t signals, + Dart_Handle callback) { + if (!is_valid()) { + FML_LOG(WARNING) << "Attempt to wait on an invalid handle."; + return nullptr; + } + + fml::RefPtr waiter = + HandleWaiter::Create(this, signals, callback); + waiters_.push_back(waiter.get()); + + return waiter; +} + +void Handle::ReleaseWaiter(HandleWaiter* waiter) { + FML_DCHECK(waiter); + auto iter = std::find(waiters_.cbegin(), waiters_.cend(), waiter); + FML_DCHECK(iter != waiters_.cend()); + FML_DCHECK(*iter == waiter); + waiters_.erase(iter); +} + +Dart_Handle Handle::Duplicate(uint32_t rights) { + if (!is_valid()) { + return ToDart(Create(ZX_HANDLE_INVALID)); + } + + zx_handle_t out_handle; + zx_status_t status = zx_handle_duplicate(handle_, rights, &out_handle); + if (status != ZX_OK) { + return ToDart(Create(ZX_HANDLE_INVALID)); + } + return ToDart(Create(out_handle)); +} + +// clang-format: off + +#define FOR_EACH_STATIC_BINDING(V) V(Handle, CreateInvalid) + +#define FOR_EACH_BINDING(V) \ + V(Handle, handle) \ + V(Handle, is_valid) \ + V(Handle, Close) \ + V(Handle, AsyncWait) \ + V(Handle, Duplicate) + +// clang-format: on + +// Tonic is missing a comma. +#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ + DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), + +FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void Handle::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_) + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +} // namespace dart +} // namespace zircon diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h new file mode 100644 index 0000000000..945a567d3b --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.h @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_ + +#include + +#include + +#include "flutter/fml/memory/ref_counted.h" +#include "handle_waiter.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_wrappable.h" +#include "third_party/tonic/typed_data/dart_byte_data.h" + +namespace zircon { +namespace dart { +/** + * Handle is the native peer of a Dart object (Handle in dart:zircon) + * that holds an zx_handle_t. It tracks active waiters on handle too. + */ +class Handle : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(Handle); + FML_FRIEND_MAKE_REF_COUNTED(Handle); + + public: + ~Handle(); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + static fml::RefPtr Create(zx_handle_t handle); + static fml::RefPtr Create(zx::handle handle) { + return Create(handle.release()); + } + + static fml::RefPtr Unwrap(Dart_Handle handle) { + return fml::RefPtr( + tonic::DartConverter::FromDart(handle)); + } + + static Dart_Handle CreateInvalid(); + + zx_handle_t ReleaseHandle(); + + bool is_valid() const { return handle_ != ZX_HANDLE_INVALID; } + + zx_handle_t handle() const { return handle_; } + + zx_status_t Close(); + + fml::RefPtr AsyncWait(zx_signals_t signals, + Dart_Handle callback); + + void ReleaseWaiter(HandleWaiter* waiter); + + Dart_Handle Duplicate(uint32_t rights); + + private: + explicit Handle(zx_handle_t handle); + + void RetainDartWrappableReference() const override { AddRef(); } + + void ReleaseDartWrappableReference() const override { Release(); } + + zx_handle_t handle_; + + std::vector waiters_; +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc new file mode 100644 index 0000000000..724c7f5967 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "handle_waiter.h" + +#include + +#include "handle.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/dart_args.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_message_handler.h" +#include "third_party/tonic/logging/dart_invoke.h" + +using tonic::DartInvokeField; +using tonic::DartState; +using tonic::ToDart; + +namespace zircon { +namespace dart { + +IMPLEMENT_WRAPPERTYPEINFO(zircon, HandleWaiter); + +#define FOR_EACH_BINDING(V) V(HandleWaiter, Cancel) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void HandleWaiter::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +fml::RefPtr HandleWaiter::Create(Handle* handle, + zx_signals_t signals, + Dart_Handle callback) { + return fml::MakeRefCounted(handle, signals, callback); +} + +HandleWaiter::HandleWaiter(Handle* handle, + zx_signals_t signals, + Dart_Handle callback) + : wait_(this, handle->handle(), signals), + handle_(handle), + callback_(DartState::Current(), callback) { + FML_CHECK(handle_ != nullptr); + FML_CHECK(handle_->is_valid()); + + zx_status_t status = wait_.Begin(async_get_default_dispatcher()); + FML_DCHECK(status == ZX_OK); +} + +HandleWaiter::~HandleWaiter() { + Cancel(); +} + +void HandleWaiter::Cancel() { + FML_DCHECK(wait_.is_pending() == !!handle_); + if (handle_) { + // Cancel the wait. + wait_.Cancel(); + + // Release this object from the handle and clear handle_. + handle_->ReleaseWaiter(this); + handle_ = nullptr; + } + FML_DCHECK(!wait_.is_pending()); +} + +void HandleWaiter::OnWaitComplete(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal) { + FML_DCHECK(handle_); + + FML_DCHECK(!callback_.is_empty()); + + // Hold a reference to this object. + fml::RefPtr ref(this); + + // Remove this waiter from the handle. + handle_->ReleaseWaiter(this); + + // Clear handle_. + handle_ = nullptr; + + auto state = callback_.dart_state().lock(); + FML_DCHECK(state); + DartState::Scope scope(state); + + std::vector args{ToDart(status), ToDart(signal->observed)}; + FML_DCHECK(!callback_.is_empty()); + Dart_Handle result = + Dart_InvokeClosure(callback_.Release(), args.size(), args.data()); + // If there was an uncaught error from the callback propagate it out. + if (tonic::LogIfError(result)) { + state->message_handler().UnhandledError(result); + } +} + +} // namespace dart +} // namespace zircon diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h new file mode 100644 index 0000000000..6d3814e88a --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ + +#include +#include + +#include "/Users/chinmaygarde/VersionControlled/engine/src/flutter/fml/memory/ref_counted.h" +#include "third_party/tonic/dart_wrappable.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace zircon { +namespace dart { + +class Handle; + +class HandleWaiter : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(HandleWaiter); + FML_FRIEND_MAKE_REF_COUNTED(HandleWaiter); + + public: + static fml::RefPtr Create(Handle* handle, + zx_signals_t signals, + Dart_Handle callback); + + void Cancel(); + + bool is_pending() { return wait_.is_pending(); } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit HandleWaiter(Handle* handle, + zx_signals_t signals, + Dart_Handle callback); + ~HandleWaiter(); + + void OnWaitComplete(async_dispatcher_t* dispatcher, + async::WaitBase* wait, + zx_status_t status, + const zx_packet_signal_t* signal); + + void RetainDartWrappableReference() const override { AddRef(); } + + void ReleaseDartWrappableReference() const override { Release(); } + + async::WaitMethod wait_; + Handle* handle_; + tonic::DartPersistentValue callback_; +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc new file mode 100644 index 0000000000..591bf6c352 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc @@ -0,0 +1,83 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "natives.h" + +#include + +#include +#include + +#include +#include + +#include "handle.h" +#include "handle_waiter.h" +#include "system.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" +#include "third_party/tonic/dart_class_provider.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_state.h" +#include "third_party/tonic/logging/dart_invoke.h" +#include "third_party/tonic/typed_data/uint8_list.h" + +using tonic::ToDart; + +namespace zircon { +namespace dart { +namespace { + +static tonic::DartLibraryNatives* g_natives; + +tonic::DartLibraryNatives* InitNatives() { + tonic::DartLibraryNatives* natives = new tonic::DartLibraryNatives(); + HandleWaiter::RegisterNatives(natives); + Handle::RegisterNatives(natives); + System::RegisterNatives(natives); + + return natives; +} + +Dart_NativeFunction NativeLookup(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + const char* function_name = nullptr; + Dart_Handle result = Dart_StringToCString(name, &function_name); + if (Dart_IsError(result)) { + Dart_PropagateError(result); + } + FML_DCHECK(function_name != nullptr); + FML_DCHECK(auto_setup_scope != nullptr); + *auto_setup_scope = true; + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); +} + +const uint8_t* NativeSymbol(Dart_NativeFunction native_function) { + if (!g_natives) + g_natives = InitNatives(); + return g_natives->GetSymbol(native_function); +} + +} // namespace + +void Initialize() { + Dart_Handle library = Dart_LookupLibrary(ToDart("dart:zircon")); + FML_CHECK(!tonic::LogIfError(library)); + Dart_Handle result = Dart_SetNativeResolver( + library, zircon::dart::NativeLookup, zircon::dart::NativeSymbol); + FML_CHECK(!tonic::LogIfError(result)); + + auto dart_state = tonic::DartState::Current(); + std::unique_ptr zircon_class_provider( + new tonic::DartClassProvider(dart_state, "dart:zircon")); + dart_state->class_library().add_provider("zircon", + std::move(zircon_class_provider)); +} + +} // namespace dart +} // namespace zircon diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h new file mode 100644 index 0000000000..f124f67203 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.h @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_NATIVES_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_NATIVES_H_ + +namespace zircon { +namespace dart { + +void Initialize(); + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_NATIVES_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc new file mode 100644 index 0000000000..34331b12ab --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc @@ -0,0 +1,516 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "system.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/unique_fd.h" +#include "third_party/tonic/dart_binding_macros.h" +#include "third_party/tonic/dart_class_library.h" + +#if !defined(FUCHSIA_SDK) +#include +#include "lib/fsl/io/fd.h" +#endif + +using tonic::ToDart; + +namespace zircon { +namespace dart { + +namespace { + +constexpr char kGetSizeResult[] = "GetSizeResult"; +constexpr char kHandlePairResult[] = "HandlePairResult"; +constexpr char kHandleResult[] = "HandleResult"; +constexpr char kReadResult[] = "ReadResult"; +constexpr char kWriteResult[] = "WriteResult"; +constexpr char kFromFileResult[] = "FromFileResult"; +constexpr char kMapResult[] = "MapResult"; + +class ByteDataScope { + public: + explicit ByteDataScope(Dart_Handle dart_handle) : dart_handle_(dart_handle) { + Acquire(); + } + + explicit ByteDataScope(size_t size) { + dart_handle_ = Dart_NewTypedData(Dart_TypedData_kByteData, size); + FML_DCHECK(!tonic::LogIfError(dart_handle_)); + Acquire(); + FML_DCHECK(size == size_); + } + + ~ByteDataScope() { + if (is_valid_) { + Release(); + } + } + + void* data() const { return data_; } + size_t size() const { return size_; } + Dart_Handle dart_handle() const { return dart_handle_; } + bool is_valid() const { return is_valid_; } + + void Release() { + FML_DCHECK(is_valid_); + Dart_Handle result = Dart_TypedDataReleaseData(dart_handle_); + tonic::LogIfError(result); + is_valid_ = false; + data_ = nullptr; + size_ = 0; + } + + private: + void Acquire() { + FML_DCHECK(size_ == 0); + FML_DCHECK(data_ == nullptr); + FML_DCHECK(!is_valid_); + + Dart_TypedData_Type type; + intptr_t size; + Dart_Handle result = + Dart_TypedDataAcquireData(dart_handle_, &type, &data_, &size); + is_valid_ = + !tonic::LogIfError(result) && type == Dart_TypedData_kByteData && data_; + if (is_valid_) { + size_ = size; + } else { + size_ = 0; + } + } + + Dart_Handle dart_handle_; + bool is_valid_ = false; + size_t size_ = 0; + void* data_ = nullptr; +}; + +Dart_Handle MakeHandleList(const std::vector& in_handles) { + tonic::DartClassLibrary& class_library = + tonic::DartState::Current()->class_library(); + Dart_Handle handle_type = class_library.GetClass("zircon", "Handle"); + Dart_Handle list = Dart_NewListOfType(handle_type, in_handles.size()); + if (Dart_IsError(list)) + return list; + for (size_t i = 0; i < in_handles.size(); i++) { + Dart_Handle result = + Dart_ListSetAt(list, i, ToDart(Handle::Create(in_handles[i]))); + if (Dart_IsError(result)) + return result; + } + return list; +} + +template +Dart_Handle ConstructDartObject(const char* class_name, Args&&... args) { + tonic::DartClassLibrary& class_library = + tonic::DartState::Current()->class_library(); + Dart_Handle type = + Dart_HandleFromPersistent(class_library.GetClass("zircon", class_name)); + FML_DCHECK(!tonic::LogIfError(type)); + + const char* cstr; + Dart_StringToCString(Dart_ToString(type), &cstr); + + std::array args_array{ + {std::forward(args)...}}; + Dart_Handle object = + Dart_New(type, Dart_EmptyString(), sizeof...(Args), args_array.data()); + FML_DCHECK(!tonic::LogIfError(object)); + return object; +} + +fml::UniqueFD FdFromPath(std::string path) { + // Grab the fdio_ns_t* out of the isolate. + Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon")); + FML_DCHECK(!tonic::LogIfError(zircon_lib)); + Dart_Handle namespace_type = + Dart_GetType(zircon_lib, ToDart("_Namespace"), 0, nullptr); + FML_DCHECK(!tonic::LogIfError(namespace_type)); + Dart_Handle namespace_field = + Dart_GetField(namespace_type, ToDart("_namespace")); + FML_DCHECK(!tonic::LogIfError(namespace_field)); + uint64_t fdio_ns_ptr; + Dart_Handle result = Dart_IntegerToUint64(namespace_field, &fdio_ns_ptr); + FML_DCHECK(!tonic::LogIfError(result)); + + // Get a VMO for the file. + fdio_ns_t* ns = reinterpret_cast(fdio_ns_ptr); + fml::UniqueFD dirfd(fdio_ns_opendir(ns)); + if (!dirfd.is_valid()) + return fml::UniqueFD(); + + const char* c_path = path.c_str(); + if (path.length() > 0 && c_path[0] == '/') + c_path = &c_path[1]; + return fml::UniqueFD(openat(dirfd.get(), c_path, O_RDONLY)); +} + +} // namespace + +IMPLEMENT_WRAPPERTYPEINFO(zircon, System); + +Dart_Handle System::ChannelCreate(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_channel_create(options, &out0, &out1); + if (status != ZX_OK) { + return ConstructDartObject(kHandlePairResult, ToDart(status)); + } else { + return ConstructDartObject(kHandlePairResult, ToDart(status), + ToDart(Handle::Create(out0)), + ToDart(Handle::Create(out1))); + } +} + +zx_status_t System::Reboot() { +#if defined(FUCHSIA_SDK) + FML_CHECK(false); + return ZX_ERR_NOT_SUPPORTED; +#else + zx::channel local, remote; + auto status = zx::channel::create(0, &local, &remote); + if (status != ZX_OK) { + return status; + } + + const std::string service = + std::string{"/svc/"} + fuchsia::device::manager::Administrator::Name_; + status = fdio_service_connect(service.c_str(), remote.get()); + if (status != ZX_OK) { + printf("failed to connect to service %s: %d\n", service.c_str(), status); + return status; + } + + zx_status_t call_status; + fuchsia::device::manager::Administrator_SyncProxy administrator( + std::move(local)); + status = administrator.Suspend(DEVICE_SUSPEND_FLAG_REBOOT, &call_status); + if (status != ZX_OK || call_status != ZX_OK) { + printf("Call to %s failed: ret: %d remote: %d\n", service.c_str(), status, + call_status); + } + + return status != ZX_OK ? status : call_status; +#endif +} + +Dart_Handle System::ChannelFromFile(std::string path) { +#if defined(FUCHSIA_SDK) + FML_CHECK(false); + return Dart_Null(); +#else + fml::UniqueFD fd = FdFromPath(path); + if (!fd.is_valid()) { + return ConstructDartObject(kHandleResult, ToDart(ZX_ERR_IO)); + } + + // Get channel from fd. + zx::channel channel = fsl::CloneChannelFromFileDescriptor(fd.get()); + if (!channel) { + return ConstructDartObject(kHandleResult, ToDart(ZX_ERR_IO)); + } + + return ConstructDartObject(kHandleResult, ToDart(ZX_OK), + ToDart(Handle::Create(channel.release()))); +#endif +} + +zx_status_t System::ChannelWrite(fml::RefPtr channel, + const tonic::DartByteData& data, + std::vector handles) { + if (!channel || !channel->is_valid()) { + data.Release(); + return ZX_ERR_BAD_HANDLE; + } + + std::vector zx_handles; + for (Handle* handle : handles) { + zx_handles.push_back(handle->handle()); + } + + zx_status_t status = zx_channel_write(channel->handle(), 0, data.data(), + data.length_in_bytes(), + zx_handles.data(), zx_handles.size()); + // Handles are always consumed. + for (Handle* handle : handles) { + handle->ReleaseHandle(); + } + + data.Release(); + return status; +} + +Dart_Handle System::ChannelQueryAndRead(fml::RefPtr channel) { + if (!channel || !channel->is_valid()) { + return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + uint32_t actual_bytes = 0; + uint32_t actual_handles = 0; + + // Query the size of the next message. + zx_status_t status = zx_channel_read(channel->handle(), 0, nullptr, nullptr, + 0, 0, &actual_bytes, &actual_handles); + if (status != ZX_ERR_BUFFER_TOO_SMALL) { + // An empty message or an error. + return ConstructDartObject(kReadResult, ToDart(status)); + } + + // Allocate space for the bytes and handles. + ByteDataScope bytes(actual_bytes); + FML_DCHECK(bytes.is_valid()); + std::vector handles(actual_handles); + + // Make the call to actually get the message. + status = zx_channel_read(channel->handle(), 0, bytes.data(), handles.data(), + bytes.size(), handles.size(), &actual_bytes, + &actual_handles); + FML_DCHECK(status != ZX_OK || bytes.size() == actual_bytes); + + bytes.Release(); + + if (status == ZX_OK) { + FML_DCHECK(handles.size() == actual_handles); + + // return a ReadResult object. + return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(), + ToDart(actual_bytes), MakeHandleList(handles)); + } else { + return ConstructDartObject(kReadResult, ToDart(status)); + } +} + +Dart_Handle System::EventpairCreate(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_eventpair_create(0, &out0, &out1); + if (status != ZX_OK) { + return ConstructDartObject(kHandlePairResult, ToDart(status)); + } else { + return ConstructDartObject(kHandlePairResult, ToDart(status), + ToDart(Handle::Create(out0)), + ToDart(Handle::Create(out1))); + } +} + +Dart_Handle System::SocketCreate(uint32_t options) { + zx_handle_t out0 = 0, out1 = 0; + zx_status_t status = zx_socket_create(options, &out0, &out1); + if (status != ZX_OK) { + return ConstructDartObject(kHandlePairResult, ToDart(status)); + } else { + return ConstructDartObject(kHandlePairResult, ToDart(status), + ToDart(Handle::Create(out0)), + ToDart(Handle::Create(out1))); + } +} + +Dart_Handle System::SocketWrite(fml::RefPtr socket, + const tonic::DartByteData& data, + int options) { + if (!socket || !socket->is_valid()) { + data.Release(); + return ConstructDartObject(kWriteResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + size_t actual; + zx_status_t status = zx_socket_write(socket->handle(), options, data.data(), + data.length_in_bytes(), &actual); + data.Release(); + return ConstructDartObject(kWriteResult, ToDart(status), ToDart(actual)); +} + +Dart_Handle System::SocketRead(fml::RefPtr socket, size_t size) { + if (!socket || !socket->is_valid()) { + return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + ByteDataScope bytes(size); + size_t actual; + zx_status_t status = + zx_socket_read(socket->handle(), 0, bytes.data(), size, &actual); + bytes.Release(); + if (status == ZX_OK) { + FML_DCHECK(actual <= size); + return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(), + ToDart(actual)); + } + + return ConstructDartObject(kReadResult, ToDart(status)); +} + +Dart_Handle System::VmoCreate(uint64_t size, uint32_t options) { + zx_handle_t vmo = ZX_HANDLE_INVALID; + zx_status_t status = zx_vmo_create(size, options, &vmo); + if (status != ZX_OK) { + return ConstructDartObject(kHandleResult, ToDart(status)); + } else { + return ConstructDartObject(kHandleResult, ToDart(status), + ToDart(Handle::Create(vmo))); + } +} + +Dart_Handle System::VmoFromFile(std::string path) { + fml::UniqueFD fd = FdFromPath(path); + if (!fd.is_valid()) + return ConstructDartObject(kFromFileResult, ToDart(ZX_ERR_IO)); + + struct stat stat_struct; + if (fstat(fd.get(), &stat_struct) == -1) + return ConstructDartObject(kFromFileResult, ToDart(ZX_ERR_IO)); + zx_handle_t vmo = ZX_HANDLE_INVALID; + zx_status_t status = fdio_get_vmo_clone(fd.get(), &vmo); + if (status != ZX_OK) + return ConstructDartObject(kFromFileResult, ToDart(status)); + + return ConstructDartObject(kFromFileResult, ToDart(status), + ToDart(Handle::Create(vmo)), + ToDart(stat_struct.st_size)); +} + +Dart_Handle System::VmoGetSize(fml::RefPtr vmo) { + if (!vmo || !vmo->is_valid()) { + return ConstructDartObject(kGetSizeResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + uint64_t size; + zx_status_t status = zx_vmo_get_size(vmo->handle(), &size); + + return ConstructDartObject(kGetSizeResult, ToDart(status), ToDart(size)); +} + +zx_status_t System::VmoSetSize(fml::RefPtr vmo, uint64_t size) { + if (!vmo || !vmo->is_valid()) { + return ZX_ERR_BAD_HANDLE; + } + return zx_vmo_set_size(vmo->handle(), size); +} + +zx_status_t System::VmoWrite(fml::RefPtr vmo, + uint64_t offset, + const tonic::DartByteData& data) { + if (!vmo || !vmo->is_valid()) { + data.Release(); + return ZX_ERR_BAD_HANDLE; + } + + zx_status_t status = + zx_vmo_write(vmo->handle(), data.data(), offset, data.length_in_bytes()); + + data.Release(); + return status; +} + +Dart_Handle System::VmoRead(fml::RefPtr vmo, + uint64_t offset, + size_t size) { + if (!vmo || !vmo->is_valid()) { + return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE)); + } + + // TODO: constrain size? + ByteDataScope bytes(size); + zx_status_t status = zx_vmo_read(vmo->handle(), bytes.data(), offset, size); + bytes.Release(); + if (status == ZX_OK) { + return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(), + ToDart(size)); + } + return ConstructDartObject(kReadResult, ToDart(status)); +} + +struct SizedRegion { + SizedRegion(void* r, size_t s) : region(r), size(s) {} + void* region; + size_t size; +}; + +void System::VmoMapFinalizer(void* isolate_callback_data, + Dart_WeakPersistentHandle handle, + void* peer) { + SizedRegion* r = reinterpret_cast(peer); + zx_vmar_unmap(zx_vmar_root_self(), reinterpret_cast(r->region), + r->size); + delete r; +} + +Dart_Handle System::VmoMap(fml::RefPtr vmo) { + if (!vmo || !vmo->is_valid()) + return ConstructDartObject(kMapResult, ToDart(ZX_ERR_BAD_HANDLE)); + + uint64_t size; + zx_status_t status = zx_vmo_get_size(vmo->handle(), &size); + if (status != ZX_OK) + return ConstructDartObject(kMapResult, ToDart(status)); + + uintptr_t mapped_addr; + status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo->handle(), + 0, size, &mapped_addr); + if (status != ZX_OK) + return ConstructDartObject(kMapResult, ToDart(status)); + + void* data = reinterpret_cast(mapped_addr); + Dart_Handle object = Dart_NewExternalTypedData(Dart_TypedData_kUint8, data, + static_cast(size)); + FML_DCHECK(!tonic::LogIfError(object)); + + SizedRegion* r = new SizedRegion(data, size); + Dart_NewWeakPersistentHandle(object, reinterpret_cast(r), + static_cast(size) + sizeof(*r), + System::VmoMapFinalizer); + + return ConstructDartObject(kMapResult, ToDart(ZX_OK), object); +} + +uint64_t System::ClockGet(uint32_t clock_id) { + return zx_clock_get(clock_id); +} + +// clang-format: off + +#define FOR_EACH_STATIC_BINDING(V) \ + V(System, ChannelCreate) \ + V(System, ChannelFromFile) \ + V(System, ChannelWrite) \ + V(System, ChannelQueryAndRead) \ + V(System, EventpairCreate) \ + V(System, Reboot) \ + V(System, SocketCreate) \ + V(System, SocketWrite) \ + V(System, SocketRead) \ + V(System, VmoCreate) \ + V(System, VmoFromFile) \ + V(System, VmoGetSize) \ + V(System, VmoSetSize) \ + V(System, VmoRead) \ + V(System, VmoWrite) \ + V(System, VmoMap) \ + V(System, ClockGet) + +// clang-format: on + +// Tonic is missing a comma. +#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ + DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), + +FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) + +void System::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_)}); +} + +} // namespace dart +} // namespace zircon diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h new file mode 100644 index 0000000000..916eacd290 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.h @@ -0,0 +1,70 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_ +#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_ + +#include + +#include "handle.h" +#include "third_party/dart/runtime/include/dart_api.h" +#include "third_party/tonic/dart_library_natives.h" +#include "third_party/tonic/dart_wrappable.h" +#include "third_party/tonic/typed_data/dart_byte_data.h" + +namespace zircon { +namespace dart { + +class System : public fml::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FML_FRIEND_REF_COUNTED_THREAD_SAFE(System); + FML_FRIEND_MAKE_REF_COUNTED(System); + + public: + static Dart_Handle ChannelCreate(uint32_t options); + static Dart_Handle ChannelFromFile(std::string path); + static zx_status_t ChannelWrite(fml::RefPtr channel, + const tonic::DartByteData& data, + std::vector handles); + // TODO(ianloic): Add ChannelRead + static Dart_Handle ChannelQueryAndRead(fml::RefPtr channel); + + static Dart_Handle EventpairCreate(uint32_t options); + + static Dart_Handle SocketCreate(uint32_t options); + static Dart_Handle SocketWrite(fml::RefPtr socket, + const tonic::DartByteData& data, + int options); + static Dart_Handle SocketRead(fml::RefPtr socket, size_t size); + + static Dart_Handle VmoCreate(uint64_t size, uint32_t options); + static Dart_Handle VmoFromFile(std::string path); + static Dart_Handle VmoGetSize(fml::RefPtr vmo); + static zx_status_t VmoSetSize(fml::RefPtr vmo, uint64_t size); + static zx_status_t VmoWrite(fml::RefPtr vmo, + uint64_t offset, + const tonic::DartByteData& data); + static Dart_Handle VmoRead(fml::RefPtr vmo, + uint64_t offset, + size_t size); + + static Dart_Handle VmoMap(fml::RefPtr vmo); + + static uint64_t ClockGet(uint32_t clock_id); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + static zx_status_t Reboot(); + + private: + static void VmoMapFinalizer(void* isolate_callback_data, + Dart_WeakPersistentHandle handle, + void* peer); +}; + +} // namespace dart +} // namespace zircon + +#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_SYSTEM_H_ diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/channel_test.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/channel_test.dart new file mode 100644 index 0000000000..31d04fcb23 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/channel_test.dart @@ -0,0 +1,107 @@ +// Copyright 2013 The Flutter 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 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:test/test.dart'; +import 'package:zircon/zircon.dart'; + +/// Helper method to turn a [String] into a [ByteData] containing the +/// text of the string encoded as UTF-8. +ByteData utf8Bytes(final String text) { + return ByteData.view(Uint8List.fromList(utf8.encode(text)).buffer); +} + +void main() { + test('create channel', () { + final HandlePairResult pair = System.channelCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + }); + + test('close channel', () { + final HandlePairResult pair = System.channelCreate(); + expect(pair.first.close(), equals(0)); + expect(pair.first.isValid, isFalse); + expect(pair.second.isValid, isTrue); + expect(System.channelWrite(pair.first, ByteData(1), []), + equals(ZX.ERR_BAD_HANDLE)); + expect(System.channelWrite(pair.second, ByteData(1), []), + equals(ZX.ERR_PEER_CLOSED)); + }); + + test('channel bytes', () { + final HandlePairResult pair = System.channelCreate(); + + // When no data is available, ZX.ERR_SHOULD_WAIT is returned. + expect(System.channelQueryAndRead(pair.second).status, + equals(ZX.ERR_SHOULD_WAIT)); + + // Write bytes. + final ByteData data = utf8Bytes('Hello, world'); + final int status = System.channelWrite(pair.first, data, []); + expect(status, equals(ZX.OK)); + + // Read bytes. + final ReadResult readResult = System.channelQueryAndRead(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(data.lengthInBytes)); + expect(readResult.bytes.lengthInBytes, equals(data.lengthInBytes)); + expect(readResult.bytesAsUTF8String(), equals('Hello, world')); + expect(readResult.handles.length, equals(0)); + }); + + test('channel handles', () { + final HandlePairResult pair = System.channelCreate(); + final ByteData data = utf8Bytes(''); + final HandlePairResult eventPair = System.eventpairCreate(); + final int status = + System.channelWrite(pair.first, data, [eventPair.first]); + expect(status, equals(ZX.OK)); + expect(eventPair.first.isValid, isFalse); + + final ReadResult readResult = System.channelQueryAndRead(pair.second); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(0)); + expect(readResult.bytes.lengthInBytes, equals(0)); + expect(readResult.bytesAsUTF8String(), equals('')); + expect(readResult.handles.length, equals(1)); + expect(readResult.handles[0].isValid, isTrue); + }); + + test('async wait channel read', () async { + final HandlePairResult pair = System.channelCreate(); + final Completer> completer = Completer>(); + pair.first.asyncWait(ZX.CHANNEL_READABLE, (int status, int pending) { + completer.complete([status, pending]); + }); + + expect(completer.isCompleted, isFalse); + + System.channelWrite(pair.second, utf8Bytes('Hi'), []); + + final List result = await completer.future; + expect(result[0], equals(ZX.OK)); // status + expect(result[1] & ZX.CHANNEL_READABLE, + equals(ZX.CHANNEL_READABLE)); // pending + }); + + test('async wait channel closed', () async { + final HandlePairResult pair = System.channelCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.CHANNEL_PEER_CLOSED, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + + pair.second.close(); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/eventpair_test.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/eventpair_test.dart new file mode 100644 index 0000000000..aa133bb599 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/eventpair_test.dart @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter 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 'dart:async'; + +import 'package:test/test.dart'; +import 'package:zircon/zircon.dart'; + +void main() { + group('eventpair: ', () { + test('create', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + }); + + test('duplicate', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + expect(pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS).isValid, isTrue); + expect(pair.second.duplicate(ZX.RIGHT_SAME_RIGHTS).isValid, isTrue); + }); + + test('close', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.first.close(), equals(0)); + expect(pair.first.isValid, isFalse); + expect(pair.second.isValid, isTrue); + + expect(pair.second.close(), equals(0)); + expect(pair.second.isValid, isFalse); + }); + + test('async wait peer closed', () async { + final HandlePairResult pair = System.eventpairCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(EventPair.PEER_CLOSED, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + pair.second.close(); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); + }); +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/handle_test.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/handle_test.dart new file mode 100644 index 0000000000..fc0ce8d63f --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/handle_test.dart @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter 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 'package:test/test.dart'; +import 'package:zircon/zircon.dart'; + +void main() { + test('create and duplicate handle', () { + final HandlePairResult pair = System.eventpairCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + + final Handle duplicate = pair.first.duplicate(ZX.RIGHT_SAME_RIGHTS); + expect(duplicate.isValid, isTrue); + + final Handle failedDuplicate = pair.first.duplicate(-1); + expect(failedDuplicate.isValid, isFalse); + }); + + test('failure invalid handle', () { + final Handle handle = Handle.invalid(); + final Handle duplicate = handle.duplicate(ZX.RIGHT_SAME_RIGHTS); + expect(duplicate.isValid, isFalse); + }); +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/socket_test.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/socket_test.dart new file mode 100644 index 0000000000..8fbb728feb --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/socket_test.dart @@ -0,0 +1,129 @@ +// Copyright 2013 The Flutter 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 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:test/test.dart'; +import 'package:zircon/zircon.dart'; + +/// Helper method to turn a [String] into a [ByteData] containing the +/// text of the string encoded as UTF-8. +ByteData utf8Bytes(final String text) { + return ByteData.view(Uint8List.fromList(utf8.encode(text)).buffer); +} + +void main() { + // NOTE: This only tests stream sockets. + // We should add tests for datagram sockets. + + test('create socket', () { + final HandlePairResult pair = System.socketCreate(); + expect(pair.status, equals(ZX.OK)); + expect(pair.first.isValid, isTrue); + expect(pair.second.isValid, isTrue); + }); + + test('close socket', () { + final HandlePairResult pair = System.socketCreate(); + expect(pair.first.close(), equals(0)); + expect(pair.first.isValid, isFalse); + expect(pair.second.isValid, isTrue); + final WriteResult firstResult = + System.socketWrite(pair.first, ByteData(1), 0); + expect(firstResult.status, equals(ZX.ERR_BAD_HANDLE)); + final WriteResult secondResult = + System.socketWrite(pair.second, ByteData(1), 0); + expect(secondResult.status, equals(ZX.ERR_PEER_CLOSED)); + }); + + test('read write socket', () { + final HandlePairResult pair = System.socketCreate(); + + // When no data is available, ZX.ERR_SHOULD_WAIT is returned. + expect( + System.socketRead(pair.second, 1).status, equals(ZX.ERR_SHOULD_WAIT)); + + final ByteData data = utf8Bytes('Hello, world'); + final WriteResult writeResult = System.socketWrite(pair.first, data, 0); + expect(writeResult.status, equals(ZX.OK)); + + final ReadResult readResult = + System.socketRead(pair.second, data.lengthInBytes); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals(data.lengthInBytes)); + expect(readResult.bytes.lengthInBytes, equals(data.lengthInBytes)); + expect(readResult.bytesAsUTF8String(), equals('Hello, world')); + }); + + test('partial read socket', () { + final HandlePairResult pair = System.socketCreate(); + final ByteData data = utf8Bytes('Hello, world'); + final WriteResult writeResult = System.socketWrite(pair.first, data, 0); + expect(writeResult.status, equals(ZX.OK)); + + const int shortLength = 'Hello'.length; + final ReadResult shortReadResult = + System.socketRead(pair.second, shortLength); + expect(shortReadResult.status, equals(ZX.OK)); + expect(shortReadResult.numBytes, equals(shortLength)); + expect(shortReadResult.bytes.lengthInBytes, equals(shortLength)); + expect(shortReadResult.bytesAsUTF8String(), equals('Hello')); + + final int longLength = data.lengthInBytes * 2; + final ReadResult longReadResult = + System.socketRead(pair.second, longLength); + expect(longReadResult.status, equals(ZX.OK)); + expect(longReadResult.numBytes, equals(data.lengthInBytes - shortLength)); + expect(longReadResult.bytes.lengthInBytes, equals(longLength)); + expect(longReadResult.bytesAsUTF8String(), equals(', world')); + }); + + test('partial write socket', () { + final HandlePairResult pair = System.socketCreate(); + final WriteResult writeResult1 = + System.socketWrite(pair.first, utf8Bytes('Hello, '), 0); + expect(writeResult1.status, equals(ZX.OK)); + final WriteResult writeResult2 = + System.socketWrite(pair.first, utf8Bytes('world'), 0); + expect(writeResult2.status, equals(ZX.OK)); + + final ReadResult readResult = System.socketRead(pair.second, 100); + expect(readResult.status, equals(ZX.OK)); + expect(readResult.numBytes, equals('Hello, world'.length)); + expect(readResult.bytes.lengthInBytes, equals(100)); + expect(readResult.bytesAsUTF8String(), equals('Hello, world')); + }); + + test('async wait socket read', () async { + final HandlePairResult pair = System.socketCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.SOCKET_READABLE, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + + System.socketWrite(pair.second, utf8Bytes('Hi'), 0); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); + + test('async wait socket closed', () async { + final HandlePairResult pair = System.socketCreate(); + final Completer completer = Completer(); + pair.first.asyncWait(ZX.SOCKET_PEER_CLOSED, (int status, int pending) { + completer.complete(status); + }); + + expect(completer.isCompleted, isFalse); + + pair.second.close(); + + final int status = await completer.future; + expect(status, equals(ZX.OK)); + }); +} diff --git a/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/vmo_test.dart b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/vmo_test.dart new file mode 100644 index 0000000000..ca72cd9f49 --- /dev/null +++ b/engine/src/flutter/shell/platform/fuchsia/dart-pkg/zircon/test/vmo_test.dart @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter 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 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:test/test.dart'; +import 'package:zircon/zircon.dart'; + +void main() { + group('test vmo', () { + test('fromFile', () { + const String fuchsia = 'Fuchsia'; + File f = File('tmp/testdata') + ..createSync() + ..writeAsStringSync(fuchsia); + String readFuchsia = f.readAsStringSync(); + expect(readFuchsia, equals(fuchsia)); + + SizedVmo fileVmo = SizedVmo.fromFile('tmp/testdata'); + Uint8List fileData = fileVmo.map(); + String fileString = utf8.decode(fileData.sublist(0, fileVmo.size)); + expect(fileString, equals(fuchsia)); + }); + + test('duplicate', () { + const String fuchsia = 'Fuchsia'; + Uint8List data = Uint8List.fromList(fuchsia.codeUnits); + SizedVmo vmo = SizedVmo.fromUint8List(data); + final Vmo duplicate = + vmo.duplicate(ZX.RIGHTS_BASIC | ZX.RIGHT_READ | ZX.RIGHT_MAP); + expect(duplicate.isValid, isTrue); + + // Read from the duplicate. + final duplicatedVmo = SizedVmo(duplicate.handle, fuchsia.length); + Uint8List vmoData = duplicatedVmo.map(); + String vmoString = utf8.decode(vmoData.sublist(0, vmo.size)); + expect(vmoString, equals(fuchsia)); + }); + }); +}