-
Notifications
You must be signed in to change notification settings - Fork 25.2k
Expand file tree
/
Copy pathInstance.cpp
More file actions
329 lines (281 loc) · 11 KB
/
Instance.cpp
File metadata and controls
329 lines (281 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "Instance.h"
#ifndef RCT_REMOVE_LEGACY_ARCH
#include "ErrorUtils.h"
#include "JSBigString.h"
#include "JSBundleType.h"
#include "JSExecutor.h"
#include "MessageQueueThread.h"
#include "MethodCall.h"
#include "NativeToJsBridge.h"
#include "RAMBundleRegistry.h"
#include "RecoverableError.h"
#include "TraceSection.h"
#include <folly/json.h>
#include <react/debug/react_native_assert.h>
#include <glog/logging.h>
#include <condition_variable>
#include <exception>
#include <memory>
#include <mutex>
#include <string>
namespace facebook::react {
Instance::~Instance() {
if (nativeToJsBridge_) {
nativeToJsBridge_->destroy();
}
}
void Instance::unregisterFromInspector() {
if (inspectorTarget_ != nullptr) {
assert(runtimeInspectorTarget_);
inspectorTarget_->unregisterRuntime(*runtimeInspectorTarget_);
assert(parentInspectorTarget_);
parentInspectorTarget_->unregisterInstance(*inspectorTarget_);
parentInspectorTarget_ = nullptr;
inspectorTarget_ = nullptr;
}
}
void Instance::initializeBridge(
std::unique_ptr<InstanceCallback> callback,
std::shared_ptr<JSExecutorFactory> jsef,
std::shared_ptr<MessageQueueThread> jsQueue,
std::shared_ptr<ModuleRegistry> moduleRegistry,
jsinspector_modern::HostTarget* parentInspectorTarget) {
callback_ = std::move(callback);
moduleRegistry_ = std::move(moduleRegistry);
parentInspectorTarget_ = parentInspectorTarget;
jsQueue->runOnQueueSync([this, &jsef, jsQueue]() mutable {
nativeToJsBridge_ = std::make_shared<NativeToJsBridge>(
jsef.get(), moduleRegistry_, jsQueue, callback_);
// If a parent inspector HostTarget is provided, perform inspector
// initialization synchronously.
if (parentInspectorTarget_ != nullptr) {
auto inspectorExecutor = parentInspectorTarget_->executorFromThis();
std::mutex inspectorInitializedMutex;
std::condition_variable inspectorInitializedCv;
bool inspectorInitialized = false;
// Schedule work on the inspector thread. NOTE: We expect this callback
// to always execute, given the invariant that `initializeBridge` (this
// method) completes before `unregisterFromInspector` is called.
// - On iOS, instance creation and invalidation both run on the main
// queue (`RCTCxxBridge::start,invalidate` use `RCTAssertMainQueue`).
// - On Android, `ReactContext` must be initialized with a constructed
// `CatalystInstance` (in which `Instance::initializeBridge` has
// completed) before `destroy` can be called.
inspectorExecutor([this,
&inspectorInitialized,
&inspectorInitializedMutex,
&inspectorInitializedCv](
jsinspector_modern::HostTarget& hostTarget) {
// NOTE: By passing *this, we strongly assume the Instance will still
// be alive by the time this executes.
// - On iOS, instance creation is done synchronously
// (`RCTCxxBridge::_initializeBridgeLocked`).
// - On Android, we explicitly wait for instance creation before
// destruction (`ReactInstanceManager::mReactContextLock`).
inspectorTarget_ = &hostTarget.registerInstance(*this);
RuntimeExecutor runtimeExecutorIfJsi = getRuntimeExecutor();
runtimeInspectorTarget_ = &inspectorTarget_->registerRuntime(
nativeToJsBridge_->getInspectorTargetDelegate(),
runtimeExecutorIfJsi ? runtimeExecutorIfJsi : [](auto) {});
// Signal that initialization is complete
{
std::lock_guard lock(inspectorInitializedMutex);
inspectorInitialized = true;
}
inspectorInitializedCv.notify_one();
});
// Wait for the initialization work to complete
{
std::unique_lock lock(inspectorInitializedMutex);
inspectorInitializedCv.wait(
lock, [&inspectorInitialized] { return inspectorInitialized; });
}
}
// Initialize the JavaScript runtime after we've initialized the inspector
nativeToJsBridge_->initializeRuntime();
// After NativeToJsBridge is created, the jsi::Runtime should exist. Also,
// the JS message queue thread exists. So, it's safe to schedule all queued
// up JS calls.
jsCallInvoker_->setNativeToJsBridgeAndFlushCalls(nativeToJsBridge_);
std::scoped_lock lock(m_syncMutex);
m_syncReady = true;
m_syncCV.notify_all();
});
CHECK(nativeToJsBridge_);
}
void Instance::loadBundle(
std::unique_ptr<RAMBundleRegistry> bundleRegistry,
std::unique_ptr<const JSBigString> startupScript,
std::string sourceURL) {
callback_->incrementPendingJSCalls();
TraceSection s("Instance::loadBundle", "sourceURL", sourceURL);
nativeToJsBridge_->loadBundle(
std::move(bundleRegistry),
std::move(startupScript),
std::move(sourceURL));
}
void Instance::loadBundleSync(
std::unique_ptr<RAMBundleRegistry> bundleRegistry,
std::unique_ptr<const JSBigString> startupScript,
std::string sourceURL) {
std::unique_lock<std::mutex> lock(m_syncMutex);
m_syncCV.wait(lock, [this] { return m_syncReady; });
TraceSection s("Instance::loadBundleSync", "sourceURL", sourceURL);
nativeToJsBridge_->loadBundleSync(
std::move(bundleRegistry),
std::move(startupScript),
std::move(sourceURL));
}
void Instance::setSourceURL(std::string sourceURL) {
callback_->incrementPendingJSCalls();
TraceSection s("Instance::setSourceURL", "sourceURL", sourceURL);
nativeToJsBridge_->loadBundle(nullptr, nullptr, std::move(sourceURL));
}
void Instance::loadScriptFromString(
std::unique_ptr<const JSBigString> string,
std::string sourceURL,
bool loadSynchronously) {
TraceSection s("Instance::loadScriptFromString", "sourceURL", sourceURL);
if (loadSynchronously) {
loadBundleSync(nullptr, std::move(string), std::move(sourceURL));
} else {
loadBundle(nullptr, std::move(string), std::move(sourceURL));
}
}
void Instance::setGlobalVariable(
std::string propName,
std::unique_ptr<const JSBigString> jsonValue) {
nativeToJsBridge_->setGlobalVariable(
std::move(propName), std::move(jsonValue));
}
void* Instance::getJavaScriptContext() {
return nativeToJsBridge_ ? nativeToJsBridge_->getJavaScriptContext()
: nullptr;
}
bool Instance::isInspectable() {
return nativeToJsBridge_ ? nativeToJsBridge_->isInspectable() : false;
}
bool Instance::isBatchActive() {
return nativeToJsBridge_ ? nativeToJsBridge_->isBatchActive() : false;
}
void Instance::callJSFunction(
std::string&& module,
std::string&& method,
folly::dynamic&& params) {
callback_->incrementPendingJSCalls();
nativeToJsBridge_->callFunction(
std::move(module), std::move(method), std::move(params));
}
void Instance::callJSCallback(uint64_t callbackId, folly::dynamic&& params) {
TraceSection s("Instance::callJSCallback");
callback_->incrementPendingJSCalls();
nativeToJsBridge_->invokeCallback((double)callbackId, std::move(params));
}
void Instance::registerBundle(
uint32_t bundleId,
const std::string& bundlePath) {
nativeToJsBridge_->registerBundle(bundleId, bundlePath);
}
const ModuleRegistry& Instance::getModuleRegistry() const {
return *moduleRegistry_;
}
ModuleRegistry& Instance::getModuleRegistry() {
return *moduleRegistry_;
}
void Instance::handleMemoryPressure(int pressureLevel) {
if (nativeToJsBridge_) {
// This class resets `nativeToJsBridge_` only in the destructor,
// hence a race is not possible there.
nativeToJsBridge_->handleMemoryPressure(pressureLevel);
}
}
std::shared_ptr<CallInvoker> Instance::getJSCallInvoker() {
return std::static_pointer_cast<CallInvoker>(jsCallInvoker_);
}
RuntimeExecutor Instance::getRuntimeExecutor() {
// HACK: RuntimeExecutor is not compatible with non-JSIExecutor, we return
// a null callback, which the caller should handle.
if (getJavaScriptContext() == nullptr) {
return nullptr;
}
std::weak_ptr<NativeToJsBridge> weakNativeToJsBridge = nativeToJsBridge_;
return [weakNativeToJsBridge](
std::function<void(jsi::Runtime & runtime)>&& callback) {
if (auto strongNativeToJsBridge = weakNativeToJsBridge.lock()) {
strongNativeToJsBridge->runOnExecutorQueue(
[callback = std::move(callback)](JSExecutor* executor) {
// Assumes the underlying executor is a JSIExecutor
auto* runtime =
static_cast<jsi::Runtime*>(executor->getJavaScriptContext());
try {
react_native_assert(runtime != nullptr);
callback(*runtime);
executor->flush();
} catch (jsi::JSError& originalError) {
handleJSError(*runtime, originalError, true);
}
});
}
};
}
std::shared_ptr<NativeMethodCallInvoker>
Instance::getDecoratedNativeMethodCallInvoker(
std::shared_ptr<NativeMethodCallInvoker> nativeMethodCallInvoker) {
return nativeToJsBridge_->getDecoratedNativeMethodCallInvoker(
nativeMethodCallInvoker);
}
void Instance::JSCallInvoker::setNativeToJsBridgeAndFlushCalls(
std::weak_ptr<NativeToJsBridge> nativeToJsBridge) {
std::scoped_lock guard(m_mutex);
m_shouldBuffer = false;
m_nativeToJsBridge = nativeToJsBridge;
while (!m_workBuffer.empty()) {
scheduleAsync(std::move(m_workBuffer.front()));
m_workBuffer.pop_front();
}
}
void Instance::JSCallInvoker::invokeSync(CallFunc&& /*work*/) {
// TODO: Replace JS Callinvoker with RuntimeExecutor.
throw std::runtime_error(
"Synchronous native -> JS calls are currently not supported.");
}
void Instance::JSCallInvoker::invokeAsync(CallFunc&& work) noexcept {
std::scoped_lock guard(m_mutex);
/**
* Why is is necessary to queue up async work?
*
* 1. TurboModuleManager must be created synchronously after the Instance,
* before we load the source code. This is when the NativeModule system
* is initialized. RCTDevLoadingView shows bundle download progress.
* 2. TurboModuleManager requires a JS CallInvoker.
* 3. The JS CallInvoker requires the NativeToJsBridge, which is created on
* the JS thread in Instance::initializeBridge.
*
* Therefore, although we don't call invokeAsync before the JS bundle is
* executed, this buffering is implemented anyways to ensure that work
* isn't discarded.
*/
if (m_shouldBuffer) {
m_workBuffer.push_back(std::move(work));
return;
}
scheduleAsync(std::move(work));
}
void Instance::JSCallInvoker::scheduleAsync(CallFunc&& work) noexcept {
if (auto strongNativeToJsBridge = m_nativeToJsBridge.lock()) {
strongNativeToJsBridge->runOnExecutorQueue(
[work = std::move(work)](JSExecutor* executor) {
auto* runtime = (jsi::Runtime*)executor->getJavaScriptContext();
work(*runtime);
executor->flush();
});
}
}
} // namespace facebook::react
#endif // RCT_REMOVE_LEGACY_ARCH