Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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 "JSEvaluationObserver.h"

#include <algorithm>
#include <mutex>
#include <vector>

namespace facebook::react {

namespace {

struct JSEvaluationObservers {
std::mutex mutex;
std::vector<JSEvaluationObserver> observers;
uint64_t evaluations{0};
};

// Constructed on first use, so an observer added from a static initializer in
// another library finds it ready.
JSEvaluationObservers& jsEvaluationObservers() {
static auto* observers = new JSEvaluationObservers();
return *observers;
}

} // namespace

uint64_t addJSEvaluationObserver(JSEvaluationObserver observer) {
auto& state = jsEvaluationObservers();
const std::lock_guard lock(state.mutex);
if (observer != nullptr &&
std::find(state.observers.begin(), state.observers.end(), observer) ==
state.observers.end()) {
state.observers.push_back(observer);
}
return state.evaluations;
}

void removeJSEvaluationObserver(JSEvaluationObserver observer) {
auto& state = jsEvaluationObservers();
const std::lock_guard lock(state.mutex);
std::erase(state.observers, observer);
}

void notifyJSEvaluation(
JSEvaluationKind kind,
const uint8_t* data,
size_t size,
const std::string& sourceURL) {
std::vector<JSEvaluationObserver> observers;
{
auto& state = jsEvaluationObservers();
const std::lock_guard lock(state.mutex);
++state.evaluations;
observers = state.observers;
}
for (auto observer : observers) {
try {
observer(kind, data, size, sourceURL);
} catch (...) {
// An observer must not stop JavaScript from loading.
}
}
}

} // namespace facebook::react
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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.
*/

#pragma once

#include <react/cxxstableapi/FrameworksGuard.h>

#include <cstddef>
#include <cstdint>
#include <string>

#ifndef RN_EXPORT
#define RN_EXPORT __attribute__((visibility("default")))
#endif

