GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_snapshotable.cc Lines: 478 599 79.8 %
Date: 2022-08-05 04:16:08 Branches: 123 214 57.5 %

Line Branch Exec Source
1
2
#include "node_snapshotable.h"
3
#include <iostream>
4
#include <sstream>
5
#include "base_object-inl.h"
6
#include "debug_utils-inl.h"
7
#include "env-inl.h"
8
#include "node_blob.h"
9
#include "node_errors.h"
10
#include "node_external_reference.h"
11
#include "node_file.h"
12
#include "node_internals.h"
13
#include "node_main_instance.h"
14
#include "node_metadata.h"
15
#include "node_native_module.h"
16
#include "node_process.h"
17
#include "node_snapshot_builder.h"
18
#include "node_v8.h"
19
#include "node_v8_platform-inl.h"
20
21
#if HAVE_INSPECTOR
22
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
23
#endif
24
25
namespace node {
26
27
using v8::Context;
28
using v8::Function;
29
using v8::FunctionCallbackInfo;
30
using v8::HandleScope;
31
using v8::Isolate;
32
using v8::Local;
33
using v8::Object;
34
using v8::ScriptCompiler;
35
using v8::ScriptOrigin;
36
using v8::SnapshotCreator;
37
using v8::StartupData;
38
using v8::String;
39
using v8::TryCatch;
40
using v8::Value;
41
42
const uint32_t SnapshotData::kMagic;
43
44
std::ostream& operator<<(std::ostream& output,
45
                         const native_module::CodeCacheInfo& info) {
46
  output << "<native_module::CodeCacheInfo id=" << info.id
47
         << ", size=" << info.data.size() << ">\n";
48
  return output;
49
}
50
51
std::ostream& operator<<(std::ostream& output,
52
                         const std::vector<native_module::CodeCacheInfo>& vec) {
53
  output << "{\n";
54
  for (const auto& info : vec) {
55
    output << info;
56
  }
57
  output << "}\n";
58
  return output;
59
}
60
61
std::ostream& operator<<(std::ostream& output,
62
                         const std::vector<uint8_t>& vec) {
63
  output << "{\n";
64
  for (const auto& i : vec) {
65
    output << i << ",";
66
  }
67
  output << "}";
68
  return output;
69
}
70
71
class FileIO {
72
 public:
73
4
  explicit FileIO(FILE* file)
74
4
      : f(file),
75
4
        is_debug(per_process::enabled_debug_list.enabled(
76
4
            DebugCategory::MKSNAPSHOT)) {}
77
78
  template <typename... Args>
79
4028
  void Debug(const char* format, Args&&... args) const {
80
2608
    per_process::Debug(
81
        DebugCategory::MKSNAPSHOT, format, std::forward<Args>(args)...);
82
  }
83
84
  template <typename T>
85
  std::string ToStr(const T& arg) const {
86
    std::stringstream ss;
87
    ss << arg;
88
    return ss.str();
89
  }
90
91
  template <typename T>
92
  std::string GetName() const {
93
#define TYPE_LIST(V)                                                           \
94
  V(native_module::CodeCacheInfo)                                              \
95
  V(PropInfo)                                                                  \
96
  V(std::string)
97
98
#define V(TypeName)                                                            \
99
  if (std::is_same_v<T, TypeName>) {                                           \
100
    return #TypeName;                                                          \
101
  }
102
    TYPE_LIST(V)
103
#undef V
104
105
    std::string name;
106
    if (std::is_arithmetic_v<T>) {
107
      if (!std::is_signed_v<T>) {
108
        name += "u";
109
      }
110
      name += std::is_integral_v<T> ? "int" : "float";
111
      name += std::to_string(sizeof(T) * 8);
112
      name += "_t";
113
    }
114
    return name;
115
  }
116
117
  FILE* f = nullptr;
118
  bool is_debug = false;
119
};
120
121
class FileReader : public FileIO {
122
 public:
123
2
  explicit FileReader(FILE* file) : FileIO(file) {}
124
2
  ~FileReader() {}
125
126
  // Helper for reading numeric types.
127
  template <typename T>
128
3556
  T Read() {
129
    static_assert(std::is_arithmetic_v<T>, "Not an arithmetic type");
130
    T result;
131
3556
    Read(&result, 1);
132
3556
    return result;
133
  }
134
135
  // Layout of vectors:
136
  // [ 4/8 bytes ] count
137
  // [   ...     ] contents (count * size of individual elements)
138
  template <typename T>
139
1184
  std::vector<T> ReadVector() {
140
1184
    if (is_debug) {
141
      std::string name = GetName<T>();
142
      Debug("\nReadVector<%s>()(%d-byte)\n", name.c_str(), sizeof(T));
143
    }
144
1184
    size_t count = static_cast<size_t>(Read<size_t>());
145
1184
    if (count == 0) {
146
4
      return std::vector<T>();
147
    }
148
1180
    if (is_debug) {
149
      Debug("Reading %d vector elements...\n", count);
150
    }
151
2360
    std::vector<T> result = ReadVector<T>(count, std::is_arithmetic<T>{});
152
1180
    if (is_debug) {
153
      std::string str = std::is_arithmetic_v<T> ? "" : ToStr(result);
154
      std::string name = GetName<T>();
155
      Debug("ReadVector<%s>() read %s\n", name.c_str(), str.c_str());
156
    }
157
1180
    return result;
158
  }
159
160
928
  std::string ReadString() {
161
928
    size_t length = Read<size_t>();
162
163
928
    if (is_debug) {
164
      Debug("ReadString(), length=%d: ", length);
165
    }
166
167
928
    CHECK_GT(length, 0);  // There should be no empty strings.
168
1856
    MallocedBuffer<char> buf(length + 1);
169
928
    size_t r = fread(buf.data, 1, length + 1, f);
170
928
    CHECK_EQ(r, length + 1);
171
928
    std::string result(buf.data, length);  // This creates a copy of buf.data.
172
173
928
    if (is_debug) {
174
      Debug("\"%s\", read %d bytes\n", result.c_str(), r);
175
    }
176
177
928
    read_total += r;
178
928
    return result;
179
  }
180
181
  size_t read_total = 0;
182
183
 private:
184
  // Helper for reading an array of numeric types.
185
  template <typename T>
186
4720
  void Read(T* out, size_t count) {
187
    static_assert(std::is_arithmetic_v<T>, "Not an arithmetic type");
188
    DCHECK_GT(count, 0);  // Should not read contents for vectors of size 0.
189
4720
    if (is_debug) {
190
      std::string name = GetName<T>();
191
      Debug("Read<%s>()(%d-byte), count=%d: ", name.c_str(), sizeof(T), count);
192
    }
193
194
4720
    size_t r = fread(out, sizeof(T), count, f);
195
4720
    CHECK_EQ(r, count);
196
197
4720
    if (is_debug) {
198
      std::string str =
199
          "{ " + std::to_string(out[0]) + (count > 1 ? ", ... }" : " }");
200
      Debug("%s, read %d bytes\n", str.c_str(), r);
201
    }
202
4720
    read_total += r;
203
4720
  }
204
205
  // Helper for reading numeric vectors.
206
  template <typename Number>
207
1160
  std::vector<Number> ReadVector(size_t count, std::true_type) {
208
    static_assert(std::is_arithmetic_v<Number>, "Not an arithmetic type");
209
    DCHECK_GT(count, 0);  // Should not read contents for vectors of size 0.
210
1160
    std::vector<Number> result(count);
211
1160
    Read(result.data(), count);
212
1160
    return result;
213
  }
214
215
  // Helper for reading non-numeric vectors.
216
  template <typename T>
217
20
  std::vector<T> ReadVector(size_t count, std::false_type) {
218
    static_assert(!std::is_arithmetic_v<T>, "Arithmetic type");
219
    DCHECK_GT(count, 0);  // Should not read contents for vectors of size 0.
220
20
    std::vector<T> result;
221
20
    result.reserve(count);
222
20
    bool original_is_debug = is_debug;
223
20
    is_debug = original_is_debug && !std::is_same_v<T, std::string>;
224
1868
    for (size_t i = 0; i < count; ++i) {
225
1848
      if (is_debug) {
226
        Debug("\n[%d] ", i);
227
      }
228
1848
      result.push_back(Read<T>());
229
    }
230
20
    is_debug = original_is_debug;
231
232
20
    return result;
233
  }
234
};
235
236
class FileWriter : public FileIO {
237
 public:
238
2
  explicit FileWriter(FILE* file) : FileIO(file) {}
239
2
  ~FileWriter() {}
240
241
  // Helper for writing numeric types.
242
  template <typename T>
243
3556
  size_t Write(const T& data) {
244
    static_assert(std::is_arithmetic_v<T>, "Not an arithmetic type");
245
3556
    return Write(&data, 1);
246
  }
247
248
  // Layout of vectors:
249
  // [ 4/8 bytes ] count
250
  // [   ...     ] contents (count * size of individual elements)
251
  template <typename T>
252
1184
  size_t WriteVector(const std::vector<T>& data) {
253
1184
    if (is_debug) {
254
      std::string str = std::is_arithmetic_v<T> ? "" : ToStr(data);
255
      std::string name = GetName<T>();
256
      Debug("\nWriteVector<%s>() (%d-byte), count=%d: %s\n",
257
            name.c_str(),
258
            sizeof(T),
259
            data.size(),
260
            str.c_str());
261
    }
262
263
1184
    size_t written_total = Write<size_t>(data.size());
264
1184
    if (data.size() == 0) {
265
4
      return written_total;
266
    }
267
1180
    written_total += WriteVector<T>(data, std::is_arithmetic<T>{});
268
269
1180
    if (is_debug) {
270
      std::string name = GetName<T>();
271
      Debug("WriteVector<%s>() wrote %d bytes\n", name.c_str(), written_total);
272
    }
273
274
1180
    return written_total;
275
  }
276
277
  // The layout of a written string:
278
  // [  4/8 bytes     ] length
279
  // [ |length| bytes ] contents
280
928
  size_t WriteString(const std::string& data) {
281
928
    CHECK_GT(data.size(), 0);  // No empty strings should be written.
282
928
    size_t written_total = Write<size_t>(data.size());
283
928
    if (is_debug) {
284
      std::string str = ToStr(data);
285
      Debug("WriteString(), length=%d: \"%s\"\n", data.size(), data.c_str());
286
    }
287
288
928
    size_t r = fwrite(data.c_str(), 1, data.size() + 1, f);
289
928
    CHECK_EQ(r, data.size() + 1);
290
928
    written_total += r;
291
292
928
    if (is_debug) {
293
      Debug("WriteString() wrote %d bytes\n", written_total);
294
    }
295
296
928
    return written_total;
297
  }
298
299
 private:
300
  // Helper for writing an array of numeric types.
301
  template <typename T>
302
4720
  size_t Write(const T* data, size_t count) {
303
    DCHECK_GT(count, 0);  // Should not write contents for vectors of size 0.
304
4720
    if (is_debug) {
305
      std::string str =
306
          "{ " + std::to_string(data[0]) + (count > 1 ? ", ... }" : " }");
307
      std::string name = GetName<T>();
308
      Debug("Write<%s>() (%d-byte), count=%d: %s",
309
            name.c_str(),
310
            sizeof(T),
311
            count,
312
            str.c_str());
313
    }
314
315
4720
    size_t r = fwrite(data, sizeof(T), count, f);
316
4720
    CHECK_EQ(r, count);
317
318
4720
    if (is_debug) {
319
      Debug(", wrote %d bytes\n", r);
320
    }
321
4720
    return r;
322
  }
323
324
  // Helper for writing numeric vectors.
325
  template <typename Number>
326
1160
  size_t WriteVector(const std::vector<Number>& data, std::true_type) {
327
1160
    return Write(data.data(), data.size());
328
  }
329
330
  // Helper for writing non-numeric vectors.
331
  template <typename T>
332
20
  size_t WriteVector(const std::vector<T>& data, std::false_type) {
333
    DCHECK_GT(data.size(),
334
              0);  // Should not write contents for vectors of size 0.
335
20
    size_t written_total = 0;
336
20
    bool original_is_debug = is_debug;
337
20
    is_debug = original_is_debug && !std::is_same_v<T, std::string>;
338
1868
    for (size_t i = 0; i < data.size(); ++i) {
339
1848
      if (is_debug) {
340
        Debug("\n[%d] ", i);
341
      }
342
1848
      written_total += Write<T>(data[i]);
343
    }
344
20
    is_debug = original_is_debug;
345
346
20
    return written_total;
347
  }
348
};
349
350
// Layout of serialized std::string:
351
// [  4/8 bytes     ] length
352
// [ |length| bytes ] contents
353
template <>
354
232
std::string FileReader::Read() {
355
232
  return ReadString();
356
}
357
template <>
358
232
size_t FileWriter::Write(const std::string& data) {
359
232
  return WriteString(data);
360
}
361
362
// Layout of v8::StartupData
363
// [  4/8 bytes       ] raw_size
364
// [ |raw_size| bytes ] contents
365
template <>
366
2
v8::StartupData FileReader::Read() {
367
2
  Debug("Read<v8::StartupData>()\n");
368
369
2
  int raw_size = Read<int>();
370
2
  Debug("size=%d\n", raw_size);
371
372
2
  CHECK_GT(raw_size, 0);  // There should be no startup data of size 0.
373
  // The data pointer of v8::StartupData would be deleted so it must be new'ed.
374
2
  std::unique_ptr<char> buf = std::unique_ptr<char>(new char[raw_size]);
375
2
  Read<char>(buf.get(), raw_size);
376
377
2
  return v8::StartupData{buf.release(), raw_size};
378
}
379
380
template <>
381
2
size_t FileWriter::Write(const v8::StartupData& data) {
382
2
  Debug("\nWrite<v8::StartupData>() size=%d\n", data.raw_size);
383
384
2
  CHECK_GT(data.raw_size, 0);  // There should be no startup data of size 0.
385
2
  size_t written_total = Write<int>(data.raw_size);
386
2
  written_total += Write<char>(data.data, static_cast<size_t>(data.raw_size));
387
388
2
  Debug("Write<v8::StartupData>() wrote %d bytes\n\n", written_total);
389
2
  return written_total;
390
}
391
392
// Layout of native_module::CodeCacheInfo
393
// [  4/8 bytes ]  length of the module id string
394
// [    ...     ]  |length| bytes of module id
395
// [  4/8 bytes ]  length of module code cache
396
// [    ...     ]  |length| bytes of module code cache
397
template <>
398
578
native_module::CodeCacheInfo FileReader::Read() {
399
578
  Debug("Read<native_module::CodeCacheInfo>()\n");
400
401
578
  native_module::CodeCacheInfo result{ReadString(), ReadVector<uint8_t>()};
402
403
578
  if (is_debug) {
404
    std::string str = ToStr(result);
405
    Debug("Read<native_module::CodeCacheInfo>() %s\n", str.c_str());
406
  }
407
578
  return result;
408
}
409
410
template <>
411
578
size_t FileWriter::Write(const native_module::CodeCacheInfo& data) {
412
1156
  Debug("\nWrite<native_module::CodeCacheInfo>() id = %s"
413
        ", size=%d\n",
414
578
        data.id.c_str(),
415
578
        data.data.size());
416
417
578
  size_t written_total = WriteString(data.id);
418
578
  written_total += WriteVector<uint8_t>(data.data);
419
420
578
  Debug("Write<native_module::CodeCacheInfo>() wrote %d bytes\n",
421
        written_total);
422
578
  return written_total;
423
}
424
425
// Layout of PropInfo
426
// [ 4/8 bytes ]  length of the data name string
427
// [    ...    ]  |length| bytes of data name
428
// [  4 bytes  ]  index in the PropInfo vector
429
// [ 4/8 bytes ]  index in the snapshot blob, can be used with
430
//                GetDataFromSnapshotOnce().
431
template <>
432
114
PropInfo FileReader::Read() {
433
114
  Debug("Read<PropInfo>()\n");
434
435
114
  PropInfo result;
436
114
  result.name = ReadString();
437
114
  result.id = Read<uint32_t>();
438
114
  result.index = Read<SnapshotIndex>();
439
440
114
  if (is_debug) {
441
    std::string str = ToStr(result);
442
    Debug("Read<PropInfo>() %s\n", str.c_str());
443
  }
444
445
114
  return result;
446
}
447
448
template <>
449
114
size_t FileWriter::Write(const PropInfo& data) {
450
114
  if (is_debug) {
451
    std::string str = ToStr(data);
452
    Debug("Write<PropInfo>() %s\n", str.c_str());
453
  }
454
455
114
  size_t written_total = WriteString(data.name);
456
114
  written_total += Write<uint32_t>(data.id);
457
114
  written_total += Write<SnapshotIndex>(data.index);
458
459
114
  Debug("Write<PropInfo>() wrote %d bytes\n", written_total);
460
114
  return written_total;
461
}
462
463
// Layout of AsyncHooks::SerializeInfo
464
// [ 4/8 bytes ]  snapshot index of async_ids_stack
465
// [ 4/8 bytes ]  snapshot index of fields
466
// [ 4/8 bytes ]  snapshot index of async_id_fields
467
// [ 4/8 bytes ]  snapshot index of js_execution_async_resources
468
// [ 4/8 bytes ]  length of native_execution_async_resources
469
// [   ...     ]  snapshot indices of each element in
470
//                native_execution_async_resources
471
template <>
472
2
AsyncHooks::SerializeInfo FileReader::Read() {
473
2
  Debug("Read<AsyncHooks::SerializeInfo>()\n");
474
475
2
  AsyncHooks::SerializeInfo result;
476
2
  result.async_ids_stack = Read<AliasedBufferIndex>();
477
2
  result.fields = Read<AliasedBufferIndex>();
478
2
  result.async_id_fields = Read<AliasedBufferIndex>();
479
2
  result.js_execution_async_resources = Read<SnapshotIndex>();
480
2
  result.native_execution_async_resources = ReadVector<SnapshotIndex>();
481
482
2
  if (is_debug) {
483
    std::string str = ToStr(result);
484
    Debug("Read<AsyncHooks::SerializeInfo>() %s\n", str.c_str());
485
  }
486
487
2
  return result;
488
}
489
template <>
490
2
size_t FileWriter::Write(const AsyncHooks::SerializeInfo& data) {
491
2
  if (is_debug) {
492
    std::string str = ToStr(data);
493
    Debug("Write<AsyncHooks::SerializeInfo>() %s\n", str.c_str());
494
  }
495
496
2
  size_t written_total = Write<AliasedBufferIndex>(data.async_ids_stack);
497
2
  written_total += Write<AliasedBufferIndex>(data.fields);
498
2
  written_total += Write<AliasedBufferIndex>(data.async_id_fields);
499
2
  written_total += Write<SnapshotIndex>(data.js_execution_async_resources);
500
2
  written_total +=
501
2
      WriteVector<SnapshotIndex>(data.native_execution_async_resources);
502
503
2
  Debug("Write<AsyncHooks::SerializeInfo>() wrote %d bytes\n", written_total);
504
2
  return written_total;
505
}
506
507
// Layout of TickInfo::SerializeInfo
508
// [ 4/8 bytes ]  snapshot index of fields
509
template <>
510
2
TickInfo::SerializeInfo FileReader::Read() {
511
2
  Debug("Read<TickInfo::SerializeInfo>()\n");
512
513
  TickInfo::SerializeInfo result;
514
2
  result.fields = Read<AliasedBufferIndex>();
515
516
2
  if (is_debug) {
517
    std::string str = ToStr(result);
518
    Debug("Read<TickInfo::SerializeInfo>() %s\n", str.c_str());
519
  }
520
521
2
  return result;
522
}
523
524
template <>
525
2
size_t FileWriter::Write(const TickInfo::SerializeInfo& data) {
526
2
  if (is_debug) {
527
    std::string str = ToStr(data);
528
    Debug("Write<TickInfo::SerializeInfo>() %s\n", str.c_str());
529
  }
530
531
2
  size_t written_total = Write<AliasedBufferIndex>(data.fields);
532
533
2
  Debug("Write<TickInfo::SerializeInfo>() wrote %d bytes\n", written_total);
534
2
  return written_total;
535
}
536
537
// Layout of TickInfo::SerializeInfo
538
// [ 4/8 bytes ]  snapshot index of fields
539
template <>
540
2
ImmediateInfo::SerializeInfo FileReader::Read() {
541
  per_process::Debug(DebugCategory::MKSNAPSHOT,
542
                     "Read<ImmediateInfo::SerializeInfo>()\n");
543
544
  ImmediateInfo::SerializeInfo result;
545
2
  result.fields = Read<AliasedBufferIndex>();
546
2
  if (is_debug) {
547
    std::string str = ToStr(result);
548
    Debug("Read<ImmediateInfo::SerializeInfo>() %s\n", str.c_str());
549
  }
550
2
  return result;
551
}
552
553
template <>
554
2
size_t FileWriter::Write(const ImmediateInfo::SerializeInfo& data) {
555
2
  if (is_debug) {
556
    std::string str = ToStr(data);
557
    Debug("Write<ImmeidateInfo::SerializeInfo>() %s\n", str.c_str());
558
  }
559
560
2
  size_t written_total = Write<AliasedBufferIndex>(data.fields);
561
562
2
  Debug("Write<ImmeidateInfo::SerializeInfo>() wrote %d bytes\n",
563
        written_total);
564
2
  return written_total;
565
}
566
567
// Layout of PerformanceState::SerializeInfo
568
// [ 4/8 bytes ]  snapshot index of root
569
// [ 4/8 bytes ]  snapshot index of milestones
570
// [ 4/8 bytes ]  snapshot index of observers
571
template <>
572
2
performance::PerformanceState::SerializeInfo FileReader::Read() {
573
  per_process::Debug(DebugCategory::MKSNAPSHOT,
574
                     "Read<PerformanceState::SerializeInfo>()\n");
575
576
  performance::PerformanceState::SerializeInfo result;
577
2
  result.root = Read<AliasedBufferIndex>();
578
2
  result.milestones = Read<AliasedBufferIndex>();
579
2
  result.observers = Read<AliasedBufferIndex>();
580
2
  if (is_debug) {
581
    std::string str = ToStr(result);
582
    Debug("Read<PerformanceState::SerializeInfo>() %s\n", str.c_str());
583
  }
584
2
  return result;
585
}
586
587
template <>
588
2
size_t FileWriter::Write(
589
    const performance::PerformanceState::SerializeInfo& data) {
590
2
  if (is_debug) {
591
    std::string str = ToStr(data);
592
    Debug("Write<PerformanceState::SerializeInfo>() %s\n", str.c_str());
593
  }
594
595
2
  size_t written_total = Write<AliasedBufferIndex>(data.root);
596
2
  written_total += Write<AliasedBufferIndex>(data.milestones);
597
2
  written_total += Write<AliasedBufferIndex>(data.observers);
598
599
2
  Debug("Write<PerformanceState::SerializeInfo>() wrote %d bytes\n",
600
        written_total);
601
2
  return written_total;
602
}
603
604
// Layout of IsolateDataSerializeInfo
605
// [ 4/8 bytes ]  length of primitive_values vector
606
// [    ...    ]  |length| of primitive_values indices
607
// [ 4/8 bytes ]  length of template_values vector
608
// [    ...    ]  |length| of PropInfo data
609
template <>
610
2
IsolateDataSerializeInfo FileReader::Read() {
611
  per_process::Debug(DebugCategory::MKSNAPSHOT,
612
                     "Read<IsolateDataSerializeInfo>()\n");
613
614
2
  IsolateDataSerializeInfo result;
615
2
  result.primitive_values = ReadVector<SnapshotIndex>();
616
2
  result.template_values = ReadVector<PropInfo>();
617
2
  if (is_debug) {
618
    std::string str = ToStr(result);
619
    Debug("Read<IsolateDataSerializeInfo>() %s\n", str.c_str());
620
  }
621
2
  return result;
622
}
623
624
template <>
625
2
size_t FileWriter::Write(const IsolateDataSerializeInfo& data) {
626
2
  if (is_debug) {
627
    std::string str = ToStr(data);
628
    Debug("Write<IsolateDataSerializeInfo>() %s\n", str.c_str());
629
  }
630
631
2
  size_t written_total = WriteVector<SnapshotIndex>(data.primitive_values);
632
2
  written_total += WriteVector<PropInfo>(data.template_values);
633
634
2
  Debug("Write<IsolateDataSerializeInfo>() wrote %d bytes\n", written_total);
635
2
  return written_total;
636
}
637
638
template <>
639
2
EnvSerializeInfo FileReader::Read() {
640
  per_process::Debug(DebugCategory::MKSNAPSHOT, "Read<EnvSerializeInfo>()\n");
641
2
  EnvSerializeInfo result;
642
2
  result.bindings = ReadVector<PropInfo>();
643
2
  result.native_modules = ReadVector<std::string>();
644
2
  result.async_hooks = Read<AsyncHooks::SerializeInfo>();
645
2
  result.tick_info = Read<TickInfo::SerializeInfo>();
646
2
  result.immediate_info = Read<ImmediateInfo::SerializeInfo>();
647
  result.performance_state =
648
2
      Read<performance::PerformanceState::SerializeInfo>();
649
2
  result.exiting = Read<AliasedBufferIndex>();
650
2
  result.stream_base_state = Read<AliasedBufferIndex>();
651
2
  result.should_abort_on_uncaught_toggle = Read<AliasedBufferIndex>();
652
2
  result.persistent_values = ReadVector<PropInfo>();
653
2
  result.context = Read<SnapshotIndex>();
654
2
  return result;
655
}
656
657
template <>
658
2
size_t FileWriter::Write(const EnvSerializeInfo& data) {
659
2
  if (is_debug) {
660
    std::string str = ToStr(data);
661
    Debug("\nWrite<EnvSerializeInfo>() %s\n", str.c_str());
662
  }
663
664
  // Use += here to ensure order of evaluation.
665
2
  size_t written_total = WriteVector<PropInfo>(data.bindings);
666
2
  written_total += WriteVector<std::string>(data.native_modules);
667
2
  written_total += Write<AsyncHooks::SerializeInfo>(data.async_hooks);
668
2
  written_total += Write<TickInfo::SerializeInfo>(data.tick_info);
669
2
  written_total += Write<ImmediateInfo::SerializeInfo>(data.immediate_info);
670
4
  written_total += Write<performance::PerformanceState::SerializeInfo>(
671
2
      data.performance_state);
672
2
  written_total += Write<AliasedBufferIndex>(data.exiting);
673
2
  written_total += Write<AliasedBufferIndex>(data.stream_base_state);
674
2
  written_total +=
675
2
      Write<AliasedBufferIndex>(data.should_abort_on_uncaught_toggle);
676
2
  written_total += WriteVector<PropInfo>(data.persistent_values);
677
2
  written_total += Write<SnapshotIndex>(data.context);
678
679
2
  Debug("Write<EnvSerializeInfo>() wrote %d bytes\n", written_total);
680
2
  return written_total;
681
}
682
683
// Layout of the snapshot blob
684
// [   4 bytes    ]  kMagic
685
// [   4/8 bytes  ]  length of Node.js version string
686
// [    ...       ]  contents of Node.js version string
687
// [   4/8 bytes  ]  length of Node.js arch string
688
// [    ...       ]  contents of Node.js arch string
689
// [    ...       ]  v8_snapshot_blob_data from SnapshotCreator::CreateBlob()
690
// [    ...       ]  isolate_data_info
691
// [    ...       ]  env_info
692
// [    ...       ]  code_cache
693
694
2
void SnapshotData::ToBlob(FILE* out) const {
695
4
  FileWriter w(out);
696
2
  w.Debug("SnapshotData::ToBlob()\n");
697
698
2
  size_t written_total = 0;
699
  // Metadata
700
2
  w.Debug("Write magic %" PRIx32 "\n", kMagic);
701
2
  written_total += w.Write<uint32_t>(kMagic);
702
2
  w.Debug("Write version %s\n", NODE_VERSION);
703
2
  written_total += w.WriteString(NODE_VERSION);
704
2
  w.Debug("Write arch %s\n", NODE_ARCH);
705
2
  written_total += w.WriteString(NODE_ARCH);
706
707
2
  written_total += w.Write<v8::StartupData>(v8_snapshot_blob_data);
708
2
  w.Debug("Write isolate_data_indices\n");
709
2
  written_total += w.Write<IsolateDataSerializeInfo>(isolate_data_info);
710
2
  written_total += w.Write<EnvSerializeInfo>(env_info);
711
2
  w.Debug("Write code_cache\n");
712
2
  written_total += w.WriteVector<native_module::CodeCacheInfo>(code_cache);
713
2
  w.Debug("SnapshotData::ToBlob() Wrote %d bytes\n", written_total);
714
2
}
715
716
2
void SnapshotData::FromBlob(SnapshotData* out, FILE* in) {
717
4
  FileReader r(in);
718
2
  r.Debug("SnapshotData::FromBlob()\n");
719
720
  // Metadata
721
2
  uint32_t magic = r.Read<uint32_t>();
722
2
  r.Debug("Read magic %" PRIx64 "\n", magic);
723
2
  CHECK_EQ(magic, kMagic);
724
4
  std::string version = r.ReadString();
725
2
  r.Debug("Read version %s\n", version.c_str());
726
2
  CHECK_EQ(version, NODE_VERSION);
727
4
  std::string arch = r.ReadString();
728
2
  r.Debug("Read arch %s\n", arch.c_str());
729
2
  CHECK_EQ(arch, NODE_ARCH);
730
731
  DCHECK_EQ(out->data_ownership, SnapshotData::DataOwnership::kOwned);
732
2
  out->v8_snapshot_blob_data = r.Read<v8::StartupData>();
733
2
  r.Debug("Read isolate_data_info\n");
734
2
  out->isolate_data_info = r.Read<IsolateDataSerializeInfo>();
735
2
  out->env_info = r.Read<EnvSerializeInfo>();
736
2
  r.Debug("Read code_cache\n");
737
2
  out->code_cache = r.ReadVector<native_module::CodeCacheInfo>();
738
739
2
  r.Debug("SnapshotData::FromBlob() read %d bytes\n", r.read_total);
740
2
}
741
742
5381
SnapshotData::~SnapshotData() {
743
5381
  if (data_ownership == DataOwnership::kOwned &&
744
9
      v8_snapshot_blob_data.data != nullptr) {
745
8
    delete[] v8_snapshot_blob_data.data;
746
  }
747
5381
}
748
749
template <typename T>
750
3480
void WriteVector(std::ostream* ss, const T* vec, size_t size) {
751
25793528
  for (size_t i = 0; i < size; i++) {
752
25790048
    *ss << std::to_string(vec[i]) << (i == size - 1 ? '\n' : ',');
753
  }
754
3480
}
755
756
3468
static std::string GetCodeCacheDefName(const std::string& id) {
757
3468
  char buf[64] = {0};
758
3468
  size_t size = id.size();
759
3468
  CHECK_LT(size, sizeof(buf));
760
77472
  for (size_t i = 0; i < size; ++i) {
761
74004
    char ch = id[i];
762

74004
    buf[i] = (ch == '-' || ch == '/') ? '_' : ch;
763
  }
764
3468
  return std::string(buf) + std::string("_cache_data");
765
}
766
767
1734
static std::string FormatSize(size_t size) {
768
1734
  char buf[64] = {0};
769
1734
  if (size < 1024) {
770
156
    snprintf(buf, sizeof(buf), "%.2fB", static_cast<double>(size));
771
1578
  } else if (size < 1024 * 1024) {
772
1578
    snprintf(buf, sizeof(buf), "%.2fKB", static_cast<double>(size / 1024));
773
  } else {
774
    snprintf(
775
        buf, sizeof(buf), "%.2fMB", static_cast<double>(size / 1024 / 1024));
776
  }
777
1734
  return buf;
778
}
779
780
1734
static void WriteStaticCodeCacheData(std::ostream* ss,
781
                                     const native_module::CodeCacheInfo& info) {
782
1734
  *ss << "static const uint8_t " << GetCodeCacheDefName(info.id) << "[] = {\n";
783
1734
  WriteVector(ss, info.data.data(), info.data.size());
784
1734
  *ss << "};";
785
1734
}
786
787
1734
static void WriteCodeCacheInitializer(std::ostream* ss, const std::string& id) {
788
3468
  std::string def_name = GetCodeCacheDefName(id);
789
1734
  *ss << "    { \"" << id << "\",\n";
790
1734
  *ss << "      {" << def_name << ",\n";
791
1734
  *ss << "       " << def_name << " + arraysize(" << def_name << "),\n";
792
1734
  *ss << "      }\n";
793
1734
  *ss << "    },\n";
794
1734
}
795
796
6
void FormatBlob(std::ostream& ss, SnapshotData* data) {
797
6
  ss << R"(#include <cstddef>
798
#include "env.h"
799
#include "node_snapshot_builder.h"
800
#include "v8.h"
801
802
// This file is generated by tools/snapshot. Do not edit.
803
804
namespace node {
805
806
static const char v8_snapshot_blob_data[] = {
807
)";
808
6
  WriteVector(&ss,
809
              data->v8_snapshot_blob_data.data,
810
6
              data->v8_snapshot_blob_data.raw_size);
811
6
  ss << R"(};
812
813
static const int v8_snapshot_blob_size = )"
814
6
     << data->v8_snapshot_blob_data.raw_size << ";";
815
816
  // Windows can't deal with too many large vector initializers.
817
  // Store the data into static arrays first.
818
1740
  for (const auto& item : data->code_cache) {
819
1734
    WriteStaticCodeCacheData(&ss, item);
820
  }
821
822
6
  ss << R"(SnapshotData snapshot_data {
823
  // -- data_ownership begins --
824
  SnapshotData::DataOwnership::kNotOwned,
825
  // -- data_ownership ends --
826
  // -- v8_snapshot_blob_data begins --
827
  { v8_snapshot_blob_data, v8_snapshot_blob_size },
828
  // -- v8_snapshot_blob_data ends --
829
  // -- isolate_data_indices begins --
830
6
)" << data->isolate_data_info
831
6
     << R"(
832
  // -- isolate_data_indices ends --
833
  ,
834
  // -- env_info begins --
835
6
)" << data->env_info
836
6
     << R"(
