Skip to content

Commit 8a3e9db

Browse files
anuagragithAnukrati AgrawalCopilot
authored
Store the Hermes bytecode cache in an app-specific folder (#16563)
* Store the Hermes bytecode cache in an app-specific folder The cache now lives in the app's LocalCache folder (packaged apps) or a per-app folder under LocalAppData (unpackaged apps) instead of the shared temp folder. If neither is available the app runs without the cache. Cache files with non-ASCII paths are now handled, and files that are too small are ignored. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6571d0a2-c95e-4c83-8fb7-82debbd8de73 * Support Windows 10 1809 for the unpackaged bytecode cache folder Use SHGetKnownFolderPath (delay-loaded) instead of UserDataPaths, which requires Windows 10 1903. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6571d0a2-c95e-4c83-8fb7-82debbd8de73 * Change files Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6571d0a2-c95e-4c83-8fb7-82debbd8de73 * Clarify bytecode cache folder comment Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6571d0a2-c95e-4c83-8fb7-82debbd8de73 --------- Co-authored-by: Anukrati Agrawal <anuagra@microsoft.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6571d0a2-c95e-4c83-8fb7-82debbd8de73
1 parent 0180c04 commit 8a3e9db

5 files changed

Lines changed: 166 additions & 7 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"type": "prerelease",
3+
"comment": "Store the Hermes bytecode cache in an app-specific folder",
4+
"packageName": "react-native-windows",
5+
"email": "anuagra@microsoft.com",
6+
"dependentChangeType": "patch"
7+
}

‎vnext/Desktop.UnitTests/ScriptStoreTests.cpp‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
// Standard Library
1313
#include <cstdio>
1414
#include <cstdlib>
15+
#include <filesystem>
16+
#include <string>
1517

1618
using namespace facebook::jsi;
1719
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
@@ -69,4 +71,69 @@ TEST_CLASS (ScriptStoreIntegrationTest) {
6971
Assert::IsTrue(endWorkingSet - startWorkingSet < fileSize * 1.1);
7072
}
7173
};
74+
75+
TEST_CLASS (PreparedScriptStoreTest) {
76+
// Returns a fixed buffer for any id, simulating a cache file with arbitrary content.
77+
struct FixedBufferStore : facebook::react::BufferStore {
78+
explicit FixedBufferStore(std::string content) : content_(std::move(content)) {}
79+
80+
std::unique_ptr<const Buffer> getBuffer(const std::string &) noexcept override {
81+
return make_unique<StringBuffer>(content_);
82+
}
83+
84+
bool persistBuffer(const std::string &, std::unique_ptr<const Buffer>) noexcept override {
85+
return false;
86+
}
87+
88+
std::string content_;
89+
};
90+
91+
TEST_METHOD(TruncatedPreparedScriptIsRejected) {
92+
const auto scriptSignature = ScriptSignature{"myscheme://my/path.js", 0};
93+
const auto runtimeSignature = JSRuntimeSignature{"Hermes", 1};
94+
95+
for (const std::string content : {std::string{}, std::string{"RNWPREP"}, std::string(40, 'x')}) {
96+
facebook::react::BasePreparedScriptStoreImpl store{make_shared<FixedBufferStore>(content)};
97+
Assert::IsNull(store.tryGetPreparedScript(scriptSignature, runtimeSignature, "perf").get());
98+
}
99+
}
100+
101+
TEST_METHOD(PersistAndRetrieveInNonAsciiDirectory) {
102+
wchar_t tempPath[MAX_PATH];
103+
Assert::AreNotEqual(0ul, GetTempPathW(MAX_PATH, tempPath));
104+
std::filesystem::path directory{tempPath};
105+
directory /= L"rnw_script_store_\u00e9\u4e2d_" + std::to_wstring(GetCurrentProcessId());
106+
std::filesystem::create_directories(directory);
107+
struct DirectoryCleanup {
108+
const std::filesystem::path &path;
109+
~DirectoryCleanup() {
110+
std::error_code ec;
111+
std::filesystem::remove_all(path, ec);
112+
}
113+
} cleanup{directory};
114+
115+
const std::string storeDirectory = winrt::to_string(directory.wstring() + L"\\");
116+
const auto scriptSignature = ScriptSignature{"myscheme://my/path.js", 0};
117+
const auto runtimeSignature = JSRuntimeSignature{"Hermes", 1};
118+
const std::string content = "prepared script content";
119+
120+
for (bool memoryMapped : {false, true}) {
121+
React::SetRuntimeOptionBool("JSI.MemoryMappedScriptStore", memoryMapped);
122+
123+
facebook::react::BasePreparedScriptStoreImpl store{storeDirectory};
124+
store.persistPreparedScript(make_shared<StringBuffer>(content), scriptSignature, runtimeSignature, "perf");
125+
126+
auto prepared = store.tryGetPreparedScript(scriptSignature, runtimeSignature, "perf");
127+
Assert::IsNotNull(prepared.get());
128+
Assert::AreEqual(content, std::string{reinterpret_cast<const char *>(prepared->data()), prepared->size()});
129+
}
130+
131+
// The file must be created in the requested directory, not in a mis-decoded (ANSI) path.
132+
size_t fileCount = 0;
133+
for ([[maybe_unused]] const auto &entry : std::filesystem::directory_iterator(directory)) {
134+
++fileCount;
135+
}
136+
Assert::AreEqual<size_t>(1, fileCount);
137+
}
138+
};
72139
} // namespace Microsoft::JSI::Test

