GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: async_wrap.cc Lines: 284 305 93.1 %
Date: 2022-02-16 04:15:12 Branches: 804 1408 57.1 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "async_wrap.h"  // NOLINT(build/include_inline)
23
#include "async_wrap-inl.h"
24
#include "env-inl.h"
25
#include "node_errors.h"
26
#include "node_external_reference.h"
27
#include "tracing/traced_value.h"
28
#include "util-inl.h"
29
30
#include "v8.h"
31
32
using v8::Context;
33
using v8::DontDelete;
34
using v8::EscapableHandleScope;
35
using v8::Function;
36
using v8::FunctionCallbackInfo;
37
using v8::FunctionTemplate;
38
using v8::Global;
39
using v8::HandleScope;
40
using v8::Integer;
41
using v8::Isolate;
42
using v8::Local;
43
using v8::MaybeLocal;
44
using v8::Nothing;
45
using v8::Number;
46
using v8::Object;
47
using v8::PropertyAttribute;
48
using v8::ReadOnly;
49
using v8::String;
50
using v8::Undefined;
51
using v8::Value;
52
using v8::WeakCallbackInfo;
53
using v8::WeakCallbackType;
54
55
using TryCatchScope = node::errors::TryCatchScope;
56
57
namespace node {
58
59
static const char* const provider_names[] = {
60
#define V(PROVIDER)                                                           \
61
  #PROVIDER,
62
  NODE_ASYNC_PROVIDER_TYPES(V)
63
#undef V
64
};
65
66
24178
void AsyncWrap::DestroyAsyncIdsCallback(Environment* env) {
67
24178
  Local<Function> fn = env->async_hooks_destroy_function();
68
69
24178
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
70
71
2
  do {
72
24180
    std::vector<double> destroy_async_id_list;
73
24180
    destroy_async_id_list.swap(*env->destroy_async_id_list());
74
24180
    if (!env->can_call_into_js()) return;
75
143492
    for (auto async_id : destroy_async_id_list) {
76
      // Want each callback to be cleaned up after itself, instead of cleaning
77
      // them all up after the while() loop completes.
78
119314
      HandleScope scope(env->isolate());
79
238628
      Local<Value> async_id_value = Number::New(env->isolate(), async_id);
80
      MaybeLocal<Value> ret = fn->Call(
81
238628
          env->context(), Undefined(env->isolate()), 1, &async_id_value);
82
83
119312
      if (ret.IsEmpty())
84
        return;
85
    }
86
24178
  } while (!env->destroy_async_id_list()->empty());
87
}
88
89
991753
void Emit(Environment* env, double async_id, AsyncHooks::Fields type,
90
          Local<Function> fn) {
91
991753
  AsyncHooks* async_hooks = env->async_hooks();
92
93

991753
  if (async_hooks->fields()[type] == 0 || !env->can_call_into_js())
94
991421
    return;
95
96
664
  HandleScope handle_scope(env->isolate());
97
332
  Local<Value> async_id_value = Number::New(env->isolate(), async_id);
98
332
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
99
664
  USE(fn->Call(env->context(), Undefined(env->isolate()), 1, &async_id_value));
100
}
101
102
103
void AsyncWrap::EmitPromiseResolve(Environment* env, double async_id) {
104
  Emit(env, async_id, AsyncHooks::kPromiseResolve,
105
       env->async_hooks_promise_resolve_function());
106
}
107
108
109
356949
void AsyncWrap::EmitTraceEventBefore() {
110














356949
  switch (provider_type()) {
111
#define V(PROVIDER)                                                           \
112
    case PROVIDER_ ## PROVIDER:                                               \
113
      TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(                                      \
114
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
115
        #PROVIDER "_CALLBACK", static_cast<int64_t>(get_async_id()));         \
116
      break;
117


























































723063
    NODE_ASYNC_PROVIDER_TYPES(V)
118
#undef V
119
    default:
120
      UNREACHABLE();
121
  }
122
356949
}
123
124
125
495913
void AsyncWrap::EmitBefore(Environment* env, double async_id) {
126
495913
  Emit(env, async_id, AsyncHooks::kBefore,
127
       env->async_hooks_before_function());
128
495913
}
129
130
131
356812
void AsyncWrap::EmitTraceEventAfter(ProviderType type, double async_id) {
132














356812
  switch (type) {
133
#define V(PROVIDER)                                                           \
134
    case PROVIDER_ ## PROVIDER:                                               \
135
      TRACE_EVENT_NESTABLE_ASYNC_END0(                                        \
136
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
137
        #PROVIDER "_CALLBACK", static_cast<int64_t>(async_id));               \
138
      break;
139


























































722742
    NODE_ASYNC_PROVIDER_TYPES(V)
140
#undef V
141
    default:
142
      UNREACHABLE();
143
  }
144
356812
}
145
146
147
495840
void AsyncWrap::EmitAfter(Environment* env, double async_id) {
148
  // If the user's callback failed then the after() hooks will be called at the
149
  // end of _fatalException().
150
495840
  Emit(env, async_id, AsyncHooks::kAfter,
151
       env->async_hooks_after_function());
152
495840
}
153
154
620
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
155
620
  Environment* env = Environment::GetCurrent(args);
156
157
620
  CHECK(args[0]->IsObject());
158
159
  // All of init, before, after, destroy, and promise_resolve are supplied by
160
  // async_hooks internally, so this should only ever be called once. At which
161
  // time all the functions should be set. Detect this by checking if
162
  // init !IsEmpty().
163
1240
  CHECK(env->async_hooks_init_function().IsEmpty());
164
165
1240
  Local<Object> fn_obj = args[0].As<Object>();
166
167
#define SET_HOOK_FN(name)                                                      \
168
  do {                                                                         \
169
    Local<Value> v =                                                           \
170
        fn_obj->Get(env->context(),                                            \
171
                    FIXED_ONE_BYTE_STRING(env->isolate(), #name))              \
172
            .ToLocalChecked();                                                 \
173
    CHECK(v->IsFunction());                                                    \
174
    env->set_async_hooks_##name##_function(v.As<Function>());                  \
175
  } while (0)
176
177
2480
  SET_HOOK_FN(init);
178
2480
  SET_HOOK_FN(before);
179
2480
  SET_HOOK_FN(after);
180
3100
  SET_HOOK_FN(destroy);
181
2480
  SET_HOOK_FN(promise_resolve);
182
#undef SET_HOOK_FN
183
620
}
184
185
17160
static void SetPromiseHooks(const FunctionCallbackInfo<Value>& args) {
186
17160
  Environment* env = Environment::GetCurrent(args);
187
188


94798
  env->async_hooks()->SetJSPromiseHooks(
189
26158
    args[0]->IsFunction() ? args[0].As<Function>() : Local<Function>(),
190
25896
    args[1]->IsFunction() ? args[1].As<Function>() : Local<Function>(),
191
25607
    args[2]->IsFunction() ? args[2].As<Function>() : Local<Function>(),
192
17385
    args[3]->IsFunction() ? args[3].As<Function>() : Local<Function>());
193
17160
}
194
195
class DestroyParam {
196
 public:
197
  double asyncId;
198
  Environment* env;
199
  Global<Object> target;
200
  Global<Object> propBag;
201
};
202
203
99
static void DestroyParamCleanupHook(void* ptr) {
204
99
  delete static_cast<DestroyParam*>(ptr);
205
99
}
206
207
24789
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
208
24789
  HandleScope scope(info.GetIsolate());
209
210
24789
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
211
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
212
24789
                                                      p->propBag);
213
  Local<Value> val;
214
215
24789
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
216
217
49578
  if (!prop_bag->Get(p->env->context(), p->env->destroyed_string())
218
24789
        .ToLocal(&val)) {
219
    return;
220
  }
221
222
24789
  if (val->IsFalse()) {
223
24782
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
224
  }
225
  // unique_ptr goes out of scope here and pointer is deleted.
226
}
227
228
229
25625
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
230
25625
  CHECK(args[0]->IsObject());
231
25625
  CHECK(args[1]->IsNumber());
232
25625
  CHECK(args[2]->IsObject());
233
234
25625
  Isolate* isolate = args.GetIsolate();
235
25625
  DestroyParam* p = new DestroyParam();
236
51250
  p->asyncId = args[1].As<Number>()->Value();
237
25625
  p->env = Environment::GetCurrent(args);
238
76875
  p->target.Reset(isolate, args[0].As<Object>());
239
76875
  p->propBag.Reset(isolate, args[2].As<Object>());
240
25625
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
241
25625
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
242
25625
}
243
244
97283
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
245
  AsyncWrap* wrap;
246
194566
  args.GetReturnValue().Set(kInvalidAsyncId);
247
97283
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
248
194524
  args.GetReturnValue().Set(wrap->get_async_id());
249
}
250
251
252
4
void AsyncWrap::PushAsyncContext(const FunctionCallbackInfo<Value>& args) {
253
4
  Environment* env = Environment::GetCurrent(args);
254
  // No need for CHECK(IsNumber()) on args because if FromJust() doesn't fail
255
  // then the checks in push_async_ids() and pop_async_id() will.
256
8
  double async_id = args[0]->NumberValue(env->context()).FromJust();
257
4
  double trigger_async_id = args[1]->NumberValue(env->context()).FromJust();
258
4
  env->async_hooks()->push_async_context(async_id, trigger_async_id, {});
259
4
}
260
261
262
3
void AsyncWrap::PopAsyncContext(const FunctionCallbackInfo<Value>& args) {
263
3
  Environment* env = Environment::GetCurrent(args);
264
6
  double async_id = args[0]->NumberValue(env->context()).FromJust();
265
3
  args.GetReturnValue().Set(env->async_hooks()->pop_async_context(async_id));
266
}
267
268
269
2401
void AsyncWrap::ExecutionAsyncResource(
270
    const FunctionCallbackInfo<Value>& args) {
271
2401
  Environment* env = Environment::GetCurrent(args);
272
  uint32_t index;
273
4802
  if (!args[0]->Uint32Value(env->context()).To(&index)) return;
274
4802
  args.GetReturnValue().Set(
275
      env->async_hooks()->native_execution_async_resource(index));
276
}
277
278
279
1257
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
280
1257
  Environment* env = Environment::GetCurrent(args);
