This patch combine three patch which is related to "--gcov" flag.
[platform/framework/web/chromium-efl.git] / gin / v8_initializer.cc
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "gin/v8_initializer.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <cstdint>
11 #include <memory>
12 #include <string>
13 #include <utility>
14 #include <vector>
15
16 #include "base/allocator/partition_allocator/src/partition_alloc/page_allocator.h"
17 #include "base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h"
18 #include "base/bits.h"
19 #include "base/check.h"
20 #include "base/check_op.h"
21 #include "base/debug/alias.h"
22 #include "base/debug/crash_logging.h"
23 #include "base/feature_list.h"
24 #include "base/files/file.h"
25 #include "base/files/file_path.h"
26 #include "base/files/memory_mapped_file.h"
27 #include "base/lazy_instance.h"
28 #include "base/metrics/histogram_functions.h"
29 #include "base/metrics/histogram_macros.h"
30 #include "base/notreached.h"
31 #include "base/path_service.h"
32 #include "base/rand_util.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/string_split.h"
35 #include "base/strings/string_util.h"
36 #include "base/system/sys_info.h"
37 #include "base/threading/platform_thread.h"
38 #include "base/time/time.h"
39 #include "build/build_config.h"
40 #include "gin/array_buffer.h"
41 #include "gin/gin_features.h"
42 #include "third_party/abseil-cpp/absl/types/optional.h"
43 #include "tools/v8_context_snapshot/buildflags.h"
44 #include "v8/include/v8-initialization.h"
45 #include "v8/include/v8-snapshot.h"
46
47 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
48 #if BUILDFLAG(IS_ANDROID)
49 #include "base/android/apk_assets.h"
50 #elif BUILDFLAG(IS_MAC)
51 #include "base/apple/foundation_util.h"
52 #endif
53 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
54
55 namespace gin {
56
57 namespace {
58
59 // This global is never freed nor closed.
60 base::MemoryMappedFile* g_mapped_snapshot = nullptr;
61
62 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
63 absl::optional<gin::V8SnapshotFileType> g_snapshot_file_type;
64 #endif
65
66 bool GenerateEntropy(unsigned char* buffer, size_t amount) {
67   base::RandBytes(buffer, amount);
68   return true;
69 }
70
71 void GetMappedFileData(base::MemoryMappedFile* mapped_file,
72                        v8::StartupData* data) {
73   if (mapped_file) {
74     data->data = reinterpret_cast<const char*>(mapped_file->data());
75     data->raw_size = static_cast<int>(mapped_file->length());
76   } else {
77     data->data = nullptr;
78     data->raw_size = 0;
79   }
80 }
81
82 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
83
84 #if BUILDFLAG(IS_ANDROID)
85 const char kV8ContextSnapshotFileName64[] = "v8_context_snapshot_64.bin";
86 const char kV8ContextSnapshotFileName32[] = "v8_context_snapshot_32.bin";
87 const char kSnapshotFileName64[] = "snapshot_blob_64.bin";
88 const char kSnapshotFileName32[] = "snapshot_blob_32.bin";
89
90 #if defined(__LP64__)
91 #define kV8ContextSnapshotFileName kV8ContextSnapshotFileName64
92 #define kSnapshotFileName kSnapshotFileName64
93 #else
94 #define kV8ContextSnapshotFileName kV8ContextSnapshotFileName32
95 #define kSnapshotFileName kSnapshotFileName32
96 #endif
97
98 #else  // BUILDFLAG(IS_ANDROID)
99 #if BUILDFLAG(USE_V8_CONTEXT_SNAPSHOT)
100 const char kV8ContextSnapshotFileName[] =
101     BUILDFLAG(V8_CONTEXT_SNAPSHOT_FILENAME);
102 #endif
103 const char kSnapshotFileName[] = "snapshot_blob.bin";
104 #endif  // BUILDFLAG(IS_ANDROID)
105
106 const char* GetSnapshotFileName(const V8SnapshotFileType file_type) {
107   switch (file_type) {
108     case V8SnapshotFileType::kDefault:
109       return kSnapshotFileName;
110     case V8SnapshotFileType::kWithAdditionalContext:
111 #if BUILDFLAG(USE_V8_CONTEXT_SNAPSHOT)
112       return kV8ContextSnapshotFileName;
113 #else
114       NOTREACHED();
115       return nullptr;
116 #endif
117   }
118   NOTREACHED();
119   return nullptr;
120 }
121
122 void GetV8FilePath(const char* file_name, base::FilePath* path_out) {
123 #if BUILDFLAG(IS_ANDROID)
124   // This is the path within the .apk.
125   *path_out =
126       base::FilePath(FILE_PATH_LITERAL("assets")).AppendASCII(file_name);
127 #elif BUILDFLAG(IS_MAC)
128   *path_out = base::apple::PathForFrameworkBundleResource(file_name);
129 #else
130   base::FilePath data_path;
131   bool r = base::PathService::Get(base::DIR_ASSETS, &data_path);
132   DCHECK(r);
133   *path_out = data_path.AppendASCII(file_name);
134 #endif
135 }
136
137 bool MapV8File(base::File file,
138                base::MemoryMappedFile::Region region,
139                base::MemoryMappedFile** mmapped_file_out) {
140   DCHECK(*mmapped_file_out == NULL);
141   std::unique_ptr<base::MemoryMappedFile> mmapped_file(
142       new base::MemoryMappedFile());
143   if (mmapped_file->Initialize(std::move(file), region)) {
144     *mmapped_file_out = mmapped_file.release();
145     return true;
146   }
147   return false;
148 }
149
150 base::File OpenV8File(const char* file_name,
151                       base::MemoryMappedFile::Region* region_out) {
152   // Re-try logic here is motivated by http://crbug.com/479537
153   // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
154
155   // These match tools/metrics/histograms.xml
156   enum OpenV8FileResult {
157     OPENED = 0,
158     OPENED_RETRY,
159     FAILED_IN_USE,
160     FAILED_OTHER,
161     MAX_VALUE
162   };
163   base::FilePath path;
164   GetV8FilePath(file_name, &path);
165
166 #if BUILDFLAG(IS_ANDROID)
167   base::File file(base::android::OpenApkAsset(path.value(), region_out));
168   OpenV8FileResult result = file.IsValid() ? OpenV8FileResult::OPENED
169                                            : OpenV8FileResult::FAILED_OTHER;
170 #else
171   // Re-try logic here is motivated by http://crbug.com/479537
172   // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
173   const int kMaxOpenAttempts = 5;
174   const int kOpenRetryDelayMillis = 250;
175
176   OpenV8FileResult result = OpenV8FileResult::FAILED_IN_USE;
177   int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
178   base::File file;
179   for (int attempt = 0; attempt < kMaxOpenAttempts; attempt++) {
180     file.Initialize(path, flags);
181     if (file.IsValid()) {
182       *region_out = base::MemoryMappedFile::Region::kWholeFile;
183       if (attempt == 0) {
184         result = OpenV8FileResult::OPENED;
185         break;
186       } else {
187         result = OpenV8FileResult::OPENED_RETRY;
188         break;
189       }
190     } else if (file.error_details() != base::File::FILE_ERROR_IN_USE) {
191       result = OpenV8FileResult::FAILED_OTHER;
192       break;
193     } else if (kMaxOpenAttempts - 1 != attempt) {
194       base::PlatformThread::Sleep(base::Milliseconds(kOpenRetryDelayMillis));
195     }
196   }
197 #endif  // BUILDFLAG(IS_ANDROID)
198
199   UMA_HISTOGRAM_ENUMERATION("V8.Initializer.OpenV8File.Result", result,
200                             OpenV8FileResult::MAX_VALUE);
201   return file;
202 }
203
204 #endif  // defined(V8_USE_EXTERNAL_STARTUP_DATA)
205
206 template <int LENGTH>
207 void SetV8Flags(const char (&flag)[LENGTH]) {
208   v8::V8::SetFlagsFromString(flag, LENGTH - 1);
209 }
210
211 void SetV8FlagsFormatted(const char* format, ...) {
212   char buffer[128];
213   va_list args;
214   va_start(args, format);
215   int length = base::vsnprintf(buffer, sizeof(buffer), format, args);
216   if (length <= 0 || sizeof(buffer) <= static_cast<unsigned>(length)) {
217     PLOG(ERROR) << "Invalid formatted V8 flag: " << format;
218     return;
219   }
220   v8::V8::SetFlagsFromString(buffer, length);
221 }
222
223 template <size_t N, size_t M>
224 void SetV8FlagsIfOverridden(const base::Feature& feature,
225                             const char (&enabling_flag)[N],
226                             const char (&disabling_flag)[M]) {
227   auto overridden_state = base::FeatureList::GetStateIfOverridden(feature);
228   if (!overridden_state.has_value()) {
229     return;
230   }
231   if (overridden_state.value()) {
232     SetV8Flags(enabling_flag);
233   } else {
234     SetV8Flags(disabling_flag);
235   }
236 }
237
238 void SetFlags(IsolateHolder::ScriptMode mode,
239               const std::string js_command_line_flags) {
240   // We assume that all feature flag defaults correspond to the default
241   // values of the corresponding V8 flags.
242   SetV8FlagsIfOverridden(features::kV8CompactCodeSpaceWithStack,
243                          "--compact-code-space-with-stack",
244                          "--no-compact-code-space-with-stack");
245   SetV8FlagsIfOverridden(features::kV8CompactWithStack, "--compact-with-stack",
246                          "--no-compact-with-stack");
247   SetV8FlagsIfOverridden(features::kV8OptimizeJavascript, "--opt", "--no-opt");
248   SetV8FlagsIfOverridden(features::kV8FlushBytecode, "--flush-bytecode",
249                          "--no-flush-bytecode");
250   SetV8FlagsIfOverridden(features::kV8FlushBaselineCode,
251                          "--flush-baseline-code", "--no-flush-baseline-code");
252   SetV8FlagsIfOverridden(features::kV8FlushCodeBasedOnTabVisibility,
253                          "--flush-code-based-on-tab-visibility",
254                          "--no-flush-code-based-on-tab-visibility");
255   SetV8FlagsIfOverridden(features::kV8FlushCodeBasedOnTime,
256                          "--flush-code-based-on-time",
257                          "--no-flush-code-based-on-time");
258   SetV8FlagsIfOverridden(features::kV8OffThreadFinalization,
259                          "--finalize-streaming-on-background",
260                          "--no-finalize-streaming-on-background");
261   if (base::FeatureList::IsEnabled(features::kV8DelayMemoryReducer)) {
262     SetV8FlagsFormatted(
263         "--gc-memory-reducer-start-delay-ms=%i",
264         static_cast<int>(
265             features::kV8MemoryReducerStartDelay.Get().InMilliseconds()));
266   }
267   SetV8FlagsIfOverridden(features::kV8ConcurrentMarkingHighPriorityThreads,
268                          "--concurrent-marking-high-priority-threads",
269                          "--no-concurrent-marking-high-priority-threads");
270   SetV8FlagsIfOverridden(features::kV8LazyFeedbackAllocation,
271                          "--lazy-feedback-allocation",
272                          "--no-lazy-feedback-allocation");
273   SetV8FlagsIfOverridden(features::kV8PerContextMarkingWorklist,
274                          "--stress-per-context-marking-worklist",
275                          "--no-stress-per-context-marking-worklist");
276   SetV8FlagsIfOverridden(features::kV8FlushEmbeddedBlobICache,
277                          "--experimental-flush-embedded-blob-icache",
278                          "--no-experimental-flush-embedded-blob-icache");
279   SetV8FlagsIfOverridden(features::kV8ReduceConcurrentMarkingTasks,
280                          "--gc-experiment-reduce-concurrent-marking-tasks",
281                          "--no-gc-experiment-reduce-concurrent-marking-tasks");
282   SetV8FlagsIfOverridden(features::kV8NoReclaimUnmodifiedWrappers,
283                          "--no-reclaim-unmodified-wrappers",
284                          "--reclaim-unmodified-wrappers");
285   SetV8FlagsIfOverridden(
286       features::kV8ExperimentalRegexpEngine,
287       "--enable-experimental-regexp-engine-on-excessive-backtracks",
288       "--no-enable-experimental-regexp-engine-on-excessive-backtracks");
289   SetV8FlagsIfOverridden(features::kV8TurboFastApiCalls,
290                          "--turbo-fast-api-calls", "--no-turbo-fast-api-calls");
291   SetV8FlagsIfOverridden(features::kV8MegaDomIC, "--mega-dom-ic",
292                          "--no-mega-dom-ic");
293   SetV8FlagsIfOverridden(features::kV8Maglev, "--maglev", "--no-maglev");
294   if (base::FeatureList::IsEnabled(features::kV8MemoryReducer)) {
295     SetV8FlagsFormatted("--memory-reducer-gc-count=%i",
296                         features::kV8MemoryReducerGCCount.Get());
297   }
298   SetV8FlagsIfOverridden(features::kV8MinorMS, "--minor-ms", "--no-minor-ms");
299   SetV8FlagsIfOverridden(features::kV8Sparkplug, "--sparkplug",
300                          "--no-sparkplug");
301   SetV8FlagsIfOverridden(features::kV8Turbofan, "--turbofan", "--no-turbofan");
302   SetV8FlagsIfOverridden(features::kV8Turboshaft, "--turboshaft",
303                          "--no-turboshaft");
304   SetV8FlagsIfOverridden(features::kV8TurboshaftInstructionSelection,
305                          "--turboshaft-instruction-selection",
306                          "--no-turboshaft-instruction-selection");
307   SetV8FlagsIfOverridden(features::kV8ConcurrentSparkplug,
308                          "--concurrent-sparkplug", "--no-concurrent-sparkplug");
309   SetV8FlagsIfOverridden(features::kV8SparkplugNeedsShortBuiltinCalls,
310                          "--sparkplug-needs-short-builtins",
311                          "--no-sparkplug-needs-short-builtins");
312   SetV8FlagsIfOverridden(features::kV8ShortBuiltinCalls,
313                          "--short-builtin-calls", "--no-short-builtin-calls");
314   SetV8FlagsIfOverridden(features::kV8CodeMemoryWriteProtection,
315                          "--write-protect-code-memory",
316                          "--no-write-protect-code-memory");
317   SetV8FlagsIfOverridden(features::kV8SlowHistograms, "--slow-histograms",
318                          "--no-slow-histograms");
319   SetV8FlagsIfOverridden(features::kV8SingleThreadedGCInBackground,
320                          "--single-threaded-gc-in-background",
321                          "--no-single-threaded-gc-in-background");
322   SetV8FlagsIfOverridden(features::kV8MidtierRegallocFallback,
323                          "--turbo-use-mid-tier-regalloc-for-huge-functions",
324                          "--no-turbo-use-mid-tier-regalloc-for-huge-functions");
325
326   if (base::FeatureList::IsEnabled(features::kV8ConcurrentSparkplug)) {
327     if (int max_threads = features::kV8ConcurrentSparkplugMaxThreads.Get()) {
328       SetV8FlagsFormatted("--concurrent-sparkplug-max-threads=%i", max_threads);
329     }
330     SetV8FlagsIfOverridden(features::kV8ConcurrentSparkplugHighPriorityThreads,
331                            "--concurrent-sparkplug-high-priority-threads",
332                            "--no-concurrent-sparkplug-high-priority-threads");
333   }
334
335   if (base::FeatureList::IsEnabled(features::kV8FlushBytecode)) {
336     if (int old_age = features::kV8FlushBytecodeOldAge.Get()) {
337       SetV8FlagsFormatted("--bytecode-old-age=%i", old_age);
338     }
339   }
340
341   if (base::FeatureList::IsEnabled(features::kV8FlushCodeBasedOnTime)) {
342     if (int old_time = features::kV8FlushCodeOldTime.Get()) {
343       SetV8FlagsFormatted("--bytecode-old-time=%i", old_time);
344     }
345   }
346
347   // Make sure aliases of kV8SlowHistograms only enable the feature to
348   // avoid contradicting settings between multiple finch experiments.
349   bool any_slow_histograms_alias =
350       base::FeatureList::IsEnabled(
351           features::kV8SlowHistogramsCodeMemoryWriteProtection) ||
352       base::FeatureList::IsEnabled(features::kV8SlowHistogramsSparkplug) ||
353       base::FeatureList::IsEnabled(
354           features::kV8SlowHistogramsSparkplugAndroid) ||
355       base::FeatureList::IsEnabled(features::kV8SlowHistogramsNoTurbofan);
356   if (any_slow_histograms_alias) {
357     SetV8Flags("--slow-histograms");
358   } else {
359     SetV8FlagsIfOverridden(features::kV8SlowHistograms, "--slow-histograms",
360                            "--no-slow-histograms");
361   }
362
363   SetV8FlagsIfOverridden(features::kV8IgnitionElideRedundantTdzChecks,
364                          "--ignition-elide-redundant-tdz-checks",
365                          "--no-ignition-elide-redundant-tdz-checks");
366
367   // JavaScript language features.
368   SetV8FlagsIfOverridden(features::kJavaScriptSymbolAsWeakMapKey,
369                          "--harmony-symbol-as-weakmap-key",
370                          "--no-harmony-symbol-as-weakmap-key");
371   SetV8FlagsIfOverridden(features::kJavaScriptChangeArrayByCopy,
372                          "--harmony-change-array-by-copy",
373                          "--no-harmony-change-array-by-copy");
374   if (base::FeatureList::IsEnabled(features::kJavaScriptRabGsab)) {
375     SetV8Flags("--harmony-rab-gsab");
376   } else {
377     SetV8Flags("--no-harmony-rab-gsab");
378   }
379   SetV8FlagsIfOverridden(features::kJavaScriptRegExpUnicodeSets,
380                          "--harmony-regexp-unicode-sets",
381                          "--no-harmony-regexp-unicode-sets");
382   SetV8FlagsIfOverridden(features::kJavaScriptJsonParseWithSource,
383                          "--harmony-json-parse-with-source",
384                          "--no-harmony-json-parse-with-source");
385   SetV8FlagsIfOverridden(features::kJavaScriptArrayBufferTransfer,
386                          "--harmony-rab-gsab-transfer",
387                          "--no-harmony-rab-gsab-transfer");
388   SetV8FlagsIfOverridden(features::kJavaScriptIteratorHelpers,
389                          "--harmony-iterator-helpers",
390                          "--no-harmony-iterator-helpers");
391   SetV8FlagsIfOverridden(features::kJavaScriptPromiseWithResolvers,
392                          "--js-promise-withresolvers",
393                          "--no-js-promise-withresolvers");
394
395   if (IsolateHolder::kStrictMode == mode) {
396     SetV8Flags("--use_strict");
397   }
398
399   SetV8FlagsIfOverridden(features::kV8UseLibmTrigFunctions,
400                          "--use-libm-trig-functions",
401                          "--no-use-libm-trig-functions");
402
403   SetV8FlagsIfOverridden(features::kJavaScriptCompileHintsMagic,
404                          "--compile-hints-magic", "--no-compile-hints-magic");
405
406   // WebAssembly features.
407
408   SetV8FlagsIfOverridden(features::kWebAssemblyTailCall,
409                          "--experimental-wasm-return-call",
410                          "--no-experimental-wasm-return-call");
411   SetV8FlagsIfOverridden(features::kWebAssemblyInlining,
412                          "--experimental-wasm-inlining",
413                          "--no-experimental-wasm-inlining");
414   SetV8FlagsIfOverridden(features::kWebAssemblyGenericWrapper,
415                          "--wasm-to-js-generic-wrapper",
416                          "--no-wasm-to-js-generic-wrapper");
417   SetV8FlagsIfOverridden(features::kWebAssemblyMultipleMemories,
418                          "--experimental-wasm-multi-memory",
419                          "--no-experimental-wasm-multi-memory");
420   SetV8FlagsIfOverridden(features::kWebAssemblyTurboshaft, "--turboshaft-wasm",
421                          "--no-turboshaft-wasm");
422
423   if (js_command_line_flags.empty())
424     return;
425
426   // Allow the --js-flags switch to override existing flags:
427   std::vector<base::StringPiece> flag_list =
428       base::SplitStringPiece(js_command_line_flags, ",", base::TRIM_WHITESPACE,
429                              base::SPLIT_WANT_NONEMPTY);
430   for (const auto& flag : flag_list) {
431     v8::V8::SetFlagsFromString(std::string(flag).c_str(), flag.size());
432   }
433 }
434
435 }  // namespace
436
437 // static
438 void V8Initializer::Initialize(IsolateHolder::ScriptMode mode,
439                                const std::string js_command_line_flags,
440 #if defined(ENABLE_WRT_JS)
441                                v8::OOMErrorCallback oom_error_callback,
442                                bool create_v8_platform) {
443 #else
444                                v8::OOMErrorCallback oom_error_callback) {
445 #endif
446   static bool v8_is_initialized = false;
447   if (v8_is_initialized)
448     return;
449
450   // Flags need to be set before InitializePlatform as they are used for
451   // system instrumentation initialization.
452   // See https://crbug.com/v8/11043
453   SetFlags(mode, js_command_line_flags);
454
455 #if defined(ENABLE_WRT_JS)
456   if (create_v8_platform)
457 #endif
458   v8::V8::InitializePlatform(V8Platform::Get());
459
460   // Set this as early as possible in order to ensure OOM errors are reported
461   // correctly.
462   v8::V8::SetFatalMemoryErrorCallback(oom_error_callback);
463
464   // Set this early on as some initialization steps, such as the initialization
465   // of the virtual memory cage, already use V8's random number generator.
466   v8::V8::SetEntropySource(&GenerateEntropy);
467
468 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
469   if (g_mapped_snapshot) {
470     v8::StartupData snapshot;
471     GetMappedFileData(g_mapped_snapshot, &snapshot);
472     v8::V8::SetSnapshotDataBlob(&snapshot);
473   }
474 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
475
476   v8::V8::Initialize();
477
478   v8_is_initialized = true;
479
480 #if defined(V8_ENABLE_SANDBOX)
481   // Record some sandbox statistics into UMA.
482   // The main reason for capturing these histograms here instead of having V8
483   // do it is that there are no Isolates available yet, which are required
484   // for recording histograms in V8.
485
486   // Record the mode of the sandbox.
487   // These values are persisted to logs. Entries should not be renumbered and
488   // numeric values should never be reused. This should match enum
489   // V8SandboxMode in tools/metrics/histograms/enums.xml.
490   enum class V8SandboxMode {
491     kSecure = 0,
492     kInsecure = 1,
493     kMaxValue = kInsecure,
494   };
495   base::UmaHistogramEnumeration("V8.SandboxMode",
496                                 v8::V8::IsSandboxConfiguredSecurely()
497                                     ? V8SandboxMode::kSecure
498                                     : V8SandboxMode::kInsecure);
499
500   // Record the size of the address space reservation backing the sandbox.
501   // The size will always be one of a handful of values, so use a sparse
502   // histogram to capture it.
503   size_t size = v8::V8::GetSandboxReservationSizeInBytes();
504   DCHECK_GT(size, 0U);
505   size_t sizeInGB = size >> 30;
506   DCHECK_EQ(sizeInGB << 30, size);
507   base::UmaHistogramSparse("V8.SandboxReservationSizeGB", sizeInGB);
508
509   // When the sandbox is enabled, ArrayBuffers must be allocated inside of
510   // it. To achieve that, PA's ConfigurablePool is created inside the sandbox
511   // and Blink then creates the ArrayBuffer partition in that Pool.
512   v8::VirtualAddressSpace* sandbox_address_space =
513       v8::V8::GetSandboxAddressSpace();
514   const size_t max_pool_size = partition_alloc::internal::
515       PartitionAddressSpace::ConfigurablePoolMaxSize();
516   const size_t min_pool_size = partition_alloc::internal::
517       PartitionAddressSpace::ConfigurablePoolMinSize();
518   size_t pool_size = max_pool_size;
519   // Try to reserve the maximum size of the pool at first, then keep halving
520   // the size on failure until it succeeds.
521   uintptr_t pool_base = 0;
522   while (!pool_base && pool_size >= min_pool_size) {
523     pool_base = sandbox_address_space->AllocatePages(
524         0, pool_size, pool_size, v8::PagePermissions::kNoAccess);
525     if (!pool_base) {
526       pool_size /= 2;
527     }
528   }
529   // The V8 sandbox is guaranteed to be large enough to host the pool.
530   CHECK(pool_base);
531   partition_alloc::internal::PartitionAddressSpace::InitConfigurablePool(
532       pool_base, pool_size);
533   // TODO(saelo) maybe record the size of the Pool into UMA.
534 #endif  // V8_ENABLE_SANDBOX
535
536   // Initialize the partition used by gin::ArrayBufferAllocator instances. This
537   // needs to happen now, after the V8 sandbox has been initialized, so that
538   // the partition is placed inside the configurable pool initialized above.
539   ArrayBufferAllocator::InitializePartition();
540 }
541
542 // static
543 void V8Initializer::GetV8ExternalSnapshotData(v8::StartupData* snapshot) {
544   GetMappedFileData(g_mapped_snapshot, snapshot);
545 }
546
547 // static
548 void V8Initializer::GetV8ExternalSnapshotData(const char** snapshot_data_out,
549                                               int* snapshot_size_out) {
550   v8::StartupData snapshot;
551   GetV8ExternalSnapshotData(&snapshot);
552   *snapshot_data_out = snapshot.data;
553   *snapshot_size_out = snapshot.raw_size;
554 }
555
556 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
557
558 // static
559 void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) {
560   if (g_mapped_snapshot) {
561     // TODO(crbug.com/802962): Confirm not loading different type of snapshot
562     // files in a process.
563     return;
564   }
565
566   base::MemoryMappedFile::Region file_region;
567   base::File file =
568       OpenV8File(GetSnapshotFileName(snapshot_file_type), &file_region);
569   LoadV8SnapshotFromFile(std::move(file), &file_region, snapshot_file_type);
570 }
571
572 // static
573 void V8Initializer::LoadV8SnapshotFromFile(
574     base::File snapshot_file,
575     base::MemoryMappedFile::Region* snapshot_file_region,
576     V8SnapshotFileType snapshot_file_type) {
577   if (g_mapped_snapshot)
578     return;
579
580   if (!snapshot_file.IsValid()) {
581     LOG(FATAL) << "Error loading V8 startup snapshot file";
582     return;
583   }
584
585   g_snapshot_file_type = snapshot_file_type;
586   base::MemoryMappedFile::Region region =
587       base::MemoryMappedFile::Region::kWholeFile;
588   if (snapshot_file_region) {
589     region = *snapshot_file_region;
590   }
591
592   if (!MapV8File(std::move(snapshot_file), region, &g_mapped_snapshot)) {
593     LOG(FATAL) << "Error mapping V8 startup snapshot file";
594     return;
595   }
596 }
597
598 #if BUILDFLAG(IS_ANDROID)
599 // static
600 base::FilePath V8Initializer::GetSnapshotFilePath(
601     bool abi_32_bit,
602     V8SnapshotFileType snapshot_file_type) {
603   base::FilePath path;
604   const char* filename = nullptr;
605   switch (snapshot_file_type) {
606     case V8SnapshotFileType::kDefault:
607       filename = abi_32_bit ? kSnapshotFileName32 : kSnapshotFileName64;
608       break;
609     case V8SnapshotFileType::kWithAdditionalContext:
610       filename = abi_32_bit ? kV8ContextSnapshotFileName32
611                             : kV8ContextSnapshotFileName64;
612       break;
613   }
614   CHECK(filename);
615
616   GetV8FilePath(filename, &path);
617   return path;
618 }
619 #endif  // BUILDFLAG(IS_ANDROID)
620
621 V8SnapshotFileType GetLoadedSnapshotFileType() {
622   DCHECK(g_snapshot_file_type.has_value());
623   return *g_snapshot_file_type;
624 }
625
626 #endif  // defined(V8_USE_EXTERNAL_STARTUP_DATA)
627
628 }  // namespace gin