1// Copyright 2015 the V8 project 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 "src/startup-data-util.h"
6
7#include <stdlib.h>
8#include <string.h>
9
10#include "src/base/file-utils.h"
11#include "src/base/logging.h"
12#include "src/base/platform/platform.h"
13#include "src/flags.h"
14#include "src/utils.h"
15
16
17namespace v8 {
18namespace internal {
19
20#ifdef V8_USE_EXTERNAL_STARTUP_DATA
21
22namespace {
23
24v8::StartupData g_natives;
25v8::StartupData g_snapshot;
26
27
28void ClearStartupData(v8::StartupData* data) {
29 data->data = nullptr;
30 data->raw_size = 0;
31}
32
33
34void DeleteStartupData(v8::StartupData* data) {
35 delete[] data->data;
36 ClearStartupData(data);
37}
38
39
40void FreeStartupData() {
41 DeleteStartupData(&g_natives);
42 DeleteStartupData(&g_snapshot);
43}
44
45
46void Load(const char* blob_file, v8::StartupData* startup_data,
47 void (*setter_fn)(v8::StartupData*)) {
48 ClearStartupData(startup_data);
49
50 CHECK(blob_file);
51
52 FILE* file = fopen(blob_file, "rb");
53 if (!file) {
54 PrintF(stderr, "Failed to open startup resource '%s'.\n", blob_file);
55 return;
56 }
57
58 fseek(file, 0, SEEK_END);
59 startup_data->raw_size = static_cast<int>(ftell(file));
60 rewind(file);
61
62 startup_data->data = new char[startup_data->raw_size];
63 int read_size = static_cast<int>(fread(const_cast<char*>(startup_data->data),
64 1, startup_data->raw_size, file));
65 fclose(file);
66
67 if (startup_data->raw_size == read_size) {
68 (*setter_fn)(startup_data);
69 } else {
70 PrintF(stderr, "Corrupted startup resource '%s'.\n", blob_file);
71 }
72}
73
74
75void LoadFromFiles(const char* natives_blob, const char* snapshot_blob) {
76 Load(natives_blob, &g_natives, v8::V8::SetNativesDataBlob);
77 Load(snapshot_blob, &g_snapshot, v8::V8::SetSnapshotDataBlob);
78
79 atexit(&FreeStartupData);
80}
81
82} // namespace
83#endif // V8_USE_EXTERNAL_STARTUP_DATA
84
85
86void InitializeExternalStartupData(const char* directory_path) {
87#ifdef V8_USE_EXTERNAL_STARTUP_DATA
88 char* natives;
89 char* snapshot;
90 const char* snapshot_name = "snapshot_blob.bin";
91#ifdef V8_MULTI_SNAPSHOTS
92 if (!FLAG_untrusted_code_mitigations) {
93 snapshot_name = "snapshot_blob_trusted.bin";
94 }
95#endif
96 LoadFromFiles(
97 base::RelativePath(&natives, directory_path, "natives_blob.bin"),
98 base::RelativePath(&snapshot, directory_path, snapshot_name));
99 free(natives);
100 free(snapshot);
101#endif // V8_USE_EXTERNAL_STARTUP_DATA
102}
103
104
105void InitializeExternalStartupData(const char* natives_blob,
106 const char* snapshot_blob) {
107#ifdef V8_USE_EXTERNAL_STARTUP_DATA
108 LoadFromFiles(natives_blob, snapshot_blob);
109#endif // V8_USE_EXTERNAL_STARTUP_DATA
110}
111
112} // namespace internal
113} // namespace v8
114