1 // Copyright 2013 The Flutter 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. 4 5 #ifndef FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_ 6 #define FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_ 7 8 #include <memory> 9 10 #include "flutter/fml/macros.h" 11 #include "flutter/lib/ui/isolate_name_server/isolate_name_server.h" 12 #include "flutter/runtime/dart_vm.h" 13 #include "flutter/runtime/service_protocol.h" 14 15 namespace flutter { 16 17 // A strong reference to the Dart VM. There can only be one VM running in the 18 // process at any given time. A reference to the VM may only be obtained via the 19 // |Create| method. In case there is already a running instance of the VM in the 20 // process, a strong reference to that VM is obtained and the arguments to the 21 // |Create| call ignored. If there is no VM already running in the process, a VM 22 // is initialized in a thread safe manner and returned to the caller. The VM 23 // will shutdown only when all callers relinquish their references (by 24 // collecting their instances of this class). 25 // 26 // DartVMRef instances may be created on any thread. 27 class DartVMRef { 28 public: 29 FML_WARN_UNUSED_RESULT 30 static DartVMRef Create(Settings settings, 31 fml::RefPtr<DartSnapshot> vm_snapshot = nullptr, 32 fml::RefPtr<DartSnapshot> isolate_snapshot = nullptr, 33 fml::RefPtr<DartSnapshot> shared_snapshot = nullptr); 34 35 DartVMRef(DartVMRef&&); 36 37 ~DartVMRef(); 38 39 // This is an inherently racy way to check if a VM instance is running and 40 // should not be used outside of unit-tests where there is a known threading 41 // model. 42 static bool IsInstanceRunning(); 43 44 static std::shared_ptr<const DartVMData> GetVMData(); 45 46 static std::shared_ptr<ServiceProtocol> GetServiceProtocol(); 47 48 static std::shared_ptr<IsolateNameServer> GetIsolateNameServer(); 49 50 operator bool() const { return static_cast<bool>(vm_); } 51 get()52 DartVM* get() { 53 FML_DCHECK(vm_); 54 return vm_.get(); 55 } 56 57 DartVM* operator->() { 58 FML_DCHECK(vm_); 59 return vm_.get(); 60 } 61 62 DartVM* operator&() { 63 FML_DCHECK(vm_); 64 return vm_.get(); 65 } 66 67 private: 68 friend class DartIsolate; 69 70 std::shared_ptr<DartVM> vm_; 71 72 DartVMRef(std::shared_ptr<DartVM> vm); 73 74 // Only used by Dart Isolate to register itself with the VM. 75 static DartVM* GetRunningVM(); 76 77 FML_DISALLOW_COPY_AND_ASSIGN(DartVMRef); 78 }; 79 80 } // namespace flutter 81 82 #endif // FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_ 83