837
  // -- env_info ends --
838
  ,
839
  // -- code_cache begins --
840
  {)";
841
1740
  for (const auto& item : data->code_cache) {
842
1734
    WriteCodeCacheInitializer(&ss, item.id);
843
  }
844
6
  ss << R"(
845
  }
846
  // -- code_cache ends --
847
};
848
849
const SnapshotData* SnapshotBuilder::GetEmbeddedSnapshotData() {
850
  Mutex::ScopedLock lock(snapshot_data_mutex_);
851
  return &snapshot_data;
852
}
853
}  // namespace node
854
)";
855
6
}
856
857
Mutex SnapshotBuilder::snapshot_data_mutex_;
858
859
6572
const std::vector<intptr_t>& SnapshotBuilder::CollectExternalReferences() {
860

6572
  static auto registry = std::make_unique<ExternalReferenceRegistry>();
861
6572
  return registry->external_references();
862
}
863
864
6565
void SnapshotBuilder::InitializeIsolateParams(const SnapshotData* data,
865
                                              Isolate::CreateParams* params) {
866
6565
  params->external_references = CollectExternalReferences().data();
867
6565
  params->snapshot_blob =
868
6565
      const_cast<v8::StartupData*>(&(data->v8_snapshot_blob_data));
869
6565
}
870
871
// TODO(joyeecheung): share these exit code constants across the code base.
872
constexpr int UNCAUGHT_EXCEPTION_ERROR = 1;
873
constexpr int BOOTSTRAP_ERROR = 10;
874
constexpr int SNAPSHOT_ERROR = 14;
875
876
7
int SnapshotBuilder::Generate(SnapshotData* out,
877
                              const std::vector<std::string> args,
878
                              const std::vector<std::string> exec_args) {
879
  const std::vector<intptr_t>& external_references =
880
7
      CollectExternalReferences();
881
7
  Isolate* isolate = Isolate::Allocate();
882
  // Must be done before the SnapshotCreator creation so  that the
883
  // memory reducer can be initialized.
884
14
  per_process::v8_platform.Platform()->RegisterIsolate(isolate,
885
7
                                                       uv_default_loop());
886
887
14
  SnapshotCreator creator(isolate, external_references.data());
888
889
7
  isolate->SetCaptureStackTraceForUncaughtExceptions(
890
      true, 10, v8::StackTrace::StackTraceOptions::kDetailed);
891
892
7
  Environment* env = nullptr;
893
  std::unique_ptr<NodeMainInstance> main_instance =
894
      NodeMainInstance::Create(isolate,
895
                               uv_default_loop(),
896
7
                               per_process::v8_platform.Platform(),
897
                               args,
898
14
                               exec_args);
899
900
  // The cleanups should be done in case of an early exit due to errors.
901
7
  auto cleanup = OnScopeLeave([&]() {
902
    // Must be done while the snapshot creator isolate is entered i.e. the
903
    // creator is still alive. The snapshot creator destructor will destroy
904
    // the isolate.
905
7
    if (env != nullptr) {
906
7
      FreeEnvironment(env);
907
    }
908
7
    main_instance->Dispose();
909
7
    per_process::v8_platform.Platform()->UnregisterIsolate(isolate);
910
14
  });
911
912
  {
913
7
    HandleScope scope(isolate);
914
7
    TryCatch bootstrapCatch(isolate);
915
916
7
    auto print_Exception = OnScopeLeave([&]() {
917
7
      if (bootstrapCatch.HasCaught()) {
918
2
        PrintCaughtException(
919
1
            isolate, isolate->GetCurrentContext(), bootstrapCatch);
920
      }
921
7
    });
922
923
    // The default context with only things created by V8.
924
7
    Local<Context> default_context = Context::New(isolate);
925
926
    // The Node.js-specific context with primodials, can be used by workers
927
    // TODO(joyeecheung): investigate if this can be used by vm contexts
928
    // without breaking compatibility.
929
7
    Local<Context> base_context = NewContext(isolate);
930
7
    if (base_context.IsEmpty()) {
931
      return BOOTSTRAP_ERROR;
932
    }
933
934
7
    Local<Context> main_context = NewContext(isolate);
935
7
    if (main_context.IsEmpty()) {
936
      return BOOTSTRAP_ERROR;
937
    }
938
    // Initialize the main instance context.
939
    {
940
7
      Context::Scope context_scope(main_context);
941
942
      // Create the environment.
943
7
      env = new Environment(main_instance->isolate_data(),
944
                            main_context,
945
                            args,
946
                            exec_args,
947
                            nullptr,
948
                            node::EnvironmentFlags::kDefaultFlags,
949
7
                            {});
950
951
      // Run scripts in lib/internal/bootstrap/
952
14
      if (env->RunBootstrapping().IsEmpty()) {
953
        return BOOTSTRAP_ERROR;
954
      }
955
      // If --build-snapshot is true, lib/internal/main/mksnapshot.js would be
956
      // loaded via LoadEnvironment() to execute process.argv[1] as the entry
957
      // point (we currently only support this kind of entry point, but we
958
      // could also explore snapshotting other kinds of execution modes
959
      // in the future).
960
7
      if (per_process::cli_options->build_snapshot) {
961
#if HAVE_INSPECTOR
962
        // TODO(joyeecheung): move this before RunBootstrapping().
963
1
        env->InitializeInspector({});
964
#endif
965
2
        if (LoadEnvironment(env, StartExecutionCallback{}).IsEmpty()) {
966
1
          return UNCAUGHT_EXCEPTION_ERROR;
967
        }
968
        // FIXME(joyeecheung): right now running the loop in the snapshot
969
        // builder seems to introduces inconsistencies in JS land that need to
970
        // be synchronized again after snapshot restoration.
971
        int exit_code = SpinEventLoop(env).FromMaybe(UNCAUGHT_EXCEPTION_ERROR);
972
        if (exit_code != 0) {
973
          return exit_code;
974
        }
975
      }
976
977
6
      if (per_process::enabled_debug_list.enabled(DebugCategory::MKSNAPSHOT)) {
978
        env->PrintAllBaseObjects();
979
        printf("Environment = %p\n", env);
980
      }
981
982
      // Serialize the native states
983
      out->isolate_data_info =
984
6
          main_instance->isolate_data()->Serialize(&creator);
985
6
      out->env_info = env->Serialize(&creator);
986
987
#ifdef NODE_USE_NODE_CODE_CACHE
988
      // Regenerate all the code cache.
989
6
      if (!native_module::NativeModuleLoader::CompileAllBuiltins(
990
              main_context)) {
991
        return UNCAUGHT_EXCEPTION_ERROR;
992
      }
993
6
      native_module::NativeModuleLoader::CopyCodeCache(&(out->code_cache));
994
1740
      for (const auto& item : out->code_cache) {
995
1734
        std::string size_str = FormatSize(item.data.size());
996
        per_process::Debug(DebugCategory::MKSNAPSHOT,
997
                           "Generated code cache for %d: %s\n",
998
1734
                           item.id.c_str(),
999
3468
                           size_str.c_str());
1000
      }
1001
#endif
1002
    }
1003
1004
    // Global handles to the contexts can't be disposed before the
1005
    // blob is created. So initialize all the contexts before adding them.
1006
    // TODO(joyeecheung): figure out how to remove this restriction.
1007
6
    creator.SetDefaultContext(default_context);
1008
6
    size_t index = creator.AddContext(base_context);
1009
6
    CHECK_EQ(index, SnapshotData::kNodeBaseContextIndex);
1010
6
    index = creator.AddContext(main_context,
1011
                               {SerializeNodeContextInternalFields, env});
1012
6
    CHECK_EQ(index, SnapshotData::kNodeMainContextIndex);
1013
  }
1014
1015
  // Must be out of HandleScope
1016
  out->v8_snapshot_blob_data =
1017
6
      creator.CreateBlob(SnapshotCreator::FunctionCodeHandling::kKeep);
1018
1019
  // We must be able to rehash the blob when we restore it or otherwise
1020
  // the hash seed would be fixed by V8, introducing a vulnerability.
1021
6
  if (!out->v8_snapshot_blob_data.CanBeRehashed()) {
1022
    return SNAPSHOT_ERROR;
1023
  }
1024
1025
  // We cannot resurrect the handles from the snapshot, so make sure that
1026
  // no handles are left open in the environment after the blob is created
1027
  // (which should trigger a GC and close all handles that can be closed).
1028
  bool queues_are_empty =
1029

6
      env->req_wrap_queue()->IsEmpty() && env->handle_wrap_queue()->IsEmpty();
1030

12
  if (!queues_are_empty ||
1031
6
      per_process::enabled_debug_list.enabled(DebugCategory::MKSNAPSHOT)) {
1032
    PrintLibuvHandleInformation(env->event_loop(), stderr);
1033
  }
1034
6
  if (!queues_are_empty) {
1035
    return SNAPSHOT_ERROR;
1036
  }
1037
6
  return 0;
1038
}
1039
1040
6
int SnapshotBuilder::Generate(std::ostream& out,
1041
                              const std::vector<std::string> args,
1042
                              const std::vector<std::string> exec_args) {
1043
12
  SnapshotData data;
1044
6
  int exit_code = Generate(&data, args, exec_args);
1045
6
  if (exit_code != 0) {
1046
    return exit_code;
1047
  }
1048
6
  FormatBlob(out, &data);
1049
6
  return exit_code;
1050
}
1051
1052
26448
SnapshotableObject::SnapshotableObject(Environment* env,
1053
                                       Local<Object> wrap,
1054
26448
                                       EmbedderObjectType type)
