Repository navigation
Expand file tree
/
Copy pathembed_helpers.cc
More file actions
528 lines (456 loc) Β· 17.5 KB
/
Copy pathembed_helpers.cc
File metadata and controls
528 lines (456 loc) Β· 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#include <cstdio>
#include <cstdlib>
#include "debug_utils-inl.h"
#include "env-inl.h"
#include "node.h"
#include "node_internals.h"
#include "node_snapshot_builder.h"
using v8::Context;
using v8::Function;
using v8::Global;
using v8::HandleScope;
using v8::Isolate;
using v8::Just;
using v8::Local;
using v8::Locker;
using v8::Maybe;
using v8::Nothing;
using v8::SealHandleScope;
using v8::SnapshotCreator;
using v8::TryCatch;
namespace node {
#if defined(NODE_USE_V8SHIM)
extern "C" int v8shim_wait_host_tasks(void);
// The host engine runs microtasks only when no JS is on the stack, so when
// uv_run() returns some may still be queued (a promise the host settled while
// the loop was waiting, say). Run them and the ticks they schedule before
// deciding that the loop is done, as V8 would have run them already. Returns
// whether the loop has work again.
static bool SettleHostWork(Environment* env) {
Isolate* isolate = env->isolate();
HandleScope handle_scope(isolate);
Local<Context> context = env->context();
TickInfo* tick_info = env->tick_info();
for (;;) {
context->GetMicrotaskQueue()->PerformCheckpoint(isolate);
if (env->is_stopping() || !env->can_call_into_js()) return false;
if (!tick_info->has_tick_scheduled() && !tick_info->has_rejection_to_warn())
break;
if (env->tick_callback_function()
->Call(context, env->process_object(), 0, nullptr)
.IsEmpty())
return false;
}
if (uv_loop_alive(env->event_loop())) return true;
return v8shim_wait_host_tasks() != 0;
}
extern "C" int v8shim_event_loop_parks(void);
extern "C" [[noreturn]] void v8shim_park_thread(void);
extern "C" int32_t v8shim_host_tasks_pending(void);
static Maybe<ExitCode> FinishEventLoop(Environment* env);
namespace {
// The main thread's loop, parked for the host to turn (an engine without JSPI:
// see event_loop_parks in deps/v8shim/src/host.h).
struct ParkedLoop {
Environment* env = nullptr;
MultiIsolatePlatform* platform = nullptr;
// Wakes a blocking turn's poll so the host gets the thread back now and then
// for its own work (messages from other threads, say). Unreferenced: it does
// not keep the loop alive.
uv_timer_t wake;
// The last turn found the loop with nothing left. One more turn after the
// host has run its microtasks tells whether they gave it work again.
bool drained = false;
};
ParkedLoop parked_loop;
constexpr uint64_t kParkedWakeMs = 100;
// What node_event_loop_turn returns.
constexpr int32_t kTurnAgain = 0; // work is ready: turn again right away
constexpr int32_t kTurnIdle = 1; // waiting: the next turn may block
constexpr int32_t kTurnHostTasks = 2; // only the host's pending work is left
} // namespace
// One turn of the parked loop, for the host to call with no JavaScript on the
// stack, after it has run the microtasks the previous turn queued. With
// `may_block`, the turn waits in poll() for what comes next (at most
// kParkedWakeMs). When the loop is done, the process exits from here.
extern "C" __attribute__((export_name("node_event_loop_turn"))) int32_t
node_event_loop_turn(int32_t may_block) {
Environment* env = parked_loop.env;
Isolate* isolate = env->isolate();
HandleScope handle_scope(isolate);
Context::Scope context_scope(env->context());
TickInfo* tick_info = env->tick_info();
uv_loop_t* loop = env->event_loop();
// The host ran the microtasks between the turns; process.nextTick() calls
// they made wait for node's tick callback, as after any callback into JS.
if (!env->is_stopping() &&
(tick_info->has_tick_scheduled() || tick_info->has_rejection_to_warn())) {
parked_loop.drained = false;
if (env->tick_callback_function()
->Call(env->context(), env->process_object(), 0, nullptr)
.IsEmpty() ||
env->is_stopping()) {
exit(static_cast<int>(FinishEventLoop(env).FromMaybe(
ExitCode::kGenericUserError)));
}
return kTurnAgain;
}
// The previous turn found the loop with nothing left, and the host has run
// the microtasks since: decide only now, with no callback run in between
// (one could queue microtasks that give the loop work again).
if (parked_loop.drained && !env->is_stopping() && !uv_loop_alive(loop) &&
v8shim_host_tasks_pending() == 0) {
parked_loop.drained = false;
// Emit `beforeExit`; the loop goes on if that gave it work.
if (EmitProcessBeforeExit(env).IsJust() && !env->is_stopping()) {
HandleScope handle_scope(isolate);
if (!env->RunSnapshotSerializeCallback().IsEmpty() &&
uv_loop_alive(loop) && !env->is_stopping())
return kTurnAgain;
}
exit(static_cast<int>(
FinishEventLoop(env).FromMaybe(ExitCode::kGenericUserError)));
}
parked_loop.drained = false;
if (!env->is_stopping()) {
if (may_block)
uv_timer_start(&parked_loop.wake, [](uv_timer_t*) {}, kParkedWakeMs, 0);
uv_run(loop, may_block ? UV_RUN_ONCE : UV_RUN_NOWAIT);
uv_timer_stop(&parked_loop.wake);
}
if (!env->is_stopping()) parked_loop.platform->DrainTasks(isolate);
if (!env->is_stopping()) {
if (uv_loop_alive(loop))
return uv_backend_timeout(loop) == 0 ? kTurnAgain : kTurnIdle;
if (v8shim_host_tasks_pending() != 0) return kTurnHostTasks;
// Nothing left as far as the loop knows; the callbacks just run may have
// queued microtasks that change that. Let the host run them first.
parked_loop.drained = true;
return kTurnAgain;
}
exit(static_cast<int>(
FinishEventLoop(env).FromMaybe(ExitCode::kGenericUserError)));
}
#endif
Maybe<ExitCode> SpinEventLoopInternal(Environment* env) {
CHECK_NOT_NULL(env);
MultiIsolatePlatform* platform = GetMultiIsolatePlatform(env);
CHECK_NOT_NULL(platform);
Isolate* isolate = env->isolate();
HandleScope handle_scope(isolate);
Context::Scope context_scope(env->context());
SealHandleScope seal(isolate);
if (env->is_stopping()) return Nothing<ExitCode>();
env->set_trace_sync_io(env->options()->trace_sync_io);
{
bool more;
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
#if defined(NODE_USE_V8SHIM)
// Without JSPI the thread cannot wait for the host's microtasks and events
// inside this loop: hand the loop to the host, which turns it from outside
// (node_event_loop_turn). Only the main thread does: it ends the process
// with exit(), while a worker's thread has its own ending to go through.
// A worker's thread has no such way out yet: say so and end it rather
// than leave its messages unanswered for good.
if (!env->is_main_thread() && v8shim_event_loop_parks()) {
fprintf(stderr,
"browser-nodev2: worker_threads needs JSPI "
"(WebAssembly.Suspending), which this browser does not have\n");
return Just(ExitCode::kGenericUserError);
}
if (env->is_main_thread() && v8shim_event_loop_parks()) {
parked_loop.env = env;
parked_loop.platform = platform;
uv_timer_init(env->event_loop(), &parked_loop.wake);
uv_unref(reinterpret_cast<uv_handle_t*>(&parked_loop.wake));
v8shim_park_thread();
}
#endif
do {
if (env->is_stopping()) break;
uv_run(env->event_loop(), UV_RUN_DEFAULT);
if (env->is_stopping()) break;
platform->DrainTasks(isolate);
more = uv_loop_alive(env->event_loop());
if (more && !env->is_stopping()) continue;
#if defined(NODE_USE_V8SHIM)
// Queued host microtasks first, then the host's pending work (an async
// WebAssembly compile, an import()): DrainTasks waits for V8's own.
// (`continue` in this do-while checks `more`.)
if (SettleHostWork(env) && !env->is_stopping()) {
more = true;
continue;
}
#endif
if (EmitProcessBeforeExit(env).IsNothing())
break;
{
HandleScope handle_scope(isolate);
if (env->RunSnapshotSerializeCallback().IsEmpty()) {
break;
}
}
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
} while (more == true && !env->is_stopping());
}
#if defined(NODE_USE_V8SHIM)
return FinishEventLoop(env);
}
// What follows the loop: shared with the parked loop's last turn.
static Maybe<ExitCode> FinishEventLoop(Environment* env) {
#endif
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
if (env->is_stopping()) return Nothing<ExitCode>();
env->set_trace_sync_io(false);
// Clear the serialize callback even though the JS-land queue should
// be empty this point so that the deserialized instance won't
// attempt to call into JS again.
env->set_snapshot_serialize_callback(Local<Function>());
env->PrintInfoForSnapshotIfDebug();
env->ForEachRealm([](Realm* realm) { realm->VerifyNoStrongBaseObjects(); });
return EmitProcessExitInternal(env);
}
struct CommonEnvironmentSetup::Impl {
MultiIsolatePlatform* platform = nullptr;
uv_loop_t loop;
std::shared_ptr<ArrayBufferAllocator> allocator;
std::optional<SnapshotCreator> snapshot_creator;
Isolate* isolate = nullptr;
DeleteFnPtr<IsolateData, FreeIsolateData> isolate_data;
DeleteFnPtr<Environment, FreeEnvironment> env;
Global<Context> main_context;
};
CommonEnvironmentSetup::CommonEnvironmentSetup(
MultiIsolatePlatform* platform,
std::vector<std::string>* errors,
const EmbedderSnapshotData* snapshot_data,
uint32_t flags,
std::function<Environment*(const CommonEnvironmentSetup*)> make_env,
const SnapshotConfig* snapshot_config)
: impl_(new Impl()) {
CHECK_NOT_NULL(platform);
CHECK_NOT_NULL(errors);
impl_->platform = platform;
uv_loop_t* loop = &impl_->loop;
// Use `data` to tell the destructor whether the loop was initialized or not.
loop->data = nullptr;
int ret = uv_loop_init(loop);
if (ret != 0) {
errors->push_back(
SPrintF("Failed to initialize loop: %s", uv_err_name(ret)));
return;
}
loop->data = this;
impl_->allocator = ArrayBufferAllocator::Create();
const std::vector<intptr_t>& external_references =
SnapshotBuilder::CollectExternalReferences();
Isolate::CreateParams params;
params.array_buffer_allocator = impl_->allocator.get();
params.external_references = external_references.data();
Isolate* isolate;
// Isolates created for snapshotting should be set up differently since
// it will be owned by the snapshot creator and needs to be cleaned up
// before serialization.
if (flags & Flags::kIsForSnapshotting) {
// The isolate must be registered before the SnapshotCreator initializes the
// isolate, so that the memory reducer can be initialized.
isolate = impl_->isolate = Isolate::Allocate(GetOrCreateIsolateGroup());
platform->RegisterIsolate(isolate, loop);
params.cpp_heap =
v8::CppHeap::Create(platform, v8::CppHeapCreateParams{{}}).release();
impl_->snapshot_creator.emplace(isolate, params);
isolate->SetCaptureStackTraceForUncaughtExceptions(
true,
static_cast<int>(
per_process::cli_options->per_isolate->stack_trace_limit),
v8::StackTrace::StackTraceOptions::kDetailed);
SetIsolateMiscHandlers(isolate, {});
} else {
isolate = impl_->isolate =
NewIsolate(¶ms,
&impl_->loop,
platform,
SnapshotData::FromEmbedderWrapper(snapshot_data));
}
{
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
TryCatch bootstrapCatch(isolate);
auto print_Exception = OnScopeLeave([&]() {
if (bootstrapCatch.HasCaught()) {
errors->push_back(FormatCaughtException(
isolate, isolate->GetCurrentContext(), bootstrapCatch));
}
});
impl_->isolate_data.reset(CreateIsolateData(
isolate, loop, platform, impl_->allocator.get(), snapshot_data));
impl_->isolate_data->set_snapshot_config(snapshot_config);
if (snapshot_data) {
impl_->env.reset(make_env(this));
if (impl_->env) {
impl_->main_context.Reset(isolate, impl_->env->context());
}
return;
}
Local<Context> context = NewContext(isolate);
impl_->main_context.Reset(isolate, context);
if (context.IsEmpty()) {
errors->push_back("Failed to initialize V8 Context");
return;
}
Context::Scope context_scope(context);
impl_->env.reset(make_env(this));
}
}
CommonEnvironmentSetup::CommonEnvironmentSetup(
MultiIsolatePlatform* platform,
std::vector<std::string>* errors,
std::function<Environment*(const CommonEnvironmentSetup*)> make_env)
: CommonEnvironmentSetup(platform, errors, nullptr, false, make_env) {}
std::unique_ptr<CommonEnvironmentSetup>
CommonEnvironmentSetup::CreateForSnapshotting(
MultiIsolatePlatform* platform,
std::vector<std::string>* errors,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args,
const SnapshotConfig& snapshot_config) {
// It's not guaranteed that a context that goes through
// v8_inspector::V8Inspector::contextCreated() is runtime-independent,
// so do not start the inspector on the main context when building
// the default snapshot.
uint64_t env_flags =
EnvironmentFlags::kDefaultFlags | EnvironmentFlags::kNoCreateInspector;
auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
platform,
errors,
nullptr,
true,
[&](const CommonEnvironmentSetup* setup) -> Environment* {
return CreateEnvironment(
setup->isolate_data(),
setup->context(),
args,
exec_args,
static_cast<EnvironmentFlags::Flags>(env_flags));
},
&snapshot_config));
if (!errors->empty()) ret.reset();
return ret;
}
CommonEnvironmentSetup::~CommonEnvironmentSetup() {
if (impl_->isolate != nullptr) {
Isolate* isolate = impl_->isolate;
{
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
impl_->main_context.Reset();
impl_->env.reset();
impl_->isolate_data.reset();
}
bool platform_finished = false;
impl_->platform->AddIsolateFinishedCallback(
isolate,
[](void* data) {
bool* ptr = static_cast<bool*>(data);
*ptr = true;
},
&platform_finished);
if (impl_->snapshot_creator.has_value()) {
impl_->snapshot_creator.reset();
}
impl_->platform->DisposeIsolate(isolate);
// Wait until the platform has cleaned up all relevant resources.
while (!platform_finished)
uv_run(&impl_->loop, UV_RUN_ONCE);
}
if (impl_->isolate || impl_->loop.data != nullptr)
CheckedUvLoopClose(&impl_->loop);
delete impl_;
}
EmbedderSnapshotData::Pointer CommonEnvironmentSetup::CreateSnapshot() {
CHECK_NOT_NULL(snapshot_creator());
SnapshotData* snapshot_data = new SnapshotData();
EmbedderSnapshotData::Pointer result{
new EmbedderSnapshotData(snapshot_data, true)};
auto exit_code = SnapshotBuilder::CreateSnapshot(snapshot_data, this);
if (exit_code != ExitCode::kNoFailure) return {};
return result;
}
Maybe<int> SpinEventLoop(Environment* env) {
Maybe<ExitCode> result = SpinEventLoopInternal(env);
if (result.IsNothing()) {
return Nothing<int>();
}
return Just(static_cast<int>(result.FromJust()));
}
uv_loop_t* CommonEnvironmentSetup::event_loop() const {
return &impl_->loop;
}
std::shared_ptr<ArrayBufferAllocator>
CommonEnvironmentSetup::array_buffer_allocator() const {
return impl_->allocator;
}
Isolate* CommonEnvironmentSetup::isolate() const {
return impl_->isolate;
}
IsolateData* CommonEnvironmentSetup::isolate_data() const {
return impl_->isolate_data.get();
}
Environment* CommonEnvironmentSetup::env() const {
return impl_->env.get();
}
v8::Local<v8::Context> CommonEnvironmentSetup::context() const {
return impl_->main_context.Get(impl_->isolate);
}
v8::SnapshotCreator* CommonEnvironmentSetup::snapshot_creator() {
return impl_->snapshot_creator ? &impl_->snapshot_creator.value() : nullptr;
}
void EmbedderSnapshotData::DeleteSnapshotData::operator()(
const EmbedderSnapshotData* data) const {
CHECK_IMPLIES(data->owns_impl_, data->impl_);
if (data->owns_impl_ &&
data->impl_->data_ownership == SnapshotData::DataOwnership::kOwned) {
delete data->impl_;
}
delete data;
}
EmbedderSnapshotData::Pointer EmbedderSnapshotData::BuiltinSnapshotData() {
return EmbedderSnapshotData::Pointer{new EmbedderSnapshotData(
SnapshotBuilder::GetEmbeddedSnapshotData(), false)};
}
EmbedderSnapshotData::Pointer EmbedderSnapshotData::FromBlob(
const std::vector<char>& in) {
return FromBlob(std::string_view(in.data(), in.size()));
}
EmbedderSnapshotData::Pointer EmbedderSnapshotData::FromBlob(
std::string_view in) {
SnapshotData* snapshot_data = new SnapshotData();
CHECK_EQ(snapshot_data->data_ownership, SnapshotData::DataOwnership::kOwned);
EmbedderSnapshotData::Pointer result{
new EmbedderSnapshotData(snapshot_data, true)};
if (!SnapshotData::FromBlob(snapshot_data, in)) {
return {};
}
return result;
}
EmbedderSnapshotData::Pointer EmbedderSnapshotData::FromFile(FILE* in) {
return FromBlob(ReadFileSync(in));
}
std::vector<char> EmbedderSnapshotData::ToBlob() const {
return impl_->ToBlob();
}
void EmbedderSnapshotData::ToFile(FILE* out) const {
impl_->ToFile(out);
}
EmbedderSnapshotData::EmbedderSnapshotData(const SnapshotData* impl,
bool owns_impl)
: impl_(impl), owns_impl_(owns_impl) {}
bool EmbedderSnapshotData::CanUseCustomSnapshotPerIsolate() {
return false;
}
} // namespace node