1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/fuchsia/service_directory_client.h"
7 #include <lib/fdio/directory.h>
10 #include "base/fuchsia/file_utils.h"
11 #include "base/fuchsia/fuchsia_logging.h"
12 #include "base/logging.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/no_destructor.h"
19 ServiceDirectoryClient::ServiceDirectoryClient(
20 fidl::InterfaceHandle<::fuchsia::io::Directory> directory)
21 : directory_(std::move(directory)) {
25 ServiceDirectoryClient::~ServiceDirectoryClient() = default;
28 const ServiceDirectoryClient* ServiceDirectoryClient::ForCurrentProcess() {
29 return ServiceDirectoryClient::ProcessInstance()->get();
32 zx_status_t ServiceDirectoryClient::ConnectToServiceUnsafe(
34 zx::channel request) const {
35 DCHECK(request.is_valid());
36 return fdio_service_connect_at(directory_.channel().get(), name,
40 ServiceDirectoryClient::ServiceDirectoryClient() {}
43 std::unique_ptr<ServiceDirectoryClient>
44 ServiceDirectoryClient::CreateForProcess() {
45 fidl::InterfaceHandle<::fuchsia::io::Directory> directory =
46 OpenDirectory(base::FilePath(kServiceDirectoryPath));
48 return std::make_unique<ServiceDirectoryClient>(std::move(directory));
49 LOG(WARNING) << "/svc is not available.";
50 return base::WrapUnique(new ServiceDirectoryClient);
54 std::unique_ptr<ServiceDirectoryClient>*
55 ServiceDirectoryClient::ProcessInstance() {
56 static base::NoDestructor<std::unique_ptr<ServiceDirectoryClient>>
57 service_directory_client_ptr(CreateForProcess());
58 return service_directory_client_ptr.get();
61 ScopedServiceDirectoryClientForCurrentProcessForTest::
62 ScopedServiceDirectoryClientForCurrentProcessForTest(
63 fidl::InterfaceHandle<::fuchsia::io::Directory> directory)
64 : old_client_(std::move(*ServiceDirectoryClient::ProcessInstance())) {
65 *ServiceDirectoryClient::ProcessInstance() =
66 std::make_unique<ServiceDirectoryClient>(std::move(directory));
67 client_ = ServiceDirectoryClient::ProcessInstance()->get();
70 ScopedServiceDirectoryClientForCurrentProcessForTest::
71 ~ScopedServiceDirectoryClientForCurrentProcessForTest() {
72 DCHECK_EQ(ServiceDirectoryClient::ProcessInstance()->get(), client_);
73 *ServiceDirectoryClient::ProcessInstance() = std::move(old_client_);
76 } // namespace fuchsia