1055
26448
    : BaseObject(env, wrap), type_(type) {
1056
26448
}
1057
1058
24
const char* SnapshotableObject::GetTypeNameChars() const {
1059

24
  switch (type_) {
1060
#define V(PropertyName, NativeTypeName)                                        \
1061
  case EmbedderObjectType::k_##PropertyName: {                                 \
1062
    return NativeTypeName::type_name.c_str();                                  \
1063
  }
1064
24
    SERIALIZABLE_OBJECT_TYPES(V)
1065
#undef V
1066
    default: { UNREACHABLE(); }
1067
  }
1068
}
1069
1070
24
bool IsSnapshotableType(FastStringKey key) {
1071
#define V(PropertyName, NativeTypeName)                                        \
1072
  if (key == NativeTypeName::type_name) {                                      \
1073
    return true;                                                               \
1074
  }
1075


24
  SERIALIZABLE_OBJECT_TYPES(V)
1076
#undef V
1077
1078
  return false;
1079
}
1080
1081
21228
void DeserializeNodeInternalFields(Local<Object> holder,
1082
                                   int index,
1083
                                   StartupData payload,
1084
                                   void* env) {
1085
21228
  if (payload.raw_size == 0) {
1086
    holder->SetAlignedPointerInInternalField(index, nullptr);
1087
    return;
1088
  }
1089
  per_process::Debug(DebugCategory::MKSNAPSHOT,
1090
                     "Deserialize internal field %d of %p, size=%d\n",
1091
42456
                     static_cast<int>(index),
1092
21228
                     (*holder),
1093
21228
                     static_cast<int>(payload.raw_size));
1094
21228
  Environment* env_ptr = static_cast<Environment*>(env);
1095
21228
  const InternalFieldInfo* info =
1096
      reinterpret_cast<const InternalFieldInfo*>(payload.data);
1097
1098

21228
  switch (info->type) {
1099
#define V(PropertyName, NativeTypeName)                                        \
1100
  case EmbedderObjectType::k_##PropertyName: {                                 \
1101
    per_process::Debug(DebugCategory::MKSNAPSHOT,                              \
1102
                       "Object %p is %s\n",                                    \
1103
                       (*holder),                                              \
1104
                       NativeTypeName::type_name.c_str());                     \
1105
    env_ptr->EnqueueDeserializeRequest(                                        \
1106
        NativeTypeName::Deserialize, holder, index, info->Copy());             \
1107
    break;                                                                     \
1108
  }
1109
42456
    SERIALIZABLE_OBJECT_TYPES(V)
1110
#undef V
1111
    default: { UNREACHABLE(); }
1112
  }
