From 7f898b5c521aac38cf87d95288a2ba85372521c0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 16:18:16 -0300 Subject: [PATCH 01/40] build(runtime): take the base64 codec from the shared runtime-common core The new NativeScript/runtime-common submodule pins the NativeScript/runtime-common repository, the C++ shared with the Android runtime. It builds as the RuntimeCommon static library target, linked into NativeScript.framework, with the framework's prefix header for the V8 configuration, V8 as a system header path, and no header map, so core sources only see their own headers and V8's. The atob/btoa natives and the forgiving-base64 codec now come from there; Base64.cpp keeps the builtin wiring. --- .gitmodules | 3 + NativeScript/runtime-common | 1 + NativeScript/runtime/Base64.cpp | 166 +------------------------------- v8ios.xcodeproj/project.pbxproj | 145 ++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+), 161 deletions(-) create mode 160000 NativeScript/runtime-common diff --git a/.gitmodules b/.gitmodules index 0170f4ed0..17e552aff 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,6 @@ path = TestRunner/app/shared url = https://github.com/NativeScript/common-runtime-tests-app.git branch = master +[submodule "NativeScript/runtime-common"] + path = NativeScript/runtime-common + url = https://github.com/NativeScript/runtime-common.git diff --git a/NativeScript/runtime-common b/NativeScript/runtime-common new file mode 160000 index 000000000..49dd52bc9 --- /dev/null +++ b/NativeScript/runtime-common @@ -0,0 +1 @@ +Subproject commit 49dd52bc926997bcaa15eebc08ae9c7815feac02 diff --git a/NativeScript/runtime/Base64.cpp b/NativeScript/runtime/Base64.cpp index 221ba91d2..0b13794d8 100644 --- a/NativeScript/runtime/Base64.cpp +++ b/NativeScript/runtime/Base64.cpp @@ -1,9 +1,8 @@ #include "Base64.h" -#include - #include "BuiltinLoader.h" #include "Helpers.h" +#include "ns/Base64Binding.h" using namespace v8; @@ -11,168 +10,13 @@ namespace tns { namespace { -constexpr char kAlphabet[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// 6-bit value per ASCII byte; 0xFF marks everything outside the alphabet. -constexpr uint8_t kInvalid = 0xFF; - -uint8_t SixBits(uint8_t c) { - if (c >= 'A' && c <= 'Z') { - return static_cast(c - 'A'); - } - if (c >= 'a' && c <= 'z') { - return static_cast(c - 'a' + 26); - } - if (c >= '0' && c <= '9') { - return static_cast(c - '0' + 52); - } - if (c == '+') { - return 62; - } - if (c == '/') { - return 63; - } - return kInvalid; -} - -bool IsAsciiWhitespace(uint8_t c) { - return c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' '; -} - -// The string's code units as bytes. Fails when any unit is above U+00FF, -// which neither op can represent. -bool GetLatin1Bytes(Isolate* isolate, Local value, - std::vector* out) { - if (!value->IsString()) { - return false; - } - Local str = value.As(); - if (!str->ContainsOnlyOneByte()) { - return false; - } - const int length = str->Length(); - out->resize(static_cast(length)); - if (length > 0) { - str->WriteOneByteV2(isolate, 0, static_cast(length), out->data()); - } - return true; -} - -// btoa: base64-encode the input's code units. -void BtoaCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector input; - if (!GetLatin1Bytes(isolate, info[0], &input)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve((input.size() + 2) / 3 * 4); - size_t i = 0; - for (; i + 3 <= input.size(); i += 3) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8) | - input[i + 2]; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back(kAlphabet[group & 0x3F]); - } - const size_t remaining = input.size() - i; - if (remaining == 1) { - const uint32_t group = static_cast(input[i]) << 16; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back('='); - out.push_back('='); - } else if (remaining == 2) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8); - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back('='); - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - -// atob: forgiving-base64 decode -// (https://infra.spec.whatwg.org/#forgiving-base64-decode). -void AtobCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector raw; - if (!GetLatin1Bytes(isolate, info[0], &raw)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector data; - data.reserve(raw.size()); - for (uint8_t c : raw) { - if (!IsAsciiWhitespace(c)) { - data.push_back(c); - } - } - - if (data.size() % 4 == 0) { - size_t strip = 0; - while (strip < 2 && !data.empty() && data.back() == '=') { - data.pop_back(); - strip++; - } - } - if (data.size() % 4 == 1) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve(data.size() / 4 * 3 + 2); - uint32_t accumulator = 0; - uint32_t bits = 0; - for (uint8_t c : data) { - const uint8_t value = SixBits(c); - if (value == kInvalid) { - info.GetReturnValue().SetNull(); - return; - } - accumulator = (accumulator << 6) | value; - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((accumulator >> bits) & 0xFF)); - } - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - MaybeLocal CreateBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - tns::SetMethodNoSideEffect(context, binding, "btoa", BtoaCallback); - tns::SetMethodNoSideEffect(context, binding, "atob", AtobCallback); + tns::SetMethodNoSideEffect(context, binding, "btoa", + nativescript::common::base64::Btoa); + tns::SetMethodNoSideEffect(context, binding, "atob", + nativescript::common::base64::Atob); return binding; } diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 06ac797f9..71967d0d3 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -367,6 +367,9 @@ A1EA4B0E0000000000000012 /* NativeScriptLeakProbe.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = A1EA4B0E0000000000000001 /* NativeScriptLeakProbe.framework */; platformFilters = (ios, maccatalyst, xros, ); settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; A1EA4B0E0000000000000014 /* LeakProbeSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = A1EA4B0E0000000000000013 /* LeakProbeSPI.h */; }; 4426A118ED82F704A1361CE0 /* Checks.h in Headers */ = {isa = PBXBuildFile; fileRef = A139A5040624EECB430D25A8 /* Checks.h */; }; + 5C0AA1C00000000000000005 /* Base64.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000001 /* Base64.cpp */; }; + 5C0AA1C00000000000000006 /* Base64Binding.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000002 /* Base64Binding.cpp */; }; + 5C0AA1C00000000000000007 /* libRuntimeCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000003 /* libRuntimeCommon.a */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -426,6 +429,13 @@ remoteGlobalIDString = A1EA4B0E000000000000000B; remoteInfo = NativeScriptLeakProbe; }; + 5C0AA1C0000000000000000E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = C27E277822202663009C10A3 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 5C0AA1C0000000000000000A; + remoteInfo = RuntimeCommon; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -935,6 +945,9 @@ A1EA4B0E0000000000000003 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A1EA4B0E0000000000000013 /* LeakProbeSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LeakProbeSPI.h; sourceTree = ""; }; A139A5040624EECB430D25A8 /* Checks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Checks.h; sourceTree = ""; }; + 5C0AA1C00000000000000001 /* Base64.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Base64.cpp; path = src/Base64.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000002 /* Base64Binding.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Base64Binding.cpp; path = src/Base64Binding.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000003 /* libRuntimeCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRuntimeCommon.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -982,6 +995,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 5C0AA1C00000000000000007 /* libRuntimeCommon.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1007,6 +1021,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 5C0AA1C00000000000000009 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -1192,6 +1213,7 @@ C27E278122202664009C10A3 /* Products */ = { isa = PBXGroup; children = ( + 5C0AA1C00000000000000003 /* libRuntimeCommon.a */, C2DDEB16229EA89000345BFE /* TestRunner.app */, C2DDEB32229EAB3B00345BFE /* NativeScript.framework */, C29374E2229FC0F60075CB16 /* libTestFixtures.a */, @@ -1502,6 +1524,7 @@ C2DDEB33229EAB3B00345BFE /* NativeScript */ = { isa = PBXGroup; children = ( + 5C0AA1C00000000000000004 /* runtime-common */, 3C48F68C2F57905500C14231 /* third_party */, 2BFE21F12AC1B79F00307752 /* embedding */, F1F30E862B58FE28006A62C0 /* ada */, @@ -1741,6 +1764,15 @@ path = NativeScriptLeakProbe; sourceTree = ""; }; + 5C0AA1C00000000000000004 /* runtime-common */ = { + isa = PBXGroup; + children = ( + 5C0AA1C00000000000000001 /* Base64.cpp */, + 5C0AA1C00000000000000002 /* Base64Binding.cpp */, + ); + path = "runtime-common"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -1988,6 +2020,7 @@ buildRules = ( ); dependencies = ( + 5C0AA1C0000000000000000F /* PBXTargetDependency */, ); name = NativeScript; productName = NativeScript; @@ -2045,6 +2078,22 @@ productReference = A1EA4B0E0000000000000001 /* NativeScriptLeakProbe.framework */; productType = "com.apple.product-type.framework"; }; + 5C0AA1C0000000000000000A /* RuntimeCommon */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5C0AA1C0000000000000000B /* Build configuration list for PBXNativeTarget "RuntimeCommon" */; + buildPhases = ( + 5C0AA1C00000000000000008 /* Sources */, + 5C0AA1C00000000000000009 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RuntimeCommon; + productName = RuntimeCommon; + productReference = 5C0AA1C00000000000000003 /* libRuntimeCommon.a */; + productType = "com.apple.product-type.library.static"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -2098,6 +2147,7 @@ C2DDEB15229EA89000345BFE /* TestRunner */, C27E5D8A22F31CC900498ED0 /* AppWithModules */, C2DDEB31229EAB3B00345BFE /* NativeScript */, + 5C0AA1C0000000000000000A /* RuntimeCommon */, C29374E1229FC0F60075CB16 /* TestFixtures */, C2F4CBB222C60BFD0036B56F /* metadata-generator */, C23992C6236C2D6E00D2F720 /* TestRunnerTests */, @@ -2622,6 +2672,15 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 5C0AA1C00000000000000008 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5C0AA1C00000000000000005 /* Base64.cpp in Sources */, + 5C0AA1C00000000000000006 /* Base64Binding.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -2686,6 +2745,11 @@ target = A1EA4B0E000000000000000B /* NativeScriptLeakProbe */; targetProxy = A1EA4B0E000000000000000F /* PBXContainerItemProxy */; }; + 5C0AA1C0000000000000000F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 5C0AA1C0000000000000000A /* RuntimeCommon */; + targetProxy = 5C0AA1C0000000000000000E /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ @@ -3288,6 +3352,7 @@ USER_HEADER_SEARCH_PATHS = ( "$(SRCROOT)/NativeScript", "$(SRCROOT)/NativeScript/include", + "$(SRCROOT)/NativeScript/runtime-common/include", "$(SRCROOT)/NativeScript/inspector", "$(SRCROOT)/NativeScript/v8runtime", "$(SRCROOT)/NativeScript/jsi", @@ -3385,6 +3450,7 @@ USER_HEADER_SEARCH_PATHS = ( "$(SRCROOT)/NativeScript", "$(SRCROOT)/NativeScript/include", + "$(SRCROOT)/NativeScript/runtime-common/include", "$(SRCROOT)/NativeScript/inspector", "$(SRCROOT)/NativeScript/v8runtime", "$(SRCROOT)/NativeScript/jsi", @@ -3610,6 +3676,76 @@ }; name = Release; }; + 5C0AA1C0000000000000000C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALLOW_TARGET_PLATFORM_SPECIALIZATION = NO; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "c++20"; + CLANG_ENABLE_MODULES = NO; + CLANG_ENABLE_OBJC_ARC = NO; + EXCLUDED_ARCHS = ""; + "EXCLUDED_ARCHS[sdk=xros*]" = x86_64; + "EXCLUDED_ARCHS[sdk=xrsimulator*]" = x86_64; + GCC_PREFIX_HEADER = "NativeScript/NativeScript-Prefix.pch"; + HEADER_SEARCH_PATHS = "$(SRCROOT)/NativeScript/runtime-common/include"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + OTHER_CFLAGS = ( + "-fno-rtti", + "-Wall", + "-Werror", + "-Wshorten-64-to-32", + "-Wdeprecated-declarations", + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = ""; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator xros xrsimulator"; + SUPPORTS_MACCATALYST = YES; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SYSTEM_HEADER_SEARCH_PATHS = "$(SRCROOT)/NativeScript/include"; + TARGETED_DEVICE_FAMILY = "1,2,7"; + USER_HEADER_SEARCH_PATHS = ""; + USE_HEADERMAP = NO; + }; + name = Debug; + }; + 5C0AA1C0000000000000000D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALLOW_TARGET_PLATFORM_SPECIALIZATION = NO; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "c++20"; + CLANG_ENABLE_MODULES = NO; + CLANG_ENABLE_OBJC_ARC = NO; + EXCLUDED_ARCHS = ""; + "EXCLUDED_ARCHS[sdk=xros*]" = x86_64; + "EXCLUDED_ARCHS[sdk=xrsimulator*]" = x86_64; + GCC_PREFIX_HEADER = "NativeScript/NativeScript-Prefix.pch"; + HEADER_SEARCH_PATHS = "$(SRCROOT)/NativeScript/runtime-common/include"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + OTHER_CFLAGS = ( + "-fno-rtti", + "-Wall", + "-Werror", + "-Wshorten-64-to-32", + "-Wdeprecated-declarations", + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = ""; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator xros xrsimulator"; + SUPPORTS_MACCATALYST = YES; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SYSTEM_HEADER_SEARCH_PATHS = "$(SRCROOT)/NativeScript/include"; + TARGETED_DEVICE_FAMILY = "1,2,7"; + USER_HEADER_SEARCH_PATHS = ""; + USE_HEADERMAP = NO; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -3703,6 +3839,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 5C0AA1C0000000000000000B /* Build configuration list for PBXNativeTarget "RuntimeCommon" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5C0AA1C0000000000000000C /* Debug */, + 5C0AA1C0000000000000000D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ }; rootObject = C27E277822202663009C10A3 /* Project object */; From fba7f6b8f54270714eb69c0e9547c37c43a90f62 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 01:02:52 -0300 Subject: [PATCH 02/40] feat(runtime): run the HTTP module loader on runtime-common The gate, classification, retry and deadline policy, the cache switch and Clear-Site-Data come from the shared core (ns/http); HttpLoader keeps the NSURLSession transport and the per-isolate canonicalization vocabulary. User-visible changes: - requests send User-Agent: NativeScript-HTTP-ESM; - in release builds with a remote module allowlist, a redirect that ends outside it is refused; - a failed cache clear throws from clearHttpCache() and answers -32000 to Network.clearBrowserCache; - graph-load fetch deadlines are monotonic (steady_clock). --- NativeScript/inspector/JsV8InspectorClient.mm | 16 +- NativeScript/runtime-common | 2 +- NativeScript/runtime/HttpLoader.h | 201 +-- NativeScript/runtime/HttpLoader.mm | 1200 ++++------------- .../runtime/ModuleInternalCallbacks.h | 12 +- .../runtime/ModuleInternalCallbacks.mm | 32 +- NativeScript/runtime/RuntimeCommonPlatform.mm | 88 ++ docs/ns-builtin-modules.md | 6 +- types/ns-module.d.ts | 2 + v8ios.xcodeproj/project.pbxproj | 38 +- 10 files changed, 489 insertions(+), 1108 deletions(-) create mode 100644 NativeScript/runtime/RuntimeCommonPlatform.mm diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index cd433198a..1696facbb 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -433,7 +433,7 @@ bool GetInt32(const json& value, long long& out) { } // Its Network.setCacheDisabled lasts only as long as the connection. - tns::SetModuleHttpCacheDisabledByInspector(connectionId, false); + tns::SetModuleHttpCacheDisabledBy(connectionId, false); // Free the process-global trace controller for other frontends. { @@ -520,15 +520,23 @@ bool GetInt32(const json& value, long long& out) { // DispatchFrontendMessage answers it when there is none. Worker sessions // have no JS domain handlers, so they are answered here. A sessionId that // names no worker of this frontend changes nothing and is left to - // RouteToWorker's "Session not found". + // RouteToWorker's "Session not found". A clear that failed is answered here + // for every session, since the domain handler cannot tell. if ((method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") && (sessionId.empty() || this->HasWorkerSession(connectionId, sessionId))) { const std::optional cacheDisabled = SetCacheDisabledParam(parsed); const bool valid = method == "Network.clearBrowserCache" || cacheDisabled.has_value(); if (method == "Network.clearBrowserCache") { - tns::ClearModuleHttpCache(); + const tns::CacheOpResult cleared = tns::ClearModuleHttpCache(); + if (!cleared.ok) { + if (msgId >= 0) { + json error = {{"id", msgId}, {"error", {{"code", -32000}, {"message", cleared.error}}}}; + this->SendRawToConnection(connectionId, WithSessionId(error, sessionId).dump()); + } + return; + } } else if (valid) { - tns::SetModuleHttpCacheDisabledByInspector(connectionId, *cacheDisabled); + tns::SetModuleHttpCacheDisabledBy(connectionId, *cacheDisabled); } if (!sessionId.empty()) { if (msgId >= 0) { diff --git a/NativeScript/runtime-common b/NativeScript/runtime-common index 49dd52bc9..3ebf3bc80 160000 --- a/NativeScript/runtime-common +++ b/NativeScript/runtime-common @@ -1 +1 @@ -Subproject commit 49dd52bc926997bcaa15eebc08ae9c7815feac02 +Subproject commit 3ebf3bc8078fd5372bf172d84750d876fa9d3bae diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index 666765e8b..6aa2bdfc8 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -1,176 +1,61 @@ #pragma once -#include -#include +#include #include #include -namespace tns { - -// HttpLoader: the native half of the NativeScript HTTP module-loader -// contract. -// -// The runtime deliberately exposes *mechanism* only: -// - the synchronous HTTP text fetch backing the HTTP ESM loader's -// fallback path (V8's ResolveModuleCallback is synchronous — still -// true as of 14.9.207.39 — so the fallback must be native), -// - the async NSURLSession fetch behind the phase-1 module-graph walk -// (StartModuleGraphLoad), which is how module bodies -// normally arrive, -// - the boot-evaluation flag that arms the cold-boot runloop pump only -// while an entry module is evaluating (derived by the runtime itself), -// - the remote-module security gate, seeded once from nativescript.config -// at boot and never exposed on ns:runtime getConfig/setConfig. +#include "ns/http/ModuleFetch.h" -// ───────────────────────────────────────────────────────────── -// HTTP loader helpers (used by dev/HMR and general-purpose HTTP module loading) +namespace tns { -// Canonicalization vocabulary (client-supplied policy). -// -// The canonical-key *mechanism* (fragment strip, cache-buster param drop, -// param sort) must be native because it keys the module registry inside -// V8's synchronous resolve walk. The *vocabulary* — which query params are -// pure cache busters, which path prefixes identify dev endpoints whose -// queries may be normalized, and which paths must keep their query verbatim -// because the query IS the identity — is server/framework policy, supplied -// by the dev client via -// ns:module `configureLoader({ canonicalization: {...} })` and consumed by -// `CanonicalizeHttpUrlKey`. It is per-isolate loader vocabulary — installed -// through SetCanonicalizationConfig in ModuleInternalCallbacks.h — so -// CanonicalizeHttpUrlKey runs on the isolate's own thread only. The transport -// never canonicalizes. +// The HTTP module loader: policy, fetch orchestration and the cache switch are +// the shared core's (ns/http/ModuleFetch.h); this runtime supplies the +// NSURLSession transport and the per-isolate canonicalization vocabulary. // -// When unconfigured, canonicalization is purely mechanical (fragment strip). -struct CanonicalizationConfig { - std::vector stripParams; // query param names to drop - std::vector devPathPrefixes; // StartsWith → normalize query - std::vector preserveQueryPrefixes; // contains → keep query -}; - -// Normalize an HTTP(S) URL into a stable module registry/cache key. -// - Always strips URL fragments. -// - For NativeScript dev endpoints, drops known cache busters (t/v/import) -// and sorts remaining query params for stability. -// - For non-dev/public URLs, preserves the full query string as part of the -// cache key. -// Module identity IS the (canonical) URL — the dev server serves every -// module under exactly one URL and never varies it for freshness. +// V8's ResolveModuleCallback is synchronous (still true as of 14.9.207.39), so +// the fallback fetch HttpFetchModule has to block natively. Module bodies +// normally arrive through FetchModuleBodyAsync, driven by the module-graph walk +// (StartModuleGraphLoad in ModuleInternalCallbacks.h). + +using nativescript::common::http::CacheOpResult; +using nativescript::common::http::CanonicalizationConfig; +using nativescript::common::http::ClearModuleHttpCache; +using nativescript::common::http::FetchModuleBodyAsync; +using nativescript::common::http::HttpFetchModule; +using nativescript::common::http::IsRemoteModulesAllowed; +using nativescript::common::http::IsRemoteUrlAllowed; +using nativescript::common::http::ModuleFetchDeadline; +using nativescript::common::http::ModuleFetchResult; +using nativescript::common::http::ModuleHttpCacheEnabled; +using nativescript::common::http::ModuleResponseKind; +using nativescript::common::http::RemoteModuleAllowlist; +using nativescript::common::http::RemoteModuleAllowlistFromConfig; +using nativescript::common::http::RemoteUrlAllowedByAllowlist; +using nativescript::common::http::SetModuleHttpCacheDisabledBy; +using nativescript::common::http::SetModuleHttpCacheEnabled; + +// The module registry key of an HTTP(S) URL under the current isolate's +// vocabulary (ns:module `configureLoader({ canonicalization })`); without one +// only the fragment is stripped. Isolate thread only. std::string CanonicalizeHttpUrlKey(const std::string& url); // CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); -// What a module response turned out to be. Decided once, by the shared -// classifier, for whichever transport produced the response. -enum class ModuleResponseKind { - kJavaScript, - kJson, -}; - -// The outcome of fetching one module over HTTP. Both transports produce this -// same verdict, so the synchronous fallback and the async graph walk cannot -// drift apart on what counts as a usable module. -struct ModuleFetchResult { - bool ok = false; - int status = 0; - ModuleResponseKind kind = ModuleResponseKind::kJavaScript; - // Normalized: an empty 2xx JavaScript body becomes the canonical empty - // module. Meaningful only when `ok`. - std::string body; - std::string contentType; // as received, parameters included - // Reader-facing explanation, non-empty exactly when `!ok`. This is the text - // that reaches the importer's rejection, so it names the URL and the cause. - std::string failureReason; -}; - -// Synchronous module fetch with one retry on transport error — the fallback -// path for anything the async module-graph walk missed. Blocks the calling -// thread, for at most a few seconds past the request timeout per attempt: a -// response that has not arrived by then fails the fetch. Uses the same HTTP -// cache as FetchModuleBodyAsync, through sessions (and so connections) of its -// own. Returns `result.ok`. -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); - -// Asynchronous single-URL module fetch — the I/O primitive behind the -// module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h). -// Same response policy as HttpFetchModule, minus the JS-thread block: -// - security gate (IsRemoteUrlAllowed) checked up front, -// - an NSURLSession GET on a background queue with the same request shape -// as the sync path (no cookies, HTTP caching as the response headers -// allow) and one retry on transport error. -// `fetchDeadline` is the enclosing graph load's fetch budget as an absolute -// CFAbsoluteTime (double; 0 = unbounded): attempts clamp their request -// timeout to the time remaining and the transport-error retry is skipped -// once no budget is left, so a bounded fetch can never outlive the wait -// that is pumping for it. -// `completion(result)` is invoked exactly once, on an arbitrary thread — -// callers must hop to their JS thread before touching V8. -void FetchModuleBodyAsync( - const std::string& url, double fetchDeadline, - std::function completion); - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate -// -// Seeded once from nativescript.config / package.json -// (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) the first -// time a fetch is gated. Debug builds always allow. These values are not -// readable or writable through ns:runtime getConfig/setConfig — only -// nativescript.config at boot. - -// In debug mode (RuntimeConfig.IsDebug): always returns true. -// Otherwise returns the boot-time `security.allowRemoteModules` value. -bool IsRemoteModulesAllowed(); - -// Whether `url` may be fetched as a remote ES module. Debug builds always -// allow. Production requires allowRemoteModules, then an allowlist match -// (or all URLs if the allowlist is empty). -bool IsRemoteUrlAllowed(const std::string& url); - -// The allowlist IsRemoteUrlAllowed applies once remote modules are enabled. -struct RemoteModuleAllowlist { - // False only when `security.remoteModuleAllowlist` is absent, not an array, - // or an empty array: then every URL is allowed. - bool inForce = false; - // The usable items, each spelled the way the loader spells the URLs it - // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against - // resolved paths, or kept verbatim when it is not an http(s) URL. An item - // that is not a string, is empty or has no exact UTF-8 form is not here: it - // matches nothing but still keeps the list in force. - std::vector entries; -}; +// The NSURLSession transport, for platform::HttpTransport(). Process lifetime. +nativescript::common::http::ModuleTransport& ModuleHttpTransport(); #ifdef __OBJC__ -// The allowlist for the raw `security.remoteModuleAllowlist` config value. -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value); +// The raw `security.remoteModuleAllowlist` value as the core reads it: nullopt +// unless an NSArray; each item nullopt unless an NSString with an exact UTF-8 +// form. +std::optional>> +RemoteModuleAllowlistItems(id value); + +inline RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value) { + return nativescript::common::http::RemoteModuleAllowlistFromConfig( + RemoteModuleAllowlistItems(value)); +} #endif -// Whether `url` (as fetched) passes `allowlist`: always when it is not in -// force, otherwise when one entry matches it by prefix with the match ending -// at a URL-component boundary. -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); - -// ───────────────────────────────────────────────────────────── -// Module HTTP cache controls -// -// Process-wide, shared by every isolate, callable from any thread. A fetch -// uses the cache when it is enabled and no inspector connection has it -// disabled; that is decided when the fetch is issued, so fetches in flight are -// unaffected. Disabled means nothing is read from or written to it. The launch -// arguments `--nativescript-no-module-cache` and -// `--nativescript-clear-module-cache` and the `moduleHttpCache` app config key -// are read once per process, before the first fetch. - -void SetModuleHttpCacheEnabled(bool enabled); - -// Records whether inspector connection `connectionId` has the cache disabled; -// false also forgets the connection. -void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId, - bool disabled); - -// Empties the cache of every origin before returning, durably: a process -// killed right after the call does not find the old entries at its next -// launch. -void ClearModuleHttpCache(); - } // namespace tns diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 638fb03fc..58913460f 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -1,144 +1,30 @@ #include "HttpLoader.h" #import + #include #include -#include - -#include +#include +#include +#include +#include #include #include #include -#include #include +#include #include -#include "Caches.h" + #include "Helpers.h" -#include "ModuleInternal.h" #include "ModuleInternalCallbacks.h" #include "ModuleUrl.h" -#include "Runtime.h" -#include "RuntimeConfig.h" +#include "ns/http/ModuleTransport.h" namespace tns { -static inline bool StartsWith(const std::string& s, const char* prefix) { - size_t n = strlen(prefix); - return s.size() >= n && s.compare(0, n, prefix) == 0; -} - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate -// -// Boot-time only: values come from nativescript.config / package.json -// (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) and -// are never registered on ns:runtime getConfig/setConfig. - -static std::once_flag s_securityConfigInitFlag; -static bool s_allowRemoteModules = false; -static RemoteModuleAllowlist s_remoteModuleAllowlist; - -// Returns true when `url` is authorized by allowlist `entry`. -// -// This is intentionally stricter than a raw string-prefix test: after the -// matched entry text, the next character in `url` must be a URL-component -// boundary ('/', '?', or '#'), the URL must end exactly at the entry, or the -// entry must itself end in '/'. That refuses lookalike-host and lookalike-port -// bypasses — an entry of "https://cdn.example.com" must NOT authorize -// "https://cdn.example.com.attacker.com/x.js" or -// "https://cdn.example.com:9999/x.js". To allow a specific port, include it in -// the allowlist entry (deny-by-default for anything not explicitly listed). -static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::string& entry) { - if (entry.empty()) return false; - if (url.size() < entry.size()) return false; - if (url.compare(0, entry.size(), entry) != 0) return false; - if (url.size() == entry.size()) return true; // exact match - if (entry.back() == '/') return true; // entry ended at a boundary - const char next = url[entry.size()]; - return next == '/' || next == '?' || next == '#'; -} - -static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { - const std::string url = NormalizeHttpModuleUrl(entry); - return url.empty() ? entry : url; -} - -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value) { - RemoteModuleAllowlist allowlist; - if (![value isKindOfClass:[NSArray class]] || [(NSArray*)value count] == 0) { - return allowlist; - } - allowlist.inForce = true; - for (id item in (NSArray*)value) { - if (![item isKindOfClass:[NSString class]]) { - continue; - } - const std::optional entry = ToExactUtf8((NSString*)item); - if (entry.has_value() && !entry->empty()) { - allowlist.entries.push_back(NormalizeRemoteModuleAllowlistEntry(*entry)); - } - } - return allowlist; -} - -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist) { - if (!allowlist.inForce) { - return true; - } - for (const std::string& entry : allowlist.entries) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - return false; -} - -static void InitializeSecurityConfig() { - std::call_once(s_securityConfigInitFlag, []() { - @autoreleasepool { - id securityValue = Runtime::GetAppConfigValue("security"); - if (!securityValue || ![securityValue isKindOfClass:[NSDictionary class]]) { - return; - } - - NSDictionary* security = (NSDictionary*)securityValue; - - id allowRemote = security[@"allowRemoteModules"]; - if (allowRemote && [allowRemote respondsToSelector:@selector(boolValue)]) { - s_allowRemoteModules = [allowRemote boolValue]; - } - - s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(security[@"remoteModuleAllowlist"]); - } - }); -} - -bool IsRemoteModulesAllowed() { - if (RuntimeConfig.IsDebug) { - return true; - } - - InitializeSecurityConfig(); - return s_allowRemoteModules; -} - -bool IsRemoteUrlAllowed(const std::string& url) { - if (RuntimeConfig.IsDebug) { - return true; - } - - InitializeSecurityConfig(); - if (!s_allowRemoteModules) { - return false; - } - - return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); -} - -// ───────────────────────────────────────────────────────────── -// Boot-evaluation flag -// -// ───────────────────────────────────────────────────────────── -// HTTP loader helpers +using nativescript::common::http::AttemptOutcome; +using nativescript::common::http::AttemptRequest; +using nativescript::common::http::FetchPath; +using nativescript::common::http::ModuleTransport; // URLs touched before the client configures anything (the local trampoline's // clean `/ns/core/*` imports) carry no query, so they canonicalize identically @@ -149,383 +35,30 @@ bool IsRemoteUrlAllowed(const std::string& url) { } std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { - // Per-isolate vocabulary, so this runs on the isolate's own thread only. - const CanonicalizationConfig* canonConfig = CanonicalizationConfigForCurrentIsolate(); - // Drop fragment entirely - size_t hashPos = normalizedUrl.find('#'); - std::string noHash = - (hashPos == std::string::npos) ? normalizedUrl : normalizedUrl.substr(0, hashPos); - - // Locate path start and query start - size_t schemePos = noHash.find("://"); - if (schemePos == std::string::npos) { - // Unexpected shape; fall back to removing whole query - size_t q = noHash.find('?'); - return (q == std::string::npos) ? noHash : noHash.substr(0, q); - } - size_t pathStart = noHash.find('/', schemePos + 3); - if (pathStart == std::string::npos) { - // No path; nothing to normalize - return noHash; - } - size_t qPos = noHash.find('?', pathStart); - std::string originAndPath = (qPos == std::string::npos) ? noHash : noHash.substr(0, qPos); - std::string query = (qPos == std::string::npos) ? std::string() : noHash.substr(qPos + 1); - - // IMPORTANT: This function is used as an HTTP module registry/cache key. - // For general-purpose HTTP module loading (public internet), the query string - // can be part of the module's identity (auth, content versioning, routing, etc). - // Therefore query normalization (sorting/dropping) applies only to dev - // endpoints, per the client-supplied vocabulary above. - // - // The dev server serves every module under ONE canonical URL — module - // identity IS the URL string. Freshness after an HMR edit is handled by - // ns:module `invalidateModules` (registry evict) and the server's own - // response caching headers, never by URL variation. There is deliberately - // no path-tag vocabulary to collapse here. - // - // Why `preserveQueryFor` exists (and is checked BEFORE the dev-endpoint - // prefix test, so it covers endpoints nested under a dev prefix): for some - // endpoints the query IS the identity. A framework that fetches recompiled - // component metadata under a timestamped query is the motivating case — - // stripping that timestamp would collapse every HMR fetch onto the boot-time - // cache key, and the client would forever replay stale metadata. - // - // Until a client supplies that vocabulary, canonicalization is purely - // mechanical: the fragment is gone and the query stays, because which params - // are cache-busters and which paths are dev endpoints is knowledge only the - // client has. Guessing would silently collapse two distinct modules onto one - // registry key. - if (canonConfig == nullptr) { - return noHash; - } - - { - std::string pathOnly = originAndPath.substr(pathStart); - for (const auto& p : canonConfig->preserveQueryPrefixes) { - if (!p.empty() && pathOnly.find(p) != std::string::npos) { - return noHash; // query preserved verbatim (fragment already removed) - } - } - bool isDevEndpoint = false; - for (const auto& p : canonConfig->devPathPrefixes) { - if (!p.empty() && StartsWith(pathOnly, p.c_str())) { - isDevEndpoint = true; - break; - } - } - if (!isDevEndpoint) { - return noHash; - } - } - - if (query.empty()) return originAndPath; - - // Keep all params except the configured cache busters; sort for stability. - std::vector kept; - size_t start = 0; - while (start <= query.size()) { - size_t amp = query.find('&', start); - std::string pair = - (amp == std::string::npos) ? query.substr(start) : query.substr(start, amp - start); - if (!pair.empty()) { - size_t eq = pair.find('='); - std::string name = (eq == std::string::npos) ? pair : pair.substr(0, eq); - bool drop = std::find(canonConfig->stripParams.begin(), canonConfig->stripParams.end(), - name) != canonConfig->stripParams.end(); - if (!drop) kept.push_back(pair); - } - if (amp == std::string::npos) break; - start = amp + 1; - } - if (kept.empty()) return originAndPath; - std::sort(kept.begin(), kept.end()); - std::string rebuilt = originAndPath + "?"; - for (size_t i = 0; i < kept.size(); i++) { - if (i > 0) rebuilt += "&"; - rebuilt += kept[i]; - } - return rebuilt; -} - -// ============================================================================ -// HTTP module fetching -// ============================================================================ -// -// Two fetch primitives back the HTTP ESM loader: -// - `HttpFetchModule` — the synchronous fetch V8's ResolveModuleCallback -// falls back to for anything the module-graph walk missed -// (the callback is synchronous — still true as of 14.9.207.39 — so -// this fallback must be native and blocking). -// - `FetchModuleBodyAsync` — the primitive behind the module-graph walk -// (StartModuleGraphLoad), which fetches the transitive closure -// concurrently off the JS thread before instantiation begins. -// -// Both issue their requests through StartModuleFetchTask, so they share one -// HTTP cache and its switch, BuildModuleFetchRequest shapes every request, -// and ClassifyModuleResponse judges every response. Neither can drift into -// its own idea of what a valid module response is. -// -// Concurrent per-module fetches overlap with on-device compile, which -// measured fastest on real apps (HMR_API_NECESSITY_REVIEW.md §8.3). - -// Forward declarations — these helpers are defined below their first use, -// matching the existing convention in this file. -static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, - std::string& contentType, int& status, bool& waitExpired); - -// ── The module-fetch timeout policy ────────────────────────────────────────── -// -// One request timeout for every module-fetch attempt, read by every path: the -// synchronous fallback, each async attempt, and the session's own default. It -// MUST live in exactly one place — the async session once said 10s while every -// NSMutableURLRequest overrode it to 5s, so raising the session alone would -// have changed nothing. -// -// Debug runtimes get 30s: dev servers transform cold modules on demand, and -// real toolchain responses have been measured at 5–9s — comfortably past the -// old flat 5s, which expired mid-transform. A timed-out dependency fetch left -// the module absent from the registry, hid its subtree from the graph walk, -// and dumped it onto the blocking synchronous fallback (the "module graph -// walk missed" warnings). Release keeps 5s: remote module loading there is -// opt-in through the security gate, and nothing measured justifies relaxing -// its budget. -static NSTimeInterval ModuleFetchTimeoutInterval() { - return RuntimeConfig.IsDebug ? 30.0 : 5.0; -} - -// Transport-error retry delay, shared by the sync and async paths. Long enough -// to let a transient hiccup pass, short enough not to matter against the -// request timeout. -static constexpr double kModuleFetchRetryDelaySeconds = 0.12; - -// How long the synchronous fallback waits past the request timeout before it -// gives up on a task whose completion never arrived. The request timeout is an -// idle timeout, so a response still trickling in can legitimately outlast it; -// this margin is what makes the blocking wait finite regardless. -static constexpr double kModuleFetchSyncWaitMarginSeconds = 5.0; - -// synchronous-fetch timing histogram. -// -// The histogram is intentionally coarse — -// just three buckets — and we log a summary once per kFetchSyncSummaryEvery -// completions. That keeps the noise low (one line per ~100 fetches) while -// still surfacing tail behavior. The "fast" bucket means a request landed -// in <10ms (typical for a kept-alive HTTP/1.1 connection on loopback); -// "slow" means >100ms (which usually means a fresh TCP/TLS handshake or -// a large response body). If most fetches are "fast", keep-alive is -// working. If most are "slow", we still have churn to track down. -static std::atomic g_fetchSyncCount{0}; -static std::atomic g_fetchSyncTotalMs{0}; -static std::atomic g_fetchSyncFast{0}; // <10ms -static std::atomic g_fetchSyncMedium{0}; // 10–99ms -static std::atomic g_fetchSyncSlow{0}; // >=100ms -static constexpr size_t kFetchSyncSummaryEvery = 100; - -// ── The module response policy ─────────────────────────────────────────────── -// -// Module scripts are strict about MIME: the HTML spec's "fetch a single module -// script" fails the fetch outright for anything that is not a JavaScript or -// JSON MIME type, where a classic script would sniff and run it anyway. That -// strictness is the whole point — an SPA dev server answering an unknown path -// with `200 text/html` should say so, not hand HTML to the parser and produce -// `Unexpected token '<'` from somewhere deep in the graph. -// -// Both transports classify here, so the synchronous fallback and the async -// walk cannot disagree about what a response means. - -// "text/javascript; charset=utf-8" → "text/javascript": parameters stripped, -// trimmed, lowercased. -static std::string MimeEssence(const std::string& contentType) { - size_t semi = contentType.find(';'); - std::string essence = semi == std::string::npos ? contentType : contentType.substr(0, semi); - size_t begin = essence.find_first_not_of(" \t"); - if (begin == std::string::npos) { - return ""; - } - size_t end = essence.find_last_not_of(" \t"); - essence = essence.substr(begin, end - begin + 1); - for (char& c : essence) { - c = (char)tolower((unsigned char)c); - } - return essence; -} - -// The HTML spec's JavaScript MIME type essence list, verbatim. -static bool IsJavaScriptMimeEssence(const std::string& essence) { - static const char* const kJavaScriptEssences[] = {"application/ecmascript", - "application/javascript", - "application/x-ecmascript", - "application/x-javascript", - "text/ecmascript", - "text/javascript", - "text/javascript1.0", - "text/javascript1.1", - "text/javascript1.2", - "text/javascript1.3", - "text/javascript1.4", - "text/javascript1.5", - "text/jscript", - "text/livescript", - "text/x-ecmascript", - "text/x-javascript"}; - for (const char* candidate : kJavaScriptEssences) { - if (essence == candidate) { - return true; - } - } - return false; -} - -// A JSON MIME type is application/json, text/json, or any `+json` subtype. -static bool IsJsonMimeEssence(const std::string& essence) { - if (essence == "application/json" || essence == "text/json") { - return true; - } - const std::string suffix = "+json"; - return essence.size() > suffix.size() && - essence.compare(essence.size() - suffix.size(), suffix.size(), suffix) == 0; -} - -// `transportOk` means a response arrived at all; everything else about it — -// status, MIME, emptiness — is policy decided here. `body` is moved into the -// result on success. -static void ClassifyModuleResponse(const std::string& url, bool transportOk, int status, - const std::string& contentType, std::string& body, - ModuleFetchResult& result) { - result.status = status; - result.contentType = contentType; - - if (!transportOk) { - result.failureReason = "HTTP import failed: " + url + " (network error)"; - return; - } - if (status == 204 || status == 205) { - // "No content" carries no module, which the web treats as a network error - // for a module script rather than as an empty module. - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + ", no content)"; - return; - } - if (status < 200 || status >= 300) { - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + ")"; - return; - } - - const std::string essence = MimeEssence(contentType); - if (essence.empty()) { - result.failureReason = - "Expected a JavaScript module but '" + url + "' responded with no MIME type"; - return; - } - - if (IsJsonMimeEssence(essence)) { - if (body.empty()) { - result.failureReason = - "Expected a JSON module but '" + url + "' responded with an empty body"; - return; - } - result.kind = ModuleResponseKind::kJson; - } else if (IsJavaScriptMimeEssence(essence)) { - result.kind = ModuleResponseKind::kJavaScript; - // An empty 2xx JavaScript body is a valid module: type-only TypeScript - // modules transform to zero runtime code and dev servers serve them as - // empty 200s. Failing here would kill the whole graph with a misleading - // "status=200". - if (body.empty()) { - body = "export {};\n"; - TNS_DEBUG(Esm, "[http-loader] empty 2xx body for %s — serving canonical empty module", - url.c_str()); - } - } else { - result.failureReason = - "Expected a JavaScript module but '" + url + "' responded with MIME type '" + essence + "'"; - return; - } - - result.ok = true; - result.body = std::move(body); + return nativescript::common::http::CanonicalizeNormalizedHttpUrlKey( + normalizedUrl, CanonicalizationConfigForCurrentIsolate()); } -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { - result = ModuleFetchResult(); - - // Security gate: the single point of enforcement for all HTTP module - // loading, checked before any network turn. - if (!IsRemoteUrlAllowed(url)) { - result.status = 403; - result.failureReason = "HTTP import blocked: remote module loading is not allowed for " + url; - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - return false; - } - - // Hoist the category check once per call so the branches below share a - // single read. - const bool traceFetch = tns::LogCategoryEnabled(tns::LogCategory::Fetch); - - // Time the network branch end-to-end so the per-URL log can attribute - // milliseconds to each fetch. Measured here rather than inside - // PerformHttpFetchOnceSync so the retry interval is billed to the URL too — - // which is what the user sees as "this URL was slow". - const uint64_t netStartUs = - traceFetch ? (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0) : 0ull; - - std::string body; - std::string contentType; - int status = 0; - bool waitExpired = false; - bool transportOk = PerformHttpFetchOnceSync(url, body, contentType, status, waitExpired); - if (!transportOk && !waitExpired) { - // One retry, and only for a transport error: an HTTP status is an answer, - // not a failure to communicate, so asking again would just repeat it. An - // expired wait is not retried: it already blocked this thread for longer - // than a request may take. - TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str()); - usleep((useconds_t)(kModuleFetchRetryDelaySeconds * 1000.0 * 1000.0)); - transportOk = PerformHttpFetchOnceSync(url, body, contentType, status, waitExpired); - } - // NOTE: no long dev-server-startup retry loop here on purpose. The CLI's - // `compileWithWatch` gates app deploy/restart on its `vite serve` - // readiness probe (bundler-compiler-service), so a connection-refused at - // boot is a real failure, not a startup race — surface it immediately. - - ClassifyModuleResponse(url, transportOk, status, contentType, body, result); - if (waitExpired) { - result.failureReason = - "HTTP import failed: " + url + " (no response within " + - std::to_string((int)(ModuleFetchTimeoutInterval() + kModuleFetchSyncWaitMarginSeconds)) + - "s)"; +std::optional>> RemoteModuleAllowlistItems(id value) { + if (![value isKindOfClass:[NSArray class]]) { + return std::nullopt; } - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); - return false; - } - - if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - const char* ctstr = result.contentType.empty() ? "" : result.contentType.c_str(); - TNS_DEBUG(Esm, "[http-loader] fetched status=%d content-type=%s bytes=%llu", result.status, - ctstr, (unsigned long long)result.body.size()); - } - if (traceFetch) { - const uint64_t netEndUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t netMs = netEndUs > netStartUs ? (netEndUs - netStartUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][network] %s bytes=%lu ms=%llu", url.c_str(), - (unsigned long)result.body.size(), (unsigned long long)netMs); + std::vector> items; + for (id item in (NSArray*)value) { + items.push_back([item isKindOfClass:[NSString class]] ? ToExactUtf8((NSString*)item) + : std::nullopt); } - - return true; + return items; } // ───────────────────────────────────────────────────────────── // The module HTTP cache // // Module fetches use ephemeral sessions, so no cookies or credentials persist. -// While the cache is enabled each origin has an on-disk NSURLCache in its own +// Each origin fetched with the cache on has an on-disk NSURLCache in its own // directory, so one origin's cache can be dropped without touching another's; -// the app's shared NSURLCache is never read, replaced or resized. While it is -// disabled fetches go through sessions without a cache. +// the app's shared NSURLCache is never read, replaced or resized. Fetches with +// the cache off go through sessions without a cache. // // The graph walk and the synchronous fallback each have sessions of their // own, configured alike, so a blocking fallback fetch never waits for a @@ -547,8 +80,10 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // its highest generation, and removes the others when it does. At most // kModuleCacheMaxOrigins origin directories outlive a launch. // -// All of it is process-wide, guarded by one mutex: fetch threads, every -// isolate's thread and the inspector's socket thread read and change it. +// All of it is process-wide, guarded by one mutex: fetch completions, every +// isolate's thread and the inspector's socket thread read and change it. An +// attempt's outcome goes to the core, which may clear the cache in response, so +// nothing is delivered to the core while that mutex is held. static constexpr NSUInteger kModuleCacheMemoryCapacity = 8 * 1024 * 1024; static constexpr NSUInteger kModuleCacheDiskCapacity = 256 * 1024 * 1024; @@ -558,21 +93,16 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // of the most recently opened ones. static constexpr NSUInteger kModuleCacheMaxOrigins = 8; -// Top-level app config key; `false` starts the process with the cache off. -static constexpr const char* kModuleHttpCacheConfigKey = "moduleHttpCache"; - namespace { -enum class ModuleFetchPath { kGraphWalk, kSynchronousFallback }; - // One session per path; the fallback's is created on first use, since most // processes never take the fallback. struct ModuleSessions { NSURLSession* graphWalk = nil; // retained NSURLSession* synchronousFallback = nil; // retained - NSURLSession*& For(ModuleFetchPath path) { - return path == ModuleFetchPath::kGraphWalk ? graphWalk : synchronousFallback; + NSURLSession*& For(FetchPath path) { + return path == FetchPath::kGraphWalk ? graphWalk : synchronousFallback; } }; @@ -586,8 +116,6 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { struct ModuleHttpCacheState { std::mutex mutex; bool initialized = false; - bool userEnabled = true; - std::set inspectorDisabledConnections; std::map partitions; // The generation each origin must open next, set when its cache is dropped // in this process. @@ -596,30 +124,18 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { NSURL* root = nil; // retained }; -ModuleHttpCacheState& CacheState() { - static auto* state = new ModuleHttpCacheState(); - return *state; -} - -} // namespace - -static NSURLSessionConfiguration* ModuleSessionConfiguration(NSURLCache* cache) { +NSURLSessionConfiguration* ModuleSessionConfiguration(NSURLCache* cache) { NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; // nil, not the ephemeral configuration's default in-memory cache: an // uncached session must not cache at all. config.URLCache = cache; config.HTTPShouldSetCookies = NO; - // Every module request overrides this (BuildModuleFetchRequest sets the - // same policy value); the session default exists so the two settings can - // never disagree about the budget again. - config.timeoutIntervalForRequest = ModuleFetchTimeoutInterval(); config.HTTPMaximumConnectionsPerHost = 32; return config; } // The session `path` uses with `cache` (nil: uncached), created on first use. -static NSURLSession* SessionLocked(ModuleSessions& sessions, ModuleFetchPath path, - NSURLCache* cache) { +NSURLSession* SessionLocked(ModuleSessions& sessions, FetchPath path, NSURLCache* cache) { NSURLSession*& session = sessions.For(path); if (session == nil) { session = [[NSURLSession sessionWithConfiguration:ModuleSessionConfiguration(cache)] retain]; @@ -628,7 +144,7 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { } // The sessions finish what they have in flight without being used again. -static void RetireSessions(ModuleSessions& sessions) { +void RetireSessions(ModuleSessions& sessions) { for (NSURLSession* session : {sessions.graphWalk, sessions.synchronousFallback}) { [session finishTasksAndInvalidate]; [session release]; @@ -636,17 +152,17 @@ static void RetireSessions(ModuleSessions& sessions) { sessions = ModuleSessions(); } -static NSURL* OriginsDirectory(ModuleHttpCacheState& state) { +NSURL* OriginsDirectory(ModuleHttpCacheState& state) { return [state.root URLByAppendingPathComponent:@"origins" isDirectory:YES]; } -static NSURL* TrashDirectory(ModuleHttpCacheState& state) { +NSURL* TrashDirectory(ModuleHttpCacheState& state) { return [state.root URLByAppendingPathComponent:@"trash" isDirectory:YES]; } // Moves `item` into trash under a fresh name. Returns false only when `item` -// still exists afterwards. -static bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item) { +// still exists afterwards, with the reason in `error`. +bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item, std::string* error = nullptr) { NSFileManager* fm = [NSFileManager defaultManager]; NSURL* trash = TrashDirectory(state); [fm createDirectoryAtURL:trash withIntermediateDirectories:YES attributes:nil error:nil]; @@ -657,10 +173,21 @@ static bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item) { if (![fm fileExistsAtPath:item.path]) { return true; } - return [fm removeItemAtURL:item error:nil]; + NSError* removeError = nil; + if ([fm removeItemAtURL:item error:&removeError]) { + return true; + } + if (error != nullptr) { + NSString* description = removeError.localizedDescription + ?: [NSString stringWithFormat:@"could not remove %@", item.path]; + *error = description.UTF8String ?: "could not remove a cache directory"; + } + return false; } -static void PurgeTrashInBackground(ModuleHttpCacheState& state) { +// Only removes what is inside trash, so concurrent purges, and a purge racing +// a MoveToTrash, at worst both try to remove one item. +void PurgeTrashInBackground(ModuleHttpCacheState& state) { NSURL* trash = TrashDirectory(state); dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ @autoreleasepool { @@ -677,7 +204,7 @@ static void PurgeTrashInBackground(ModuleHttpCacheState& state) { // "http://127.0.0.1:8080" → "http%3A%2F%2F127.0.0.1%3A8080": collision-free // and a single path component. -static NSString* OriginDirectoryName(const std::string& origin) { +NSString* OriginDirectoryName(const std::string& origin) { static const char kHex[] = "0123456789ABCDEF"; std::string name; for (unsigned char c : origin) { @@ -692,11 +219,16 @@ static void PurgeTrashInBackground(ModuleHttpCacheState& state) { return [NSString stringWithUTF8String:name.c_str()]; } +NSURL* OriginDirectory(ModuleHttpCacheState& state, const std::string& origin) { + return [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) + isDirectory:YES]; +} + // Keeps the kModuleCacheMaxOrigins origin directories opened most recently // (PartitionLocked stamps each one's modification date) and trashes the rest; // one whose date cannot be read counts as the oldest. Only safe before any // partition is open. -static void PruneOriginsLocked(ModuleHttpCacheState& state) { +void PruneOriginsLocked(ModuleHttpCacheState& state) { NSArray* origins = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:OriginsDirectory(state) includingPropertiesForKeys:@[ NSURLContentModificationDateKey ] @@ -719,7 +251,8 @@ static void PruneOriginsLocked(ModuleHttpCacheState& state) { } } -static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { +// Before the first fetch and the first clear in the process. +void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { if (state.initialized) { return; } @@ -731,19 +264,11 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { state.root = [[caches URLByAppendingPathComponent:@"ns-module-http-cache" isDirectory:YES] retain]; - NSArray* arguments = [NSProcessInfo processInfo].arguments; - id configured = Runtime::GetAppConfigValue(kModuleHttpCacheConfigKey); - if ([configured isKindOfClass:[NSNumber class]] && ![(NSNumber*)configured boolValue]) { - state.userEnabled = false; - } - if ([arguments containsObject:@"--nativescript-no-module-cache"]) { - state.userEnabled = false; - } - // Anything at the root besides the two directories above is not a cache // this runtime opens, so it goes too. NSFileManager* fm = [NSFileManager defaultManager]; - const bool clearAtLaunch = [arguments containsObject:@"--nativescript-clear-module-cache"]; + const bool clearAtLaunch = + [[NSProcessInfo processInfo].arguments containsObject:@"--nativescript-clear-module-cache"]; for (NSURL* item in [fm contentsOfDirectoryAtURL:state.root includingPropertiesForKeys:nil options:0 @@ -761,17 +286,14 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { // The partition for `origin`, opened on first use in this process. Opening // reuses the origin's highest generation on disk unless its cache was dropped // in this process, and removes every other generation. -static ModuleCachePartition& PartitionLocked(ModuleHttpCacheState& state, - const std::string& origin) { +ModuleCachePartition& PartitionLocked(ModuleHttpCacheState& state, const std::string& origin) { auto it = state.partitions.find(origin); if (it != state.partitions.end()) { return it->second; } NSFileManager* fm = [NSFileManager defaultManager]; - NSURL* originDirectory = - [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) - isDirectory:YES]; + NSURL* originDirectory = OriginDirectory(state, origin); uint64_t highest = 0; NSArray* entries = [fm contentsOfDirectoryAtURL:originDirectory includingPropertiesForKeys:nil @@ -814,16 +336,17 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { // Drops the cache of one open partition: its directory moves to trash, an // empty directory for the next generation takes its place, and both sessions -// are retired. -static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin) { +// are retired. False when the old directory could not be removed. +bool DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin, + std::string* error) { auto it = state.partitions.find(origin); if (it == state.partitions.end()) { - return; + return true; } ModuleCachePartition partition = it->second; state.partitions.erase(it); - MoveToTrash(state, partition.directory); + const bool trashed = MoveToTrash(state, partition.directory, error); const uint64_t next = partition.generation + 1; state.reservedGenerations[origin] = next; NSURL* nextDirectory = [[partition.directory URLByDeletingLastPathComponent] @@ -837,427 +360,256 @@ static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& RetireSessions(partition.sessions); [partition.cache release]; [partition.directory release]; + return trashed; } -static void ClearModuleHttpCacheLocked(ModuleHttpCacheState& state) { - // Every origin at once, opened in this process or not; the open ones then - // get their next-generation directory back. - MoveToTrash(state, OriginsDirectory(state)); - std::vector open; - for (const auto& entry : state.partitions) { - open.push_back(entry.first); - } - for (const std::string& origin : open) { - DropPartitionLocked(state, origin); - } - PurgeTrashInBackground(state); -} - -void SetModuleHttpCacheEnabled(bool enabled) { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - @autoreleasepool { - InitializeModuleHttpCacheLocked(state); - } - state.userEnabled = enabled; +nativescript::common::http::CacheOpResult CacheOpFailed(const std::string& error) { + return {false, "could not clear the module HTTP cache: " + error}; } -void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId, bool disabled) { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - if (disabled) { - state.inspectorDisabledConnections.insert(connectionId); - } else { - state.inspectorDisabledConnections.erase(connectionId); - } -} - -void ClearModuleHttpCache() { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - @autoreleasepool { - InitializeModuleHttpCacheLocked(state); - ClearModuleHttpCacheLocked(state); - } -} - -// Whether a Clear-Site-Data value, a comma-separated list of quoted strings, -// holds "cache" or "*". -static bool ClearSiteDataClearsCache(NSString* value) { - NSCharacterSet* whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; - for (NSString* item in [value componentsSeparatedByString:@","]) { - NSString* directive = [item stringByTrimmingCharactersInSet:whitespace]; - if ([directive isEqualToString:@"\"cache\""] || [directive isEqualToString:@"\"*\""]) { - return true; +void ApplyRequestHeaders(NSMutableURLRequest* urlRequest, const AttemptRequest& request) { + for (const auto& header : request.headers) { + NSString* name = [NSString stringWithUTF8String:header.name.c_str()]; + NSString* value = [NSString stringWithUTF8String:header.value.c_str()]; + if (name != nil && value != nil) { + [urlRequest addValue:value forHTTPHeaderField:name]; } } - return false; } -// Clear-Site-Data "cache" drops the cache of the response URL's origin. The -// partition the response was fetched through goes too, which is the same one -// unless a redirect crossed origins: the carrier itself is stored there, and -// left in place it would be replayed from the cache and clear again on every -// hit. Plain http: origins are honoured as well. -static void ApplyClearSiteData(NSURLResponse* response, const std::string& fetchingOrigin) { - if (![response isKindOfClass:[NSHTTPURLResponse class]]) { - return; - } - NSString* value = [(NSHTTPURLResponse*)response valueForHTTPHeaderField:@"Clear-Site-Data"]; - if (value == nil || !ClearSiteDataClearsCache(value)) { - return; - } - const std::string responseOrigin = HttpUrlOrigin(response.URL.absoluteString.UTF8String ?: ""); - - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - std::vector origins{responseOrigin}; - // Each origin once: a second pass would also trash the next-generation - // directory the first one reserved. - if (fetchingOrigin != responseOrigin) { - origins.push_back(fetchingOrigin); +// Autoreleased; nil when NSURL cannot parse the URL. +NSMutableURLRequest* BuildModuleFetchRequest(const AttemptRequest& request) { + NSString* string = [NSString stringWithUTF8String:request.url.c_str()]; + NSURL* url = string != nil ? [NSURL URLWithString:string] : nil; + if (url == nil) { + return nil; } - for (const std::string& origin : origins) { - if (origin.empty()) { - continue; - } - if (state.partitions.count(origin) != 0) { - DropPartitionLocked(state, origin); - } else { - MoveToTrash(state, - [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) - isDirectory:YES]); - } + NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url]; + [urlRequest setHTTPMethod:@"GET"]; + ApplyRequestHeaders(urlRequest, request); + [urlRequest setTimeoutInterval:std::chrono::duration(request.timeout).count()]; + [urlRequest setHTTPShouldHandleCookies:NO]; + if (!request.useCache) { + [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - PurgeTrashInBackground(state); + return urlRequest; } -// Shared request builder for every module fetch. Caching follows the protocol -// policy, so the server's response headers decide freshness. Returns an -// autoreleased NSMutableURLRequest (nil for unparseable URLs). -static NSMutableURLRequest* BuildModuleFetchRequest(const std::string& url) { - NSURL* u = [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; - if (!u) { - return nil; - } - - NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:u]; - [request setHTTPMethod:@"GET"]; - [request setValue:@"application/javascript, text/javascript, */*;q=0.1" - forHTTPHeaderField:@"Accept"]; - [request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; - [request setTimeoutInterval:ModuleFetchTimeoutInterval()]; - [request setHTTPShouldHandleCookies:NO]; - return request; +std::string Utf8(NSString* string) { + const char* utf8 = string.UTF8String; + return utf8 != nullptr ? std::string(utf8) : std::string(); } -// What a finished module fetch task produced, read off the NSURLResponse. -// `transportOk` means a response arrived at all; whether it is a usable module -// is ClassifyModuleResponse's call. -struct ModuleFetchOutcome { - bool transportOk = false; - int status = 0; - std::string contentType; - std::string body; -}; - -static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* response, - NSError* error) { - ModuleFetchOutcome outcome; - outcome.transportOk = error == nil; +// What a finished task produced. NSURLSession reports a body that failed after +// the status line as an error alongside the response, so a response counts as +// arrived only without an error; its status and headers are still reported. +AttemptOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* response, NSError* error) { + AttemptOutcome outcome; if ([response isKindOfClass:[NSHTTPURLResponse class]]) { - NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*)response; - outcome.status = (int)[httpResp statusCode]; - NSString* ct = [httpResp allHeaderFields][@"Content-Type"]; - if (ct) { - const char* utf8 = [ct UTF8String]; - if (utf8) outcome.contentType = std::string(utf8); + NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; + outcome.arrived = error == nil; + outcome.status = (int)httpResponse.statusCode; + outcome.contentType = Utf8([httpResponse valueForHTTPHeaderField:@"Content-Type"]); + outcome.finalUrl = Utf8(httpResponse.URL.absoluteString); + NSString* clearSiteData = [httpResponse valueForHTTPHeaderField:@"Clear-Site-Data"]; + if (clearSiteData != nil) { + outcome.clearSiteData.push_back(Utf8(clearSiteData)); } } - if (data && [data length] > 0) { - outcome.body.assign(static_cast([data bytes]), static_cast([data length])); + if (data.length > 0) { + outcome.body.assign(static_cast(data.bytes), static_cast(data.length)); } - return outcome; -} - -// Every module request goes out through here, whichever path issued it: the -// cache switch is read now, so it decides this request alone. `handler` runs -// exactly once, on the session's delegate queue, after the response's -// Clear-Site-Data has taken effect, so nothing the loader requests from then on -// can come from the cleared cache. `path` picks which of the two paths' sessions -// carries it. Returns the resumed task, autoreleased. -static NSURLSessionDataTask* StartModuleFetchTask(ModuleFetchPath path, - NSMutableURLRequest* request, - void (^handler)(NSData*, NSURLResponse*, - NSError*)) { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - InitializeModuleHttpCacheLocked(state); - - const bool enabled = state.userEnabled && state.inspectorDisabledConnections.empty(); - const std::string origin = - enabled ? HttpUrlOrigin(request.URL.absoluteString.UTF8String ?: "") : std::string(); - NSURLSession* session = nil; - if (!origin.empty()) { - ModuleCachePartition& partition = PartitionLocked(state, origin); - session = SessionLocked(partition.sessions, path, partition.cache); - } else { - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; - [request setValue:@"no-cache" forHTTPHeaderField:@"Pragma"]; - session = SessionLocked(state.uncached, path, nil); + if (error != nil) { + NSString* description = error.localizedDescription ?: @""; + NSString* domain = error.domain ?: @""; + outcome.errorDescription = + Utf8(domain) + " code=" + std::to_string((long)error.code) + " " + Utf8(description); } - void (^delivered)(NSData*, NSURLResponse*, NSError*) = - ^(NSData* data, NSURLResponse* response, NSError* error) { - @autoreleasepool { - try { - ApplyClearSiteData(response, origin); - } catch (...) { - Log(@"NativeScript: could not apply Clear-Site-Data from a module response"); - } - } - handler(data, response, error); - }; - // Created and resumed under the lock: a cache dropped on another thread - // invalidates its session, which then refuses new tasks. - NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:delivered]; - [task resume]; - return task; + return outcome; } -// One blocking fetch attempt for the synchronous fallback, on the fallback's -// own session over the same cache as the async path. The wait is bounded: `waitExpired` reports a -// task that had not completed when it ran out, which is then cancelled. -static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, - std::string& contentType, int& status, bool& waitExpired) { - waitExpired = false; - @autoreleasepool { - NSMutableURLRequest* request = BuildModuleFetchRequest(url); - if (!request) { - status = 0; - return false; - } +class NSURLSessionModuleTransport final : public ModuleTransport { + public: + const char* Name() const override { return "nsurlsession"; } - // Shared with the completion handler, which can outlive this frame when - // the wait expires. - struct SyncFetchState { - dispatch_semaphore_t done = dispatch_semaphore_create(0); - ModuleFetchOutcome outcome; - std::string errorDescription; - ~SyncFetchState() { dispatch_release(done); } - }; - auto state = std::make_shared(); + bool SchedulesItself() const override { return true; } - const auto fetchStartUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); + AttemptOutcome FetchBlocking(const AttemptRequest& request) override { + @autoreleasepool { + NSMutableURLRequest* urlRequest = BuildModuleFetchRequest(request); + if (urlRequest == nil) { + return MalformedUrl(); + } - NSURLSessionDataTask* task = StartModuleFetchTask( - ModuleFetchPath::kSynchronousFallback, request, - ^(NSData* data, NSURLResponse* response, NSError* error) { - try { - state->outcome = ReadModuleFetchOutcome(data, response, error); - if (error != nil) { - NSString* desc = error.localizedDescription ?: @""; - NSString* domain = error.domain ?: @""; - state->errorDescription = std::string(domain.UTF8String) + - " code=" + std::to_string((long)error.code) + " " + - desc.UTF8String; + // Shared with the completion handler, which can outlive this frame when + // the wait expires. + struct SyncFetchState { + dispatch_semaphore_t done = dispatch_semaphore_create(0); + AttemptOutcome outcome; + ~SyncFetchState() { dispatch_release(done); } + }; + auto sync = std::make_shared(); + + NSURLSessionDataTask* task = + StartTask(request, urlRequest, ^(NSData* data, NSURLResponse* response, NSError* error) { + @autoreleasepool { + try { + sync->outcome = ReadModuleFetchOutcome(data, response, error); + } catch (...) { + sync->outcome = AttemptOutcome(); + } } - } catch (...) { - state->outcome = ModuleFetchOutcome(); - } - dispatch_semaphore_signal(state->done); - }); + dispatch_semaphore_signal(sync->done); + }); + if (task == nil) { + return NoTask(); + } - const double waitSeconds = request.timeoutInterval + kModuleFetchSyncWaitMarginSeconds; - if (dispatch_semaphore_wait( - state->done, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitSeconds * NSEC_PER_SEC))) != - 0) { - [task cancel]; - waitExpired = true; - status = 0; - Log(@"NativeScript: synchronous module fetch of %s got no response within %.0fs", url.c_str(), - waitSeconds); - return false; + const dispatch_time_t waitUntil = + request.waitBound.count() > 0 + ? dispatch_time( + DISPATCH_TIME_NOW, + std::chrono::duration_cast(request.waitBound).count()) + : DISPATCH_TIME_FOREVER; + if (dispatch_semaphore_wait(sync->done, waitUntil) != 0) { + [task cancel]; + AttemptOutcome expired; + expired.waitExpired = true; + return expired; + } + return std::move(sync->outcome); } + } - const auto fetchEndUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t fetchMs = - fetchEndUs > fetchStartUs ? (fetchEndUs - fetchStartUs) / 1000ull : 0ull; - g_fetchSyncTotalMs.fetch_add(fetchMs, std::memory_order_relaxed); - if (fetchMs < 10) { - g_fetchSyncFast.fetch_add(1, std::memory_order_relaxed); - } else if (fetchMs < 100) { - g_fetchSyncMedium.fetch_add(1, std::memory_order_relaxed); - } else { - g_fetchSyncSlow.fetch_add(1, std::memory_order_relaxed); - } - const size_t syncCount = g_fetchSyncCount.fetch_add(1, std::memory_order_relaxed) + 1; - if (syncCount > 0 && syncCount % kFetchSyncSummaryEvery == 0 && - tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - const size_t fast = g_fetchSyncFast.load(std::memory_order_relaxed); - const size_t medium = g_fetchSyncMedium.load(std::memory_order_relaxed); - const size_t slow = g_fetchSyncSlow.load(std::memory_order_relaxed); - const uint64_t totalMs = g_fetchSyncTotalMs.load(std::memory_order_relaxed); - const uint64_t avgMs = syncCount ? totalMs / (uint64_t)syncCount : 0; - TNS_DEBUG(Esm, - "[http-loader][fetch-sync][summary] count=%lu avg=%llums fast(<10ms)=%lu " - "medium=%lu slow(>=100ms)=%lu", - (unsigned long)syncCount, (unsigned long long)avgMs, (unsigned long)fast, - (unsigned long)medium, (unsigned long)slow); + void FetchAsync(AttemptRequest request, std::function done) override { + auto deliver = std::make_shared>(std::move(done)); + @autoreleasepool { + NSMutableURLRequest* urlRequest = BuildModuleFetchRequest(request); + if (urlRequest == nil) { + (*deliver)(MalformedUrl()); + return; + } + NSURLSessionDataTask* task = + StartTask(request, urlRequest, ^(NSData* data, NSURLResponse* response, NSError* error) { + // NSURLSession invokes this block, so an exception leaving it is an + // std::terminate rather than a failed fetch. + @autoreleasepool { + AttemptOutcome outcome; + try { + outcome = ReadModuleFetchOutcome(data, response, error); + } catch (...) { + outcome = AttemptOutcome(); + } + try { + (*deliver)(std::move(outcome)); + } catch (...) { + } + } + }); + if (task == nil) { + (*deliver)(NoTask()); + } } + } - ModuleFetchOutcome& outcome = state->outcome; - status = outcome.status; - contentType = outcome.contentType; - if (!outcome.transportOk) { - TNS_DEBUG(Esm, "[http-loader][fetch-error] url=%s %s status=%d bodyEmpty=%d ms=%llu", - url.c_str(), state->errorDescription.c_str(), outcome.status, - outcome.body.empty() ? 1 : 0, (unsigned long long)fetchMs); - return false; - } - out.swap(outcome.body); + bool PostDelayed(std::chrono::milliseconds delay, std::function task) override { + auto run = std::make_shared>(std::move(task)); + dispatch_after( + dispatch_time(DISPATCH_TIME_NOW, + std::chrono::duration_cast(delay).count()), + dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + @autoreleasepool { + try { + (*run)(); + } catch (...) { + } + } + }); return true; } -} -// One network attempt for FetchModuleBodyAsync. Takes ownership of -// `completionHeap` (heap-allocated so the ObjC block can carry the -// std::function across threads without ARC) and guarantees exactly one -// invocation + delete. Retries once on transport error, mirroring the -// single-retry policy of the synchronous path. -// -// `fetchDeadline` (absolute CFAbsoluteTime, 0 = unbounded) is the enclosing -// graph load's fetch budget. Two full policy attempts plus the retry delay -// can outlast the pumped wait's deadline (e.g. 30s + 0.12s + 30s vs a 60s -// graph budget), so a bounded attempt clamps its request timeout to the time -// remaining and the retry fires only while some budget is left. A fetch that -// lands late is still reported — a dep failure stays on the designed path — -// but no request is issued that could only complete past the deadline. -static void PerformModuleFetchAsyncAttempt( - const std::string& url, int attempt, CFAbsoluteTime fetchDeadline, - std::function* completionHeap) { - @autoreleasepool { - const double remaining = - fetchDeadline > 0 ? fetchDeadline - CFAbsoluteTimeGetCurrent() : 0; - if (fetchDeadline > 0 && remaining <= 0) { - ModuleFetchResult failed; - failed.failureReason = - "HTTP import failed: " + url + " (module graph fetch deadline exceeded)"; - (*completionHeap)(std::move(failed)); - delete completionHeap; - return; + nativescript::common::http::CacheOpResult ClearAll() override { + std::lock_guard lock(state_.mutex); + @autoreleasepool { + InitializeModuleHttpCacheLocked(state_); + // Every origin at once, opened in this process or not; the open ones + // then get their next-generation directory back. + std::string error; + const bool trashed = MoveToTrash(state_, OriginsDirectory(state_), &error); + std::vector open; + for (const auto& entry : state_.partitions) { + open.push_back(entry.first); + } + for (const std::string& origin : open) { + DropPartitionLocked(state_, origin, nullptr); + } + PurgeTrashInBackground(state_); + return trashed ? nativescript::common::http::CacheOpResult{} : CacheOpFailed(error); } + } - NSMutableURLRequest* request = BuildModuleFetchRequest(url); - if (!request) { - ModuleFetchResult failed; - failed.failureReason = "HTTP import failed: " + url + " (malformed request URL)"; - (*completionHeap)(std::move(failed)); - delete completionHeap; - return; + // Each call drops what the origin has now. Called twice for one origin, the + // second finds no open partition and trashes the origin's directory, the + // reserved next generation included; PartitionLocked recreates that + // generation's directory when it reopens the origin. + nativescript::common::http::CacheOpResult ClearOrigin(const std::string& origin) override { + std::lock_guard lock(state_.mutex); + @autoreleasepool { + InitializeModuleHttpCacheLocked(state_); + std::string error; + const bool trashed = state_.partitions.count(origin) != 0 + ? DropPartitionLocked(state_, origin, &error) + : MoveToTrash(state_, OriginDirectory(state_, origin), &error); + PurgeTrashInBackground(state_); + return trashed ? nativescript::common::http::CacheOpResult{} : CacheOpFailed(error); } + } - if (fetchDeadline > 0 && remaining < request.timeoutInterval) { - [request setTimeoutInterval:remaining]; - } + private: + static AttemptOutcome MalformedUrl() { + AttemptOutcome outcome; + outcome.malformedUrl = true; + return outcome; + } - const std::string urlCopy = url; - const uint64_t startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - StartModuleFetchTask( - ModuleFetchPath::kGraphWalk, request, - ^(NSData* data, NSURLResponse* response, NSError* error) { - // NSURLSession invokes this block, so a C++ exception leaving it is - // an std::terminate rather than a failure anyone can report. Nothing - // here runs JS — the compile is posted to the isolate's own thread — - // so an escape could only come from an allocation failure, but the - // containment is structural on purpose: the graph load must hear - // back exactly once or it waits out its entire deadline. - bool retrying = false; - ModuleFetchResult result; - try { - ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); - int status = outcome.status; - std::string contentType = std::move(outcome.contentType); - std::string body = std::move(outcome.body); + static AttemptOutcome NoTask() { + AttemptOutcome outcome; + outcome.errorDescription = "NSURLSession created no task"; + return outcome; + } - // Transport error → one retry while the enclosing load's budget - // can still fit the delay — the same single-retry policy the - // sync path applies, without blocking any thread. The retry's - // own request clamps to whatever remains when it fires. - const bool retryFitsDeadline = - fetchDeadline <= 0 || - fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; - if (error != nil && attempt == 0 && retryFitsDeadline) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", - urlCopy.c_str(), - (error.localizedDescription ?: @"").UTF8String); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, - (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), - dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, - completionHeap); - }); - // Set only once the retry is actually queued: it now owns the - // completion, and this attempt must not settle it too. - retrying = true; - } else { - ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); + // Creates and resumes the task for `request` on the session its path and + // cache choice use; autoreleased, nil when the session would not create one. + // `handler` runs on the session's delegate queue. + NSURLSessionDataTask* StartTask(const AttemptRequest& request, NSMutableURLRequest* urlRequest, + void (^handler)(NSData*, NSURLResponse*, NSError*)) { + std::lock_guard lock(state_.mutex); + InitializeModuleHttpCacheLocked(state_); - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, - result.failureReason.c_str()); - } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { - const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", - urlCopy.c_str(), (unsigned long)result.body.size(), - (unsigned long long)ms); - } - } - } catch (...) { - if (retrying) { - // The retry owns the completion and will settle it; nothing to - // report from here. - return; - } - result = ModuleFetchResult(); - result.failureReason = - "HTTP import failed: " + urlCopy + " (internal error handling the response)"; - } - - if (retrying) { - return; - } - // Guarded for the same reason: the completion posts to the - // isolate's loop, and a throw on the way out would cross the - // ObjC boundary instead of failing the load. - try { - (*completionHeap)(std::move(result)); - } catch (...) { - Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); - } - delete completionHeap; - }); + const std::string origin = request.useCache ? HttpUrlOrigin(request.url) : std::string(); + NSURLSession* session = nil; + if (!origin.empty()) { + ModuleCachePartition& partition = PartitionLocked(state_, origin); + session = SessionLocked(partition.sessions, request.path, partition.cache); + } else { + [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + session = SessionLocked(state_.uncached, request.path, nil); + } + // Created and resumed under the lock: a cache dropped on another thread + // invalidates its session, which then refuses new tasks. + NSURLSessionDataTask* task = [session dataTaskWithRequest:urlRequest completionHandler:handler]; + [task resume]; + return task; } -} -void FetchModuleBodyAsync(const std::string& url, CFAbsoluteTime fetchDeadline, - std::function completion) { - // Security gate: single point of enforcement, same as HttpFetchModule. - if (!IsRemoteUrlAllowed(url)) { - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - ModuleFetchResult blocked; - blocked.status = 403; - blocked.failureReason = "HTTP import blocked: remote module loading is not allowed for " + url; - completion(std::move(blocked)); - return; - } + ModuleHttpCacheState state_; +}; - auto* completionHeap = new std::function(std::move(completion)); - PerformModuleFetchAsyncAttempt(url, 0, fetchDeadline, completionHeap); -} +} // namespace -// Cold-boot JS-thread runloop pump. -// +ModuleTransport& ModuleHttpTransport() { + static auto* transport = new NSURLSessionModuleTransport(); + return *transport; +} } // namespace tns diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index 76f5e5e4f..393ac206d 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -153,11 +153,11 @@ v8::MaybeLocal LoadHttpModuleForUrl( // Compilation runs no user code, so pre-compiling the closure cannot change // evaluation order: V8 still evaluates in spec order from the root. // -// `fetchDeadline` bounds the walk's HTTP fetches as an absolute CFAbsoluteTime -// (double; 0 = unbounded): each attempt clamps its request timeout to the -// time remaining and transport-error retries stop once no budget is left. -// Callers that pump for the load pass their own wait deadline so a fetch can -// never outlive the wait; callers that simply queue work pass 0. +// `fetchDeadline` bounds the walk's HTTP fetches (nullopt = unbounded): each +// attempt clamps its request timeout to the time remaining and +// transport-error retries stop once no budget is left. Callers that pump for +// the load pass their own wait deadline so a fetch can never outlive the +// wait; callers that simply queue work pass nullopt. // // `onComplete(ok, errorMessage, context)` runs exactly once on the isolate's // JS thread with the isolate entered and `context` (the context captured at @@ -184,7 +184,7 @@ struct ModuleGraphRoot { void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, - const ModuleGraphRoot& root, double fetchDeadline, + const ModuleGraphRoot& root, ModuleFetchDeadline fetchDeadline, std::function context)> onComplete); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 701f31c5b..a1dc048ec 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1418,10 +1418,10 @@ void SetCanonicalizationConfig(CanonicalizationConfig config) { size_t fetchedCount = 0; size_t compiledCount = 0; uint64_t startUs = 0; - // Absolute CFAbsoluteTime bounding this load's fetch attempts and their - // retries — the same deadline the pumped wait enforces, so a bounded fetch - // can never outlive the wait pumping for it. 0 = unbounded. - CFAbsoluteTime fetchDeadline = 0; + // Bounds this load's fetch attempts and their retries — the same deadline + // the pumped wait enforces, so a bounded fetch can never outlive the wait + // pumping for it. nullopt = unbounded. + ModuleFetchDeadline fetchDeadline; std::atomic dead{false}; // set by isolate teardown (any thread) std::function context)> onComplete; @@ -2841,7 +2841,7 @@ static ModuleResolution ResolutionForRoot(const ModuleGraphRoot& root) { static std::shared_ptr BeginModuleGraphLoad( v8::Isolate* isolate, v8::Local context, const ModuleGraphRoot& root, - double fetchDeadline, + ModuleFetchDeadline fetchDeadline, std::function context)> onComplete) { const ModuleResolution rootResolution = ResolutionForRoot(root); @@ -2878,7 +2878,7 @@ static ModuleResolution ResolutionForRoot(const ModuleGraphRoot& root) { void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, const ModuleGraphRoot& root, - double fetchDeadline, + ModuleFetchDeadline fetchDeadline, std::function context)> onComplete) { BeginModuleGraphLoad(isolate, context, root, fetchDeadline, std::move(onComplete)); @@ -2908,7 +2908,10 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local conte // issues: attempts clamp to the time remaining and retries stop once no // budget is left, so a fetch can never still be running after this wait // has given up on it. - const CFAbsoluteTime deadline = CFAbsoluteTimeGetCurrent() + timeoutSeconds; + const std::chrono::steady_clock::time_point deadline = + std::chrono::steady_clock::now() + + std::chrono::duration_cast( + std::chrono::duration(timeoutSeconds)); auto done = std::make_shared(false); SyncModuleLoadScope syncLoad(isolate); const std::shared_ptr load = @@ -2946,7 +2949,7 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local conte if (*done) { break; } - if (CFAbsoluteTimeGetCurrent() >= deadline) { + if (std::chrono::steady_clock::now() >= deadline) { break; } const uint64_t seen = fileJobSignal != nullptr ? fileJobSignal->Generation() : 0; @@ -4530,7 +4533,7 @@ static void SettleFileDynamicImport(v8::Isolate* isolate, v8::Local // immediately — no synchronous fetch, no runloop pump. const std::string requestUrl = normalizedSpec; StartModuleGraphLoad( - isolate, context, ModuleGraphRoot::HttpUrl(requestUrl), /*fetchDeadline=*/0, + isolate, context, ModuleGraphRoot::HttpUrl(requestUrl), /*fetchDeadline=*/std::nullopt, [key, requestUrl, isolate](bool ok, const std::string& errorMessage, v8::Local completionContext) { // JS thread; isolate entered and context scoped by the pipeline. @@ -4559,7 +4562,10 @@ static void SettleFileDynamicImport(v8::Isolate* isolate, v8::Local const uint64_t importId = moduleState->nextFileDynamicImportId++; moduleState->fileDynamicImports[importId].Reset(isolate, resolver); StartModuleGraphLoad( - isolate, context, root, CFAbsoluteTimeGetCurrent() + tns::kModuleEvaluateDeadlineSeconds, + isolate, context, root, + std::chrono::steady_clock::now() + + std::chrono::duration_cast( + std::chrono::duration(tns::kModuleEvaluateDeadlineSeconds)), [isolate, importId, resolution, normalizedSpec](bool ok, const std::string& errorMessage, v8::Local completionContext) { auto* state = ModuleLoaderStateFor(isolate); @@ -4893,7 +4899,11 @@ void SetHttpCacheEnabledCallback(const v8::FunctionCallbackInfo& info } void ClearHttpCacheCallback(const v8::FunctionCallbackInfo& info) { - tns::ClearModuleHttpCache(); + const tns::CacheOpResult cleared = tns::ClearModuleHttpCache(); + if (!cleared.ok) { + v8::Isolate* isolate = info.GetIsolate(); + isolate->ThrowException(v8::Exception::Error(tns::ToV8String(isolate, cleared.error))); + } } } // namespace diff --git a/NativeScript/runtime/RuntimeCommonPlatform.mm b/NativeScript/runtime/RuntimeCommonPlatform.mm new file mode 100644 index 000000000..f058cd44e --- /dev/null +++ b/NativeScript/runtime/RuntimeCommonPlatform.mm @@ -0,0 +1,88 @@ +// The link-time platform functions of the runtime-common core. +// +// ns/Platform.h declares a function named Log, which Helpers.h defines as a +// macro, so it is included first and the definition below names it in +// parentheses. +#include "ns/Platform.h" +#include "ns/http/ModuleTransport.h" + +#import + +#include +#include + +#include "Helpers.h" +#include "HttpLoader.h" +#include "ModuleUrl.h" +#include "Runtime.h" +#include "RuntimeConfig.h" + +namespace nativescript::common::platform { + +namespace { + +tns::LogCategory ToLogCategory(TraceCategory category) { + switch (category) { + case TraceCategory::kEsm: + return tns::LogCategory::Esm; + case TraceCategory::kFetch: + return tns::LogCategory::Fetch; + } + return tns::LogCategory::Esm; +} + +} // namespace + +void(Log)(std::string_view message) { + const std::string line(message); + Log(@"%s", line.c_str()); +} + +bool TraceEnabled(TraceCategory category) { + return tns::LogCategoryEnabled(ToLogCategory(category)); +} + +void Trace(TraceCategory category, std::string_view message) { + const tns::LogCategory logCategory = ToLogCategory(category); + if (tns::LogCategoryEnabled(logCategory)) { + const std::string line(message); + tns::EmitDebugLog(logCategory, "%s", line.c_str()); + } +} + +std::string NormalizeHttpModuleUrl(const std::string& input) { + return tns::NormalizeHttpModuleUrl(input); +} + +std::string HttpUrlOrigin(const std::string& url) { return tns::HttpUrlOrigin(url); } + +// Runs once, under the core's state mutex, on whichever thread first needs the +// loader; it reads app config and launch arguments only. +http::HttpLoaderConfig ReadHttpLoaderConfig() { + http::HttpLoaderConfig config; + config.isDebug = RuntimeConfig.IsDebug; + @autoreleasepool { + id security = tns::Runtime::GetAppConfigValue("security"); + if ([security isKindOfClass:[NSDictionary class]]) { + id allowRemote = ((NSDictionary*)security)[@"allowRemoteModules"]; + if ([allowRemote respondsToSelector:@selector(boolValue)]) { + config.allowRemoteModules = [allowRemote boolValue]; + } + config.remoteModuleAllowlist = + tns::RemoteModuleAllowlistItems(((NSDictionary*)security)[@"remoteModuleAllowlist"]); + } + + id moduleHttpCache = tns::Runtime::GetAppConfigValue("moduleHttpCache"); + if ([moduleHttpCache isKindOfClass:[NSNumber class]] && ![moduleHttpCache boolValue]) { + config.moduleHttpCacheAtStartup = false; + } + if ([[NSProcessInfo processInfo].arguments containsObject:@"--nativescript-no-module-cache"]) { + config.moduleHttpCacheAtStartup = false; + } + } + return config; +} + +http::ModuleTransport& HttpTransport() { return tns::ModuleHttpTransport(); } + +} // namespace nativescript::common::platform diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 4cd814ed3..3f44ad909 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -551,7 +551,7 @@ apply, worker teardown) belongs to whatever tooling drives it. | `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry, so the next import of each requests it again. While the HTTP cache is on, that request goes through it, so the server's caching headers decide whether it reaches the network; see [HTTP caching](#http-caching). Takes an array of strings; throws `TypeError` otherwise. | | `getLoadedModuleUrls()` | The **URL-like** keys currently in the module registry, as an array of strings (used to compute full-reload eviction sets). A key qualifies when it starts with `blob:` or contains `://` — plain filesystem paths are deliberately excluded, because a reload computes its eviction set from what a server can re-serve. | | `setHttpCacheEnabled(enabled)` | Turns the loader's HTTP cache on or off for the whole process, workers included; see [Turning the cache off and clearing it](#turning-the-cache-off-and-clearing-it). Throws `TypeError` unless `enabled` is a boolean. | -| `clearHttpCache()` | Empties the loader's HTTP cache for every origin, for the whole process and for later launches. | +| `clearHttpCache()` | Empties the loader's HTTP cache for every origin, for the whole process and for later launches. Throws `Error` if the cache could not be removed from disk. | | `createRequire(filenameOrURL)` | A `require` resolving against `filenameOrURL`'s directory (a trailing slash names the directory itself). Accepts an absolute path string, a `file:` URL string, or a URL object; anything else throws `TypeError`, and an `http(s)` base is refused outright because `require()` of a dev-served module is not supported — import those. ES module graphs load under Node's `require(esm)` rule: a graph containing top-level await is refused before it evaluates. | | `createPumpingRequire(filenameOrURL, options?)` | Same argument contract and same resolution, but an ES module graph with top-level await is evaluated by driving the loop until it settles, instead of being refused. **Callable only from a task context.** See [Pumping requires](#pumping-requires). | @@ -1397,7 +1397,9 @@ main one. On the main session they then still reach a `Network` domain handler the app registered (`@nativescript/core` registers one, and can clear its own state there), and that handler's reply is the one the frontend gets; without such a handler the runtime replies `{}`. A worker session's reply is -always the runtime's `{}`. +always the runtime's `{}`. A `Network.clearBrowserCache` that could not remove +the cache from disk is answered by the runtime with error `-32000`, on any +session, and does not reach the handler. ### App entries and bootstraps diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index f0a67408a..579571057 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -120,6 +120,8 @@ declare module "ns:module" { * Empties the loader's HTTP cache for every origin, for the whole process. * The next fetch of any module goes to the server, in this launch and in * later ones. The app's own HTTP cache is not touched. + * + * Throws `Error` if the cache could not be removed from disk. */ export function clearHttpCache(): void; diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 71967d0d3..05371b3d9 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -369,6 +369,13 @@ 4426A118ED82F704A1361CE0 /* Checks.h in Headers */ = {isa = PBXBuildFile; fileRef = A139A5040624EECB430D25A8 /* Checks.h */; }; 5C0AA1C00000000000000005 /* Base64.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000001 /* Base64.cpp */; }; 5C0AA1C00000000000000006 /* Base64Binding.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000002 /* Base64Binding.cpp */; }; + 5C0AA1C00000000000000020 /* Trace.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000010 /* Trace.cpp */; }; + 5C0AA1C00000000000000021 /* Canonicalize.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000011 /* Canonicalize.cpp */; }; + 5C0AA1C00000000000000022 /* HostClass.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000012 /* HostClass.cpp */; }; + 5C0AA1C00000000000000023 /* ModuleFetch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000013 /* ModuleFetch.cpp */; }; + 5C0AA1C00000000000000024 /* ModuleResponse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000014 /* ModuleResponse.cpp */; }; + 5C0AA1C00000000000000025 /* RemoteModuleAllowlist.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000015 /* RemoteModuleAllowlist.cpp */; }; + 5C0AA1C00000000000000031 /* RuntimeCommonPlatform.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */; }; 5C0AA1C00000000000000007 /* libRuntimeCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000003 /* libRuntimeCommon.a */; }; /* End PBXBuildFile section */ @@ -947,6 +954,13 @@ A139A5040624EECB430D25A8 /* Checks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Checks.h; sourceTree = ""; }; 5C0AA1C00000000000000001 /* Base64.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Base64.cpp; path = src/Base64.cpp; sourceTree = ""; }; 5C0AA1C00000000000000002 /* Base64Binding.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Base64Binding.cpp; path = src/Base64Binding.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000010 /* Trace.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Trace.cpp; path = src/Trace.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000011 /* Canonicalize.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Canonicalize.cpp; path = src/http/Canonicalize.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000012 /* HostClass.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = HostClass.cpp; path = src/http/HostClass.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000013 /* ModuleFetch.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = ModuleFetch.cpp; path = src/http/ModuleFetch.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000014 /* ModuleResponse.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = ModuleResponse.cpp; path = src/http/ModuleResponse.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000015 /* RemoteModuleAllowlist.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = RemoteModuleAllowlist.cpp; path = src/http/RemoteModuleAllowlist.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = RuntimeCommonPlatform.mm; sourceTree = ""; }; 5C0AA1C00000000000000003 /* libRuntimeCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRuntimeCommon.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -1593,6 +1607,7 @@ C2DDEB7D229EAC8200345BFE /* Helpers.mm */, AA5DBFD12EC191F8008D12F9 /* HttpLoader.h */, AA5DBFD22EC191F8008D12F9 /* HttpLoader.mm */, + 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */, C2FEA16E22A3C75C00A5C0FC /* InlineFunctions.h */, C2FEA16D22A3C75C00A5C0FC /* InlineFunctions.cpp */, C2DDEB65229EAC8100345BFE /* Interop.h */, @@ -1769,6 +1784,12 @@ children = ( 5C0AA1C00000000000000001 /* Base64.cpp */, 5C0AA1C00000000000000002 /* Base64Binding.cpp */, + 5C0AA1C00000000000000010 /* Trace.cpp */, + 5C0AA1C00000000000000011 /* Canonicalize.cpp */, + 5C0AA1C00000000000000012 /* HostClass.cpp */, + 5C0AA1C00000000000000013 /* ModuleFetch.cpp */, + 5C0AA1C00000000000000014 /* ModuleResponse.cpp */, + 5C0AA1C00000000000000015 /* RemoteModuleAllowlist.cpp */, ); path = "runtime-common"; sourceTree = ""; @@ -2620,6 +2641,7 @@ 3C78BA5C2A0D600100C20A88 /* ModuleBinding.cpp in Sources */, C2F4D0AD232F85E20008A2EB /* SymbolIterator.mm in Sources */, AA5DBFD32EC191F8008D12F9 /* HttpLoader.mm in Sources */, + 5C0AA1C00000000000000031 /* RuntimeCommonPlatform.mm in Sources */, C2DDEBA5229EAC8300345BFE /* Runtime.mm in Sources */, 6573B9CF291FE29F00B0ED7C /* V8Runtime.cpp in Sources */, 6573B9E3291FE2A700B0ED7C /* jsilib-posix.cpp in Sources */, @@ -2678,6 +2700,12 @@ files = ( 5C0AA1C00000000000000005 /* Base64.cpp in Sources */, 5C0AA1C00000000000000006 /* Base64Binding.cpp in Sources */, + 5C0AA1C00000000000000020 /* Trace.cpp in Sources */, + 5C0AA1C00000000000000021 /* Canonicalize.cpp in Sources */, + 5C0AA1C00000000000000022 /* HostClass.cpp in Sources */, + 5C0AA1C00000000000000023 /* ModuleFetch.cpp in Sources */, + 5C0AA1C00000000000000024 /* ModuleResponse.cpp in Sources */, + 5C0AA1C00000000000000025 /* RemoteModuleAllowlist.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3688,7 +3716,10 @@ "EXCLUDED_ARCHS[sdk=xros*]" = x86_64; "EXCLUDED_ARCHS[sdk=xrsimulator*]" = x86_64; GCC_PREFIX_HEADER = "NativeScript/NativeScript-Prefix.pch"; - HEADER_SEARCH_PATHS = "$(SRCROOT)/NativeScript/runtime-common/include"; + HEADER_SEARCH_PATHS = ( + "$(SRCROOT)/NativeScript/runtime-common/include", + "$(SRCROOT)/NativeScript/runtime-common/src", + ); IPHONEOS_DEPLOYMENT_TARGET = 13.0; OTHER_CFLAGS = ( "-fno-rtti", @@ -3723,7 +3754,10 @@ "EXCLUDED_ARCHS[sdk=xros*]" = x86_64; "EXCLUDED_ARCHS[sdk=xrsimulator*]" = x86_64; GCC_PREFIX_HEADER = "NativeScript/NativeScript-Prefix.pch"; - HEADER_SEARCH_PATHS = "$(SRCROOT)/NativeScript/runtime-common/include"; + HEADER_SEARCH_PATHS = ( + "$(SRCROOT)/NativeScript/runtime-common/include", + "$(SRCROOT)/NativeScript/runtime-common/src", + ); IPHONEOS_DEPLOYMENT_TARGET = 13.0; OTHER_CFLAGS = ( "-fno-rtti", From eca54cad9a1a21b32826872f037e169fe225a796 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:03:52 -0300 Subject: [PATCH 03/40] build: pin runtime-common foundation and implement its platform functions Pin NativeScript/runtime-common to ebb7b87 (foundation headers and the Loop interface) and compile its new sources in the RuntimeCommon target. Implement the new link-time platform functions: Loader() from RuntimeConfig (refreshed whenever initializeWithConfig writes it, with the V8 flag string the process actually applied), ApplyThreadPriority via pthread QoS, RunJob inside an autorelease pool, IsRuntimeAlive, MainContext, and the kRegistry trace category. Teach every loader-reachable catch boundary the core's JsError and Terminated ahead of its generic clauses: RequireCallback, RunModule, RunMainScript, the event loop's RunGuarded, the worker entry, the inspector modules entry, the graph walk's local compile, the resolver's file compile, and both import() settle paths. --- NativeScript/NativeScript.mm | 1 + NativeScript/inspector/JsV8InspectorClient.mm | 5 ++ NativeScript/runtime-common | 2 +- NativeScript/runtime/EventLoop.mm | 6 ++ NativeScript/runtime/ModuleInternal.mm | 15 +++++ .../runtime/ModuleInternalCallbacks.mm | 54 ++++++++++++++++ NativeScript/runtime/Runtime.h | 4 ++ NativeScript/runtime/Runtime.mm | 31 +++++++--- NativeScript/runtime/RuntimeCommonPlatform.mm | 61 ++++++++++++++++++- NativeScript/runtime/RuntimeConfig.h | 8 +++ NativeScript/runtime/Worker.mm | 9 +++ v8ios.xcodeproj/project.pbxproj | 32 ++++++++++ 12 files changed, 218 insertions(+), 10 deletions(-) diff --git a/NativeScript/NativeScript.mm b/NativeScript/NativeScript.mm index a660a6b64..bde2482f0 100644 --- a/NativeScript/NativeScript.mm +++ b/NativeScript/NativeScript.mm @@ -246,6 +246,7 @@ - (instancetype)initializeWithConfig:(Config*)config { Runtime::Initialize(); StartStdioForwarding(); DestroyMainRuntime(); + RefreshLoaderConfig(); std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); runtime_ = new Runtime(); Isolate* isolate = runtime_->GetIsolate(); diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 1696facbb..a63e086fe 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -12,6 +12,8 @@ #include "src/inspector/v8-runtime-agent-impl.h" #include "src/inspector/v8-stack-trace-impl.h" +#include "ns/JsError.h" + #include "Caches.h" #include "Helpers.h" #include "HttpLoader.h" @@ -1567,6 +1569,9 @@ bool GetInt32(const json& value, long long& out) { // Inspector modules are optional tooling; a failure must not take the // app down, but it must be visible. Log(@"Inspector modules failed to load: %s", ex.getMessage().c_str()); + } catch (nativescript::common::JsError& ex) { + Log(@"Inspector modules failed to load: %s", ex.what()); + } catch (nativescript::common::Terminated&) { } // FIXME: This triggers some DCHECK failures, due to the entered v8::Context in // Runtime::init(). diff --git a/NativeScript/runtime-common b/NativeScript/runtime-common index 3ebf3bc80..ebb7b87b9 160000 --- a/NativeScript/runtime-common +++ b/NativeScript/runtime-common @@ -1 +1 @@ -Subproject commit 3ebf3bc8078fd5372bf172d84750d876fa9d3bae +Subproject commit ebb7b87b9452320b8b9bfaea97142d7d4f6b95a8 diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index c33c42168..5623bcb9c 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -1,5 +1,7 @@ #include "EventLoop.h" +#include "ns/JsError.h" + #include #include #include @@ -29,6 +31,10 @@ void RunGuarded(F&& body) { } catch (tns::NativeScriptException& ex) { Log(@"NativeScript: uncaught NativeScriptException in event loop task: %s", ex.getMessage().c_str()); + } catch (nativescript::common::JsError& ex) { + Log(@"NativeScript: uncaught error in event loop task: %s", ex.what()); + } catch (nativescript::common::Terminated&) { + // the isolate is terminating; there is nothing left to report to } catch (std::exception& ex) { Log(@"NativeScript: c++ exception in event loop task: %s", ex.what()); } diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index da21b17be..429b634a6 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -19,6 +19,7 @@ #include "Runtime.h" #include "RuntimeConfig.h" #include "napi/NapiModules.h" +#include "ns/JsError.h" using namespace v8; @@ -246,6 +247,13 @@ static bool IsHttpModulePath(const std::string& path) { Log(@"Exception: %s", ex.getMessage().c_str()); } throw; + } catch (const nativescript::common::JsError& ex) { + if (RuntimeConfig.IsDebug) { + Log(@"***** JavaScript exception occurred *****"); + Log(@"Error loading ES module: %s", path.c_str()); + Log(@"Exception: %s", ex.what()); + } + throw; } if (moduleNamespace.IsEmpty()) { // `LoadESModule` returned an empty value without throwing. Provide a @@ -626,6 +634,13 @@ throw NativeScriptException( callingModuleDirName.c_str(), fullPath != nil ? [fullPath UTF8String] : "", ex.getMessage().c_str()); ex.ReThrowToV8(isolate); + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[require][fail] module=%s from=%s resolved=%s: %s", moduleName.c_str(), + callingModuleDirName.c_str(), + fullPath != nil ? [fullPath UTF8String] : "", ex.what()); + ex.ThrowToV8(isolate); + } catch (nativescript::common::Terminated& ex) { + ex.ThrowToV8(isolate); } } diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index a1dc048ec..90c90d10b 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -34,6 +34,7 @@ #include "NsBuiltinModules.h" #include "Runtime.h" // for GetAppConfigValue #include "RuntimeConfig.h" +#include "ns/JsError.h" // Do NOT pull all v8 symbols into namespace here; String would clash with // other typedefs inside the NativeScript codebase. We refer to v8 symbols @@ -2348,6 +2349,12 @@ static void AsyncGraphCompileLocalModule(const std::shared_ptr& TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), ex.getMessage().c_str()); return; + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), + ex.what()); + return; + } catch (nativescript::common::Terminated&) { + return; } if (!compiled) { TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), @@ -3505,6 +3512,12 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); return v8::MaybeLocal(); + } catch (nativescript::common::JsError& ex) { + ex.ThrowToV8(isolate); + return v8::MaybeLocal(); + } catch (nativescript::common::Terminated& ex) { + ex.ThrowToV8(isolate); + return v8::MaybeLocal(); } } @@ -3736,6 +3749,37 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local return CanonicalizeRegistryKey(resourceName); } +// Delivers `error` through an import() promise; on a terminating isolate, +// which can build no reason, the promise stays pending. +static void RejectWithJsError(v8::Isolate* isolate, v8::Local context, + v8::Local resolver, + const nativescript::common::JsError& error) { + v8::Local reason = error.ToV8(isolate); + if (!reason.IsEmpty()) { + resolver->Reject(context, reason).FromMaybe(false); + } +} + +// Rejects an import() promise with the error Terminated::ThrowToV8 builds +// while the termination is only requested; once V8 is terminating it builds +// none and the promise stays pending. +static void RejectWithTerminated(v8::Isolate* isolate, v8::Local context, + v8::Local resolver, + const nativescript::common::Terminated& terminated) { + v8::Local reason; + { + v8::TryCatch tc(isolate); + terminated.ThrowToV8(isolate); + if (tc.HasCaught() && !tc.HasTerminated()) { + reason = tc.Exception(); + } + tc.Reset(); + } + if (!reason.IsEmpty()) { + resolver->Reject(context, reason).FromMaybe(false); + } +} + // Links and evaluates the file module `resolution` names once its graph walk // has ended, and settles `resolver` with the outcome. The walk leaves JSON, // and any module it could not compile, to the load below, which also replaces @@ -3913,6 +3957,11 @@ static void SettleFileDynamicImport(v8::Isolate* isolate, v8::Local nativeTc.Reset(); } resolver->Reject(context, reason).FromMaybe(false); + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[dyn-import] ✗ native failed %s", normalizedSpec.c_str()); + RejectWithJsError(isolate, context, resolver, ex); + } catch (nativescript::common::Terminated& ex) { + RejectWithTerminated(isolate, context, resolver, ex); } } @@ -4606,6 +4655,11 @@ static void SettleFileDynamicImport(v8::Isolate* isolate, v8::Local nativeTc.Reset(); } resolver->Reject(context, reason).FromMaybe(false); + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[dyn-import] ✗ native failed %s", [specStr UTF8String]); + RejectWithJsError(isolate, context, resolver, ex); + } catch (nativescript::common::Terminated& ex) { + RejectWithTerminated(isolate, context, resolver, ex); } return scope.Escape(resolver->GetPromise()); diff --git a/NativeScript/runtime/Runtime.h b/NativeScript/runtime/Runtime.h index cb2fe7dc2..091c99c44 100644 --- a/NativeScript/runtime/Runtime.h +++ b/NativeScript/runtime/Runtime.h @@ -103,6 +103,10 @@ class Runtime { static void Initialize(); + // The string passed to v8::V8::SetFlagsFromString, which the first runtime + // of the process applies. Reads app config, so RuntimeConfig must be set. + static const std::string& V8Flags(); + static Runtime* GetCurrentRuntime() { return currentRuntime_; } static Runtime* GetRuntime(v8::Isolate* isolate); diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 8cba98744..f14b18190 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -1,5 +1,4 @@ #include "Runtime.h" -#include "DataWrapper.h" #include #include #include "ArgConverter.h" @@ -7,6 +6,7 @@ #include "Caches.h" #include "Console.h" #include "Constants.h" +#include "DataWrapper.h" #include "ErrorEvents.h" #include "Events.h" #include "ExternalMemory.h" @@ -29,6 +29,7 @@ #include "WeakRef.h" #include "Worker.h" #include "generated/Version.h" +#include "ns/JsError.h" #include "IsolateWrapper.h" @@ -216,6 +217,21 @@ static bool ShouldEnableJit() { } #endif +const std::string& Runtime::V8Flags() { + // Computed once: V8 freezes its flags at V8::Initialize(), so a later + // restartWithConfig with another IsDebug keeps running under these. + static const std::string flags = [] { + std::string result = RuntimeConfig.IsDebug ? "--expose_gc" : "--expose_gc --no-lazy"; +#if TARGET_OS_MACCATALYST + if (!ShouldEnableJit()) { + result += " --jitless"; + } +#endif + return result; + }(); + return flags; +} + Runtime::Runtime(const RuntimeOptions& options) : workerId_(options.workerId) { currentRuntime_ = this; workerCache_ = Caches::Workers; @@ -229,12 +245,7 @@ static bool ShouldEnableJit() { // Flags must be set before V8::Initialize(), which freezes them; changing a // flag afterwards aborts the process. iOS V8 is built in lite mode, which // already implies --jitless; only Mac Catalyst decides at launch. - std::string flags = RuntimeConfig.IsDebug ? "--expose_gc" : "--expose_gc --no-lazy"; -#if TARGET_OS_MACCATALYST - if (!ShouldEnableJit()) { - flags += " --jitless"; - } -#endif + const std::string& flags = V8Flags(); V8::SetFlagsFromString(flags.c_str(), flags.size()); // wrap the default platform so foreground tasks ride each runtime @@ -532,6 +543,12 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { // print exception details. Log(@"Fatal: the main module failed to run: %s", ex.getMessage().c_str()); throw; + } catch (nativescript::common::JsError& ex) { + Log(@"Fatal: the main module failed to run: %s", ex.what()); + throw; + } catch (nativescript::common::Terminated& ex) { + Log(@"Fatal: the main module failed to run: %s", ex.what()); + throw; } } diff --git a/NativeScript/runtime/RuntimeCommonPlatform.mm b/NativeScript/runtime/RuntimeCommonPlatform.mm index f058cd44e..d22e45482 100644 --- a/NativeScript/runtime/RuntimeCommonPlatform.mm +++ b/NativeScript/runtime/RuntimeCommonPlatform.mm @@ -1,16 +1,21 @@ // The link-time platform functions of the runtime-common core. // // ns/Platform.h declares a function named Log, which Helpers.h defines as a -// macro, so it is included first and the definition below names it in -// parentheses. +// macro, so the core headers come before Helpers.h and the definition below +// names it in parentheses. +#include "ns/LoaderConfig.h" #include "ns/Platform.h" +#include "ns/RuntimeAccess.h" +#include "ns/Thread.h" #include "ns/http/ModuleTransport.h" #import +#include #include #include +#include "Caches.h" #include "Helpers.h" #include "HttpLoader.h" #include "ModuleUrl.h" @@ -27,12 +32,46 @@ return tns::LogCategory::Esm; case TraceCategory::kFetch: return tns::LogCategory::Fetch; + case TraceCategory::kRegistry: + return tns::LogCategory::Registry; } return tns::LogCategory::Esm; } +LoaderConfig& LoaderConfigStorage() { + static LoaderConfig config; + return config; +} + } // namespace +const LoaderConfig& Loader() { return LoaderConfigStorage(); } + +void ApplyThreadPriority(ThreadPriority priority) { + qos_class_t qos = QOS_CLASS_USER_INITIATED; + switch (priority) { + case ThreadPriority::kUserInitiated: + qos = QOS_CLASS_USER_INITIATED; + break; + case ThreadPriority::kUtility: + qos = QOS_CLASS_UTILITY; + break; + } + pthread_set_qos_class_self_np(qos, 0); +} + +void RunJob(const std::function& job) { + @autoreleasepool { + job(); + } +} + +bool IsRuntimeAlive(v8::Isolate* isolate) { return tns::Runtime::GetRuntime(isolate) != nullptr; } + +v8::Local MainContext(v8::Isolate* isolate) { + return tns::Caches::Get(isolate)->GetContext(); +} + void(Log)(std::string_view message) { const std::string line(message); Log(@"%s", line.c_str()); @@ -86,3 +125,21 @@ void Trace(TraceCategory category, std::string_view message) { http::ModuleTransport& HttpTransport() { return tns::ModuleHttpTransport(); } } // namespace nativescript::common::platform + +namespace tns { + +void RefreshLoaderConfig() { + nativescript::common::LoaderConfig& config = + nativescript::common::platform::LoaderConfigStorage(); + config.appRoot = RuntimeConfig.ApplicationPath; + config.reportedPathPrefix = RuntimeConfig.BaseDir; + config.isDebug = RuntimeConfig.IsDebug; + config.codeCacheEnabled = !RuntimeConfig.IsDebug; + @autoreleasepool { + NSArray* caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + config.codeCacheDir = caches.count > 0 ? [caches[0] UTF8String] : ""; + } + config.v8Flags = Runtime::V8Flags(); +} + +} // namespace tns diff --git a/NativeScript/runtime/RuntimeConfig.h b/NativeScript/runtime/RuntimeConfig.h index dfa840930..3292db5cd 100644 --- a/NativeScript/runtime/RuntimeConfig.h +++ b/NativeScript/runtime/RuntimeConfig.h @@ -14,4 +14,12 @@ struct RuntimeConfig { extern struct RuntimeConfig RuntimeConfig; +namespace tns { + +// Rebuilds the runtime-common LoaderConfig from RuntimeConfig. Call whenever +// RuntimeConfig is written, before the main runtime that reads it starts. +void RefreshLoaderConfig(); + +} // namespace tns + #endif /* RuntimeConfig_h */ diff --git a/NativeScript/runtime/Worker.mm b/NativeScript/runtime/Worker.mm index ad49e9efe..18e578899 100644 --- a/NativeScript/runtime/Worker.mm +++ b/NativeScript/runtime/Worker.mm @@ -15,6 +15,7 @@ #include "ObjectManager.h" #include "Runtime.h" #include "RuntimeConfig.h" +#include "ns/JsError.h" using namespace v8; @@ -545,6 +546,14 @@ throw NativeScriptException("Cannot resolve worker path \"" + workerPath + HandleScope handle_scope(isolate); ex.ReThrowToV8(isolate); } + } catch (nativescript::common::JsError& ex) { + if (!worker->IsTerminating()) { + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + ex.ThrowToV8(isolate); + } + } catch (nativescript::common::Terminated&) { + // nothing may be thrown on a terminating isolate } // The entry was cut short — by terminate(), or by the near-heap-limit diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 05371b3d9..c035f0d4a 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -375,6 +375,14 @@ 5C0AA1C00000000000000023 /* ModuleFetch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000013 /* ModuleFetch.cpp */; }; 5C0AA1C00000000000000024 /* ModuleResponse.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000014 /* ModuleResponse.cpp */; }; 5C0AA1C00000000000000025 /* RemoteModuleAllowlist.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000015 /* RemoteModuleAllowlist.cpp */; }; + 5C0AA1C00000000000000050 /* HeaderCheck.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000040 /* HeaderCheck.cpp */; }; + 5C0AA1C00000000000000051 /* IsolateStateBag.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000041 /* IsolateStateBag.cpp */; }; + 5C0AA1C00000000000000052 /* JsError.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000042 /* JsError.cpp */; }; + 5C0AA1C00000000000000053 /* Loop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000043 /* Loop.cpp */; }; + 5C0AA1C00000000000000054 /* Thread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000044 /* Thread.cpp */; }; + 5C0AA1C00000000000000055 /* Utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000045 /* Utf8.cpp */; }; + 5C0AA1C00000000000000056 /* V8Flags.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000046 /* V8Flags.cpp */; }; + 5C0AA1C00000000000000057 /* V8Helpers.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000047 /* V8Helpers.cpp */; }; 5C0AA1C00000000000000031 /* RuntimeCommonPlatform.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */; }; 5C0AA1C00000000000000007 /* libRuntimeCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000003 /* libRuntimeCommon.a */; }; /* End PBXBuildFile section */ @@ -960,6 +968,14 @@ 5C0AA1C00000000000000013 /* ModuleFetch.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = ModuleFetch.cpp; path = src/http/ModuleFetch.cpp; sourceTree = ""; }; 5C0AA1C00000000000000014 /* ModuleResponse.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = ModuleResponse.cpp; path = src/http/ModuleResponse.cpp; sourceTree = ""; }; 5C0AA1C00000000000000015 /* RemoteModuleAllowlist.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = RemoteModuleAllowlist.cpp; path = src/http/RemoteModuleAllowlist.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000040 /* HeaderCheck.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = HeaderCheck.cpp; path = src/HeaderCheck.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000041 /* IsolateStateBag.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = IsolateStateBag.cpp; path = src/IsolateStateBag.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000042 /* JsError.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = JsError.cpp; path = src/JsError.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000043 /* Loop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Loop.cpp; path = src/Loop.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000044 /* Thread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Thread.cpp; path = src/Thread.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000045 /* Utf8.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Utf8.cpp; path = src/Utf8.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000046 /* V8Flags.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = V8Flags.cpp; path = src/V8Flags.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000047 /* V8Helpers.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = V8Helpers.cpp; path = src/V8Helpers.cpp; sourceTree = ""; }; 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = RuntimeCommonPlatform.mm; sourceTree = ""; }; 5C0AA1C00000000000000003 /* libRuntimeCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRuntimeCommon.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -1790,6 +1806,14 @@ 5C0AA1C00000000000000013 /* ModuleFetch.cpp */, 5C0AA1C00000000000000014 /* ModuleResponse.cpp */, 5C0AA1C00000000000000015 /* RemoteModuleAllowlist.cpp */, + 5C0AA1C00000000000000040 /* HeaderCheck.cpp */, + 5C0AA1C00000000000000041 /* IsolateStateBag.cpp */, + 5C0AA1C00000000000000042 /* JsError.cpp */, + 5C0AA1C00000000000000043 /* Loop.cpp */, + 5C0AA1C00000000000000044 /* Thread.cpp */, + 5C0AA1C00000000000000045 /* Utf8.cpp */, + 5C0AA1C00000000000000046 /* V8Flags.cpp */, + 5C0AA1C00000000000000047 /* V8Helpers.cpp */, ); path = "runtime-common"; sourceTree = ""; @@ -2706,6 +2730,14 @@ 5C0AA1C00000000000000023 /* ModuleFetch.cpp in Sources */, 5C0AA1C00000000000000024 /* ModuleResponse.cpp in Sources */, 5C0AA1C00000000000000025 /* RemoteModuleAllowlist.cpp in Sources */, + 5C0AA1C00000000000000050 /* HeaderCheck.cpp in Sources */, + 5C0AA1C00000000000000051 /* IsolateStateBag.cpp in Sources */, + 5C0AA1C00000000000000052 /* JsError.cpp in Sources */, + 5C0AA1C00000000000000053 /* Loop.cpp in Sources */, + 5C0AA1C00000000000000054 /* Thread.cpp in Sources */, + 5C0AA1C00000000000000055 /* Utf8.cpp in Sources */, + 5C0AA1C00000000000000056 /* V8Flags.cpp in Sources */, + 5C0AA1C00000000000000057 /* V8Helpers.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From cae3f7fd69b6cc77f00f21b588a181414402d214 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:09:49 -0300 Subject: [PATCH 04/40] feat(runtime): pump through Loop::PumpUntil tns::EventLoop implements the core's Loop interface. PumpUntil checks termination (the loop's flag, a terminating isolate, a stopped loop), then the caller's predicate, then a steady-clock deadline before every slice, and runs kNestableOnly, kV8Tasks or kPlatformWork slices with the waits the runtime's pumps already used. The termination flag moves onto the loop; Runtime forwards to it. The TLA settle pump, the pumped graph walk and the boot backstop now go through PumpUntil, so their deadlines are monotonic. The backstop runs short pumps under its own scopes and drains Tasks outside them, since the drain may enter UIApplicationMain and never return. A pumped walk that ended on a stopped loop is reported as a termination. --- NativeScript/NativeScript.mm | 49 +++++++--- NativeScript/runtime/EventLoop.h | 43 +++++++-- NativeScript/runtime/EventLoop.mm | 88 ++++++++++++++++++ NativeScript/runtime/ModuleInternal.mm | 93 +++++++------------ .../runtime/ModuleInternalCallbacks.mm | 90 ++++++++---------- NativeScript/runtime/Runtime.h | 25 +---- NativeScript/runtime/Runtime.mm | 10 -- NativeScript/runtime/RuntimeCommonPlatform.mm | 7 ++ 8 files changed, 247 insertions(+), 158 deletions(-) diff --git a/NativeScript/NativeScript.mm b/NativeScript/NativeScript.mm index bde2482f0..e8fe514c1 100644 --- a/NativeScript/NativeScript.mm +++ b/NativeScript/NativeScript.mm @@ -4,6 +4,9 @@ #include #include #include "inspector/JsV8InspectorClient.h" +#include "ns/Deadline.h" +#include "ns/Loop.h" +#include "runtime/Caches.h" #include "runtime/Console.h" #include "runtime/Helpers.h" #include "runtime/ModuleInternal.h" @@ -152,27 +155,45 @@ - (void)runMainApplication { bool entryRejected = false; if (entryPending || tns::HasPendingAsyncModuleGraphWork()) { - const CFAbsoluteTime deadline = - CFAbsoluteTimeGetCurrent() + 2 * tns::kModuleEvaluateDeadlineSeconds; + using nativescript::common::Deadline; + using nativescript::common::PumpMode; + using nativescript::common::PumpResult; + // Short, so a completion that registers the UIApplicationMain task gets to + // the Drain below promptly. + constexpr double kSliceSeconds = 0.01; + + const Deadline deadline = + nativescript::common::DeadlineAfterSeconds(2 * tns::kModuleEvaluateDeadlineSeconds); + Isolate* isolate = runtime_->GetIsolate(); + std::shared_ptr eventLoop = runtime_->GetEventLoop(); bool terminated = false; for (;;) { - // Termination outranks everything, including an entry that settled in the - // same slice: boot must report the terminating fatal rather than take the - // normal exit and carry on into an app on a stopping isolate. Nothing - // pending can complete after this point either. Both signals: V8 reports - // only a materialized termination, which needs JS to run, and an entry - // parked on a promise nothing settles never runs any. - if (runtime_->IsExecutionTerminating() || runtime_->IsTerminationRequested()) { - terminated = true; - break; + PumpResult result; + { + v8::Locker locker(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Context::Scope context_scope(Caches::Get(isolate)->GetContext()); + Deadline slice = nativescript::common::DeadlineAfterSeconds(kSliceSeconds); + if (deadline.has_value() && slice.has_value() && *deadline < *slice) { + slice = deadline; + } + result = eventLoop->PumpUntil( + slice, [&]() { return !(entryPending || tns::HasPendingAsyncModuleGraphWork()); }, + PumpMode::kPlatformWork); } - if (!(entryPending || tns::HasPendingAsyncModuleGraphWork())) { + if (result == PumpResult::kTerminated) { + // Outranks an entry that settled in the same slice: boot must report + // the terminating fatal rather than take the normal exit and carry on + // into an app on a stopping isolate. Nothing pending can complete now. + terminated = true; break; } - if (CFAbsoluteTimeGetCurrent() >= deadline) { + if (result == PumpResult::kSettled || nativescript::common::DeadlinePassed(deadline)) { break; } - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true); + // Outside every scope above: it may call UIApplicationMain and never + // return, and nothing held here may outlive that. tns::Tasks::Drain(); if (entryPending) { diff --git a/NativeScript/runtime/EventLoop.h b/NativeScript/runtime/EventLoop.h index fc36a0264..16a65f314 100644 --- a/NativeScript/runtime/EventLoop.h +++ b/NativeScript/runtime/EventLoop.h @@ -3,6 +3,8 @@ #include +#include +#include #include #include #include @@ -13,6 +15,7 @@ #include #include "Common.h" +#include "ns/Loop.h" #include "v8-platform.h" // 1: JS timers keep exact fire-date order with foreign runloop timers at the @@ -98,11 +101,11 @@ class OrderedTaskSource { * sibling, possibly on this loop), so Shutdown moves the lanes out and lets * them die after the unlock. */ -class EventLoop { +class EventLoop : public nativescript::common::Loop { public: explicit EventLoop(v8::Isolate* isolate) : isolate_(isolate) {} - ~EventLoop(); + ~EventLoop() override; /** * Attaches both lanes to the calling thread's CFRunLoop and flushes work @@ -153,8 +156,8 @@ class EventLoop { // internal lane: runs on the home thread as soon as the runloop polls. // Returns false if the post was dropped (loop already shut down). - bool PostInternal(std::function fn); - bool PostInternalDelayed(std::function fn, double delayMs); + bool PostInternal(std::function fn) override; + bool PostInternalDelayed(std::function fn, double delayMs) override; /** * Internal-lane post whose fn does its OWN isolate ceremony: RunEntry skips @@ -171,13 +174,13 @@ class EventLoop { * platform's per-isolate v8::TaskRunner adapter, from any thread. */ void PostV8Task(std::unique_ptr task, bool nestable, - double delaySeconds); + double delaySeconds) override; /** * True once Shutdown ran. A stopped loop found in the platform registry for * a (reused) isolate pointer is stale and must be replaced. */ - bool IsStopped(); + bool IsStopped() override; /** * Runs the internal-lane v8 tasks that are due and nestable, bounded to the @@ -186,7 +189,30 @@ class EventLoop { * tasks and plain function posts stay queued and run from their own wakeups * after the loop unwinds. */ - void RunNestableV8Tasks(); + void RunNestableV8Tasks() override; + + /** + * See nativescript::common::Loop::PumpUntil. A kPlatformWork slice is a + * default-mode CFRunLoop slice, so it also runs non-nestable tasks, bare + * posts, ordered entries and JS timers. + */ + nativescript::common::PumpResult PumpUntil( + const nativescript::common::Deadline& deadline, + const std::function& settled, nativescript::common::PumpMode mode, + const std::function& idle = nullptr) override; + + /** + * Records that termination was requested for this loop's isolate. Called on + * the requesting thread before TerminateExecution: V8 reports a termination + * only once running JS materializes it, and a pump parked on a promise + * nothing settles runs none, so without the flag it would spend its whole + * deadline. One-way: a worker never un-terminates. + */ + void RequestTermination(); + bool TerminationRequested() const override; + + // False until BindToCurrentThread has run. + bool IsOnHomeThread() const override; /** * Runs at most one due ordered-lane item (an entry, a timer, or a @@ -271,6 +297,9 @@ class EventLoop { CFRunLoopSourceRef internalSource_ = nullptr; CFRunLoopTimerRef internalTimer_ = nullptr; bool stopped_ = false; + std::atomic terminationRequested_{false}; + // pthread_threadid_np of the bound thread; 0 while unbound + std::atomic homeThreadId_{0}; }; } // namespace tns diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index 5623bcb9c..eee20e7a0 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -2,6 +2,9 @@ #include "ns/JsError.h" +#include +#include + #include #include #include @@ -13,6 +16,9 @@ #include "NativeScriptException.h" using namespace v8; +using nativescript::common::Deadline; +using nativescript::common::PumpMode; +using nativescript::common::PumpResult; namespace { @@ -103,6 +109,9 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { } loop_ = CFRunLoopGetCurrent(); + uint64_t threadId = 0; + pthread_threadid_np(nullptr, &threadId); + homeThreadId_.store(threadId, std::memory_order_release); CFRunLoopSourceContext sourceContext = { 0, this, nullptr, nullptr, nullptr, @@ -527,6 +536,85 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { } } +PumpResult EventLoop::PumpUntil(const Deadline& deadline, const std::function& settled, + PumpMode mode, const std::function& idle) { + // Short, so a completion posted during a wait is picked up promptly. The + // kV8Tasks wait must stay within the 10 ms Loop.h allows. + constexpr int kNestableOnlyIdleMs = 2; + constexpr useconds_t kV8TasksIdleMicros = 1000; + constexpr CFTimeInterval kPlatformSliceSeconds = 0.01; + + for (;;) { + if (TerminationRequested() || isolate_->IsExecutionTerminating() || IsStopped()) { + return PumpResult::kTerminated; + } + if (settled()) { + return PumpResult::kSettled; + } + if (nativescript::common::DeadlinePassed(deadline)) { + return PumpResult::kDeadline; + } + + switch (mode) { + case PumpMode::kNestableOnly: { + { + v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); + RunNestableV8Tasks(); + } + if (settled()) { + // back to the head, where termination outranks this settlement + continue; + } + if (idle != nullptr) { + idle(kNestableOnlyIdleMs); + } else { + usleep(kNestableOnlyIdleMs * 1000); + } + break; + } + case PumpMode::kV8Tasks: { + RunNestableV8Tasks(); + isolate_->PerformMicrotaskCheckpoint(); + if (settled()) { + continue; + } + usleep(kV8TasksIdleMicros); + break; + } + case PumpMode::kPlatformWork: { + RunNestableV8Tasks(); + isolate_->PerformMicrotaskCheckpoint(); + if (settled()) { + continue; + } + @autoreleasepool { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, kPlatformSliceSeconds, true); + } + isolate_->PerformMicrotaskCheckpoint(); + break; + } + } + } +} + +void EventLoop::RequestTermination() { + terminationRequested_.store(true, std::memory_order_relaxed); +} + +bool EventLoop::TerminationRequested() const { + return terminationRequested_.load(std::memory_order_relaxed); +} + +bool EventLoop::IsOnHomeThread() const { + const uint64_t home = homeThreadId_.load(std::memory_order_acquire); + if (home == 0) { + return false; + } + uint64_t self = 0; + pthread_threadid_np(nullptr, &self); + return self == home; +} + void EventLoop::RunOrderedTask() { // one anonymous token = one due slot across the whole ordered domain: pick // the earliest due item among the ordered entries and the timer source, diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index 429b634a6..166aeaba4 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -22,6 +22,8 @@ #include "ns/JsError.h" using namespace v8; +using nativescript::common::PumpMode; +using nativescript::common::PumpResult; namespace tns { @@ -1363,41 +1365,21 @@ throw NativeScriptException("ES module " + canonicalPath + // An await whose resolution arrives as a v8 foreground task (e.g. // Atomics.waitAsync, streaming compilation) never settles from // checkpoints alone; JS frames are on the stack, so like the inspector - // pause loops only nestable tasks may run here. + // pause loops only nestable tasks may run here, unless the caller opted + // into runloop slices. Runtime* runtime = Runtime::GetRuntime(isolate); std::shared_ptr eventLoop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; - auto pumpAsyncProgress = [&]() { - if (eventLoop != nullptr) { - eventLoop->RunNestableV8Tasks(); - } - isolate->PerformMicrotaskCheckpoint(); - if (options.pumpRunLoop) { - @autoreleasepool { - NSRunLoop* runLoop = - [NSThread isMainThread] ? [NSRunLoop mainRunLoop] : [NSRunLoop currentRunLoop]; - NSDate* sliceDeadline = [NSDate dateWithTimeIntervalSinceNow:0.01]; - [runLoop runMode:NSDefaultRunLoopMode beforeDate:sliceDeadline]; - } - isolate->PerformMicrotaskCheckpoint(); - } - }; - - NSDate* deadline = [NSDate dateWithTimeIntervalSinceNow:options.deadlineSeconds]; - bool settled = false; - // Termination outranks a settled result and a timeout alike. Handing back a // namespace would send the caller on to run more JS — enabling a queue, // draining messages — on an isolate V8 has already been told to stop, and // reporting a timeout would name a reason that is not the real one. // - // Three signals are consulted: V8 only reports a termination it has already - // materialized, which needs JS to run, and a graph parked on a promise - // nothing settles never gives it any; one that materialized inside a - // checkpoint lands in promiseTc. Message-only exception: building a V8 - // error on a terminating isolate is not allowed. - auto throwIfTerminating = [&]() { - if (!promiseTc.HasTerminated() && !isolate->IsExecutionTerminating() && + // Besides the pump's verdict, a termination that materialized inside a + // checkpoint lands in promiseTc, which the pump cannot see. Message-only + // exception: building a V8 error on a terminating isolate is not allowed. + auto throwIfTerminating = [&](bool pumpTerminated) { + if (!pumpTerminated && !promiseTc.HasTerminated() && !isolate->IsExecutionTerminating() && (runtime == nullptr || !runtime->IsTerminationRequested())) { return; } @@ -1413,38 +1395,34 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio canonicalPath); }; - // State is checked before the first pump: a synchronous graph's - // evaluation promise is already settled when Evaluate() returns, so it - // exits here without paying for a runloop slice. - while (!promiseTc.HasCaught()) { - throwIfTerminating(); + // Probed before the first slice: a synchronous graph's evaluation promise is + // already settled when Evaluate() returns, so it costs no slice. Anything + // promiseTc catches ends the wait as well. + auto settledOrCaught = [&]() { + return promiseTc.HasCaught() || promise->State() != Promise::kPending; + }; + PumpResult pumpResult; + if (eventLoop != nullptr) { + pumpResult = eventLoop->PumpUntil( + nativescript::common::DeadlineAfterSeconds(options.deadlineSeconds), settledOrCaught, + options.pumpRunLoop ? PumpMode::kPlatformWork : PumpMode::kV8Tasks); + } else { + pumpResult = settledOrCaught() ? PumpResult::kSettled : PumpResult::kDeadline; + } + throwIfTerminating(pumpResult == PumpResult::kTerminated); + if (!promiseTc.HasCaught()) { Promise::PromiseState state = promise->State(); - if (state != Promise::kPending) { - settled = true; - if (state == Promise::kRejected) { - ThrowModuleEvaluationRejection(isolate, promise, promiseTc, canonicalPath); - } - LogEsmPhase(canonicalPath, "evaluate", "promise-resolved"); - break; - } - - if ([deadline timeIntervalSinceNow] <= 0) { - break; + if (state == Promise::kRejected) { + ThrowModuleEvaluationRejection(isolate, promise, promiseTc, canonicalPath); } - - pumpAsyncProgress(); - if (!options.pumpRunLoop) { - usleep(1000); // 1ms delay for non-HTTP top-level await polling + if (state == Promise::kFulfilled) { + LogEsmPhase(canonicalPath, "evaluate", "promise-resolved"); + return MaybeLocal(); } } - // The loop leaves through its condition when a pump materializes the - // termination, and through the deadline when the request arrived during the - // final slice. - throwIfTerminating(); - - if (!settled && promise->State() == Promise::kPending) { + if (promise->State() == Promise::kPending) { LogEsmPhase(canonicalPath, "evaluate", "promise-timeout"); if (options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow) { RemoveModuleFromRegistry(isolate, canonicalPath); @@ -1467,14 +1445,15 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio return MaybeLocal(); } -// A pumped graph walk bails on a termination request but reports nothing; -// what follows it would compile, fetch synchronously or evaluate on an -// isolate that must not run anything more. +// A pumped graph walk bails on a termination request (or a stopped loop) but +// reports nothing; what follows it would compile, fetch synchronously or +// evaluate on an isolate that must not run anything more. static void ThrowIfLoadInterruptedByTermination(Isolate* isolate, const std::string& canonicalPath) { Runtime* runtime = Runtime::GetRuntime(isolate); if (!isolate->IsExecutionTerminating() && - (runtime == nullptr || !runtime->IsTerminationRequested())) { + (runtime == nullptr || + (!runtime->IsTerminationRequested() && !runtime->GetEventLoop()->IsStopped()))) { return; } LogEsmPhase(canonicalPath, "load", "terminated"); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 90c90d10b..d99d280a9 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -2908,6 +2908,9 @@ void StartModuleGraphLoad( bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local context, const ModuleGraphRoot& root, double timeoutSeconds) { + using nativescript::common::PumpMode; + using nativescript::common::PumpResult; + if (timeoutSeconds <= 0.0) { timeoutSeconds = 60.0; } @@ -2915,10 +2918,7 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local conte // issues: attempts clamp to the time remaining and retries stop once no // budget is left, so a fetch can never still be running after this wait // has given up on it. - const std::chrono::steady_clock::time_point deadline = - std::chrono::steady_clock::now() + - std::chrono::duration_cast( - std::chrono::duration(timeoutSeconds)); + const ModuleFetchDeadline deadline = nativescript::common::DeadlineAfterSeconds(timeoutSeconds); auto done = std::make_shared(false); SyncModuleLoadScope syncLoad(isolate); const std::shared_ptr load = @@ -2930,59 +2930,51 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local conte moduleState != nullptr ? moduleState->fileJobSignal : nullptr; // Manual pump ("until either all is settled or UIApplicationMain is - // called"). Fetch completions are nestable v8 foreground tasks on the - // isolate's event loop, drained directly; the short RunInMode slice stays - // as the idle-wait and still services any other runloop-delivered work the - // walk indirectly depends on. If UIApplicationMain takes over later, its - // runloop services the remainder instead. + // called"). Fetch and file completions are nestable v8 foreground tasks on + // the isolate's event loop. With an HTTP fetch outstanding the walk takes + // runloop slices, which also service any other runloop-delivered work a + // fetch indirectly depends on. While only background file loads are + // outstanding it sleeps on their signal instead, which keeps timers, promise + // jobs and other event-loop work out of a synchronous require(); the wait is + // short because a background compile may be waiting on a GC it asked this + // thread for, which also arrives as a nestable task. A landed file can + // reveal HTTP edges, so the mode is chosen again whenever the other one's + // condition flips. If UIApplicationMain takes over later, its runloop + // services the remainder instead. + // + // Termination outranks completion: a walk that finished in the slice + // termination began must still report failure, since success sends the + // caller on to instantiate and evaluate the graph on an isolate V8 has been + // told to stop. Runtime* runtime = Runtime::GetRuntime(isolate); std::shared_ptr eventLoop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; - for (;;) { - // Termination outranks completion, which is why this precedes the `*done` - // test rather than sharing a loop condition with it. A walk that finished - // in the same slice termination began must still report failure: returning - // success sends the caller on to instantiate and evaluate the graph, which - // is more JS on an isolate V8 has been told to stop. No fetch completion - // can arrive after this point either, so the remaining budget would only be - // spent waiting for work that cannot come. The requested-flag is consulted - // too: V8 surfaces a termination only once it has materialized it, which - // takes JS this wait may never run. - if (isolate->IsExecutionTerminating() || - (runtime != nullptr && runtime->IsTerminationRequested())) { + while (eventLoop != nullptr) { + PumpResult result; + if (load->pendingHttpFetches > 0 || fileJobSignal == nullptr) { + result = eventLoop->PumpUntil( + deadline, + [&]() { return *done || (fileJobSignal != nullptr && load->pendingHttpFetches == 0); }, + PumpMode::kPlatformWork); + } else { + // Sampled before each drain, so a completion posted while the pump + // drains ends the next wait at once. + uint64_t seen = fileJobSignal->Generation(); + result = eventLoop->PumpUntil( + deadline, [&]() { return *done || load->pendingHttpFetches > 0; }, + PumpMode::kNestableOnly, + [&](int waitMs) { + fileJobSignal->WaitForChange(seen, std::chrono::milliseconds(waitMs)); + seen = fileJobSignal->Generation(); + }); + } + if (result == PumpResult::kTerminated) { TNS_DEBUG(Esm, "[graph][pumped] execution terminating, abandoning wait for %s", (root.http ? root.url : root.key).c_str()); return false; } - if (*done) { - break; - } - if (std::chrono::steady_clock::now() >= deadline) { + if (result == PumpResult::kDeadline || *done) { break; } - const uint64_t seen = fileJobSignal != nullptr ? fileJobSignal->Generation() : 0; - if (eventLoop != nullptr && load->pendingHttpFetches == 0) { - // Nothing the walk waits for needs a microtask, and running them here - // would run promise jobs inside a synchronous require(). - v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate); - eventLoop->RunNestableV8Tasks(); - } else if (eventLoop != nullptr) { - eventLoop->RunNestableV8Tasks(); - } - if (*done) { - // Back to the loop head rather than breaking here: the termination check - // gets the last word on a completion the drain just produced. - continue; - } - if (load->pendingHttpFetches > 0 || fileJobSignal == nullptr || eventLoop == nullptr) { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true); - } else { - // Only background file loads are outstanding, and their completions - // are nestable V8 tasks: sleeping here instead of in the runloop keeps - // timers and other event-loop work out of a synchronous require(). The - // timeout bounds how long a background compile waits for a GC it asked - // this thread for, which also arrives as a nestable V8 task. - fileJobSignal->WaitForChange(seen, std::chrono::milliseconds(2)); - } } if (!*done) { TNS_DEBUG(Esm, "[graph][pumped][timeout] root=%s after %.1fs (sync loader takes over)", diff --git a/NativeScript/runtime/Runtime.h b/NativeScript/runtime/Runtime.h index 091c99c44..2ce5de095 100644 --- a/NativeScript/runtime/Runtime.h +++ b/NativeScript/runtime/Runtime.h @@ -73,27 +73,11 @@ class Runtime { // fall off main() yet. EntryEvaluationState PollMainEntryEvaluation(std::string* rejectionReason); - // Whether V8 has been asked to terminate execution on this isolate, entering - // it the same way PollMainEntryEvaluation does. The boot pump asks so it can - // stop waiting on work that can no longer make progress. - bool IsExecutionTerminating(); - - // Whether termination has been *requested* for this runtime's isolate. - // - // v8::Isolate::IsExecutionTerminating only reports a termination that has - // already been materialized, which takes running JS to happen: a graph parked - // on a promise nothing will settle queues no microtasks and no tasks, so a - // pump waiting on it would never observe the terminate and would spend its - // entire deadline first. This flag is set on the requesting thread, before - // TerminateExecution, so the pumps can bail on the request itself. - // - // One-way on purpose: a worker never un-terminates, so there is no reset and - // no window in which a stale `true` could strand live work. - void RequestTermination() { - terminationRequested_.store(true, std::memory_order_relaxed); - } + // The event loop's termination flag (EventLoop::RequestTermination): set + // before TerminateExecution, so the pumps bail on the request itself. + void RequestTermination() { eventLoop_->RequestTermination(); } bool IsTerminationRequested() const { - return terminationRequested_.load(std::memory_order_relaxed); + return eventLoop_->TerminationRequested(); } // Drops the main entry's module from the registry, entering the isolate the @@ -192,7 +176,6 @@ class Runtime { CFRunLoopActivity activity, void* info); v8::Isolate* isolate_ = nullptr; bool initialized_ = false; - std::atomic terminationRequested_{false}; napi_env napiEnv_ = nullptr; std::unique_ptr moduleInternal_; int workerId_; diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index f14b18190..f5215b5d8 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -594,16 +594,6 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { RemoveModuleFromRegistry(isolate, ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath)); } -bool Runtime::IsExecutionTerminating() { - Isolate* isolate = this->GetIsolate(); - if (isolate == nullptr) { - return false; - } - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - return isolate->IsExecutionTerminating(); -} - void Runtime::RunScript(const std::string script) { Isolate* isolate = this->GetIsolate(); v8::Locker locker(isolate); diff --git a/NativeScript/runtime/RuntimeCommonPlatform.mm b/NativeScript/runtime/RuntimeCommonPlatform.mm index d22e45482..fcb130509 100644 --- a/NativeScript/runtime/RuntimeCommonPlatform.mm +++ b/NativeScript/runtime/RuntimeCommonPlatform.mm @@ -4,6 +4,7 @@ // macro, so the core headers come before Helpers.h and the definition below // names it in parentheses. #include "ns/LoaderConfig.h" +#include "ns/Loop.h" #include "ns/Platform.h" #include "ns/RuntimeAccess.h" #include "ns/Thread.h" @@ -19,6 +20,7 @@ #include "Helpers.h" #include "HttpLoader.h" #include "ModuleUrl.h" +#include "NativeScriptPlatform.h" #include "Runtime.h" #include "RuntimeConfig.h" @@ -66,6 +68,11 @@ void RunJob(const std::function& job) { } } +std::shared_ptr LoopFor(v8::Isolate* isolate) { + tns::NativeScriptPlatform* platform = tns::NativeScriptPlatform::Instance(); + return platform != nullptr ? platform->LookupEventLoop(isolate) : nullptr; +} + bool IsRuntimeAlive(v8::Isolate* isolate) { return tns::Runtime::GetRuntime(isolate) != nullptr; } v8::Local MainContext(v8::Isolate* isolate) { From 35fdde5818c7aa63fb862277934d4f6328e2666a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 10:44:17 -0300 Subject: [PATCH 05/40] build: pin runtime-common step 4 and implement the app-file and state platform functions Pins the core at 95d96cc (the app-file seam and the module code cache) and adds its new sources, src/loader/CodeCache.cpp, CodeCacheQueue.cpp and FileCompile.cpp, to the RuntimeCommon target. - platform::StateBag: each Runtime owns an IsolateStateBag, reached through the RUNTIME slot. ~Runtime closes it as its last step under the Locker, after Caches::Remove and while the isolate is alive, so core state lives through all of teardown (F1). - platform::Stat: stat(2); the freshness token is the source's mtime with nanoseconds (st_mtimespec). - platform::ReadFile: the whole file or failure; a short read fails. - LoaderConfig.codeCacheDir is /NativeScript/CodeCache instead of the bare Caches directory. --- NativeScript/runtime-common | 2 +- NativeScript/runtime/Runtime.h | 8 +++ NativeScript/runtime/Runtime.mm | 2 + NativeScript/runtime/RuntimeCommonPlatform.mm | 60 ++++++++++++++++++- v8ios.xcodeproj/project.pbxproj | 12 ++++ 5 files changed, 82 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime-common b/NativeScript/runtime-common index ebb7b87b9..95d96cc7c 160000 --- a/NativeScript/runtime-common +++ b/NativeScript/runtime-common @@ -1 +1 @@ -Subproject commit ebb7b87b9452320b8b9bfaea97142d7d4f6b95a8 +Subproject commit 95d96cc7c1ceb192b0bff01cb1468ce8a49f4126 diff --git a/NativeScript/runtime/Runtime.h b/NativeScript/runtime/Runtime.h index 2ce5de095..85207bfbe 100644 --- a/NativeScript/runtime/Runtime.h +++ b/NativeScript/runtime/Runtime.h @@ -12,6 +12,7 @@ #include "ModuleInternal.h" #include "SpinLock.h" #include "libplatform/libplatform.h" +#include "ns/IsolateStateBag.h" // Declared rather than included: js_native_api_types.h pins NAPI_VERSION for // the whole translation unit, and Runtime.h reaches nearly all of them. @@ -58,6 +59,12 @@ class Runtime { */ inline std::shared_ptr GetEventLoop() const { return eventLoop_; } + // The runtime-common core's per-isolate state. Live through all of ~Runtime; + // closed as its last step under the Locker, while the isolate is alive. + inline nativescript::common::IsolateStateBag* StateBag() { + return &stateBag_; + } + // Runs `moduleName` as an entry module; throws NativeScriptException on // failure (see ModuleInternal::RunModule). void RunModule(const std::string moduleName); @@ -182,6 +189,7 @@ class Runtime { CFRunLoopRef runtimeLoop_; pthread_t runtimeThread_; std::shared_ptr eventLoop_; + nativescript::common::IsolateStateBag stateBag_; // Drains unhandled promise rejections once per runloop turn // (kCFRunLoopBeforeWaiting). Torn down before isolate disposal in ~Runtime. CFRunLoopObserverRef rejectionObserver_ = nullptr; diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 99487123c..18e662271 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -298,6 +298,7 @@ static bool ShouldEnableJit() { if (!initialized_) { // Never published: no other thread can know this isolate, and it holds no // caches, gate or wrappers. + stateBag_.Close(); isolate_->Dispose(); NativeScriptPlatform::Instance()->IsolateDisposed(isolate_, eventLoop_); currentRuntime_ = nullptr; @@ -381,6 +382,7 @@ static bool ShouldEnableJit() { Caches::Workers->Remove(this->workerId_); } Caches::Remove(this->isolate_); + stateBag_.Close(); this->isolate_->SetData(Constants::RUNTIME_SLOT, nullptr); diff --git a/NativeScript/runtime/RuntimeCommonPlatform.mm b/NativeScript/runtime/RuntimeCommonPlatform.mm index fcb130509..ec700eac3 100644 --- a/NativeScript/runtime/RuntimeCommonPlatform.mm +++ b/NativeScript/runtime/RuntimeCommonPlatform.mm @@ -3,6 +3,8 @@ // ns/Platform.h declares a function named Log, which Helpers.h defines as a // macro, so the core headers come before Helpers.h and the definition below // names it in parentheses. +#include "ns/AppFiles.h" +#include "ns/IsolateState.h" #include "ns/LoaderConfig.h" #include "ns/Loop.h" #include "ns/Platform.h" @@ -11,8 +13,14 @@ #include "ns/http/ModuleTransport.h" #import +#include #include +#include +#include +#include +#include +#include #include #include @@ -75,6 +83,54 @@ void RunJob(const std::function& job) { bool IsRuntimeAlive(v8::Isolate* isolate) { return tns::Runtime::GetRuntime(isolate) != nullptr; } +IsolateStateBag* StateBag(v8::Isolate* isolate) { + tns::Runtime* runtime = tns::Runtime::GetRuntime(isolate); + return runtime != nullptr ? runtime->StateBag() : nullptr; +} + +std::optional Stat(std::string_view logicalPath) { + const std::string path(logicalPath); + struct stat st; + if (stat(path.c_str(), &st) != 0) { + return std::nullopt; + } + FileInfo info; + info.isFile = S_ISREG(st.st_mode); + info.size = static_cast(st.st_size); + char token[48]; + snprintf(token, sizeof(token), "%lld.%09ld", static_cast(st.st_mtimespec.tv_sec), + static_cast(st.st_mtimespec.tv_nsec)); + info.freshnessToken = token; + return info; +} + +bool ReadFile(std::string_view logicalPath, std::string& out) { + const std::string path(logicalPath); + int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return false; + } + struct stat st; + if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) { + close(fd); + return false; + } + out.resize(static_cast(st.st_size)); + size_t done = 0; + while (done < out.size()) { + const ssize_t got = read(fd, out.data() + done, out.size() - done); + if (got < 0 && errno == EINTR) { + continue; + } + if (got <= 0) { + break; + } + done += static_cast(got); + } + close(fd); + return done == out.size(); +} + v8::Local MainContext(v8::Isolate* isolate) { return tns::Caches::Get(isolate)->GetContext(); } @@ -144,7 +200,9 @@ void RefreshLoaderConfig() { config.codeCacheEnabled = !RuntimeConfig.IsDebug; @autoreleasepool { NSArray* caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - config.codeCacheDir = caches.count > 0 ? [caches[0] UTF8String] : ""; + NSString* cachesDir = caches.count > 0 ? caches[0] : nil; + NSString* codeCacheDir = [cachesDir stringByAppendingPathComponent:@"NativeScript/CodeCache"]; + config.codeCacheDir = codeCacheDir != nil ? [codeCacheDir UTF8String] : ""; } config.v8Flags = Runtime::V8Flags(); } diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index c035f0d4a..ac2390c2a 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -383,6 +383,9 @@ 5C0AA1C00000000000000055 /* Utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000045 /* Utf8.cpp */; }; 5C0AA1C00000000000000056 /* V8Flags.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000046 /* V8Flags.cpp */; }; 5C0AA1C00000000000000057 /* V8Helpers.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000047 /* V8Helpers.cpp */; }; + 5C0AA1C00000000000000070 /* CodeCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000060 /* CodeCache.cpp */; }; + 5C0AA1C00000000000000071 /* CodeCacheQueue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000061 /* CodeCacheQueue.cpp */; }; + 5C0AA1C00000000000000072 /* FileCompile.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000062 /* FileCompile.cpp */; }; 5C0AA1C00000000000000031 /* RuntimeCommonPlatform.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */; }; 5C0AA1C00000000000000007 /* libRuntimeCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C0AA1C00000000000000003 /* libRuntimeCommon.a */; }; /* End PBXBuildFile section */ @@ -976,6 +979,9 @@ 5C0AA1C00000000000000045 /* Utf8.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Utf8.cpp; path = src/Utf8.cpp; sourceTree = ""; }; 5C0AA1C00000000000000046 /* V8Flags.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = V8Flags.cpp; path = src/V8Flags.cpp; sourceTree = ""; }; 5C0AA1C00000000000000047 /* V8Helpers.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = V8Helpers.cpp; path = src/V8Helpers.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000060 /* CodeCache.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CodeCache.cpp; path = src/loader/CodeCache.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000061 /* CodeCacheQueue.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CodeCacheQueue.cpp; path = src/loader/CodeCacheQueue.cpp; sourceTree = ""; }; + 5C0AA1C00000000000000062 /* FileCompile.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = FileCompile.cpp; path = src/loader/FileCompile.cpp; sourceTree = ""; }; 5C0AA1C00000000000000030 /* RuntimeCommonPlatform.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = RuntimeCommonPlatform.mm; sourceTree = ""; }; 5C0AA1C00000000000000003 /* libRuntimeCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRuntimeCommon.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -1814,6 +1820,9 @@ 5C0AA1C00000000000000045 /* Utf8.cpp */, 5C0AA1C00000000000000046 /* V8Flags.cpp */, 5C0AA1C00000000000000047 /* V8Helpers.cpp */, + 5C0AA1C00000000000000060 /* CodeCache.cpp */, + 5C0AA1C00000000000000061 /* CodeCacheQueue.cpp */, + 5C0AA1C00000000000000062 /* FileCompile.cpp */, ); path = "runtime-common"; sourceTree = ""; @@ -2738,6 +2747,9 @@ 5C0AA1C00000000000000055 /* Utf8.cpp in Sources */, 5C0AA1C00000000000000056 /* V8Flags.cpp in Sources */, 5C0AA1C00000000000000057 /* V8Helpers.cpp in Sources */, + 5C0AA1C00000000000000070 /* CodeCache.cpp in Sources */, + 5C0AA1C00000000000000071 /* CodeCacheQueue.cpp in Sources */, + 5C0AA1C00000000000000072 /* FileCompile.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From ddf63e4cd532baddaf7fa644f947a7653cfb3609 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 10:44:42 -0300 Subject: [PATCH 06/40] feat(runtime): compile app files and keep their code caches through runtime-common Classic scripts and file ES modules compile through the core's CompileFileClassicScript / CompileFileEsModule, with the same script origin and source wrapper as before: the CommonJS wrapper for everything but .mjs files and the app's bundle.js. The path is normalized first. A compile error still logs in Debug and throws "Cannot compile script" for a classic script, and leaves the exception pending for an ES module. The off-thread file-module loader decides with platform::Stat, CodeCacheEntryFor and HasFreshCodeCache at dispatch. On the pool it reads with platform::ReadFile, always re-checks SourceUnchanged before consuming a cache, and loads it with LoadCodeCache; finalize queues creation with QueueCodeCache. Caches use the core's format: hashed names under codeCacheDir, a header keyed by the path relative to the app root, sub-second mtime freshness. The iOS cache machinery (LoadScriptCache, QueueScriptCache, FreshScriptCachePath, GetCacheFileName, its creation queue) and the helpers only it used (ReadModule, ReadBinary, WriteBinary, WrapModuleContent) are gone. The UIApplicationDidEnterBackground observer is registered once by the platform layer and calls loader::NotifyAppBackgrounded for every live runtime, workers included, instead of only the main one. A missing or unreadable file now throws the core's JsError ("Cannot find module" / "Cannot read module"); an unreadable .mjs no longer aborts the process. --- NativeScript/runtime/Helpers.h | 9 - NativeScript/runtime/Helpers.mm | 126 +----- NativeScript/runtime/ModuleInternal.h | 41 +- NativeScript/runtime/ModuleInternal.mm | 379 +----------------- .../runtime/ModuleInternalCallbacks.mm | 74 ++-- NativeScript/runtime/Runtime.h | 4 + NativeScript/runtime/Runtime.mm | 18 + NativeScript/runtime/RuntimeCommonPlatform.mm | 19 + TestRunner/app/tests/FileModuleLoadTests.js | 68 +++- 9 files changed, 151 insertions(+), 587 deletions(-) diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index 64ba155b1..3d6ae3cd9 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -265,16 +265,7 @@ inline bool ToBool(const v8::Local& value) { return result; } bool Exists(const char* fullPath); -v8::Local ReadModule(v8::Isolate* isolate, const std::string& filePath); std::string ReadText(const std::string& file); -// The whole file in a heap buffer the caller owns (delete[]); nullptr and a -// zero length when it cannot be read. -uint8_t* ReadBinary(const std::string& path, long& length); -// Replaces the file at `path` atomically: readers see the old contents or the -// new ones, never a partial write. A non-negative `modificationTime` stamps the -// file's mtime before it is published. -bool WriteBinary(const std::string& path, const void* data, long length, - time_t modificationTime = -1); void SetPrivateValue(const v8::Local& obj, const v8::Local& propName, const v8::Local& value); diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index e385cba67..e65ebd56b 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -69,52 +69,8 @@ return false; } -Local tns::ReadModule(Isolate* isolate, const std::string& filePath) { - static constexpr char prefix[] = "(function(module, exports, require, __filename, __dirname) { "; - static constexpr char suffix[] = "\n})"; - constexpr size_t prefixLength = sizeof(prefix) - 1; - constexpr size_t suffixLength = sizeof(suffix) - 1; - - int file = open(filePath.c_str(), O_RDONLY); - if (file < 0) { - throw NativeScriptException(isolate, "Cannot read module " + filePath); - } - - struct stat finfo; - if (fstat(file, &finfo) != 0) { - close(file); - throw NativeScriptException(isolate, "Cannot read module " + filePath); - } - size_t length = finfo.st_size; - - size_t sourceLength = prefixLength + length + suffixLength; - std::unique_ptr source(new char[sourceLength]); - memcpy(source.get(), prefix, prefixLength); - char* body = source.get() + prefixLength; - size_t bytesRead = 0; - while (bytesRead < length) { - ssize_t n = read(file, body + bytesRead, length - bytesRead); - if (n < 0 && errno == EINTR) { - continue; - } - if (n <= 0) { - break; - } - bytesRead += n; - } - close(file); - if (bytesRead != length) { - throw NativeScriptException(isolate, "Cannot read module " + filePath); - } - memcpy(body + length, suffix, suffixLength); - - return v8::String::NewFromUtf8(isolate, source.get(), NewStringType::kNormal, (int)sourceLength) - .ToLocalChecked(); -} - -// The file readers below run on the main thread and on every worker's thread -// at once (workers load shared modules and their code caches while starting), -// so each call reads into storage of its own; no scratch buffer is shared. +// Runs on the main thread and on every worker's thread at once, so each call +// reads into storage of its own; no scratch buffer is shared. std::string tns::ReadText(const std::string& filePath) { FILE* file = fopen(filePath.c_str(), "rb"); @@ -137,84 +93,6 @@ return result; } -uint8_t* tns::ReadBinary(const std::string& path, long& length) { - length = 0; - FILE* file = fopen(path.c_str(), "rb"); - if (!file) { - return nullptr; - } - - fseek(file, 0, SEEK_END); - long fileLength = ftell(file); - rewind(file); - if (fileLength <= 0) { - fclose(file); - return nullptr; - } - - uint8_t* data = new uint8_t[fileLength]; - size_t readBytes = fread(data, sizeof(uint8_t), fileLength, file); - fclose(file); - if (readBytes != static_cast(fileLength)) { - delete[] data; - return nullptr; - } - - length = fileLength; - return data; -} - -bool tns::WriteBinary(const std::string& path, const void* data, long length, - time_t modificationTime) { - // Written to a private temp file in the same directory, then renamed over the - // target: rename is atomic on the local file system, so a concurrent reader - // of `path` never observes a truncated or half-written file, and two writers - // racing on the same path leave whichever complete file landed last. - std::string tmpTemplate = path + ".XXXXXX"; - std::vector tmpPath(tmpTemplate.begin(), tmpTemplate.end()); - tmpPath.push_back('\0'); - int fd = mkstemp(tmpPath.data()); - if (fd < 0) { - return false; - } - - bool ok = true; - const uint8_t* cursor = static_cast(data); - long remaining = length; - while (remaining > 0) { - ssize_t written = write(fd, cursor, remaining); - if (written < 0) { - if (errno == EINTR) { - continue; - } - ok = false; - break; - } - cursor += written; - remaining -= written; - } - - if (ok && modificationTime >= 0) { - struct timespec times[2]; - times[0].tv_sec = time(nullptr); - times[0].tv_nsec = 0; - times[1].tv_sec = modificationTime; - times[1].tv_nsec = 0; - ok = futimens(fd, times) == 0; - } - - close(fd); - - if (ok && rename(tmpPath.data(), path.c_str()) != 0) { - ok = false; - } - if (!ok) { - unlink(tmpPath.data()); - } - - return ok; -} - Local tns::UnwrapProxyOrThrow(Isolate* isolate, Local value) { if (value.IsEmpty() || !value->IsProxy()) { return value; diff --git a/NativeScript/runtime/ModuleInternal.h b/NativeScript/runtime/ModuleInternal.h index b2b81cf57..4c984dbae 100644 --- a/NativeScript/runtime/ModuleInternal.h +++ b/NativeScript/runtime/ModuleInternal.h @@ -76,10 +76,10 @@ class ModuleInternal { v8::Local binding); // Read + wrap + compile `path` as an ES module (consuming/producing the // on-disk code cache) WITHOUT registering, instantiating, or evaluating it. - // On compile failure the exception is left pending on the isolate (or a - // NativeScriptException is thrown for setup failures) and the result is - // empty. This is the resolver's file loader: the resolver must only ever - // hand V8 a compiled module — evaluation order belongs to V8. `query` is + // On compile failure the exception is left pending on the isolate and the + // result is empty; a file that cannot be found or read throws JsError. + // This is the resolver's file loader: the resolver must only ever hand V8 + // a compiled module — evaluation order belongs to V8. `query` is // the module key's query: it is part of the reported URL (script origin, // import.meta.url), never of the file read or of the code cache's name. static v8::MaybeLocal CompileFileEsModule( @@ -102,35 +102,6 @@ class ModuleInternal { const std::string& path, std::string* rejectionReason); - // A code-cache blob is either a script blob or a module blob, and V8 rejects - // the wrong kind outright. One file compiled both ways — require('./x.js') - // and import './x.js' — would otherwise share a blob and each load would - // reject and overwrite the other's, so the two kinds get their own suffix - // and the cache actually hits. - enum class ScriptCacheKind { kClassicScript, kEsModule }; - // The blob for `path` when one was written for the file's modification time - // `sourceModifiedTime`, otherwise empty. Stats only; never reads the blob. - // Always empty in the development flavor, which never consumes a cache. - static std::string FreshScriptCachePath(const std::string& path, - ScriptCacheKind kind, - time_t sourceModifiedTime); - // Queues creation of the code cache for a script compiled from `path` as - // it was at `sourceModifiedTime`. Creation needs the isolate's thread and - // costs a fifth of a cold compile, so it runs later in short slices once - // loading goes quiet (or when the app moves to the background); the file is - // written off-thread, and skipped if the source changed since it was read. - // A no-op in the development flavor. Isolate thread only. - static void QueueScriptCache(v8::Isolate* isolate, - v8::Local script, - const std::string& path, - time_t sourceModifiedTime); - static void QueueScriptCache(v8::Isolate* isolate, - v8::Local script, - const std::string& path, - time_t sourceModifiedTime); - // Where the code cache for `path` (with its kind's suffix) lives. - static std::string GetCacheFileName(const std::string& path); - private: static void RequireCallback(const v8::FunctionCallbackInfo& info); static void CreateRequireCallback( @@ -154,8 +125,6 @@ class ModuleInternal { static v8::Local LoadESModule( v8::Isolate* isolate, const std::string& path, const ModuleEvaluationOptions& options); - static v8::Local WrapModuleContent(v8::Isolate* isolate, - const std::string& path); v8::Local LoadModule(v8::Isolate* isolate, const std::string& modulePath, const std::string& cacheKey, @@ -166,8 +135,6 @@ class ModuleInternal { const std::string& moduleName); std::string ResolvePathFromPackageJson(const std::string& packageJson, bool& error); - static v8::ScriptCompiler::CachedData* LoadScriptCache( - const std::string& path, ScriptCacheKind kind, time_t sourceModifiedTime); v8::MaybeLocal RunScriptString(v8::Isolate* isolate, v8::Local context, const std::string script); diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index 8dcf61109..7af9a1793 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -5,7 +5,6 @@ #include #include #include -#include #include #include "BuiltinLoader.h" #include "Caches.h" @@ -20,6 +19,7 @@ #include "RuntimeConfig.h" #include "napi/NapiModules.h" #include "ns/JsError.h" +#include "ns/loader/FileCompile.h" using namespace v8; using nativescript::common::PumpMode; @@ -970,47 +970,27 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio return result; } -Local