blob: 7c1d44cec9275333839fdc48c9a0a0db230d0161 [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"
oth05c26fde2015-04-05 14:30:5728
29#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
agrieve6f3002d2015-06-19 16:49:0630#if defined(OS_ANDROID)
31#include "base/android/apk_assets.h"
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5532#elif defined(OS_MACOSX)
Max Morinf0d13c92017-08-17 10:04:5933#include "base/mac/foundation_util.h"
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5534#endif
oth05c26fde2015-04-05 14:30:5735#endif // V8_USE_EXTERNAL_STARTUP_DATA
36
37namespace gin {
38
39namespace {
40
agrievefd2d44ab2015-06-19 04:33:0341// None of these globals are ever freed nor closed.
oth05c26fde2015-04-05 14:30:5742base::MemoryMappedFile* g_mapped_natives = nullptr;
43base::MemoryMappedFile* g_mapped_snapshot = nullptr;
44
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:4645bool GenerateEntropy(unsigned char* buffer, size_t amount) {
46 base::RandBytes(buffer, amount);
47 return true;
48}
49
50void GetMappedFileData(base::MemoryMappedFile* mapped_file,
51 v8::StartupData* data) {
52 if (mapped_file) {
53 data->data = reinterpret_cast<const char*>(mapped_file->data());
54 data->raw_size = static_cast<int>(mapped_file->length());
55 } else {
56 data->data = nullptr;
57 data->raw_size = 0;
58 }
59}
60
61#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
agrievefd2d44ab2015-06-19 04:33:0362
agrievefd2d44ab2015-06-19 04:33:0363// File handles intentionally never closed. Not using File here because its
64// Windows implementation guards against two instances owning the same
65// PlatformFile (which we allow since we know it is never freed).
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5566using OpenedFileMap =
67 std::map<const char*,
68 std::pair<base::PlatformFile, base::MemoryMappedFile::Region>>;
69base::LazyInstance<OpenedFileMap>::Leaky g_opened_files =
tobiasjsb20016272016-02-10 11:54:1270 LAZY_INSTANCE_INITIALIZER;
71
michaelbai020375882016-06-21 16:08:1572const char kNativesFileName[] = "natives_blob.bin";
73
michaelbai016306732015-11-03 19:48:0074#if defined(OS_ANDROID)
Hitoshi Yoshida06697232018-03-05 04:09:1575const char kV8ContextSnapshotFileName64[] = "v8_context_snapshot_64.bin";
76const char kV8ContextSnapshotFileName32[] = "v8_context_snapshot_32.bin";
tobiasjsb20016272016-02-10 11:54:1277const char kSnapshotFileName64[] = "snapshot_blob_64.bin";
tobiasjsb20016272016-02-10 11:54:1278const char kSnapshotFileName32[] = "snapshot_blob_32.bin";
79
80#if defined(__LP64__)
Hitoshi Yoshida06697232018-03-05 04:09:1581#define kV8ContextSnapshotFileName kV8ContextSnapshotFileName64
tobiasjsb20016272016-02-10 11:54:1282#define kSnapshotFileName kSnapshotFileName64
michaelbai016306732015-11-03 19:48:0083#else
Hitoshi Yoshida06697232018-03-05 04:09:1584#define kV8ContextSnapshotFileName kV8ContextSnapshotFileName32
tobiasjsb20016272016-02-10 11:54:1285#define kSnapshotFileName kSnapshotFileName32
86#endif
michaelbai016306732015-11-03 19:48:0087
88#else // defined(OS_ANDROID)
Hitoshi Yoshida06697232018-03-05 04:09:1589const char kV8ContextSnapshotFileName[] = "v8_context_snapshot.bin";
rmcilroy54fab5e2015-04-06 21:14:5890const char kSnapshotFileName[] = "snapshot_blob.bin";
michaelbai016306732015-11-03 19:48:0091#endif // defined(OS_ANDROID)
rmcilroy54fab5e2015-04-06 21:14:5892
Hitoshi Yoshida9aff02e2018-01-19 16:55:0393const char* GetSnapshotFileName(
94 const V8Initializer::V8SnapshotFileType file_type) {
95 switch (file_type) {
96 case V8Initializer::V8SnapshotFileType::kDefault:
97 return kSnapshotFileName;
98 case V8Initializer::V8SnapshotFileType::kWithAdditionalContext:
99 return kV8ContextSnapshotFileName;
100 }
101 NOTREACHED();
102 return nullptr;
103}
104
erikcorryc94eff12015-06-08 11:29:16105void GetV8FilePath(const char* file_name, base::FilePath* path_out) {
agrieve6f3002d2015-06-19 16:49:06106#if defined(OS_ANDROID)
107 // This is the path within the .apk.
Sergey Ulanovd5ae68e2018-02-07 20:14:21108 *path_out =
109 base::FilePath(FILE_PATH_LITERAL("assets")).AppendASCII(file_name);
110#elif defined(OS_MACOSX)
rmcilroy54fab5e2015-04-06 21:14:58111 base::ScopedCFTypeRef<CFStringRef> natives_file_name(
erikcorryc94eff12015-06-08 11:29:16112 base::SysUTF8ToCFStringRef(file_name));
113 *path_out = base::mac::PathForFrameworkBundleResource(natives_file_name);
Sergey Ulanovd5ae68e2018-02-07 20:14:21114#else
115 base::FilePath data_path;
116 bool r = PathService::Get(base::DIR_ASSETS, &data_path);
117 DCHECK(r);
118 *path_out = data_path.AppendASCII(file_name);
119#endif
rmcilroy54fab5e2015-04-06 21:14:58120}
121
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55122bool MapV8File(base::PlatformFile platform_file,
123 base::MemoryMappedFile::Region region,
124 base::MemoryMappedFile** mmapped_file_out) {
erikcorryc94eff12015-06-08 11:29:16125 DCHECK(*mmapped_file_out == NULL);
mostynbc862da82016-04-03 15:54:33126 std::unique_ptr<base::MemoryMappedFile> mmapped_file(
127 new base::MemoryMappedFile());
agrievefd2d44ab2015-06-19 04:33:03128 if (mmapped_file->Initialize(base::File(platform_file), region)) {
129 *mmapped_file_out = mmapped_file.release();
130 return true;
oth05c26fde2015-04-05 14:30:57131 }
agrievefd2d44ab2015-06-19 04:33:03132 return false;
oth05c26fde2015-04-05 14:30:57133}
134
agrievefd2d44ab2015-06-19 04:33:03135base::PlatformFile OpenV8File(const char* file_name,
136 base::MemoryMappedFile::Region* region_out) {
oth575f7fb52015-05-08 17:35:00137 // Re-try logic here is motivated by http://crbug.com/479537
138 // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
139
140 // These match tools/metrics/histograms.xml
141 enum OpenV8FileResult {
142 OPENED = 0,
143 OPENED_RETRY,
144 FAILED_IN_USE,
145 FAILED_OTHER,
146 MAX_VALUE
147 };
agrievefd2d44ab2015-06-19 04:33:03148 base::FilePath path;
149 GetV8FilePath(file_name, &path);
150
agrieve6f3002d2015-06-19 16:49:06151#if defined(OS_ANDROID)
152 base::File file(base::android::OpenApkAsset(path.value(), region_out));
153 OpenV8FileResult result = file.IsValid() ? OpenV8FileResult::OPENED
154 : OpenV8FileResult::FAILED_OTHER;
155#else
156 // Re-try logic here is motivated by http://crbug.com/479537
157 // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
158 const int kMaxOpenAttempts = 5;
159 const int kOpenRetryDelayMillis = 250;
160
oth575f7fb52015-05-08 17:35:00161 OpenV8FileResult result = OpenV8FileResult::FAILED_IN_USE;
agrievefd2d44ab2015-06-19 04:33:03162 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
163 base::File file;
oth575f7fb52015-05-08 17:35:00164 for (int attempt = 0; attempt < kMaxOpenAttempts; attempt++) {
165 file.Initialize(path, flags);
166 if (file.IsValid()) {
agrievefd2d44ab2015-06-19 04:33:03167 *region_out = base::MemoryMappedFile::Region::kWholeFile;
oth575f7fb52015-05-08 17:35:00168 if (attempt == 0) {
169 result = OpenV8FileResult::OPENED;
170 break;
171 } else {
172 result = OpenV8FileResult::OPENED_RETRY;
173 break;
174 }
175 } else if (file.error_details() != base::File::FILE_ERROR_IN_USE) {
176 result = OpenV8FileResult::FAILED_OTHER;
oth29c7ed92015-06-19 14:40:00177#ifdef OS_WIN
178 // TODO(oth): temporary diagnostics for http://crbug.com/479537
179 std::string narrow(kNativesFileName);
180 base::FilePath::StringType nativesBlob(narrow.begin(), narrow.end());
181 if (path.BaseName().value() == nativesBlob) {
182 base::File::Error file_error = file.error_details();
183 base::debug::Alias(&file_error);
184 LOG(FATAL) << "Failed to open V8 file '" << path.value()
185 << "' (reason: " << file.error_details() << ")";
186 }
187#endif // OS_WIN
oth575f7fb52015-05-08 17:35:00188 break;
189 } else if (kMaxOpenAttempts - 1 != attempt) {
190 base::PlatformThread::Sleep(
191 base::TimeDelta::FromMilliseconds(kOpenRetryDelayMillis));
192 }
193 }
agrieve6f3002d2015-06-19 16:49:06194#endif // defined(OS_ANDROID)
oth575f7fb52015-05-08 17:35:00195
196 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.OpenV8File.Result",
197 result,
198 OpenV8FileResult::MAX_VALUE);
agrievefd2d44ab2015-06-19 04:33:03199 return file.TakePlatformFile();
200}
oth575f7fb52015-05-08 17:35:00201
Hitoshi Yoshida129ff2b2017-08-24 02:19:10202OpenedFileMap::mapped_type& GetOpenedFile(const char* filename) {
203 OpenedFileMap& opened_files(g_opened_files.Get());
Jeremy Roman6a3b3d42017-08-24 17:13:51204 auto result = opened_files.emplace(filename, OpenedFileMap::mapped_type());
205 OpenedFileMap::mapped_type& opened_file = result.first->second;
206 bool is_new_file = result.second;
Hitoshi Yoshida129ff2b2017-08-24 02:19:10207
Jeremy Roman6a3b3d42017-08-24 17:13:51208 // If we have no cache, try to open it and cache the result.
209 if (is_new_file)
210 opened_file.first = OpenV8File(filename, &opened_file.second);
211
212 return opened_file;
oth575f7fb52015-05-08 17:35:00213}
214
erikcorryc94eff12015-06-08 11:29:16215enum LoadV8FileResult {
216 V8_LOAD_SUCCESS = 0,
217 V8_LOAD_FAILED_OPEN,
218 V8_LOAD_FAILED_MAP,
jcivellidbe3dec2017-02-07 16:58:23219 V8_LOAD_FAILED_VERIFY, // Deprecated.
erikcorryc94eff12015-06-08 11:29:16220 V8_LOAD_MAX_VALUE
221};
oth575f7fb52015-05-08 17:35:00222
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55223LoadV8FileResult MapOpenedFile(const OpenedFileMap::mapped_type& file_region,
224 base::MemoryMappedFile** mmapped_file_out) {
rockot5d4213ff2016-05-25 19:07:10225 if (file_region.first == base::kInvalidPlatformFile)
erikcorryc94eff12015-06-08 11:29:16226 return V8_LOAD_FAILED_OPEN;
tobiasjsb20016272016-02-10 11:54:12227 if (!MapV8File(file_region.first, file_region.second, mmapped_file_out))
erikcorryc94eff12015-06-08 11:29:16228 return V8_LOAD_FAILED_MAP;
erikcorryc94eff12015-06-08 11:29:16229 return V8_LOAD_SUCCESS;
oth05c26fde2015-04-05 14:30:57230}
231
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46232#endif // defined(V8_USE_EXTERNAL_STATUP_DATA)
Hitoshi Yoshida129ff2b2017-08-24 02:19:10233
jcivellidbe3dec2017-02-07 16:58:23234} // namespace
235
oth05c26fde2015-04-05 14:30:57236// static
yhirano93150242015-12-07 12:28:33237void V8Initializer::Initialize(IsolateHolder::ScriptMode mode,
238 IsolateHolder::V8ExtrasMode v8_extras_mode) {
oth05c26fde2015-04-05 14:30:57239 static bool v8_is_initialized = false;
240 if (v8_is_initialized)
241 return;
242
243 v8::V8::InitializePlatform(V8Platform::Get());
oth05c26fde2015-04-05 14:30:57244
yhirano93150242015-12-07 12:28:33245 if (IsolateHolder::kStrictMode == mode) {
oth05c26fde2015-04-05 14:30:57246 static const char use_strict[] = "--use_strict";
247 v8::V8::SetFlagsFromString(use_strict, sizeof(use_strict) - 1);
248 }
yhirano93150242015-12-07 12:28:33249 if (IsolateHolder::kStableAndExperimentalV8Extras == v8_extras_mode) {
250 static const char flag[] = "--experimental_extras";
251 v8::V8::SetFlagsFromString(flag, sizeof(flag) - 1);
252 }
oth05c26fde2015-04-05 14:30:57253
254#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
255 v8::StartupData natives;
Hitoshi Yoshida9aff02e2018-01-19 16:55:03256 GetMappedFileData(g_mapped_natives, &natives);
oth05c26fde2015-04-05 14:30:57257 v8::V8::SetNativesDataBlob(&natives);
258
Hitoshi Yoshida231de8352017-12-08 01:06:33259 if (g_mapped_snapshot) {
Robert Liao1e7eb052017-12-15 00:30:05260 v8::StartupData snapshot;
Hitoshi Yoshida9aff02e2018-01-19 16:55:03261 GetMappedFileData(g_mapped_snapshot, &snapshot);
Hitoshi Yoshida231de8352017-12-08 01:06:33262 v8::V8::SetSnapshotDataBlob(&snapshot);
263 }
oth05c26fde2015-04-05 14:30:57264#endif // V8_USE_EXTERNAL_STARTUP_DATA
265
266 v8::V8::SetEntropySource(&GenerateEntropy);
267 v8::V8::Initialize();
268
269 v8_is_initialized = true;
270}
271
272// static
Hitoshi Yoshidad88a223e2017-09-10 05:55:25273void V8Initializer::GetV8ExternalSnapshotData(v8::StartupData* natives,
274 v8::StartupData* snapshot) {
275 GetMappedFileData(g_mapped_natives, natives);
276 GetMappedFileData(g_mapped_snapshot, snapshot);
277}
278
279// static
oth05c26fde2015-04-05 14:30:57280void V8Initializer::GetV8ExternalSnapshotData(const char** natives_data_out,
281 int* natives_size_out,
282 const char** snapshot_data_out,
283 int* snapshot_size_out) {
Hitoshi Yoshidad88a223e2017-09-10 05:55:25284 v8::StartupData natives;
285 v8::StartupData snapshot;
286 GetV8ExternalSnapshotData(&natives, &snapshot);
287 *natives_data_out = natives.data;
288 *natives_size_out = natives.raw_size;
289 *snapshot_data_out = snapshot.data;
290 *snapshot_size_out = snapshot.raw_size;
oth05c26fde2015-04-05 14:30:57291}
292
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46293#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
294
295// static
Hitoshi Yoshida9aff02e2018-01-19 16:55:03296void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) {
297 if (g_mapped_snapshot) {
298 // TODO(crbug.com/802962): Confirm not loading different type of snapshot
299 // files in a process.
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46300 return;
Hitoshi Yoshida9aff02e2018-01-19 16:55:03301 }
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46302
Hitoshi Yoshida9aff02e2018-01-19 16:55:03303 LoadV8FileResult result =
304 MapOpenedFile(GetOpenedFile(GetSnapshotFileName(snapshot_file_type)),
305 &g_mapped_snapshot);
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46306 // V8 can't start up without the source of the natives, but it can
307 // start up (slower) without the snapshot.
308 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.LoadV8Snapshot.Result", result,
309 V8_LOAD_MAX_VALUE);
310}
311
Hitoshi Yoshida9aff02e2018-01-19 16:55:03312// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46313void V8Initializer::LoadV8Natives() {
314 if (g_mapped_natives)
315 return;
316
317 LoadV8FileResult result = MapOpenedFile(GetOpenedFile(kNativesFileName),
318 &g_mapped_natives);
319 if (result != V8_LOAD_SUCCESS) {
320 LOG(FATAL) << "Couldn't mmap v8 natives data file, status code is "
321 << static_cast<int>(result);
322 }
323}
324
325// static
Hitoshi Yoshida9aff02e2018-01-19 16:55:03326void V8Initializer::LoadV8SnapshotFromFD(
327 base::PlatformFile snapshot_pf,
328 int64_t snapshot_offset,
329 int64_t snapshot_size,
330 V8SnapshotFileType snapshot_file_type) {
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46331 if (g_mapped_snapshot)
332 return;
333
334 if (snapshot_pf == base::kInvalidPlatformFile)
335 return;
336
337 base::MemoryMappedFile::Region snapshot_region =
338 base::MemoryMappedFile::Region::kWholeFile;
339 if (snapshot_size != 0 || snapshot_offset != 0) {
340 snapshot_region.offset = snapshot_offset;
341 snapshot_region.size = snapshot_size;
342 }
343
344 LoadV8FileResult result = V8_LOAD_SUCCESS;
345 if (!MapV8File(snapshot_pf, snapshot_region, &g_mapped_snapshot))
346 result = V8_LOAD_FAILED_MAP;
347 if (result == V8_LOAD_SUCCESS) {
Hitoshi Yoshida9aff02e2018-01-19 16:55:03348 g_opened_files.Get()[GetSnapshotFileName(snapshot_file_type)] =
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46349 std::make_pair(snapshot_pf, snapshot_region);
350 }
351 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.LoadV8Snapshot.Result", result,
352 V8_LOAD_MAX_VALUE);
353}
354
355// static
356void V8Initializer::LoadV8NativesFromFD(base::PlatformFile natives_pf,
357 int64_t natives_offset,
358 int64_t natives_size) {
359 if (g_mapped_natives)
360 return;
361
362 CHECK_NE(natives_pf, base::kInvalidPlatformFile);
363
364 base::MemoryMappedFile::Region natives_region =
365 base::MemoryMappedFile::Region::kWholeFile;
366 if (natives_size != 0 || natives_offset != 0) {
367 natives_region.offset = natives_offset;
368 natives_region.size = natives_size;
369 }
370
371 if (!MapV8File(natives_pf, natives_region, &g_mapped_natives)) {
372 LOG(FATAL) << "Couldn't mmap v8 natives data file";
373 }
374 g_opened_files.Get()[kNativesFileName] =
375 std::make_pair(natives_pf, natives_region);
376}
377
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46378#if defined(OS_ANDROID)
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55379// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46380base::FilePath V8Initializer::GetNativesFilePath() {
381 base::FilePath path;
382 GetV8FilePath(kNativesFileName, &path);
383 return path;
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55384}
385
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46386// static
Hitoshi Yoshida06697232018-03-05 04:09:15387base::FilePath V8Initializer::GetSnapshotFilePath(
388 bool abi_32_bit,
389 V8SnapshotFileType snapshot_file_type) {
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46390 base::FilePath path;
Hitoshi Yoshida06697232018-03-05 04:09:15391 const char* filename = nullptr;
392 switch (snapshot_file_type) {
393 case V8Initializer::V8SnapshotFileType::kDefault:
394 filename = abi_32_bit ? kSnapshotFileName32 : kSnapshotFileName64;
395 break;
396 case V8Initializer::V8SnapshotFileType::kWithAdditionalContext:
397 filename = abi_32_bit ? kV8ContextSnapshotFileName32
398 : kV8ContextSnapshotFileName64;
399 break;
400 }
401 CHECK(filename);
402
403 GetV8FilePath(filename, &path);
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46404 return path;
405}
406#endif // defined(OS_ANDROID)
407#endif // defined(V8_USE_EXTERNAL_STARTUP_DATA)
408
oth05c26fde2015-04-05 14:30:57409} // namespace gin