281
1257
  env->async_hooks()->clear_async_id_stack();
282
1257
}
283
284
285
264
void AsyncWrap::AsyncReset(const FunctionCallbackInfo<Value>& args) {
286
264
  CHECK(args[0]->IsObject());
287
288
  AsyncWrap* wrap;
289
264
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
290
291
528
  Local<Object> resource = args[0].As<Object>();
292
  double execution_async_id =
293
264
      args[1]->IsNumber() ? args[1].As<Number>()->Value() : kInvalidAsyncId;
294
264
  wrap->AsyncReset(resource, execution_async_id);
295
}
296
297
298
264
void AsyncWrap::GetProviderType(const FunctionCallbackInfo<Value>& args) {
299
  AsyncWrap* wrap;
300
528
  args.GetReturnValue().Set(AsyncWrap::PROVIDER_NONE);
301
264
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
302
528
  args.GetReturnValue().Set(wrap->provider_type());
303
}
304
305
306
209451
void AsyncWrap::EmitDestroy(bool from_gc) {
307
209451
  AsyncWrap::EmitDestroy(env(), async_id_);
308
  // Ensure no double destroy is emitted via AsyncReset().
309
209451
  async_id_ = kInvalidAsyncId;
310
311

209451
  if (!persistent().IsEmpty() && !from_gc) {
312
6557
    HandleScope handle_scope(env()->isolate());
313
26228
    USE(object()->Set(env()->context(), env()->resource_symbol(), object()));
314
  }
315
209451
}
316
317
77964
void AsyncWrap::QueueDestroyAsyncId(const FunctionCallbackInfo<Value>& args) {
318
77964
  CHECK(args[0]->IsNumber());
319
77964
  AsyncWrap::EmitDestroy(
320
      Environment::GetCurrent(args),
321
155928
      args[0].As<Number>()->Value());
322
77964
}
323
324
624
void AsyncWrap::SetCallbackTrampoline(const FunctionCallbackInfo<Value>& args) {
325
624
  Environment* env = Environment::GetCurrent(args);
326
327
624
  if (args[0]->IsFunction()) {
328
914
    env->set_async_hooks_callback_trampoline(args[0].As<Function>());
329
  } else {
330
167
    env->set_async_hooks_callback_trampoline(Local<Function>());
331
  }
332
624
}
333
334
132980
Local<FunctionTemplate> AsyncWrap::GetConstructorTemplate(Environment* env) {
335
132980
  Local<FunctionTemplate> tmpl = env->async_wrap_ctor_template();
336
132980
  if (tmpl.IsEmpty()) {
337
620
    tmpl = env->NewFunctionTemplate(nullptr);
338
620
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "AsyncWrap"));
339
620
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
340
620
    env->SetProtoMethod(tmpl, "getAsyncId", AsyncWrap::GetAsyncId);
