blob: be2b9149e4407a7a946aa9fd240781fe25e9a51e [file] [log] [blame]
oth05c26fde2015-04-05 14:30:571// 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
5#include "gin/v8_initializer.h"
6
avi90e658dd2015-12-21 07:16:197#include <stddef.h>
8#include <stdint.h>
9
mostynbc862da82016-04-03 15:54:3310#include <memory>
11
oth29c7ed92015-06-19 14:40:0012#include "base/debug/alias.h"
rmcilroy462e47e2016-06-24 20:45:0813#include "base/debug/crash_logging.h"
rmcilroyfe515ad2016-04-08 17:59:1014#include "base/feature_list.h"
oth05c26fde2015-04-05 14:30:5715#include "base/files/file.h"
16#include "base/files/file_path.h"
17#include "base/files/memory_mapped_file.h"
tobiasjsb20016272016-02-10 11:54:1218#include "base/lazy_instance.h"
oth05c26fde2015-04-05 14:30:5719#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0820#include "base/metrics/histogram_macros.h"
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5521#include "base/path_service.h"
oth05c26fde2015-04-05 14:30:5722#include "base/rand_util.h"
23#include "base/strings/sys_string_conversions.h"
rmcilroy542f61c2016-06-06 16:08:1924#include "base/sys_info.h"
oth575f7fb52015-05-08 17:35:0025#include "base/threading/platform_thread.h"
26#include "base/time/time.h"
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5527#include "build/build_config.h"
Ross McIlroy45e9500a2018-03-27 17:06:0228#include "gin/gin_features.h"
oth05c26fde2015-04-05 14:30:5729
30#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
agrieve6f3002d2015-06-19 16:49:0631#if defined(OS_ANDROID)
32#include "base/android/apk_assets.h"
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5533#elif defined(OS_MACOSX)
Max Morinf0d13c92017-08-17 10:04:5934#include "base/mac/foundation_util.h"
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5535#endif
oth05c26fde2015-04-05 14:30:5736#endif // V8_USE_EXTERNAL_STARTUP_DATA
37
38namespace gin {
39
40namespace {
41
agrievefd2d44ab2015-06-19 04:33:0342// None of these globals are ever freed nor closed.
oth05c26fde2015-04-05 14:30:5743base::MemoryMappedFile* g_mapped_natives = nullptr;
44base::MemoryMappedFile* g_mapped_snapshot = nullptr;
45
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:4646bool GenerateEntropy(unsigned char* buffer, size_t amount) {
47 base::RandBytes(buffer, amount);
48 return true;
49}
50
51void GetMappedFileData(base::MemoryMappedFile* mapped_file,
52 v8::StartupData* data) {
53 if (mapped_file) {
54 data->data = reinterpret_cast<const char*>(mapped_file->data());
55 data->raw_size = static_cast<int>(mapped_file->length());
56 } else {
57 data->data = nullptr;
58 data->raw_size = 0;
59 }
60}
61
62#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
agrievefd2d44ab2015-06-19 04:33:0363
agrievefd2d44ab2015-06-19 04:33:0364// File handles intentionally never closed. Not using File here because its
65// Windows implementation guards against two instances owning the same
66// PlatformFile (which we allow since we know it is never freed).
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5567using OpenedFileMap =
68 std::map<const char*,
69 std::pair<base::PlatformFile, base::MemoryMappedFile::Region>>;
70base::LazyInstance<OpenedFileMap>::Leaky g_opened_files =
tobiasjsb20016272016-02-10 11:54:1271 LAZY_INSTANCE_INITIALIZER;
72
michaelbai020375882016-06-21 16:08:1573const char kNativesFileName[] = "natives_blob.bin";
74
michaelbai016306732015-11-03 19:48:0075#if defined(OS_ANDROID)
Hitoshi Yoshida06697232018-03-05 04:09:1576const char kV8ContextSnapshotFileName64[] = "v8_context_snapshot_64.bin";
77const char kV8ContextSnapshotFileName32[] = "v8_context_snapshot_32.bin";
tobiasjsb20016272016-02-10 11:54:1278const char kSnapshotFileName64[] = "snapshot_blob_64.bin";
tobiasjsb20016272016-02-10 11:54:1279const char kSnapshotFileName32[] = "snapshot_blob_32.bin";
80
81#if defined(__LP64__)
Hitoshi Yoshida06697232018-03-05 04:09:1582#define kV8ContextSnapshotFileName kV8ContextSnapshotFileName64
tobiasjsb20016272016-02-10 11:54:1283#define kSnapshotFileName kSnapshotFileName64
michaelbai016306732015-11-03 19:48:0084#else
Hitoshi Yoshida06697232018-03-05 04:09:1585#define kV8ContextSnapshotFileName kV8ContextSnapshotFileName32
tobiasjsb20016272016-02-10 11:54:1286#define kSnapshotFileName kSnapshotFileName32
87#endif
michaelbai016306732015-11-03 19:48:0088
89#else // defined(OS_ANDROID)
Hitoshi Yoshida06697232018-03-05 04:09:1590const char kV8ContextSnapshotFileName[] = "v8_context_snapshot.bin";
rmcilroy54fab5e2015-04-06 21:14:5891const char kSnapshotFileName[] = "snapshot_blob.bin";
michaelbai016306732015-11-03 19:48:0092#endif // defined(OS_ANDROID)
rmcilroy54fab5e2015-04-06 21:14:5893
Hitoshi Yoshida9aff02e2018-01-19 16:55:0394const char* GetSnapshotFileName(
95 const V8Initializer::V8SnapshotFileType file_type) {
96 switch (file_type) {
97 case V8Initializer::V8SnapshotFileType::kDefault:
98 return kSnapshotFileName;
99 case V8Initializer::V8SnapshotFileType::kWithAdditionalContext:
100 return kV8ContextSnapshotFileName;
101 }
102 NOTREACHED();
103 return nullptr;
104}
105
erikcorryc94eff12015-06-08 11:29:16106void GetV8FilePath(const char* file_name, base::FilePath* path_out) {
agrieve6f3002d2015-06-19 16:49:06107#if defined(OS_ANDROID)
108 // This is the path within the .apk.
Sergey Ulanovd5ae68e2018-02-07 20:14:21109 *path_out =
110 base::FilePath(FILE_PATH_LITERAL("assets")).AppendASCII(file_name);
111#elif defined(OS_MACOSX)
rmcilroy54fab5e2015-04-06 21:14:58112 base::ScopedCFTypeRef<CFStringRef> natives_file_name(
erikcorryc94eff12015-06-08 11:29:16113 base::SysUTF8ToCFStringRef(file_name));
114 *path_out = base::mac::PathForFrameworkBundleResource(natives_file_name);
Sergey Ulanovd5ae68e2018-02-07 20:14:21115#else
116 base::FilePath data_path;
Avi Drissmanea15ea02018-05-07 18:55:12117 bool r = base::PathService::Get(base::DIR_ASSETS, &data_path);
Sergey Ulanovd5ae68e2018-02-07 20:14:21118 DCHECK(r);
119 *path_out = data_path.AppendASCII(file_name);
120#endif
rmcilroy54fab5e2015-04-06 21:14:58121}
122
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55123bool MapV8File(base::PlatformFile platform_file,
124 base::MemoryMappedFile::Region region,
125 base::MemoryMappedFile** mmapped_file_out) {
erikcorryc94eff12015-06-08 11:29:16126 DCHECK(*mmapped_file_out == NULL);
mostynbc862da82016-04-03 15:54:33127 std::unique_ptr<base::MemoryMappedFile> mmapped_file(
128 new base::MemoryMappedFile());
agrievefd2d44ab2015-06-19 04:33:03129 if (mmapped_file->Initialize(base::File(platform_file), region)) {
130 *mmapped_file_out = mmapped_file.release();
131 return true;
oth05c26fde2015-04-05 14:30:57132 }
agrievefd2d44ab2015-06-19 04:33:03133 return false;
oth05c26fde2015-04-05 14:30:57134}
135
agrievefd2d44ab2015-06-19 04:33:03136base::PlatformFile OpenV8File(const char* file_name,
137 base::MemoryMappedFile::Region* region_out) {
oth575f7fb52015-05-08 17:35:00138 // Re-try logic here is motivated by http://crbug.com/479537
139 // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
140
141 // These match tools/metrics/histograms.xml
142 enum OpenV8FileResult {
143 OPENED = 0,
144 OPENED_RETRY,
145 FAILED_IN_USE,
146 FAILED_OTHER,
147 MAX_VALUE
148 };
agrievefd2d44ab2015-06-19 04:33:03149 base::FilePath path;
150 GetV8FilePath(file_name, &path);
151
agrieve6f3002d2015-06-19 16:49:06152#if defined(OS_ANDROID)
153 base::File file(base::android::OpenApkAsset(path.value(), region_out));
154 OpenV8FileResult result = file.IsValid() ? OpenV8FileResult::OPENED
155 : OpenV8FileResult::FAILED_OTHER;
156#else
157 // Re-try logic here is motivated by http://crbug.com/479537
158 // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
159 const int kMaxOpenAttempts = 5;
160 const int kOpenRetryDelayMillis = 250;
161
oth575f7fb52015-05-08 17:35:00162 OpenV8FileResult result = OpenV8FileResult::FAILED_IN_USE;
agrievefd2d44ab2015-06-19 04:33:03163 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
164 base::File file;
oth575f7fb52015-05-08 17:35:00165 for (int attempt = 0; attempt < kMaxOpenAttempts; attempt++) {
166 file.Initialize(path, flags);
167 if (file.IsValid()) {
agrievefd2d44ab2015-06-19 04:33:03168 *region_out = base::MemoryMappedFile::Region::kWholeFile;
oth575f7fb52015-05-08 17:35:00169 if (attempt == 0) {
170 result = OpenV8FileResult::OPENED;
171 break;
172 } else {
173 result = OpenV8FileResult::OPENED_RETRY;
174 break;
175 }
176 } else if (file.error_details() != base::File::FILE_ERROR_IN_USE) {
177 result = OpenV8FileResult::FAILED_OTHER;
oth29c7ed92015-06-19 14:40:00178#ifdef OS_WIN
179 // TODO(oth): temporary diagnostics for http://crbug.com/479537
180 std::string narrow(kNativesFileName);
181 base::FilePath::StringType nativesBlob(narrow.begin(), narrow.end());
182 if (path.BaseName().value() == nativesBlob) {
183 base::File::Error file_error = file.error_details();
184 base::debug::Alias(&file_error);
185 LOG(FATAL) << "Failed to open V8 file '" << path.value()
186 << "' (reason: " << file.error_details() << ")";
187 }
188#endif // OS_WIN
oth575f7fb52015-05-08 17:35:00189 break;
190 } else if (kMaxOpenAttempts - 1 != attempt) {
191 base::PlatformThread::Sleep(
192 base::TimeDelta::FromMilliseconds(kOpenRetryDelayMillis));
193 }
194 }
agrieve6f3002d2015-06-19 16:49:06195#endif // defined(OS_ANDROID)
oth575f7fb52015-05-08 17:35:00196
197 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.OpenV8File.Result",
198 result,
199 OpenV8FileResult::MAX_VALUE);
agrievefd2d44ab2015-06-19 04:33:03200 return file.TakePlatformFile();
201}
oth575f7fb52015-05-08 17:35:00202
Hitoshi Yoshida129ff2b2017-08-24 02:19:10203OpenedFileMap::mapped_type& GetOpenedFile(const char* filename) {
204 OpenedFileMap& opened_files(g_opened_files.Get());
Jeremy Roman6a3b3d42017-08-24 17:13:51205 auto result = opened_files.emplace(filename, OpenedFileMap::mapped_type());
206 OpenedFileMap::mapped_type& opened_file = result.first->second;
207 bool is_new_file = result.second;
Hitoshi Yoshida129ff2b2017-08-24 02:19:10208
Jeremy Roman6a3b3d42017-08-24 17:13:51209 // If we have no cache, try to open it and cache the result.
210 if (is_new_file)
211 opened_file.first = OpenV8File(filename, &opened_file.second);
212
213 return opened_file;
oth575f7fb52015-05-08 17:35:00214}
215
erikcorryc94eff12015-06-08 11:29:16216enum LoadV8FileResult {
217 V8_LOAD_SUCCESS = 0,
218 V8_LOAD_FAILED_OPEN,
219 V8_LOAD_FAILED_MAP,
jcivellidbe3dec2017-02-07 16:58:23220 V8_LOAD_FAILED_VERIFY, // Deprecated.
erikcorryc94eff12015-06-08 11:29:16221 V8_LOAD_MAX_VALUE
222};
oth575f7fb52015-05-08 17:35:00223
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55224LoadV8FileResult MapOpenedFile(const OpenedFileMap::mapped_type& file_region,
225 base::MemoryMappedFile** mmapped_file_out) {
rockot5d4213ff2016-05-25 19:07:10226 if (file_region.first == base::kInvalidPlatformFile)
erikcorryc94eff12015-06-08 11:29:16227 return V8_LOAD_FAILED_OPEN;
tobiasjsb20016272016-02-10 11:54:12228 if (!MapV8File(file_region.first, file_region.second, mmapped_file_out))
erikcorryc94eff12015-06-08 11:29:16229 return V8_LOAD_FAILED_MAP;
erikcorryc94eff12015-06-08 11:29:16230 return V8_LOAD_SUCCESS;
oth05c26fde2015-04-05 14:30:57231}
232
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46233#endif // defined(V8_USE_EXTERNAL_STATUP_DATA)
Hitoshi Yoshida129ff2b2017-08-24 02:19:10234
jcivellidbe3dec2017-02-07 16:58:23235} // namespace
236
oth05c26fde2015-04-05 14:30:57237// static
yhirano93150242015-12-07 12:28:33238void V8Initializer::Initialize(IsolateHolder::ScriptMode mode,
239 IsolateHolder::V8ExtrasMode v8_extras_mode) {
oth05c26fde2015-04-05 14:30:57240 static bool v8_is_initialized = false;
241 if (v8_is_initialized)
242 return;
243
244 v8::V8::InitializePlatform(V8Platform::Get());
oth05c26fde2015-04-05 14:30:57245
Ross McIlroy45e9500a2018-03-27 17:06:02246 if (base::FeatureList::IsEnabled(features::kV8OptimizeJavascript)) {
247 static const char optimize[] = "--opt";
248 v8::V8::SetFlagsFromString(optimize, sizeof(optimize) - 1);
249 } else {
250 static const char no_optimize[] = "--no-opt";
251 v8::V8::SetFlagsFromString(no_optimize, sizeof(no_optimize) - 1);
252 }
253
yhirano93150242015-12-07 12:28:33254 if (IsolateHolder::kStrictMode == mode) {
oth05c26fde2015-04-05 14:30:57255 static const char use_strict[] = "--use_strict";
256 v8::V8::SetFlagsFromString(use_strict, sizeof(use_strict) - 1);
257 }
yhirano93150242015-12-07 12:28:33258 if (IsolateHolder::kStableAndExperimentalV8Extras == v8_extras_mode) {
259 static const char flag[] = "--experimental_extras";
260 v8::V8::SetFlagsFromString(flag, sizeof(flag) - 1);
261 }
oth05c26fde2015-04-05 14:30:57262
263#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
264 v8::StartupData natives;
Hitoshi Yoshida9aff02e2018-01-19 16:55:03265 GetMappedFileData(g_mapped_natives, &natives);
oth05c26fde2015-04-05 14:30:57266 v8::V8::SetNativesDataBlob(&natives);
267
Hitoshi Yoshida231de8352017-12-08 01:06:33268 if (g_mapped_snapshot) {
Robert Liao1e7eb052017-12-15 00:30:05269 v8::StartupData snapshot;
Hitoshi Yoshida9aff02e2018-01-19 16:55:03270 GetMappedFileData(g_mapped_snapshot, &snapshot);
Hitoshi Yoshida231de8352017-12-08 01:06:33271 v8::V8::SetSnapshotDataBlob(&snapshot);
272 }
oth05c26fde2015-04-05 14:30:57273#endif // V8_USE_EXTERNAL_STARTUP_DATA
274
275 v8::V8::SetEntropySource(&GenerateEntropy);
276 v8::V8::Initialize();
277
278 v8_is_initialized = true;
279}
280
281// static
Hitoshi Yoshidad88a223e2017-09-10 05:55:25282void V8Initializer::GetV8ExternalSnapshotData(v8::StartupData* natives,
283 v8::StartupData* snapshot) {
284 GetMappedFileData(g_mapped_natives, natives);
285 GetMappedFileData(g_mapped_snapshot, snapshot);
286}
287
288// static
oth05c26fde2015-04-05 14:30:57289void V8Initializer::GetV8ExternalSnapshotData(const char** natives_data_out,
290 int* natives_size_out,
291 const char** snapshot_data_out,
292 int* snapshot_size_out) {
Hitoshi Yoshidad88a223e2017-09-10 05:55:25293 v8::StartupData natives;
294 v8::StartupData snapshot;
295 GetV8ExternalSnapshotData(&natives, &snapshot);
296 *natives_data_out = natives.data;
297 *natives_size_out = natives.raw_size;
298 *snapshot_data_out = snapshot.data;
299 *snapshot_size_out = snapshot.raw_size;
oth05c26fde2015-04-05 14:30:57300}
301
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46302#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
303
304// static
Hitoshi Yoshida9aff02e2018-01-19 16:55:03305void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) {
306 if (g_mapped_snapshot) {
307 // TODO(crbug.com/802962): Confirm not loading different type of snapshot
308 // files in a process.
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46309 return;
Hitoshi Yoshida9aff02e2018-01-19 16:55:03310 }
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46311
Hitoshi Yoshida9aff02e2018-01-19 16:55:03312 LoadV8FileResult result =
313 MapOpenedFile(GetOpenedFile(GetSnapshotFileName(snapshot_file_type)),
314 &g_mapped_snapshot);
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46315 // V8 can't start up without the source of the natives, but it can
316 // start up (slower) without the snapshot.
317 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.LoadV8Snapshot.Result", result,
318 V8_LOAD_MAX_VALUE);
319}
320
Hitoshi Yoshida9aff02e2018-01-19 16:55:03321// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46322void V8Initializer::LoadV8Natives() {
323 if (g_mapped_natives)
324 return;
325
326 LoadV8FileResult result = MapOpenedFile(GetOpenedFile(kNativesFileName),
327 &g_mapped_natives);
328 if (result != V8_LOAD_SUCCESS) {
329 LOG(FATAL) << "Couldn't mmap v8 natives data file, status code is "
330 << static_cast<int>(result);
331 }
332}
333
334// static
Hitoshi Yoshida9aff02e2018-01-19 16:55:03335void V8Initializer::LoadV8SnapshotFromFD(
336 base::PlatformFile snapshot_pf,
337 int64_t snapshot_offset,
338 int64_t snapshot_size,
339 V8SnapshotFileType snapshot_file_type) {
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46340 if (g_mapped_snapshot)
341 return;
342
343 if (snapshot_pf == base::kInvalidPlatformFile)
344 return;
345
346 base::MemoryMappedFile::Region snapshot_region =
347 base::MemoryMappedFile::Region::kWholeFile;
348 if (snapshot_size != 0 || snapshot_offset != 0) {
349 snapshot_region.offset = snapshot_offset;
350 snapshot_region.size = snapshot_size;
351 }
352
353 LoadV8FileResult result = V8_LOAD_SUCCESS;
354 if (!MapV8File(snapshot_pf, snapshot_region, &g_mapped_snapshot))
355 result = V8_LOAD_FAILED_MAP;
356 if (result == V8_LOAD_SUCCESS) {
Hitoshi Yoshida9aff02e2018-01-19 16:55:03357 g_opened_files.Get()[GetSnapshotFileName(snapshot_file_type)] =
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46358 std::make_pair(snapshot_pf, snapshot_region);
359 }
360 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.LoadV8Snapshot.Result", result,
361 V8_LOAD_MAX_VALUE);
362}
363
364// static
365void V8Initializer::LoadV8NativesFromFD(base::PlatformFile natives_pf,
366 int64_t natives_offset,
367 int64_t natives_size) {
368 if (g_mapped_natives)
369 return;
370
371 CHECK_NE(natives_pf, base::kInvalidPlatformFile);
372
373 base::MemoryMappedFile::Region natives_region =
374 base::MemoryMappedFile::Region::kWholeFile;
375 if (natives_size != 0 || natives_offset != 0) {
376 natives_region.offset = natives_offset;
377 natives_region.size = natives_size;
378 }
379
380 if (!MapV8File(natives_pf, natives_region, &g_mapped_natives)) {
381 LOG(FATAL) << "Couldn't mmap v8 natives data file";
382 }
383 g_opened_files.Get()[kNativesFileName] =
384 std::make_pair(natives_pf, natives_region);
385}
386
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46387#if defined(OS_ANDROID)
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55388// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46389base::FilePath V8Initializer::GetNativesFilePath() {
390 base::FilePath path;
391 GetV8FilePath(kNativesFileName, &path);
392 return path;
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55393}
394
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46395// static
Hitoshi Yoshida06697232018-03-05 04:09:15396base::FilePath V8Initializer::GetSnapshotFilePath(
397 bool abi_32_bit,
398 V8SnapshotFileType snapshot_file_type) {
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46399 base::FilePath path;
Hitoshi Yoshida06697232018-03-05 04:09:15400 const char* filename = nullptr;
401 switch (snapshot_file_type) {
402 case V8Initializer::V8SnapshotFileType::kDefault:
403 filename = abi_32_bit ? kSnapshotFileName32 : kSnapshotFileName64;
404 break;
405 case V8Initializer::V8SnapshotFileType::kWithAdditionalContext:
406 filename = abi_32_bit ? kV8ContextSnapshotFileName32
407 : kV8ContextSnapshotFileName64;
408 break;
409 }
410 CHECK(filename);
411
412 GetV8FilePath(filename, &path);
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46413 return path;
414}
415#endif // defined(OS_ANDROID)
416#endif // defined(V8_USE_EXTERNAL_STARTUP_DATA)
417
oth05c26fde2015-04-05 14:30:57418} // namespace gin