‎vnext/Microsoft.ReactNative/Microsoft.ReactNative.vcxproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@
150150
api-ms-win-core-file-l1-2-0.dll;
151151
api-ms-win-core-windowserrorreporting-l1-1-0.dll;
152152
ext-ms-win-uiacore-l1-1-1.dll;
153+
ext-ms-win-shell32-shellfolders-l1-1-0.dll;
153154
%(DelayLoadDLLs)
154155
</DelayLoadDLLs>
155156
<SubSystem>Console</SubSystem>

‎vnext/Microsoft.ReactNative/ReactHost/ReactInstanceWin.cpp‎

Lines changed: 84 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include <PackagerConnection.h>
1818
#include <QuirkSettings.h>
1919
#include <Shared/DevServerHelper.h>
20+
#include <ShlObj.h>
2021
#include <Threading/MessageDispatchQueue.h>
2122
#include <Threading/MessageQueueThreadFactory.h>
2223
#include <TurboModuleManager.h>
@@ -28,11 +29,13 @@
2829
#include <react/renderer/runtimescheduler/RuntimeScheduler.h>
2930
#include <react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h>
3031
#include <winrt/Windows.Storage.h>
32+
#include <filesystem>
3133
#include <tuple>
3234
#include "BaseScriptStoreImpl.h"
3335
#include "CrashManager.h"
3436
#include "DevMenu.h"
3537
#include "DynamicWriter.h"
38+
#include "Hasher.h"
3639
#include "HermesRuntimeHolder.h"
3740
#include "IReactContext.h"
3841
#include "IReactDispatcher.h"
@@ -412,13 +415,89 @@ Mso::DispatchQueueSettings CreateDispatchQueueSettings(
412415
return queueSettings;
413416
}
414417