341
620
    env->SetProtoMethod(tmpl, "asyncReset", AsyncWrap::AsyncReset);
342
620
    env->SetProtoMethod(tmpl, "getProviderType", AsyncWrap::GetProviderType);
343
620
    env->set_async_wrap_ctor_template(tmpl);
344
  }
345
132980
  return tmpl;
346
}
347
348
620
void AsyncWrap::Initialize(Local<Object> target,
349
                           Local<Value> unused,
350
                           Local<Context> context,
351
                           void* priv) {
352
620
  Environment* env = Environment::GetCurrent(context);
353
620
  Isolate* isolate = env->isolate();
354
1240
  HandleScope scope(isolate);
355
356
620
  env->SetMethod(target, "setupHooks", SetupHooks);
357
620
  env->SetMethod(target, "setCallbackTrampoline", SetCallbackTrampoline);
358
620
  env->SetMethod(target, "pushAsyncContext", PushAsyncContext);
359
620
  env->SetMethod(target, "popAsyncContext", PopAsyncContext);
360
620
  env->SetMethod(target, "executionAsyncResource", ExecutionAsyncResource);
361
620
  env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack);
362
620
  env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId);
363
620
  env->SetMethod(target, "setPromiseHooks", SetPromiseHooks);
364
620
  env->SetMethod(target, "registerDestroyHook", RegisterDestroyHook);
