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