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
15namespace 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.
27class DartVMRef {
28 public:
29 [[nodiscard]] static DartVMRef Create(
30 Settings settings,
31 fml::RefPtr<DartSnapshot> vm_snapshot = nullptr,
32 fml::RefPtr<DartSnapshot> isolate_snapshot = nullptr);
33
34 DartVMRef(DartVMRef&&);
35
36 ~DartVMRef();
37
38 // This is an inherently racy way to check if a VM instance is running and
39 // should not be used outside of unit-tests where there is a known threading
40 // model.
41 static bool IsInstanceRunning();
42
43 static std::shared_ptr<const DartVMData> GetVMData();
44
45 static std::shared_ptr<ServiceProtocol> GetServiceProtocol();
46
47 static std::shared_ptr<IsolateNameServer> GetIsolateNameServer();
48
49 operator bool() const { return static_cast<bool>(vm_); }
50
51 DartVM* get() {
52 FML_DCHECK(vm_);
53 return vm_.get();
54 }
55
56 DartVM* operator->() {
57 FML_DCHECK(vm_);
58 return vm_.get();
59 }
60
61 DartVM* operator&() {
62 FML_DCHECK(vm_);
63 return vm_.get();
64 }
65
66 private:
67 friend class DartIsolate;
68
69 std::shared_ptr<DartVM> vm_;
70
71 DartVMRef(std::shared_ptr<DartVM> vm);
72
73 // Only used by Dart Isolate to register itself with the VM.
74 static DartVM* GetRunningVM();
75
76 FML_DISALLOW_COPY_AND_ASSIGN(DartVMRef);
77};
78
79} // namespace flutter
80
81#endif // FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_
82