365
366
620
  PropertyAttribute ReadOnlyDontDelete =
367
      static_cast<PropertyAttribute>(ReadOnly | DontDelete);
368
369
#define FORCE_SET_TARGET_FIELD(obj, str, field)                               \
370
  (obj)->DefineOwnProperty(context,                                           \
371
                           FIXED_ONE_BYTE_STRING(isolate, str),               \
372
                           field,                                             \
373
                           ReadOnlyDontDelete).FromJust()
374
375
  // Attach the uint32_t[] where each slot contains the count of the number of
376
  // callbacks waiting to be called on a particular event. It can then be
377
  // incremented/decremented from JS quickly to communicate to C++ if there are
378
  // any callbacks waiting to be called.
379
2480
  FORCE_SET_TARGET_FIELD(target,
380
                         "async_hook_fields",
381
                         env->async_hooks()->fields().GetJSArray());
382
383
  // The following v8::Float64Array has 5 fields. These fields are shared in
384
  // this way to allow JS and C++ to read/write each value as quickly as
385
  // possible. The fields are represented as follows:
386
  //
387
  // kAsyncIdCounter: Maintains the state of the next unique id to be assigned.
388
  //
389
  // kDefaultTriggerAsyncId: Write the id of the resource responsible for a
390
  //   handle's creation just before calling the new handle's constructor.
391
  //   After the new handle is constructed kDefaultTriggerAsyncId is set back
392
  //   to kInvalidAsyncId.
393
2480
  FORCE_SET_TARGET_FIELD(target,
394
                         "async_id_fields",
395
                         env->async_hooks()->async_id_fields().GetJSArray());
396
397
2480
  FORCE_SET_TARGET_FIELD(target,
398
                         "execution_async_resources",
399
                         env->async_hooks()->js_execution_async_resources());
400
401
620
  target->Set(context,
402
              env->async_ids_stack_string(),
403
1860
              env->async_hooks()->async_ids_stack().GetJSArray()).Check();
404
405
620
  Local<Object> constants = Object::New(isolate);
406
#define SET_HOOKS_CONSTANT(name)                                              \
407
  FORCE_SET_TARGET_FIELD(                                                     \
408
      constants, #name, Integer::New(isolate, AsyncHooks::name))
409
410
2480
  SET_HOOKS_CONSTANT(kInit);
411
2480
  SET_HOOKS_CONSTANT(kBefore);
412
2480
  SET_HOOKS_CONSTANT(kAfter);
413
2480
  SET_HOOKS_CONSTANT(kDestroy);
414
2480
  SET_HOOKS_CONSTANT(kPromiseResolve);
415
2480
  SET_HOOKS_CONSTANT(kTotals);
416
2480
  SET_HOOKS_CONSTANT(kCheck);
417
2480
  SET_HOOKS_CONSTANT(kExecutionAsyncId);
418
2480
  SET_HOOKS_CONSTANT(kTriggerAsyncId);
419
2480
  SET_HOOKS_CONSTANT(kAsyncIdCounter);
420
2480
  SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
421
2480
  SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource);
