1 #include <cstdio>
2 #include <fstream>
3 #include <iostream>
4 #include <sstream>
5 #include <string>
6 #include <vector>
7
8 #include "libplatform/libplatform.h"
9 #include "node_internals.h"
10 #include "node_snapshot_builder.h"
11 #include "util-inl.h"
12 #include "v8.h"
13
14 int BuildSnapshot(int argc, char* argv[]);
15
16 #ifdef _WIN32
17 #include <windows.h>
18
wmain(int argc,wchar_t * wargv[])19 int wmain(int argc, wchar_t* wargv[]) {
20 // Windows needs conversion from wchar_t to char.
21
22 // Convert argv to UTF8.
23 char** argv = new char*[argc + 1];
24 for (int i = 0; i < argc; i++) {
25 // Compute the size of the required buffer
26 DWORD size = WideCharToMultiByte(
27 CP_UTF8, 0, wargv[i], -1, nullptr, 0, nullptr, nullptr);
28 if (size == 0) {
29 // This should never happen.
30 fprintf(stderr, "Could not convert arguments to utf8.");
31 exit(1);
32 }
33 // Do the actual conversion
34 argv[i] = new char[size];
35 DWORD result = WideCharToMultiByte(
36 CP_UTF8, 0, wargv[i], -1, argv[i], size, nullptr, nullptr);
37 if (result == 0) {
38 // This should never happen.
39 fprintf(stderr, "Could not convert arguments to utf8.");
40 exit(1);
41 }
42 }
43 argv[argc] = nullptr;
44 #else // UNIX
45 int main(int argc, char* argv[]) {
46 argv = uv_setup_args(argc, argv);
47
48 // Disable stdio buffering, it interacts poorly with printf()
49 // calls elsewhere in the program (e.g., any logging from V8.)
50 setvbuf(stdout, nullptr, _IONBF, 0);
51 setvbuf(stderr, nullptr, _IONBF, 0);
52 #endif // _WIN32
53
54 v8::V8::SetFlagsFromString("--random_seed=42");
55 v8::V8::SetFlagsFromString("--harmony-import-assertions");
56 return BuildSnapshot(argc, argv);
57 }
58
59 int BuildSnapshot(int argc, char* argv[]) {
60 if (argc < 2) {
61 std::cerr << "Usage: " << argv[0] << " <path/to/output.cc>\n";
62 std::cerr << " " << argv[0] << " --build-snapshot "
63 << "<path/to/script.js> <path/to/output.cc>\n";
64 return 1;
65 }
66
67 std::unique_ptr<node::InitializationResult> result =
68 node::InitializeOncePerProcess(
69 std::vector<std::string>(argv, argv + argc));
70
71 CHECK(!result->early_return());
72 CHECK_EQ(result->exit_code(), 0);
73
74 std::string out_path;
75 if (node::per_process::cli_options->build_snapshot) {
76 out_path = result->args()[2];
77 } else {
78 out_path = result->args()[1];
79 }
80
81 std::ofstream out(out_path, std::ios::out | std::ios::binary);
82 if (!out) {
83 std::cerr << "Cannot open " << out_path << "\n";
84 return 1;
85 }
86
87 int exit_code = 0;
88 {
89 exit_code = node::SnapshotBuilder::Generate(
90 out, result->args(), result->exec_args());
91 if (exit_code == 0) {
92 if (!out) {
93 std::cerr << "Failed to write " << out_path << "\n";
94 exit_code = 1;
95 }
96 }
97 }
98
99 node::TearDownOncePerProcess();
100 return exit_code;
101 }
102