418+
// Unpackaged apps share %LOCALAPPDATA%, so give each executable its own cache folder.
419+
std::wstring GetUnpackagedAppCacheFolderName() noexcept {
420+
std::wstring exePath(MAX_PATH, L'\0');
421+
for (;;) {
422+
DWORD length = GetModuleFileNameW(nullptr, exePath.data(), static_cast<DWORD>(exePath.size()));
423+
if (length == 0) {
424+
return {};
425+
}
426+
if (length < exePath.size()) {
427+
exePath.resize(length);
428+
break;
429+
}
430+
if (exePath.size() >= 32768) {
431+
return {};
432+
}
433+
exePath.resize(exePath.size() * 2);
434+
}
435+
436+
CharLowerBuffW(exePath.data(), static_cast<DWORD>(exePath.size()));
437+
auto hash = Microsoft::ReactNative::GetSHA256Hash(exePath.data(), exePath.size() * sizeof(wchar_t));
438+
if (!hash || hash->size() < 8) {
439+
return {};
440+
}
441+
442+
static constexpr wchar_t hexDigits[] = L"0123456789abcdef";
443+
std::wstring name;
444+
for (size_t i = 0; i < 8; ++i) {
445+
name += hexDigits[(*hash)[i] >> 4];
446+
name += hexDigits[(*hash)[i] & 0xF];
447+
}
448+
return name;
449+
}
450+
451+
// The Hermes prepared script (bytecode) cache lives in an app-specific folder so that different apps don't
452+
// overwrite each other's cache entries.
453+
std::wstring GetPreparedScriptStoreDirectory() noexcept {
454+
try {
455+
std::filesystem::path directory;
456+
if (Microsoft::ReactNative::HasPackageIdentity()) {
457+
directory = std::wstring{winrt::Windows::Storage::ApplicationData::Current().LocalCacheFolder().Path()};
458+
directory /= L"ReactNative";
459+
directory /= L"PreparedScripts";
460+
} else {
461+
std::wstring appFolderName = GetUnpackagedAppCacheFolderName();
462+
if (appFolderName.empty()) {
463+
return {};
464+
}
465+
// UserDataPaths requires Windows 10 1903, so use the shell API which is also available on 1809.
466+
PWSTR localAppData = nullptr;
467+
HRESULT hr = SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_DEFAULT, nullptr, &localAppData);
468+
if (FAILED(hr) || !localAppData) {
469+
CoTaskMemFree(localAppData);
470+
return {};
471+
}
472+
directory = localAppData;
473+
CoTaskMemFree(localAppData);
474+
directory /= L"Microsoft";
475+
directory /= L"ReactNative";
476+
directory /= L"PreparedScripts";
477+
directory /= appFolderName;
478+
}
479+
480+
std::error_code ec;
481+
std::filesystem::create_directories(directory, ec);
482+
if (ec || !std::filesystem::is_directory(directory, ec)) {
483+
return {};
484+
}
485+
486+
std::wstring result = directory.wstring();
487+
result += std::filesystem::path::preferred_separator;
488+
return result;
489+
} catch (...) {
490+
return {};
491+
}
492+
}
493+
415494
std::unique_ptr<facebook::jsi::PreparedScriptStore> CreatePreparedScriptStore() noexcept {
416-
std::unique_ptr<facebook::jsi::PreparedScriptStore> preparedScriptStore = nullptr;
417-
wchar_t tempPath[MAX_PATH];
418-
if (GetTempPathW(static_cast<DWORD>(std::size(tempPath)), tempPath)) {
419-
preparedScriptStore = std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(winrt::to_string(tempPath));
495+
std::wstring directory = GetPreparedScriptStoreDirectory();
496+
if (directory.empty()) {
497+
// Run without a bytecode cache rather than falling back to a shared folder.
498+
return nullptr;
420499
}
421-
return preparedScriptStore;
500+
return std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(winrt::to_string(directory));
422501
}
423502

424503
typedef HRESULT(__stdcall *SetThreadDescriptionFn)(HANDLE, PCWSTR);

‎vnext/Shared/BaseScriptStoreImpl.cpp‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ std::unique_ptr<const jsi::Buffer> LocalFileSimpleBufferStore::getBuffer(const s
156156
}
157157
} else {
158158
// Treat buffer id as the relative path fragment.
159-
std::ifstream file(storeDirectory_ + bufferId, std::ios::binary | std::ios::ate);
159+
std::ifstream file(winrt::to_hstring(storeDirectory_ + bufferId).c_str(), std::ios::binary | std::ios::ate);
160160

161161
if (!file) {
162162
return nullptr;
@@ -182,7 +182,7 @@ bool LocalFileSimpleBufferStore::persistBuffer(
182182
std::terminate();
183183

184184
std::ofstream file;
185-
file.open(storeDirectory_ + relativeUrl, std::ios::binary | std::ios::trunc);
185+
file.open(winrt::to_hstring(storeDirectory_ + relativeUrl).c_str(), std::ios::binary | std::ios::trunc);
186186
if (!file)
187187
return false;
188188

@@ -247,6 +247,11 @@ std::shared_ptr<const jsi::Buffer> BasePreparedScriptStoreImpl::tryGetPreparedSc
247247
return nullptr;
248248
}
249249

250+
if (buffer->size() < sizeof(PreparedScriptPrefix) + sizeof(PreparedScriptSuffix)) {
251+
// Too small to contain the prefix and suffix. The file is truncated or corrupted.
252+
return nullptr;
253+
}
254+
250255
const PreparedScriptPrefix *prefix = reinterpret_cast<const PreparedScriptPrefix *>(buffer->data());
251256

252257
if (strncmp(prefix->magic, PERSIST_MAGIC, sizeof(prefix->magic)) != 0) {

0 commit comments

Comments
 (0)