v8_initializer.cc 21 KB

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