namespace facebook::react {

/// How React Native came to evaluate a piece of JavaScript.
enum class JSEvaluationKind {
/// The main bundle a host loads.
Bundle,
/// A segment registered from a file.
Segment,
/// Source evaluated through `globalEvalWithSourceUrl`: lazy segments
/// fetched from a dev server, and Fast Refresh updates.
DevServerEval,
/// A Static Hermes unit compiled into the app binary. It has no source
/// buffer.
SHUnit,
};

/// Called on the JS thread immediately before React Native evaluates a piece
/// of JavaScript, with the exact bytes it is about to evaluate (`data` is null
/// and `size` is 0 for `SHUnit`) and where they came from: the URL a host
/// loaded, a segment's file path, or the URL passed to
/// `globalEvalWithSourceUrl`. Development tooling uses it to tell which
/// JavaScript a process ran. It must not call into the runtime. An exception
/// it throws is ignored, so an observer cannot stop JavaScript from loading.
using JSEvaluationObserver =
void (*)(JSEvaluationKind kind, const uint8_t *data, size_t size, const std::string &sourceURL);

/// Starts calling `observer` before each evaluation, in every `ReactInstance`
/// in the process. Returns how many evaluations React Native had
/// already made in the process, so an observer added after JavaScript ran can
/// tell it missed some. Adding an observer twice has no effect.
RN_EXPORT uint64_t addJSEvaluationObserver(JSEvaluationObserver observer);

/// Stops calling `observer` for evaluations reported after this returns. An
/// evaluation another thread is already reporting may still call it, so an
/// observer must not depend on state its owner frees right after removing it.
RN_EXPORT void removeJSEvaluationObserver(JSEvaluationObserver observer);

RN_EXPORT void
notifyJSEvaluation(JSEvaluationKind kind, const uint8_t *data, size_t size, const std::string &sourceURL);

} // namespace facebook::react
148 changes: 80 additions & 68 deletions packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <react/featureflags/ReactNativeFeatureFlags.h>
#include <react/performance/timeline/PerformanceEntryReporter.h>
#include <react/renderer/runtimescheduler/RuntimeSchedulerBinding.h>
#include <react/runtime/JSEvaluationObserver.h>
#include <react/runtime/JSRuntimeBindings.h>
#include <react/timing/primitives.h>
#include <react/utils/jsi-utils.h>
Expand Down Expand Up @@ -250,63 +251,65 @@ void ReactInstance::loadScript(
std::shared_ptr<const jsi::Buffer> buffer(std::move(script));
std::string scriptName = simpleBasename(sourceURL);

runtimeScheduler_->scheduleWork(
[jsErrorHandler = jsErrorHandler_,
scriptName,
sourceURL = sourceURL,
buffer = std::move(buffer),
weakBufferedRuntimeExecuter =
std::weak_ptr<BufferedRuntimeExecutor>(bufferedRuntimeExecutor_),
beforeLoad,
afterLoad](jsi::Runtime& runtime) mutable {
if (beforeLoad) {
beforeLoad(runtime);
}
TraceSection s("ReactInstance::loadScript");
bool hasLogger(ReactMarker::logTaggedMarkerImpl);
if (hasLogger) {
ReactMarker::logTaggedMarker(
ReactMarker::RUN_JS_BUNDLE_START, scriptName.c_str());
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_START);
ReactMarker::logMarker(ReactMarker::APP_STARTUP_START);
}
runtimeScheduler_->scheduleWork([jsErrorHandler = jsErrorHandler_,
scriptName,
sourceURL = sourceURL,
buffer = std::move(buffer),
weakBufferedRuntimeExecuter =
std::weak_ptr<BufferedRuntimeExecutor>(
bufferedRuntimeExecutor_),
beforeLoad,
afterLoad](jsi::Runtime& runtime) mutable {
if (beforeLoad) {
beforeLoad(runtime);
}
TraceSection s("ReactInstance::loadScript");
bool hasLogger(ReactMarker::logTaggedMarkerImpl);
if (hasLogger) {
ReactMarker::logTaggedMarker(
ReactMarker::RUN_JS_BUNDLE_START, scriptName.c_str());
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_START);
ReactMarker::logMarker(ReactMarker::APP_STARTUP_START);
}

// Check if the shermes unit is avaliable.
auto* shUnitAPI = jsi::castInterface<hermes::IHermesSHUnit>(&runtime);
auto* shUnitCreator =
shUnitAPI ? shUnitAPI->getSHUnitCreator() : nullptr;
if (shUnitCreator) {
LOG(WARNING) << "ReactInstance: evaluateSHUnit";
auto* hermesAPI = jsi::castInterface<hermes::IHermes>(&runtime);
hermesAPI->evaluateSHUnit(shUnitCreator);
} else {
LOG(WARNING) << "ReactInstance: evaluateJavaScript() with JS bundle";
runtime.evaluateJavaScript(buffer, sourceURL);
}
// Check if the shermes unit is avaliable.
auto* shUnitAPI = jsi::castInterface<hermes::IHermesSHUnit>(&runtime);
auto* shUnitCreator = shUnitAPI ? shUnitAPI->getSHUnitCreator() : nullptr;
if (shUnitCreator) {
LOG(WARNING) << "ReactInstance: evaluateSHUnit";
notifyJSEvaluation(JSEvaluationKind::SHUnit, nullptr, 0, sourceURL);
auto* hermesAPI = jsi::castInterface<hermes::IHermes>(&runtime);
hermesAPI->evaluateSHUnit(shUnitCreator);
} else {
LOG(WARNING) << "ReactInstance: evaluateJavaScript() with JS bundle";
notifyJSEvaluation(
JSEvaluationKind::Bundle, buffer->data(), buffer->size(), sourceURL);
runtime.evaluateJavaScript(buffer, sourceURL);
}

/**
* TODO(T183610671): We need a safe/reliable way to enable the js
* pipeline from javascript. Remove this after we figure that out, or
* after we just remove the js pipeline.
*/
if (!jsErrorHandler->hasHandledFatalError()) {
jsErrorHandler->setRuntimeReady();
}
/**
* TODO(T183610671): We need a safe/reliable way to enable the js
* pipeline from javascript. Remove this after we figure that out, or
* after we just remove the js pipeline.
*/
if (!jsErrorHandler->hasHandledFatalError()) {
jsErrorHandler->setRuntimeReady();
}

if (hasLogger) {
ReactMarker::logTaggedMarker(
ReactMarker::RUN_JS_BUNDLE_STOP, scriptName.c_str());
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_STOP);
ReactMarker::logMarker(ReactMarker::APP_STARTUP_STOP);
}
if (auto strongBufferedRuntimeExecuter =
weakBufferedRuntimeExecuter.lock()) {
strongBufferedRuntimeExecuter->flush();
}
if (afterLoad) {
afterLoad(runtime);
}
});
if (hasLogger) {
ReactMarker::logTaggedMarker(
ReactMarker::RUN_JS_BUNDLE_STOP, scriptName.c_str());
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_STOP);
ReactMarker::logMarker(ReactMarker::APP_STARTUP_STOP);
}
if (auto strongBufferedRuntimeExecuter =
weakBufferedRuntimeExecuter.lock()) {
strongBufferedRuntimeExecuter->flush();
}
if (afterLoad) {
afterLoad(runtime);
}
});
}

