1 // Copyright 2020 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "base/fuchsia/process_context.h" 6 7 #include <fidl/fuchsia.io/cpp/hlcpp_conversion.h> 8 #include <lib/sys/cpp/component_context.h> 9 10 #include <utility> 11 12 #include "base/no_destructor.h" 13 14 namespace base { 15 16 namespace { 17 GetComponentContextPtr()18std::unique_ptr<sys::ComponentContext>* GetComponentContextPtr() { 19 static base::NoDestructor<std::unique_ptr<sys::ComponentContext>> value( 20 std::make_unique<sys::ComponentContext>( 21 sys::ServiceDirectory::CreateFromNamespace())); 22 return value.get(); 23 } 24 GetIncomingServiceDirectory()25fidl::ClientEnd<fuchsia_io::Directory>* GetIncomingServiceDirectory() { 26 static base::NoDestructor<fidl::ClientEnd<fuchsia_io::Directory>> value( 27 fidl::HLCPPToNatural( 28 GetComponentContextPtr()->get()->svc()->CloneChannel())); 29 return value.get(); 30 } 31 32 } // namespace 33 34 // TODO(crbug.com/1416555): This need to either be changed or removed when 35 // TestComponentContextForProcess is migrated to Natural bindings. ComponentContextForProcess()36sys::ComponentContext* ComponentContextForProcess() { 37 return GetComponentContextPtr()->get(); 38 } 39 40 fidl::UnownedClientEnd<fuchsia_io::Directory> BorrowIncomingServiceDirectoryForProcess()41BorrowIncomingServiceDirectoryForProcess() { 42 return GetIncomingServiceDirectory()->borrow(); 43 } 44 45 // Replaces the component context singleton value with the passed context. The 46 // incoming service directory client end is also re-mapped to the new context's 47 // outgoing directory. 48 // TODO(crbug.com/1416555): Rework this to support the natural binding backed 49 // TestComponentContextForProcess. ReplaceComponentContextForProcessForTest(std::unique_ptr<sys::ComponentContext> context)50std::unique_ptr<sys::ComponentContext> ReplaceComponentContextForProcessForTest( 51 std::unique_ptr<sys::ComponentContext> context) { 52 std::swap(*GetComponentContextPtr(), context); 53 // Hold onto a client end that's connected to the incoming service directory 54 // to limit the number of channels open to the incoming service directory. 55 fidl::ClientEnd<fuchsia_io::Directory> incoming_service_directory( 56 fidl::HLCPPToNatural( 57 GetComponentContextPtr()->get()->svc()->CloneChannel())); 58 std::swap(*GetIncomingServiceDirectory(), incoming_service_directory); 59 return context; 60 } 61 62 } // namespace base 63