1113
}
1114
1115
804
StartupData SerializeNodeContextInternalFields(Local<Object> holder,
1116
                                               int index,
1117
                                               void* env) {
1118
804
  void* ptr = holder->GetAlignedPointerFromInternalField(BaseObject::kSlot);
1119
804
  if (ptr == nullptr) {
1120
780
    return StartupData{nullptr, 0};
1121
  }
1122
  per_process::Debug(DebugCategory::MKSNAPSHOT,
1123
                     "Serialize internal field, index=%d, holder=%p\n",
1124
48
                     static_cast<int>(index),
1125
24
                     *holder);
1126
  DCHECK(static_cast<BaseObject*>(ptr)->is_snapshotable());
1127
24
  SnapshotableObject* obj = static_cast<SnapshotableObject*>(ptr);
1128
  per_process::Debug(DebugCategory::MKSNAPSHOT,
1129
                     "Object %p is %s, ",
1130
24
                     *holder,
1131
24
                     obj->GetTypeNameChars());
1132
24
  InternalFieldInfo* info = obj->Serialize(index);
1133
  per_process::Debug(DebugCategory::MKSNAPSHOT,
1134
                     "payload size=%d\n",
1135
24
                     static_cast<int>(info->length));
1136
  return StartupData{reinterpret_cast<const char*>(info),
1137
24
                     static_cast<int>(info->length)};
1138
}
1139
1140
6
void SerializeBindingData(Environment* env,
1141
                          SnapshotCreator* creator,
1142
                          EnvSerializeInfo* info) {
1143
6
  uint32_t i = 0;
1144
6
  env->ForEachBindingData([&](FastStringKey key,
1145
24
                              BaseObjectPtr<BaseObject> binding) {
1146
    per_process::Debug(DebugCategory::MKSNAPSHOT,
1147
                       "Serialize binding %i, %p, type=%s\n",
1148
96
                       static_cast<int>(i),
1149
48
                       *(binding->object()),
1150
24
                       key.c_str());
1151
1152
24
    if (IsSnapshotableType(key)) {
1153
24
      SnapshotIndex index = creator->AddData(env->context(), binding->object());
1154
      per_process::Debug(DebugCategory::MKSNAPSHOT,
1155
                         "Serialized with index=%d\n",
1156
24
                         static_cast<int>(index));
1157
24
      info->bindings.push_back({key.c_str(), i, index});
1158
24
      SnapshotableObject* ptr = static_cast<SnapshotableObject*>(binding.get());
1159
24
      ptr->PrepareForSerialization(env->context(), creator);
1160
    } else {
1161
      UNREACHABLE();
1162
    }
1163
1164
24
    i++;
1165
24
  });
1166
6
}
1167
1168
namespace mksnapshot {
1169
1170
1
void CompileSerializeMain(const FunctionCallbackInfo<Value>& args) {
1171
2
  CHECK(args[0]->IsString());
1172
2
  Local<String> filename = args[0].As<String>();
1173
2
  Local<String> source = args[1].As<String>();
1174
1
  Isolate* isolate = args.GetIsolate();
1175
1
  Local<Context> context = isolate->GetCurrentContext();
1176
1
  ScriptOrigin origin(isolate, filename, 0, 0, true);
1177
  // TODO(joyeecheung): do we need all of these? Maybe we would want a less
1178
  // internal version of them.
1179
  std::vector<Local<String>> parameters = {
1180
1
      FIXED_ONE_BYTE_STRING(isolate, "require"),
1181
1
      FIXED_ONE_BYTE_STRING(isolate, "__filename"),
1182
1
      FIXED_ONE_BYTE_STRING(isolate, "__dirname"),
1183
3
  };
1184
1
  ScriptCompiler::Source script_source(source, origin);
1185
  Local<Function> fn;
1186
1
  if (ScriptCompiler::CompileFunctionInContext(context,
1187
                                               &script_source,
1188
                                               parameters.size(),
1189
                                               parameters.data(),
1190
                                               0,
1191
                                               nullptr,
1192
1
                                               ScriptCompiler::kEagerCompile)
1193
1
          .ToLocal(&fn)) {
1194
2
    args.GetReturnValue().Set(fn);
1195
  }
1196
1
}
1197
1198
1
void SetSerializeCallback(const FunctionCallbackInfo<Value>& args) {
1199
1
  Environment* env = Environment::GetCurrent(args);
1200
2
  CHECK(env->snapshot_serialize_callback().IsEmpty());
1201
1
  CHECK(args[0]->IsFunction());
1202
2
  env->set_snapshot_serialize_callback(args[0].As<Function>());
1203
1
}
1204
1205
void SetDeserializeCallback(const FunctionCallbackInfo<Value>& args) {
1206
  Environment* env = Environment::GetCurrent(args);
1207
  CHECK(env->snapshot_deserialize_callback().IsEmpty());
1208
  CHECK(args[0]->IsFunction());
1209
  env->set_snapshot_deserialize_callback(args[0].As<Function>());
1210
}
1211
1212
void SetDeserializeMainFunction(const FunctionCallbackInfo<Value>& args) {
1213
  Environment* env = Environment::GetCurrent(args);
1214
  CHECK(env->snapshot_deserialize_main().IsEmpty());
1215
  CHECK(args[0]->IsFunction());
1216
  env->set_snapshot_deserialize_main(args[0].As<Function>());
1217
}
1218
1219
1305
void Initialize(Local<Object> target,
1220
                Local<Value> unused,
1221
                Local<Context> context,
1222
                void* priv) {
1223
1305
  SetMethod(context, target, "compileSerializeMain", CompileSerializeMain);
1224
1305
  SetMethod(context, target, "setSerializeCallback", SetSerializeCallback);
1225
1305
  SetMethod(context, target, "setDeserializeCallback", SetDeserializeCallback);
1226
1305
  SetMethod(context,
1227
            target,
1228
            "setDeserializeMainFunction",
1229
            SetDeserializeMainFunction);
1230
1305
}
1231
1232
5314
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1233
5314
  registry->Register(CompileSerializeMain);
1234
5314
  registry->Register(SetSerializeCallback);
1235
5314
  registry->Register(SetDeserializeCallback);
1236
5314
  registry->Register(SetDeserializeMainFunction);
1237
5314
}
1238
}  // namespace mksnapshot
1239
}  // namespace node
1240
1241
5386
NODE_MODULE_CONTEXT_AWARE_INTERNAL(mksnapshot, node::mksnapshot::Initialize)
1242
5314
NODE_MODULE_EXTERNAL_REFERENCE(mksnapshot,
1243
                               node::mksnapshot::RegisterExternalReferences)