blob: 03353beb9ddb6e7357c6c6159bd4296391d74dd5 [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;
Hitoshi Yoshidaf2f50de2017-08-22 13:23:5544base::MemoryMappedFile* g_mapped_v8_context_snapshot = nullptr;
oth05c26fde2015-04-05 14:30:5745
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";
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:4674const char kV8ContextSnapshotFileName[] = "v8_context_snapshot.bin";
michaelbai020375882016-06-21 16:08:1575
michaelbai016306732015-11-03 19:48:0076#if defined(OS_ANDROID)
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__)
tobiasjsb20016272016-02-10 11:54:1281#define kSnapshotFileName kSnapshotFileName64
michaelbai016306732015-11-03 19:48:0082#else
tobiasjsb20016272016-02-10 11:54:1283#define kSnapshotFileName kSnapshotFileName32
84#endif
michaelbai016306732015-11-03 19:48:0085
86#else // defined(OS_ANDROID)
rmcilroy54fab5e2015-04-06 21:14:5887const char kSnapshotFileName[] = "snapshot_blob.bin";
michaelbai016306732015-11-03 19:48:0088#endif // defined(OS_ANDROID)
rmcilroy54fab5e2015-04-06 21:14:5889
erikcorryc94eff12015-06-08 11:29:1690void GetV8FilePath(const char* file_name, base::FilePath* path_out) {
rmcilroy54fab5e2015-04-06 21:14:5891#if !defined(OS_MACOSX)
92 base::FilePath data_path;
agrieve6f3002d2015-06-19 16:49:0693#if defined(OS_ANDROID)
94 // This is the path within the .apk.
95 data_path = base::FilePath(FILE_PATH_LITERAL("assets"));
96#elif defined(OS_POSIX)
97 PathService::Get(base::DIR_EXE, &data_path);
98#elif defined(OS_WIN)
99 PathService::Get(base::DIR_MODULE, &data_path);
100#endif
rmcilroy54fab5e2015-04-06 21:14:58101 DCHECK(!data_path.empty());
102
erikcorryc94eff12015-06-08 11:29:16103 *path_out = data_path.AppendASCII(file_name);
rmcilroy54fab5e2015-04-06 21:14:58104#else // !defined(OS_MACOSX)
105 base::ScopedCFTypeRef<CFStringRef> natives_file_name(
erikcorryc94eff12015-06-08 11:29:16106 base::SysUTF8ToCFStringRef(file_name));
107 *path_out = base::mac::PathForFrameworkBundleResource(natives_file_name);
rmcilroy54fab5e2015-04-06 21:14:58108#endif // !defined(OS_MACOSX)
109}
110
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55111bool MapV8File(base::PlatformFile platform_file,
112 base::MemoryMappedFile::Region region,
113 base::MemoryMappedFile** mmapped_file_out) {
erikcorryc94eff12015-06-08 11:29:16114 DCHECK(*mmapped_file_out == NULL);
mostynbc862da82016-04-03 15:54:33115 std::unique_ptr<base::MemoryMappedFile> mmapped_file(
116 new base::MemoryMappedFile());
agrievefd2d44ab2015-06-19 04:33:03117 if (mmapped_file->Initialize(base::File(platform_file), region)) {
118 *mmapped_file_out = mmapped_file.release();
119 return true;
oth05c26fde2015-04-05 14:30:57120 }
agrievefd2d44ab2015-06-19 04:33:03121 return false;
oth05c26fde2015-04-05 14:30:57122}
123
agrievefd2d44ab2015-06-19 04:33:03124base::PlatformFile OpenV8File(const char* file_name,
125 base::MemoryMappedFile::Region* region_out) {
oth575f7fb52015-05-08 17:35:00126 // Re-try logic here is motivated by http://crbug.com/479537
127 // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
128
129 // These match tools/metrics/histograms.xml
130 enum OpenV8FileResult {
131 OPENED = 0,
132 OPENED_RETRY,
133 FAILED_IN_USE,
134 FAILED_OTHER,
135 MAX_VALUE
136 };
agrievefd2d44ab2015-06-19 04:33:03137 base::FilePath path;
138 GetV8FilePath(file_name, &path);
139
agrieve6f3002d2015-06-19 16:49:06140#if defined(OS_ANDROID)
141 base::File file(base::android::OpenApkAsset(path.value(), region_out));
142 OpenV8FileResult result = file.IsValid() ? OpenV8FileResult::OPENED
143 : OpenV8FileResult::FAILED_OTHER;
144#else
145 // Re-try logic here is motivated by http://crbug.com/479537
146 // for A/V on Windows (https://support.microsoft.com/en-us/kb/316609).
147 const int kMaxOpenAttempts = 5;
148 const int kOpenRetryDelayMillis = 250;
149
oth575f7fb52015-05-08 17:35:00150 OpenV8FileResult result = OpenV8FileResult::FAILED_IN_USE;
agrievefd2d44ab2015-06-19 04:33:03151 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
152 base::File file;
oth575f7fb52015-05-08 17:35:00153 for (int attempt = 0; attempt < kMaxOpenAttempts; attempt++) {
154 file.Initialize(path, flags);
155 if (file.IsValid()) {
agrievefd2d44ab2015-06-19 04:33:03156 *region_out = base::MemoryMappedFile::Region::kWholeFile;
oth575f7fb52015-05-08 17:35:00157 if (attempt == 0) {
158 result = OpenV8FileResult::OPENED;
159 break;
160 } else {
161 result = OpenV8FileResult::OPENED_RETRY;
162 break;
163 }
164 } else if (file.error_details() != base::File::FILE_ERROR_IN_USE) {
165 result = OpenV8FileResult::FAILED_OTHER;
oth29c7ed92015-06-19 14:40:00166#ifdef OS_WIN
167 // TODO(oth): temporary diagnostics for http://crbug.com/479537
168 std::string narrow(kNativesFileName);
169 base::FilePath::StringType nativesBlob(narrow.begin(), narrow.end());
170 if (path.BaseName().value() == nativesBlob) {
171 base::File::Error file_error = file.error_details();
172 base::debug::Alias(&file_error);
173 LOG(FATAL) << "Failed to open V8 file '" << path.value()
174 << "' (reason: " << file.error_details() << ")";
175 }
176#endif // OS_WIN
oth575f7fb52015-05-08 17:35:00177 break;
178 } else if (kMaxOpenAttempts - 1 != attempt) {
179 base::PlatformThread::Sleep(
180 base::TimeDelta::FromMilliseconds(kOpenRetryDelayMillis));
181 }
182 }
agrieve6f3002d2015-06-19 16:49:06183#endif // defined(OS_ANDROID)
oth575f7fb52015-05-08 17:35:00184
185 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.OpenV8File.Result",
186 result,
187 OpenV8FileResult::MAX_VALUE);
agrievefd2d44ab2015-06-19 04:33:03188 return file.TakePlatformFile();
189}
oth575f7fb52015-05-08 17:35:00190
Hitoshi Yoshida129ff2b2017-08-24 02:19:10191OpenedFileMap::mapped_type& GetOpenedFile(const char* filename) {
192 OpenedFileMap& opened_files(g_opened_files.Get());
Jeremy Roman6a3b3d42017-08-24 17:13:51193 auto result = opened_files.emplace(filename, OpenedFileMap::mapped_type());
194 OpenedFileMap::mapped_type& opened_file = result.first->second;
195 bool is_new_file = result.second;
Hitoshi Yoshida129ff2b2017-08-24 02:19:10196
Jeremy Roman6a3b3d42017-08-24 17:13:51197 // If we have no cache, try to open it and cache the result.
198 if (is_new_file)
199 opened_file.first = OpenV8File(filename, &opened_file.second);
200
201 return opened_file;
oth575f7fb52015-05-08 17:35:00202}
203
erikcorryc94eff12015-06-08 11:29:16204enum LoadV8FileResult {
205 V8_LOAD_SUCCESS = 0,
206 V8_LOAD_FAILED_OPEN,
207 V8_LOAD_FAILED_MAP,
jcivellidbe3dec2017-02-07 16:58:23208 V8_LOAD_FAILED_VERIFY, // Deprecated.
erikcorryc94eff12015-06-08 11:29:16209 V8_LOAD_MAX_VALUE
210};
oth575f7fb52015-05-08 17:35:00211
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55212LoadV8FileResult MapOpenedFile(const OpenedFileMap::mapped_type& file_region,
213 base::MemoryMappedFile** mmapped_file_out) {
rockot5d4213ff2016-05-25 19:07:10214 if (file_region.first == base::kInvalidPlatformFile)
erikcorryc94eff12015-06-08 11:29:16215 return V8_LOAD_FAILED_OPEN;
tobiasjsb20016272016-02-10 11:54:12216 if (!MapV8File(file_region.first, file_region.second, mmapped_file_out))
erikcorryc94eff12015-06-08 11:29:16217 return V8_LOAD_FAILED_MAP;
erikcorryc94eff12015-06-08 11:29:16218 return V8_LOAD_SUCCESS;
oth05c26fde2015-04-05 14:30:57219}
220
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46221#endif // defined(V8_USE_EXTERNAL_STATUP_DATA)
Hitoshi Yoshida129ff2b2017-08-24 02:19:10222
jcivellidbe3dec2017-02-07 16:58:23223} // namespace
224
oth05c26fde2015-04-05 14:30:57225// static
yhirano93150242015-12-07 12:28:33226void V8Initializer::Initialize(IsolateHolder::ScriptMode mode,
227 IsolateHolder::V8ExtrasMode v8_extras_mode) {
oth05c26fde2015-04-05 14:30:57228 static bool v8_is_initialized = false;
229 if (v8_is_initialized)
230 return;
231
232 v8::V8::InitializePlatform(V8Platform::Get());
oth05c26fde2015-04-05 14:30:57233
yhirano93150242015-12-07 12:28:33234 if (IsolateHolder::kStrictMode == mode) {
oth05c26fde2015-04-05 14:30:57235 static const char use_strict[] = "--use_strict";
236 v8::V8::SetFlagsFromString(use_strict, sizeof(use_strict) - 1);
237 }
yhirano93150242015-12-07 12:28:33238 if (IsolateHolder::kStableAndExperimentalV8Extras == v8_extras_mode) {
239 static const char flag[] = "--experimental_extras";
240 v8::V8::SetFlagsFromString(flag, sizeof(flag) - 1);
241 }
oth05c26fde2015-04-05 14:30:57242
243#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
244 v8::StartupData natives;
Robert Liao1e7eb052017-12-15 00:30:05245 natives.data = reinterpret_cast<const char*>(g_mapped_natives->data());
246 natives.raw_size = static_cast<int>(g_mapped_natives->length());
oth05c26fde2015-04-05 14:30:57247 v8::V8::SetNativesDataBlob(&natives);
248
Hitoshi Yoshida231de8352017-12-08 01:06:33249 if (g_mapped_snapshot) {
Robert Liao1e7eb052017-12-15 00:30:05250 v8::StartupData snapshot;
251 snapshot.data = reinterpret_cast<const char*>(g_mapped_snapshot->data());
252 snapshot.raw_size = static_cast<int>(g_mapped_snapshot->length());
Hitoshi Yoshida231de8352017-12-08 01:06:33253 v8::V8::SetSnapshotDataBlob(&snapshot);
254 }
oth05c26fde2015-04-05 14:30:57255#endif // V8_USE_EXTERNAL_STARTUP_DATA
256
257 v8::V8::SetEntropySource(&GenerateEntropy);
258 v8::V8::Initialize();
259
260 v8_is_initialized = true;
261}
262
263// static
Hitoshi Yoshidad88a223e2017-09-10 05:55:25264void V8Initializer::GetV8ExternalSnapshotData(v8::StartupData* natives,
265 v8::StartupData* snapshot) {
266 GetMappedFileData(g_mapped_natives, natives);
267 GetMappedFileData(g_mapped_snapshot, snapshot);
268}
269
270// static
oth05c26fde2015-04-05 14:30:57271void V8Initializer::GetV8ExternalSnapshotData(const char** natives_data_out,
272 int* natives_size_out,
273 const char** snapshot_data_out,
274 int* snapshot_size_out) {
Hitoshi Yoshidad88a223e2017-09-10 05:55:25275 v8::StartupData natives;
276 v8::StartupData snapshot;
277 GetV8ExternalSnapshotData(&natives, &snapshot);
278 *natives_data_out = natives.data;
279 *natives_size_out = natives.raw_size;
280 *snapshot_data_out = snapshot.data;
281 *snapshot_size_out = snapshot.raw_size;
oth05c26fde2015-04-05 14:30:57282}
283
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55284// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46285void V8Initializer::GetV8ContextSnapshotData(v8::StartupData* snapshot) {
286 GetMappedFileData(g_mapped_v8_context_snapshot, snapshot);
287}
288
289#if defined(V8_USE_EXTERNAL_STARTUP_DATA)
290
291// static
292void V8Initializer::LoadV8Snapshot() {
293 if (g_mapped_snapshot)
294 return;
295
296 LoadV8FileResult result = MapOpenedFile(GetOpenedFile(kSnapshotFileName),
297 &g_mapped_snapshot);
298 // V8 can't start up without the source of the natives, but it can
299 // start up (slower) without the snapshot.
300 UMA_HISTOGRAM_ENUMERATION("V8.Initializer.LoadV8Snapshot.Result", result,
301 V8_LOAD_MAX_VALUE);
302}
303
304void V8Initializer::LoadV8Natives() {
305 if (g_mapped_natives)
306 return;
307
308 LoadV8FileResult result = MapOpenedFile(GetOpenedFile(kNativesFileName),
309 &g_mapped_natives);
310 if (result != V8_LOAD_SUCCESS) {
311 LOG(FATAL) << "Couldn't mmap v8 natives data file, status code is "
312 << static_cast<int>(result);
313 }
314}
315
316// static
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55317void V8Initializer::LoadV8ContextSnapshot() {
318 if (g_mapped_v8_context_snapshot)
319 return;
320
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55321 MapOpenedFile(GetOpenedFile(kV8ContextSnapshotFileName),
322 &g_mapped_v8_context_snapshot);
323
324 // TODO(peria): Check if the snapshot file is loaded successfully.
325}
326
327// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46328void V8Initializer::LoadV8SnapshotFromFD(base::PlatformFile snapshot_pf,
329 int64_t snapshot_offset,
330 int64_t snapshot_size) {
331 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) {
348 g_opened_files.Get()[kSnapshotFileName] =
349 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
378// static
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55379void V8Initializer::LoadV8ContextSnapshotFromFD(base::PlatformFile snapshot_pf,
380 int64_t snapshot_offset,
381 int64_t snapshot_size) {
382 if (g_mapped_v8_context_snapshot)
383 return;
384 CHECK_NE(base::kInvalidPlatformFile, snapshot_pf);
385
386 base::MemoryMappedFile::Region snapshot_region =
387 base::MemoryMappedFile::Region::kWholeFile;
388 if (snapshot_size != 0 || snapshot_offset != 0) {
389 snapshot_region.offset = snapshot_offset;
390 snapshot_region.size = snapshot_size;
391 }
392
393 if (MapV8File(snapshot_pf, snapshot_region, &g_mapped_v8_context_snapshot)) {
394 g_opened_files.Get()[kV8ContextSnapshotFileName] =
395 std::make_pair(snapshot_pf, snapshot_region);
396 }
397}
398
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46399#if defined(OS_ANDROID)
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55400// static
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46401base::FilePath V8Initializer::GetNativesFilePath() {
402 base::FilePath path;
403 GetV8FilePath(kNativesFileName, &path);
404 return path;
Hitoshi Yoshidaf2f50de2017-08-22 13:23:55405}
406
Hitoshi Yoshidaba9c2f0f2017-11-27 03:11:46407// static
408base::FilePath V8Initializer::GetSnapshotFilePath(bool abi_32_bit) {
409 base::FilePath path;
410 GetV8FilePath(abi_32_bit ? kSnapshotFileName32 : kSnapshotFileName64, &path);
411 return path;
412}
413#endif // defined(OS_ANDROID)
414#endif // defined(V8_USE_EXTERNAL_STARTUP_DATA)
415
oth05c26fde2015-04-05 14:30:57416} // namespace gin