v8_initializer.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "gin/v8_initializer.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <cstdint>
  8. #include <memory>
  9. #include "base/allocator/partition_allocator/page_allocator.h"
  10. #include "base/allocator/partition_allocator/partition_address_space.h"
  11. #include "base/bits.h"
  12. #include "base/check.h"
  13. #include "base/debug/alias.h"
  14. #include "base/debug/crash_logging.h"
  15. #include "base/feature_list.h"
  16. #include "base/files/file.h"
  17. #include "base/files/file_path.h"
  18. #include "base/files/memory_mapped_file.h"
  19. #include "base/lazy_instance.h"
  20. #include "base/metrics/histogram_functions.h"
  21. #include "base/metrics/histogram_macros.h"
  22. #include "base/notreached.h"
  23. #include "base/path_service.h"
  24. #include "base/rand_util.h"
  25. #include "base/strings/string_piece.h"
  26. #include "base/strings/string_split.h"
  27. #include "base/strings/string_util.h"
  28. #include "base/strings/sys_string_conversions.h"
  29. #include "base/system/sys_info.h"
  30. #include "base/threading/platform_thread.h"
  31. #include "base/time/time.h"
  32. #include "build/build_config.h"
  33. #include "gin/gin_features.h"
  34. #include "third_party/abseil-cpp/absl/types/optional.h"
  35. #include "v8/include/v8-initialization.h"
  36. #include "v8/include/v8-snapshot.h"
  37. #if BUILDFLAG(IS_WIN)
  38. #include "base/win/windows_version.h"
  39. #endif
  40. #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
  41. #if BUILDFLAG(IS_ANDROID)
  42. #include "base/android/apk_assets.h"
  43. #elif BUILDFLAG(IS_MAC)
  44. #include "base/mac/foundation_util.h"
  45. #endif
  46. #endif // V8_USE_EXTERNAL_STARTUP_DATA
  47. namespace gin {
  48. namespace {
  49. // This global is never freed nor closed.
  50. base::MemoryMappedFile* g_mapped_snapshot = nullptr;
  51. #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
  52. absl::optional<gin::V8SnapshotFileType> g_snapshot_file_type;
  53. #endif
  54. bool GenerateEntropy(unsigned char* buffer, size_t amount) {
  55. base::RandBytes(buffer, amount);
  56. return true;
  57. }
  58. void GetMappedFileData(base::MemoryMappedFile* mapped_file,
  59. v8::StartupData* data) {
  60. if (mapped_file) {
  61. data->data = reinterpret_cast<const char*>(mapped_file->data());
  62. data->raw_size = static_cast<int>(mapped_file->length());
  63. } else {
  64. data->data = nullptr;
  65. data->raw_size = 0;
  66. }
  67. }
  68. #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
  69. #if BUILDFLAG(IS_ANDROID)
  70. const char kV8ContextSnapshotFileName64[] = "v8_context_snapshot_64.bin";
  71. const char kV8ContextSnapshotFileName32[] = "v8_context_snapshot_32.bin";
  72. const char kSnapshotFileName64[] = "snapshot_blob_64.bin";
  73. const char kSnapshotFileName32[] = "snapshot_blob_32.bin";
  74. #if defined(__LP64__)
  75. #define kV8ContextSnapshotFileName kV8ContextSnapshotFileName64
  76. #define kSnapshotFileName kSnapshotFileName64
  77. #else
  78. #define kV8ContextSnapshotFileName kV8ContextSnapshotFileName32
  79. #define kSnapshotFileName kSnapshotFileName32
  80. #endif
  81. #else // BUILDFLAG(IS_ANDROID)
  82. #if defined(USE_V8_CONTEXT_SNAPSHOT)
  83. const char kV8ContextSnapshotFileName[] = V8_CONTEXT_SNAPSHOT_FILENAME;
  84. #endif
  85. const char kSnapshotFileName[] = "snapshot_blob.bin";
  86. #endif // BUILDFLAG(IS_ANDROID)
  87. const char* GetSnapshotFileName(const V8SnapshotFileType file_type) {
  88. switch (file_type) {
  89. case V8SnapshotFileType::kDefault:
  90. return kSnapshotFileName;
  91. case V8SnapshotFileType::kWithAdditionalContext:
  92. #if defined(USE_V8_CONTEXT_SNAPSHOT)
  93. return kV8ContextSnapshotFileName;
  94. #else
  95. NOTREACHED();
  96. return nullptr;
  97. #endif
  98. }
  99. NOTREACHED();
  100. return nullptr;
  101. }
  102. void GetV8FilePath(const char* file_name, base::FilePath* path_out) {
  103. #if BUILDFLAG(IS_ANDROID)
  104. // This is the path within the .apk.
  105. *path_out =
  106. base::FilePath(FILE_PATH_LITERAL("assets")).AppendASCII(file_name);
  107. #elif BUILDFLAG(IS_MAC)
  108. base::ScopedCFTypeRef<CFStringRef> bundle_resource(
  109. base::SysUTF8ToCFStringRef(file_name));
  110. *path_out = base::mac::PathForFrameworkBundleResource(bundle_resource);
  111. #else
  112. base::FilePath data_path;
  113. bool r = base::PathService::Get(base::DIR_ASSETS, &data_path);
  114. DCHECK(r);
  115. *path_out = data_path.AppendASCII(file_name);
  116. #endif
  117. }
  118. bool MapV8File(base::File file,
  119. base::MemoryMappedFile::Region region,
  120. base::MemoryMappedFile** mmapped_file_out) {
  121. DCHECK(*mmapped_file_out == NULL);
  122. std::unique_ptr<base::MemoryMappedFile> mmapped_file(
  123. new base::MemoryMappedFile());
  124. if (mmapped_file->Initialize(std::move(file), region)) {
  125. *mmapped_file_out = mmapped_file.release();
  126. return true;
  127. }
  128. return false;
  129. }
  130. base::File OpenV8File(const char* file_name,
  131. base::MemoryMappedFile::Region* region_out) {
  132. // Re-try logic here is motivated by http://crbug.com/479537
  133. // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
  134. // These match tools/metrics/histograms.xml
  135. enum OpenV8FileResult {
  136. OPENED = 0,
  137. OPENED_RETRY,
  138. FAILED_IN_USE,
  139. FAILED_OTHER,
  140. MAX_VALUE
  141. };
  142. base::FilePath path;
  143. GetV8FilePath(file_name, &path);
  144. #if BUILDFLAG(IS_ANDROID)
  145. base::File file(base::android::OpenApkAsset(path.value(), region_out));
  146. OpenV8FileResult result = file.IsValid() ? OpenV8FileResult::OPENED
  147. : OpenV8FileResult::FAILED_OTHER;
  148. #else
  149. // Re-try logic here is motivated by http://crbug.com/479537
  150. // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
  151. const int kMaxOpenAttempts = 5;
  152. const int kOpenRetryDelayMillis = 250;
  153. OpenV8FileResult result = OpenV8FileResult::FAILED_IN_USE;
  154. int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
  155. base::File file;
  156. for (int attempt = 0; attempt < kMaxOpenAttempts; attempt++) {
  157. file.Initialize(path, flags);
  158. if (file.IsValid()) {
  159. *region_out = base::MemoryMappedFile::Region::kWholeFile;
  160. if (attempt == 0) {
  161. result = OpenV8FileResult::OPENED;
  162. break;
  163. } else {
  164. result = OpenV8FileResult::OPENED_RETRY;
  165. break;
  166. }
  167. } else if (file.error_details() != base::File::FILE_ERROR_IN_USE) {
  168. result = OpenV8FileResult::FAILED_OTHER;
  169. break;
  170. } else if (kMaxOpenAttempts - 1 != attempt) {
  171. base::PlatformThread::Sleep(base::Milliseconds(kOpenRetryDelayMillis));
  172. }
  173. }
  174. #endif // BUILDFLAG(IS_ANDROID)
  175. UMA_HISTOGRAM_ENUMERATION("V8.Initializer.OpenV8File.Result", result,
  176. OpenV8FileResult::MAX_VALUE);
  177. return file;
  178. }
  179. #endif // defined(V8_USE_EXTERNAL_STARTUP_DATA)
  180. template <int LENGTH>
  181. void SetV8Flags(const char (&flag)[LENGTH]) {
  182. v8::V8::SetFlagsFromString(flag, LENGTH - 1);
  183. }
  184. void SetV8FlagsFormatted(const char* format, ...) {
  185. char buffer[128];
  186. va_list args;
  187. va_start(args, format);
  188. int length = base::vsnprintf(buffer, sizeof(buffer), format, args);
  189. if (length <= 0 || sizeof(buffer) <= static_cast<unsigned>(length)) {
  190. PLOG(ERROR) << "Invalid formatted V8 flag: " << format;
  191. return;
  192. }
  193. v8::V8::SetFlagsFromString(buffer, length);
  194. }
  195. template <size_t N, size_t M>
  196. void SetV8FlagsIfOverridden(const base::Feature& feature,
  197. const char (&enabling_flag)[N],
  198. const char (&disabling_flag)[M]) {
  199. auto overridden_state = base::FeatureList::GetStateIfOverridden(feature);
  200. if (!overridden_state.has_value()) {
  201. return;
  202. }
  203. if (overridden_state.value()) {
  204. SetV8Flags(enabling_flag);
  205. } else {
  206. SetV8Flags(disabling_flag);
  207. }
  208. }
  209. void SetFlags(IsolateHolder::ScriptMode mode,
  210. const std::string js_command_line_flags) {
  211. // We assume that all feature flag defaults correspond to the default
  212. // values of the corresponding V8 flags.
  213. SetV8FlagsIfOverridden(features::kV8CompactCodeSpaceWithStack,
  214. "--compact-code-space-with-stack",
  215. "--no-compact-code-space-with-stack");
  216. SetV8FlagsIfOverridden(features::kV8CompactWithStack, "--compact-with-stack",
  217. "--no-compact-with-stack");
  218. SetV8FlagsIfOverridden(features::kV8CompactMaps, "--compact-maps",
  219. "--no-compact-maps");
  220. SetV8FlagsIfOverridden(features::kV8UseMapSpace, "--use-map-space",
  221. "--no-use-map-space");
  222. SetV8FlagsIfOverridden(features::kV8CrashOnEvacuationFailure,
  223. "--crash-on-aborted-evacuation",
  224. "--no-crash-on-aborted-evacuation");
  225. SetV8FlagsIfOverridden(features::kV8OptimizeJavascript, "--opt", "--no-opt");
  226. SetV8FlagsIfOverridden(features::kV8FlushBytecode, "--flush-bytecode",
  227. "--no-flush-bytecode");
  228. SetV8FlagsIfOverridden(features::kV8FlushBaselineCode,
  229. "--flush-baseline-code", "--no-flush-baseline-code");
  230. SetV8FlagsIfOverridden(features::kV8OffThreadFinalization,
  231. "--finalize-streaming-on-background",
  232. "--no-finalize-streaming-on-background");
  233. SetV8FlagsIfOverridden(features::kV8LazyFeedbackAllocation,
  234. "--lazy-feedback-allocation",
  235. "--no-lazy-feedback-allocation");
  236. SetV8FlagsIfOverridden(features::kV8PerContextMarkingWorklist,
  237. "--stress-per-context-marking-worklist",
  238. "--no-stress-per-context-marking-worklist");
  239. SetV8FlagsIfOverridden(features::kV8FlushEmbeddedBlobICache,
  240. "--experimental-flush-embedded-blob-icache",
  241. "--no-experimental-flush-embedded-blob-icache");
  242. SetV8FlagsIfOverridden(features::kV8ReduceConcurrentMarkingTasks,
  243. "--gc-experiment-reduce-concurrent-marking-tasks",
  244. "--no-gc-experiment-reduce-concurrent-marking-tasks");
  245. SetV8FlagsIfOverridden(features::kV8NoReclaimUnmodifiedWrappers,
  246. "--no-reclaim-unmodified-wrappers",
  247. "--reclaim-unmodified-wrappers");
  248. SetV8FlagsIfOverridden(
  249. features::kV8ExperimentalRegexpEngine,
  250. "--enable-experimental-regexp-engine-on-excessive-backtracks",
  251. "--no-enable-experimental-regexp-engine-on-excessive-backtracks");
  252. SetV8FlagsIfOverridden(features::kV8TurboFastApiCalls,
  253. "--turbo-fast-api-calls", "--no-turbo-fast-api-calls");
  254. SetV8FlagsIfOverridden(features::kV8Turboprop, "--turboprop",
  255. "--no-turboprop");
  256. SetV8FlagsIfOverridden(features::kV8Sparkplug, "--sparkplug",
  257. "--no-sparkplug");
  258. SetV8FlagsIfOverridden(features::kV8ConcurrentSparkplug,
  259. "--concurrent-sparkplug", "--no-concurrent-sparkplug");
  260. SetV8FlagsIfOverridden(features::kV8SparkplugNeedsShortBuiltinCalls,
  261. "--sparkplug-needs-short-builtins",
  262. "--no-sparkplug-needs-short-builtins");
  263. SetV8FlagsIfOverridden(features::kV8ShortBuiltinCalls,
  264. "--short-builtin-calls", "--no-short-builtin-calls");
  265. SetV8FlagsIfOverridden(features::kV8CodeMemoryWriteProtection,
  266. "--write-protect-code-memory",
  267. "--no-write-protect-code-memory");
  268. SetV8FlagsIfOverridden(features::kV8SlowHistograms, "--slow-histograms",
  269. "--no-slow-histograms");
  270. if (base::FeatureList::IsEnabled(features::kV8ConcurrentSparkplug)) {
  271. if (int max_threads = features::kV8ConcurrentSparkplugMaxThreads.Get()) {
  272. SetV8FlagsFormatted("--concurrent-sparkplug-max-threads=%i", max_threads);
  273. }
  274. }
  275. if (base::FeatureList::IsEnabled(features::kV8ScriptAblation)) {
  276. if (int delay = features::kV8ScriptDelayMs.Get()) {
  277. SetV8FlagsFormatted("--script-delay=%i", delay);
  278. }
  279. if (int delay = features::kV8ScriptDelayOnceMs.Get()) {
  280. SetV8FlagsFormatted("--script-delay-once=%i", delay);
  281. }
  282. if (double fraction = features::kV8ScriptDelayFraction.Get()) {
  283. SetV8FlagsFormatted("--script-delay-fraction=%f", fraction);
  284. }
  285. }
  286. // Make sure aliases of kV8SlowHistograms only enable the feature to
  287. // avoid contradicting settings between multiple finch experiments.
  288. bool any_slow_histograms_alias =
  289. base::FeatureList::IsEnabled(
  290. features::kV8SlowHistogramsCodeMemoryWriteProtection) ||
  291. base::FeatureList::IsEnabled(features::kV8SlowHistogramsSparkplug) ||
  292. base::FeatureList::IsEnabled(
  293. features::kV8SlowHistogramsSparkplugAndroid) ||
  294. base::FeatureList::IsEnabled(features::kV8SlowHistogramsScriptAblation);
  295. if (any_slow_histograms_alias) {
  296. SetV8Flags("--slow-histograms");
  297. } else {
  298. SetV8FlagsIfOverridden(features::kV8SlowHistograms, "--slow-histograms",
  299. "--no-slow-histograms");
  300. }
  301. if (IsolateHolder::kStrictMode == mode) {
  302. SetV8Flags("--use_strict");
  303. }
  304. if (js_command_line_flags.empty())
  305. return;
  306. // Allow the --js-flags switch to override existing flags:
  307. std::vector<base::StringPiece> flag_list =
  308. base::SplitStringPiece(js_command_line_flags, ",", base::TRIM_WHITESPACE,
  309. base::SPLIT_WANT_NONEMPTY);
  310. for (const auto& flag : flag_list) {
  311. v8::V8::SetFlagsFromString(std::string(flag).c_str(), flag.size());
  312. }
  313. }
  314. } // namespace
  315. // static
  316. void V8Initializer::Initialize(IsolateHolder::ScriptMode mode,
  317. const std::string js_command_line_flags,
  318. v8::OOMErrorCallback oom_error_callback) {
  319. static bool v8_is_initialized = false;
  320. if (v8_is_initialized)
  321. return;
  322. // Flags need to be set before InitializePlatform as they are used for
  323. // system instrumentation initialization.
  324. // See https://crbug.com/v8/11043
  325. SetFlags(mode, js_command_line_flags);
  326. v8::V8::InitializePlatform(V8Platform::Get());
  327. // Set this as early as possible in order to ensure OOM errors are reported
  328. // correctly.
  329. v8::V8::SetFatalMemoryErrorCallback(oom_error_callback);
  330. // Set this early on as some initialization steps, such as the initialization
  331. // of the virtual memory cage, already use V8's random number generator.
  332. v8::V8::SetEntropySource(&GenerateEntropy);
  333. #if defined(V8_SANDBOX)
  334. static_assert(ARCH_CPU_64_BITS, "V8 sandbox can only work in 64-bit builds");
  335. // For now, initializing the sandbox is optional, and we only do it if the
  336. // correpsonding feature is enabled. In the future, it will be mandatory when
  337. // compiling with V8_SANDBOX.
  338. // However, if V8 uses sandboxed pointers, then the sandbox must be
  339. // initialized as sandboxed pointers are simply offsets inside the sandbox.
  340. #if defined(V8_SANDBOXED_POINTERS)
  341. bool must_initialize_sandbox = true;
  342. #else
  343. bool must_initialize_sandbox = false;
  344. #endif
  345. bool v8_sandbox_is_initialized = false;
  346. if (must_initialize_sandbox ||
  347. base::FeatureList::IsEnabled(features::kV8VirtualMemoryCage)) {
  348. v8_sandbox_is_initialized = v8::V8::InitializeSandbox();
  349. CHECK(!must_initialize_sandbox || v8_sandbox_is_initialized);
  350. // Record the size of the sandbox, in GB. The size will always be a power
  351. // of two, so we use a sparse histogram to capture it. If the
  352. // initialization failed, this API will return zero. The main reason for
  353. // capturing this histogram here instead of having V8 do it is that there
  354. // are no Isolates available yet, which are required for recording
  355. // histograms in V8.
  356. size_t size = v8::V8::GetSandboxSizeInBytes();
  357. int sizeInGB = size >> 30;
  358. DCHECK(base::bits::IsPowerOfTwo(size));
  359. DCHECK(size == 0 || sizeInGB > 0);
  360. // This uses the term "cage" instead of "sandbox" for historical reasons.
  361. // TODO(1218005) remove this once the finch trial has ended.
  362. base::UmaHistogramSparse("V8.VirtualMemoryCageSizeGB", sizeInGB);
  363. }
  364. #endif // V8_SANDBOX
  365. #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
  366. if (g_mapped_snapshot) {
  367. v8::StartupData snapshot;
  368. GetMappedFileData(g_mapped_snapshot, &snapshot);
  369. v8::V8::SetSnapshotDataBlob(&snapshot);
  370. }
  371. #endif // V8_USE_EXTERNAL_STARTUP_DATA
  372. v8::V8::Initialize();
  373. v8_is_initialized = true;
  374. #if defined(V8_SANDBOX)
  375. if (v8_sandbox_is_initialized) {
  376. // These values are persisted to logs. Entries should not be renumbered and
  377. // numeric values should never be reused. This should match enum
  378. // V8VirtualMemoryCageMode in \tools\metrics\histograms\enums.xml
  379. // This uses the term "cage" instead of "sandbox" for historical reasons.
  380. // TODO(1218005) remove this once the finch trial has ended.
  381. enum class VirtualMemoryCageMode {
  382. kSecure = 0,
  383. kInsecure = 1,
  384. kMaxValue = kInsecure,
  385. };
  386. base::UmaHistogramEnumeration("V8.VirtualMemoryCageMode",
  387. v8::V8::IsSandboxConfiguredSecurely()
  388. ? VirtualMemoryCageMode::kSecure
  389. : VirtualMemoryCageMode::kInsecure);
  390. // When the sandbox is enabled, ArrayBuffers must be allocated inside of
  391. // it. To achieve that, PA's ConfigurablePool is created inside the sandbox
  392. // and Blink then creates the ArrayBuffer partition in that Pool.
  393. v8::VirtualAddressSpace* sandbox_address_space =
  394. v8::V8::GetSandboxAddressSpace();
  395. const size_t max_pool_size =
  396. base::internal::PartitionAddressSpace::ConfigurablePoolMaxSize();
  397. const size_t min_pool_size =
  398. base::internal::PartitionAddressSpace::ConfigurablePoolMinSize();
  399. size_t pool_size = max_pool_size;
  400. #if BUILDFLAG(IS_WIN)
  401. // On Windows prior to 8.1 we allocate a smaller Pool since reserving
  402. // virtual memory is expensive on these OSes.
  403. if (base::win::GetVersion() < base::win::Version::WIN8_1) {
  404. // The size chosen here should be synchronized with the size of the
  405. // virtual memory reservation for the V8 sandbox on these platforms.
  406. // Currently, that is 8GB, of which 4GB are used for V8's pointer
  407. // compression region.
  408. // TODO(saelo) give this constant a proper name and maybe move it
  409. // somewhere else.
  410. constexpr size_t kGB = 1ULL << 30;
  411. pool_size = 4ULL * kGB;
  412. DCHECK_LE(pool_size, max_pool_size);
  413. DCHECK_GE(pool_size, min_pool_size);
  414. }
  415. #endif
  416. // Try to reserve the maximum size of the pool at first, then keep halving
  417. // the size on failure until it succeeds.
  418. uintptr_t pool_base = 0;
  419. while (!pool_base && pool_size >= min_pool_size) {
  420. pool_base = sandbox_address_space->AllocatePages(
  421. 0, pool_size, pool_size, v8::PagePermissions::kNoAccess);
  422. if (!pool_base) {
  423. pool_size /= 2;
  424. }
  425. }
  426. // The V8 sandbox is guaranteed to be large enough to host the pool.
  427. CHECK(pool_base);
  428. base::internal::PartitionAddressSpace::InitConfigurablePool(pool_base,
  429. pool_size);
  430. // TODO(saelo) maybe record the size of the Pool into UMA.
  431. }
  432. #endif // V8_SANDBOX
  433. }
  434. // static
  435. void V8Initializer::GetV8ExternalSnapshotData(v8::StartupData* snapshot) {
  436. GetMappedFileData(g_mapped_snapshot, snapshot);
  437. }
  438. // static
  439. void V8Initializer::GetV8ExternalSnapshotData(const char** snapshot_data_out,
  440. int* snapshot_size_out) {
  441. v8::StartupData snapshot;
  442. GetV8ExternalSnapshotData(&snapshot);
  443. *snapshot_data_out = snapshot.data;
  444. *snapshot_size_out = snapshot.raw_size;
  445. }
  446. #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
  447. // static
  448. void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) {
  449. if (g_mapped_snapshot) {
  450. // TODO(crbug.com/802962): Confirm not loading different type of snapshot
  451. // files in a process.
  452. return;
  453. }
  454. base::MemoryMappedFile::Region file_region;
  455. base::File file =
  456. OpenV8File(GetSnapshotFileName(snapshot_file_type), &file_region);
  457. LoadV8SnapshotFromFile(std::move(file), &file_region, snapshot_file_type);
  458. }
  459. // static
  460. void V8Initializer::LoadV8SnapshotFromFile(
  461. base::File snapshot_file,
  462. base::MemoryMappedFile::Region* snapshot_file_region,
  463. V8SnapshotFileType snapshot_file_type) {
  464. if (g_mapped_snapshot)
  465. return;
  466. if (!snapshot_file.IsValid()) {
  467. LOG(FATAL) << "Error loading V8 startup snapshot file";
  468. return;
  469. }
  470. g_snapshot_file_type = snapshot_file_type;
  471. base::MemoryMappedFile::Region region =
  472. base::MemoryMappedFile::Region::kWholeFile;
  473. if (snapshot_file_region) {
  474. region = *snapshot_file_region;
  475. }
  476. if (!MapV8File(std::move(snapshot_file), region, &g_mapped_snapshot)) {
  477. LOG(FATAL) << "Error mapping V8 startup snapshot file";
  478. return;
  479. }
  480. }
  481. #if BUILDFLAG(IS_ANDROID)
  482. // static
  483. base::FilePath V8Initializer::GetSnapshotFilePath(
  484. bool abi_32_bit,
  485. V8SnapshotFileType snapshot_file_type) {
  486. base::FilePath path;
  487. const char* filename = nullptr;
  488. switch (snapshot_file_type) {
  489. case V8SnapshotFileType::kDefault:
  490. filename = abi_32_bit ? kSnapshotFileName32 : kSnapshotFileName64;
  491. break;
  492. case V8SnapshotFileType::kWithAdditionalContext:
  493. filename = abi_32_bit ? kV8ContextSnapshotFileName32
  494. : kV8ContextSnapshotFileName64;
  495. break;
  496. }
  497. CHECK(filename);
  498. GetV8FilePath(filename, &path);
  499. return path;
  500. }
  501. #endif // BUILDFLAG(IS_ANDROID)
  502. V8SnapshotFileType GetLoadedSnapshotFileType() {
  503. DCHECK(g_snapshot_file_type.has_value());
  504. return *g_snapshot_file_type;
  505. }
  506. #endif // defined(V8_USE_EXTERNAL_STARTUP_DATA)
  507. } // namespace gin