• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2006-2008 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 <errno.h>
6 #include <signal.h>
7 #include <stdio.h>
8 
9 #include <iomanip>
10 
11 #include "include/libplatform/libplatform.h"
12 #include "include/v8-initialization.h"
13 #include "src/base/platform/platform.h"
14 #include "src/base/platform/wrappers.h"
15 #include "src/base/sanitizer/msan.h"
16 #include "src/base/vector.h"
17 #include "src/codegen/assembler-arch.h"
18 #include "src/codegen/source-position-table.h"
19 #include "src/flags/flags.h"
20 #include "src/snapshot/context-serializer.h"
21 #include "src/snapshot/embedded/embedded-file-writer.h"
22 #include "src/snapshot/snapshot.h"
23 #include "src/snapshot/startup-serializer.h"
24 
25 namespace {
26 
27 class SnapshotFileWriter {
28  public:
SetSnapshotFile(const char * snapshot_cpp_file)29   void SetSnapshotFile(const char* snapshot_cpp_file) {
30     snapshot_cpp_path_ = snapshot_cpp_file;
31   }
32 
SetStartupBlobFile(const char * snapshot_blob_file)33   void SetStartupBlobFile(const char* snapshot_blob_file) {
34     snapshot_blob_path_ = snapshot_blob_file;
35   }
36 
WriteSnapshot(v8::StartupData blob) const37   void WriteSnapshot(v8::StartupData blob) const {
38     // TODO(crbug/633159): if we crash before the files have been fully created,
39     // we end up with a corrupted snapshot file. The build step would succeed,
40     // but the build target is unusable. Ideally we would write out temporary
41     // files and only move them to the final destination as last step.
42     v8::base::Vector<const i::byte> blob_vector(
43         reinterpret_cast<const i::byte*>(blob.data), blob.raw_size);
44     MaybeWriteSnapshotFile(blob_vector);
45     MaybeWriteStartupBlob(blob_vector);
46   }
47 
48  private:
MaybeWriteStartupBlob(const v8::base::Vector<const i::byte> & blob) const49   void MaybeWriteStartupBlob(
50       const v8::base::Vector<const i::byte>& blob) const {
51     if (!snapshot_blob_path_) return;
52 
53     FILE* fp = GetFileDescriptorOrDie(snapshot_blob_path_);
54     size_t written = fwrite(blob.begin(), 1, blob.length(), fp);
55     v8::base::Fclose(fp);
56     if (written != static_cast<size_t>(blob.length())) {
57       i::PrintF("Writing snapshot file failed.. Aborting.\n");
58       remove(snapshot_blob_path_);
59       exit(1);
60     }
61   }
62 
MaybeWriteSnapshotFile(const v8::base::Vector<const i::byte> & blob) const63   void MaybeWriteSnapshotFile(
64       const v8::base::Vector<const i::byte>& blob) const {
65     if (!snapshot_cpp_path_) return;
66 
67     FILE* fp = GetFileDescriptorOrDie(snapshot_cpp_path_);
68 
69     WriteSnapshotFilePrefix(fp);
70     WriteSnapshotFileData(fp, blob);
71     WriteSnapshotFileSuffix(fp);
72 
73     v8::base::Fclose(fp);
74   }
75 
WriteSnapshotFilePrefix(FILE * fp)76   static void WriteSnapshotFilePrefix(FILE* fp) {
77     fprintf(fp, "// Autogenerated snapshot file. Do not edit.\n\n");
78     fprintf(fp, "#include \"src/init/v8.h\"\n");
79     fprintf(fp, "#include \"src/base/platform/platform.h\"\n\n");
80     fprintf(fp, "#include \"src/snapshot/snapshot.h\"\n\n");
81     fprintf(fp, "namespace v8 {\n");
82     fprintf(fp, "namespace internal {\n\n");
83   }
84 
WriteSnapshotFileSuffix(FILE * fp)85   static void WriteSnapshotFileSuffix(FILE* fp) {
86     fprintf(fp, "const v8::StartupData* Snapshot::DefaultSnapshotBlob() {\n");
87     fprintf(fp, "  return &blob;\n");
88     fprintf(fp, "}\n\n");
89     fprintf(fp, "}  // namespace internal\n");
90     fprintf(fp, "}  // namespace v8\n");
91   }
92 
WriteSnapshotFileData(FILE * fp,const v8::base::Vector<const i::byte> & blob)93   static void WriteSnapshotFileData(
94       FILE* fp, const v8::base::Vector<const i::byte>& blob) {
95     fprintf(fp,
96             "alignas(kPointerAlignment) static const byte blob_data[] = {\n");
97     WriteBinaryContentsAsCArray(fp, blob);
98     fprintf(fp, "};\n");
99     fprintf(fp, "static const int blob_size = %d;\n", blob.length());
100     fprintf(fp, "static const v8::StartupData blob =\n");
101     fprintf(fp, "{ (const char*) blob_data, blob_size };\n");
102   }
103 
WriteBinaryContentsAsCArray(FILE * fp,const v8::base::Vector<const i::byte> & blob)104   static void WriteBinaryContentsAsCArray(
105       FILE* fp, const v8::base::Vector<const i::byte>& blob) {
106     for (int i = 0; i < blob.length(); i++) {
107       if ((i & 0x1F) == 0x1F) fprintf(fp, "\n");
108       if (i > 0) fprintf(fp, ",");
109       fprintf(fp, "%u", static_cast<unsigned char>(blob.at(i)));
110     }
111     fprintf(fp, "\n");
112   }
113 
GetFileDescriptorOrDie(const char * filename)114   static FILE* GetFileDescriptorOrDie(const char* filename) {
115     FILE* fp = v8::base::OS::FOpen(filename, "wb");
116     if (fp == nullptr) {
117       i::PrintF("Unable to open file \"%s\" for writing.\n", filename);
118       exit(1);
119     }
120     return fp;
121   }
122 
123   const char* snapshot_cpp_path_ = nullptr;
124   const char* snapshot_blob_path_ = nullptr;
125 };
126 
GetExtraCode(char * filename,const char * description)127 char* GetExtraCode(char* filename, const char* description) {
128   if (filename == nullptr || strlen(filename) == 0) return nullptr;
129   ::printf("Loading script for %s: %s\n", description, filename);
130   FILE* file = v8::base::OS::FOpen(filename, "rb");
131   if (file == nullptr) {
132     fprintf(stderr, "Failed to open '%s': errno %d\n", filename, errno);
133     exit(1);
134   }
135   fseek(file, 0, SEEK_END);
136   size_t size = ftell(file);
137   rewind(file);
138   char* chars = new char[size + 1];
139   chars[size] = '\0';
140   for (size_t i = 0; i < size;) {
141     size_t read = fread(&chars[i], 1, size - i, file);
142     if (ferror(file)) {
143       fprintf(stderr, "Failed to read '%s': errno %d\n", filename, errno);
144       exit(1);
145     }
146     i += read;
147   }
148   v8::base::Fclose(file);
149   return chars;
150 }
151 
CreateSnapshotDataBlob(v8::Isolate * isolate,const char * embedded_source)152 v8::StartupData CreateSnapshotDataBlob(v8::Isolate* isolate,
153                                        const char* embedded_source) {
154   v8::base::ElapsedTimer timer;
155   timer.Start();
156 
157   v8::StartupData result = i::CreateSnapshotDataBlobInternal(
158       v8::SnapshotCreator::FunctionCodeHandling::kClear, embedded_source,
159       isolate);
160 
161   if (i::FLAG_profile_deserialization) {
162     i::PrintF("[Creating snapshot took %0.3f ms]\n",
163               timer.Elapsed().InMillisecondsF());
164   }
165 
166   timer.Stop();
167   return result;
168 }
169 
WarmUpSnapshotDataBlob(v8::StartupData cold_snapshot_blob,const char * warmup_source)170 v8::StartupData WarmUpSnapshotDataBlob(v8::StartupData cold_snapshot_blob,
171                                        const char* warmup_source) {
172   v8::base::ElapsedTimer timer;
173   timer.Start();
174 
175   v8::StartupData result =
176       i::WarmUpSnapshotDataBlobInternal(cold_snapshot_blob, warmup_source);
177 
178   if (i::FLAG_profile_deserialization) {
179     i::PrintF("Warming up snapshot took %0.3f ms\n",
180               timer.Elapsed().InMillisecondsF());
181   }
182 
183   timer.Stop();
184   return result;
185 }
186 
WriteEmbeddedFile(i::EmbeddedFileWriter * writer)187 void WriteEmbeddedFile(i::EmbeddedFileWriter* writer) {
188   i::EmbeddedData embedded_blob = i::EmbeddedData::FromBlob();
189   writer->WriteEmbedded(&embedded_blob);
190 }
191 
192 using CounterMap = std::map<std::string, int>;
193 CounterMap* counter_map_ = nullptr;
194 
MaybeSetCounterFunction(v8::Isolate * isolate)195 void MaybeSetCounterFunction(v8::Isolate* isolate) {
196   // If --native-code-counters is on then we enable all counters to make
197   // sure we generate code to increment them from the snapshot.
198   //
199   // Note: For the sake of the mksnapshot, the counter function must only
200   // return distinct addresses for each counter s.t. the serializer can properly
201   // distinguish between them. In theory it should be okay to just return an
202   // incremented int value each time this function is called, but we play it
203   // safe and return a real distinct memory location tied to every counter name.
204   if (i::FLAG_native_code_counters) {
205     counter_map_ = new CounterMap();
206     isolate->SetCounterFunction([](const char* name) -> int* {
207       auto map_entry = counter_map_->find(name);
208       if (map_entry == counter_map_->end()) {
209         counter_map_->emplace(name, 0);
210       }
211       return &counter_map_->at(name);
212     });
213   }
214 }
215 
216 }  // namespace
217 
main(int argc,char ** argv)218 int main(int argc, char** argv) {
219   v8::base::EnsureConsoleOutput();
220 
221   // Make mksnapshot runs predictable to create reproducible snapshots.
222   i::FLAG_predictable = true;
223 
224   // Print the usage if an error occurs when parsing the command line
225   // flags or if the help flag is set.
226   using HelpOptions = i::FlagList::HelpOptions;
227   std::string usage = "Usage: " + std::string(argv[0]) +
228                       " [--startup-src=file]" + " [--startup-blob=file]" +
229                       " [--embedded-src=file]" + " [--embedded-variant=label]" +
230                       " [--target-arch=arch]" +
231                       " [--target-os=os] [extras]\n\n";
232   int result = i::FlagList::SetFlagsFromCommandLine(
233       &argc, argv, true, HelpOptions(HelpOptions::kExit, usage.c_str()));
234   if (result > 0 || (argc > 3)) {
235     i::PrintF(stdout, "%s", usage.c_str());
236     return result;
237   }
238 
239   i::CpuFeatures::Probe(true);
240   v8::V8::InitializeICUDefaultLocation(argv[0]);
241   std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
242   v8::V8::InitializePlatform(platform.get());
243 #ifdef V8_SANDBOX
244   if (!v8::V8::InitializeSandbox()) {
245     FATAL("Could not initialize the sandbox");
246   }
247 #endif
248   v8::V8::Initialize();
249 
250   {
251     SnapshotFileWriter snapshot_writer;
252     snapshot_writer.SetSnapshotFile(i::FLAG_startup_src);
253     snapshot_writer.SetStartupBlobFile(i::FLAG_startup_blob);
254 
255     i::EmbeddedFileWriter embedded_writer;
256     embedded_writer.SetEmbeddedFile(i::FLAG_embedded_src);
257     embedded_writer.SetEmbeddedVariant(i::FLAG_embedded_variant);
258     embedded_writer.SetTargetArch(i::FLAG_target_arch);
259     embedded_writer.SetTargetOs(i::FLAG_target_os);
260 
261     std::unique_ptr<char> embed_script(
262         GetExtraCode(argc >= 2 ? argv[1] : nullptr, "embedding"));
263     std::unique_ptr<char> warmup_script(
264         GetExtraCode(argc >= 3 ? argv[2] : nullptr, "warm up"));
265 
266     i::DisableEmbeddedBlobRefcounting();
267     v8::StartupData blob;
268     {
269       v8::Isolate* isolate = v8::Isolate::Allocate();
270 
271       MaybeSetCounterFunction(isolate);
272 
273       // Set code range such that relative jumps for builtins to
274       // builtin calls in the snapshot are possible.
275       i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
276       size_t code_range_size_mb =
277           i::kMaximalCodeRangeSize == 0
278               ? i::kMaxPCRelativeCodeRangeInMB
279               : std::min(i::kMaximalCodeRangeSize / i::MB,
280                          i::kMaxPCRelativeCodeRangeInMB);
281       v8::ResourceConstraints constraints;
282       constraints.set_code_range_size_in_bytes(code_range_size_mb * i::MB);
283       i_isolate->heap()->ConfigureHeap(constraints);
284       // The isolate contains data from builtin compilation that needs
285       // to be written out if builtins are embedded.
286       i_isolate->RegisterEmbeddedFileWriter(&embedded_writer);
287 
288       blob = CreateSnapshotDataBlob(isolate, embed_script.get());
289 
290       // At this point, the Isolate has been torn down but the embedded blob
291       // is still alive (we called DisableEmbeddedBlobRefcounting above).
292       // That's fine as far as the embedded file writer is concerned.
293       WriteEmbeddedFile(&embedded_writer);
294     }
295 
296     if (warmup_script) {
297       v8::StartupData cold = blob;
298       blob = WarmUpSnapshotDataBlob(cold, warmup_script.get());
299       delete[] cold.data;
300     }
301 
302     delete counter_map_;
303 
304     CHECK(blob.data);
305     snapshot_writer.WriteSnapshot(blob);
306     delete[] blob.data;
307   }
308   i::FreeCurrentEmbeddedBlob();
309 
310   v8::V8::Dispose();
311   v8::V8::DisposePlatform();
312   return 0;
313 }
314