422
2480
  SET_HOOKS_CONSTANT(kStackLength);
423
#undef SET_HOOKS_CONSTANT
424
1240
  FORCE_SET_TARGET_FIELD(target, "constants", constants);
425
426
620
  Local<Object> async_providers = Object::New(isolate);
427
#define V(p)                                                                  \
428
  FORCE_SET_TARGET_FIELD(                                                     \
429
      async_providers, #p, Integer::New(isolate, AsyncWrap::PROVIDER_ ## p));
430
108500
  NODE_ASYNC_PROVIDER_TYPES(V)
431
#undef V
432
1860
  FORCE_SET_TARGET_FIELD(target, "Providers", async_providers);
433
434
#undef FORCE_SET_TARGET_FIELD
435
436
620
  env->set_async_hooks_init_function(Local<Function>());
437
620
  env->set_async_hooks_before_function(Local<Function>());
438
620
  env->set_async_hooks_after_function(Local<Function>());
439
620
  env->set_async_hooks_destroy_function(Local<Function>());
440
620
  env->set_async_hooks_promise_resolve_function(Local<Function>());
441
620
  env->set_async_hooks_callback_trampoline(Local<Function>());
442
620
  env->set_async_hooks_binding(target);
443
620
}
444
445
4938
void AsyncWrap::RegisterExternalReferences(
446
    ExternalReferenceRegistry* registry) {
447
4938
  registry->Register(SetupHooks);
448
4938
  registry->Register(SetCallbackTrampoline);
449
4938
  registry->Register(PushAsyncContext);
450
4938
  registry->Register(PopAsyncContext);
451
4938
  registry->Register(ExecutionAsyncResource);
452
4938
  registry->Register(ClearAsyncIdStack);
453
4938
  registry->Register(QueueDestroyAsyncId);
454
4938
  registry->Register(SetPromiseHooks);
455
4938
  registry->Register(RegisterDestroyHook);
456
4938
  registry->Register(AsyncWrap::GetAsyncId);
457
4938
  registry->Register(AsyncWrap::AsyncReset);
458
4938
  registry->Register(AsyncWrap::GetProviderType);
459
4938
}
460
461
199684
AsyncWrap::AsyncWrap(Environment* env,
462
                     Local<Object> object,
463
                     ProviderType provider,
464
199684
                     double execution_async_id)
465
199684
    : AsyncWrap(env, object, provider, execution_async_id, false) {}
466
467
199684
AsyncWrap::AsyncWrap(Environment* env,
468
                     Local<Object> object,
469
                     ProviderType provider,
470
                     double execution_async_id,
471
199684
                     bool silent)
472
199684
    : AsyncWrap(env, object) {
473
199684
  CHECK_NE(provider, PROVIDER_NONE);
474
199684
  provider_type_ = provider;
475
476
  // Use AsyncReset() call to execute the init() callbacks.
477
199684
  AsyncReset(object, execution_async_id, silent);
478
199684
  init_hook_ran_ = true;
479
199684
}
480
481
AsyncWrap::AsyncWrap(Environment* env,
482
                     Local<Object> object,
483
                     ProviderType provider,
484
                     double execution_async_id,
485
                     double trigger_async_id)