namespace {
Expand Down Expand Up @@ -442,20 +445,23 @@ void ReactInstance::registerSegment(
"Empty segment registered with ID " + std::to_string(segmentId) +
" from " + segmentPath);
}
runtimeScheduler_->scheduleWork(
[script = std::move(script), segmentId](jsi::Runtime& runtime) {
TraceSection s("ReactInstance::registerSegment");
auto tag = std::to_string(segmentId);
ReactMarker::logTaggedMarker(
ReactMarker::REGISTER_JS_SEGMENT_START, tag.c_str());
LOG(WARNING) << "Starting to evaluate segment " << segmentId
<< " in ReactInstance::registerSegment";
runtime.evaluateJavaScript(script, getSyntheticBundlePath(segmentId));
LOG(WARNING) << "Finished evaluating segment " << segmentId
<< " in ReactInstance::registerSegment";
ReactMarker::logTaggedMarker(
ReactMarker::REGISTER_JS_SEGMENT_STOP, tag.c_str());
});
runtimeScheduler_->scheduleWork([script = std::move(script),
segmentId,
segmentPath](jsi::Runtime& runtime) {
TraceSection s("ReactInstance::registerSegment");
auto tag = std::to_string(segmentId);
ReactMarker::logTaggedMarker(
ReactMarker::REGISTER_JS_SEGMENT_START, tag.c_str());
LOG(WARNING) << "Starting to evaluate segment " << segmentId
<< " in ReactInstance::registerSegment";
notifyJSEvaluation(
JSEvaluationKind::Segment, script->data(), script->size(), segmentPath);
runtime.evaluateJavaScript(script, getSyntheticBundlePath(segmentId));
LOG(WARNING) << "Finished evaluating segment " << segmentId
<< " in ReactInstance::registerSegment";
ReactMarker::logTaggedMarker(
ReactMarker::REGISTER_JS_SEGMENT_STOP, tag.c_str());
});
}

namespace {
Expand Down Expand Up @@ -531,6 +537,12 @@ void ReactInstance::initializeRuntime(
}
// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)

notifyJSEvaluation(
JSEvaluationKind::DevServerEval,
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
reinterpret_cast<const uint8_t*>(code.data()),
code.size(),
url);
return rt.evaluateJavaScript(
std::make_unique<jsi::StringBuffer>(std::move(code)), url);
}));
Expand Down
Loading
Loading