486
    : AsyncWrap(env, object, provider, execution_async_id, true) {
487
  trigger_async_id_ = trigger_async_id;
488
}
489
490
203837
AsyncWrap::AsyncWrap(Environment* env, Local<Object> object)
491
203837
  : BaseObject(env, object) {
492
203837
}
493
494
// This method is necessary to work around one specific problem:
495
// Before the init() hook runs, if there is one, the BaseObject() constructor
496
// registers this object with the Environment for finalization and debugging
497
// purposes.
498
// If the Environment decides to inspect this object for debugging, it tries to
499
// call virtual methods on this object that are only (meaningfully) implemented
500
// by the subclasses of AsyncWrap.
501
// This could, with bad luck, happen during the AsyncWrap() constructor,
502
// because we run JS code as part of it and that in turn can lead to a heapdump
503
// being taken, either through the inspector or our programmatic API for it.
504
// The object being initialized is not fully constructed at that point, and
505
// in particular its virtual function table points to the AsyncWrap one
506
// (as the subclass constructor has not yet begun execution at that point).
507
// This means that the functions that are used for heap dump memory tracking
508
// are not yet available, and trying to call them would crash the process.
509
// We use this particular `IsDoneInitializing()` method to tell the Environment
510
// that such debugging methods are not yet available.
511
// This may be somewhat unreliable when it comes to future changes, because
512
// at this point it *only* protects AsyncWrap subclasses, and *only* for cases
513
// where heap dumps are being taken while the init() hook is on the call stack.
514
// For now, it seems like the best solution, though.
515
203946
bool AsyncWrap::IsDoneInitializing() const {
516
203946
  return init_hook_ran_;
517
}
518
519
405788
AsyncWrap::~AsyncWrap() {
520
405788
  EmitTraceEventDestroy();
521
405788
  EmitDestroy(true /* from gc */);
522
}
523
524
208992
void AsyncWrap::EmitTraceEventDestroy() {
525














208992
  switch (provider_type()) {
526
  #define V(PROVIDER)                                                         \
527
    case PROVIDER_ ## PROVIDER:                                               \
528
      TRACE_EVENT_NESTABLE_ASYNC_END0(                                        \
529
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
530
        #PROVIDER, static_cast<int64_t>(get_async_id()));                     \
531
      break;
532


























































430091
    NODE_ASYNC_PROVIDER_TYPES(V)
533
  #undef V
534
    default:
535
      UNREACHABLE();
536
  }
537
208992
}
538
539
312746
void AsyncWrap::EmitDestroy(Environment* env, double async_id) {
540

433131
  if (env->async_hooks()->fields()[AsyncHooks::kDestroy] == 0 ||
541
120385
      !env->can_call_into_js()) {
542
192530
    return;
543
  }
544
545
120216
  if (env->destroy_async_id_list()->empty()) {
546
24232
    env->SetImmediate(&DestroyAsyncIdsCallback, CallbackFlags::kUnrefed);
547
  }
548
549
  // If the list gets very large empty it faster using a Microtask.
550
  // Microtasks can't be added in GC context therefore we use an
551
  // interrupt to get this Microtask scheduled as fast as possible.
552
120216
  if (env->destroy_async_id_list()->size() == 16384) {
553
1
    env->RequestInterrupt([](Environment* env) {
554
3
      env->context()->GetMicrotaskQueue()->EnqueueMicrotask(
555
        env->isolate(),
556
1
        [](void* arg) {
557
1
          DestroyAsyncIdsCallback(static_cast<Environment*>(arg));
558
1
        }, env);
559
1
      });
560
  }
561
562
120216
  env->destroy_async_id_list()->push_back(async_id);
563
}
564
565
// Generalized call for both the constructor and for handles that are pooled
566
// and reused over their lifetime. This way a new uid can be assigned when
567
// the resource is pulled out of the pool and put back into use.
568
206436
void AsyncWrap::AsyncReset(Local<Object> resource, double execution_async_id,
569
                           bool silent) {
570
206436
  CHECK_NE(provider_type(), PROVIDER_NONE);
571
572
206436
  if (async_id_ != kInvalidAsyncId) {
573
    // This instance was in use before, we have already emitted an init with
574
    // its previous async_id and need to emit a matching destroy for that
575
    // before generating a new async_id.
576
459
    EmitDestroy();
577
  }
578
579
  // Now we can assign a new async_id_ to this instance.
580
206436
  async_id_ = execution_async_id == kInvalidAsyncId ? env()->new_async_id()
581
                                                     : execution_async_id;
582
206436
  trigger_async_id_ = env()->get_default_trigger_async_id();
583
584
  {
585
412872
    HandleScope handle_scope(env()->isolate());
586
206436
    Local<Object> obj = object();
587
206436
    CHECK(!obj.IsEmpty());
588
206436
    if (resource != obj) {
589
13504
      USE(obj->Set(env()->context(), env()->resource_symbol(), resource));
590
    }
591
  }
592
593














206436
  switch (provider_type()) {
594
#define V(PROVIDER)                                                           \
595
    case PROVIDER_ ## PROVIDER:                                               \
596
      if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(                        \
597
          TRACING_CATEGORY_NODE1(async_hooks))) {                             \
598
        auto data = tracing::TracedValue::Create();                           \
599
        data->SetInteger("executionAsyncId",                                  \
600
                         static_cast<int64_t>(env()->execution_async_id()));  \
601
        data->SetInteger("triggerAsyncId",                                    \
602
                         static_cast<int64_t>(get_trigger_async_id()));       \
603
        TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(                                    \
604
          TRACING_CATEGORY_NODE1(async_hooks),                                \
605
          #PROVIDER, static_cast<int64_t>(get_async_id()),                    \
606
          "data", std::move(data));                                           \
607
        }                                                                     \
608
      break;
609























































































206495
    NODE_ASYNC_PROVIDER_TYPES(V)
610
#undef V
611
    default:
612
      UNREACHABLE();
613
  }
614
615
206436
  if (silent) return;
616
617
412872
  EmitAsyncInit(env(), resource,
618
206436
                env()->async_hooks()->provider_string(provider_type()),
619
                async_id_, trigger_async_id_);
620
}
621
622
623
206989
void AsyncWrap::EmitAsyncInit(Environment* env,
624
                              Local<Object> object,
625
                              Local<String> type,
626
                              double async_id,
627
                              double trigger_async_id) {
628
206989
  CHECK(!object.IsEmpty());
629
206989
  CHECK(!type.IsEmpty());
630
206989
  AsyncHooks* async_hooks = env->async_hooks();
631
632
  // Nothing to execute, so can continue normally.
633
206989
  if (async_hooks->fields()[AsyncHooks::kInit] == 0) {
634
189125
    return;
635
  }
636
637
35728
  HandleScope scope(env->isolate());
638
17864
  Local<Function> init_fn = env->async_hooks_init_function();
639
640
  Local<Value> argv[] = {
641
    Number::New(env->isolate(), async_id),
642
    type,
643
    Number::New(env->isolate(), trigger_async_id),
644
    object,
645
53592
  };
646
647
17864
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
648
17864
  USE(init_fn->Call(env->context(), object, arraysize(argv), argv));
649
}
650
651
652
356949
MaybeLocal<Value> AsyncWrap::MakeCallback(const Local<Function> cb,
653
                                          int argc,
654
                                          Local<Value>* argv) {
655
356949
  EmitTraceEventBefore();
656
657
356949
  ProviderType provider = provider_type();
658
356949
  async_context context { get_async_id(), get_trigger_async_id() };
659
  MaybeLocal<Value> ret = InternalMakeCallback(
660
356949
      env(), object(), object(), cb, argc, argv, context);
661
662
  // This is a static call with cached values because the `this` object may
663
  // no longer be alive at this point.
664
356812
  EmitTraceEventAfter(provider, context.async_id);
665
666
356812
  return ret;
667
}
668
669
std::string AsyncWrap::MemoryInfoName() const {
670
  return provider_names[provider_type()];
671
}
672
673
std::string AsyncWrap::diagnostic_name() const {
674
  return MemoryInfoName() + " (" + std::to_string(env()->thread_id()) + ":" +
675
      std::to_string(static_cast<int64_t>(async_id_)) + ")";
676
}
677
678
1009
Local<Object> AsyncWrap::GetOwner() {
679
1009
  return GetOwner(env(), object());
680
}
681
682
1009
Local<Object> AsyncWrap::GetOwner(Environment* env, Local<Object> obj) {
683
1009
  EscapableHandleScope handle_scope(env->isolate());
684
1009
  CHECK(!obj.IsEmpty());
685
686
1009
  TryCatchScope ignore_exceptions(env);
687
  while (true) {
688
    Local<Value> owner;
689
6012
    if (!obj->Get(env->context(),
690

8016
                  env->owner_symbol()).ToLocal(&owner) ||
691
2004
        !owner->IsObject()) {
692
1009
      return handle_scope.Escape(obj);
693
    }
694
695
995
    obj = owner.As<Object>();
696
995
  }
697
}
698
699
}  // namespace node
700
701
4999
NODE_MODULE_CONTEXT_AWARE_INTERNAL(async_wrap, node::AsyncWrap::Initialize)
702
4938
NODE_MODULE_EXTERNAL_REFERENCE(async_wrap,
703
                               node::AsyncWrap::RegisterExternalReferences)