GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: async_wrap.cc Lines: 284 305 93.1 %
Date: 2022-02-21 04:14:21 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
24171
void AsyncWrap::DestroyAsyncIdsCallback(Environment* env) {
67
24171
  Local<Function> fn = env->async_hooks_destroy_function();
68
69
24171
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
70
71
2
  do {
72
24173
    std::vector<double> destroy_async_id_list;
73
24173
    destroy_async_id_list.swap(*env->destroy_async_id_list());
74
24173
    if (!env->can_call_into_js()) return;
75
143599
    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
119428
      HandleScope scope(env->isolate());
79
238856
      Local<Value> async_id_value = Number::New(env->isolate(), async_id);
80
      MaybeLocal<Value> ret = fn->Call(
81
238856
          env->context(), Undefined(env->isolate()), 1, &async_id_value);
82
83
119426
      if (ret.IsEmpty())
84
        return;
85
    }
86
24171
  } while (!env->destroy_async_id_list()->empty());
87
}
88
89
991638
void Emit(Environment* env, double async_id, AsyncHooks::Fields type,
90
          Local<Function> fn) {
91
991638
  AsyncHooks* async_hooks = env->async_hooks();
92
93

991638
  if (async_hooks->fields()[type] == 0 || !env->can_call_into_js())
94
991306
    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
356895
void AsyncWrap::EmitTraceEventBefore() {
110














356895
  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


























































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














356756
  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


























































722634
    NODE_ASYNC_PROVIDER_TYPES(V)
140
#undef V
141
    default:
142
      UNREACHABLE();
143
  }
144
356756
}
145
146
147
495784
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
495784
  Emit(env, async_id, AsyncHooks::kAfter,
151
       env->async_hooks_after_function());
152
495784
}
153
154
626
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
155
626
  Environment* env = Environment::GetCurrent(args);
156
157
626
  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
1252
  CHECK(env->async_hooks_init_function().IsEmpty());
164
165
1252
  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
2504
  SET_HOOK_FN(init);
178
2504
  SET_HOOK_FN(before);
179
2504
  SET_HOOK_FN(after);
180
3130
  SET_HOOK_FN(destroy);
181
2504
  SET_HOOK_FN(promise_resolve);
182
#undef SET_HOOK_FN
183
626
}
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
100
static void DestroyParamCleanupHook(void* ptr) {
204
100
  delete static_cast<DestroyParam*>(ptr);
205
100
}
206
207
24834
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
208
24834
  HandleScope scope(info.GetIsolate());
209
210
24834
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
211
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
212
24834
                                                      p->propBag);
213
  Local<Value> val;
214
215
24834
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
216
217
49668
  if (!prop_bag->Get(p->env->context(), p->env->destroyed_string())
218
24834
        .ToLocal(&val)) {
219
    return;
220
  }
221
222
24834
  if (val->IsFalse()) {
223
24828
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
224
  }
225
  // unique_ptr goes out of scope here and pointer is deleted.
226
}
227
228
229
25623
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
230
25623
  CHECK(args[0]->IsObject());
231
25623
  CHECK(args[1]->IsNumber());
232
25623
  CHECK(args[2]->IsObject());
233
234
25623
  Isolate* isolate = args.GetIsolate();
235
25623
  DestroyParam* p = new DestroyParam();
236
51246
  p->asyncId = args[1].As<Number>()->Value();
237
25623
  p->env = Environment::GetCurrent(args);
238
76869
  p->target.Reset(isolate, args[0].As<Object>());
239
76869
  p->propBag.Reset(isolate, args[2].As<Object>());
240
25623
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
241
25623
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
242
25623
}
243
244
97317
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
245
  AsyncWrap* wrap;
246
194634
  args.GetReturnValue().Set(kInvalidAsyncId);
247
97317
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
248
194592
  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
209576
void AsyncWrap::EmitDestroy(bool from_gc) {
307
209576
  AsyncWrap::EmitDestroy(env(), async_id_);
308
  // Ensure no double destroy is emitted via AsyncReset().
309
209576
  async_id_ = kInvalidAsyncId;
310
311

209576
  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
209576
}
316
317
77961
void AsyncWrap::QueueDestroyAsyncId(const FunctionCallbackInfo<Value>& args) {
318
77961
  CHECK(args[0]->IsNumber());
319
77961
  AsyncWrap::EmitDestroy(
320
      Environment::GetCurrent(args),
321
155922
      args[0].As<Number>()->Value());
322
77961
}
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
133242
Local<FunctionTemplate> AsyncWrap::GetConstructorTemplate(Environment* env) {
335
133242
  Local<FunctionTemplate> tmpl = env->async_wrap_ctor_template();
336
133242
  if (tmpl.IsEmpty()) {
337
626
    tmpl = env->NewFunctionTemplate(nullptr);
338
626
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "AsyncWrap"));
339
626
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
340
626
    env->SetProtoMethod(tmpl, "getAsyncId", AsyncWrap::GetAsyncId);
341
626
    env->SetProtoMethod(tmpl, "asyncReset", AsyncWrap::AsyncReset);
342
626
    env->SetProtoMethod(tmpl, "getProviderType", AsyncWrap::GetProviderType);
343
626
    env->set_async_wrap_ctor_template(tmpl);
344
  }
345
133242
  return tmpl;
346
}
347
348
626
void AsyncWrap::Initialize(Local<Object> target,
349
                           Local<Value> unused,
350
                           Local<Context> context,
351
                           void* priv) {
352
626
  Environment* env = Environment::GetCurrent(context);
353
626
  Isolate* isolate = env->isolate();
354
1252
  HandleScope scope(isolate);
355
356
626
  env->SetMethod(target, "setupHooks", SetupHooks);
357
626
  env->SetMethod(target, "setCallbackTrampoline", SetCallbackTrampoline);
358
626
  env->SetMethod(target, "pushAsyncContext", PushAsyncContext);
359
626
  env->SetMethod(target, "popAsyncContext", PopAsyncContext);
360
626
  env->SetMethod(target, "executionAsyncResource", ExecutionAsyncResource);
361
626
  env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack);
362
626
  env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId);
363
626
  env->SetMethod(target, "setPromiseHooks", SetPromiseHooks);
364
626
  env->SetMethod(target, "registerDestroyHook", RegisterDestroyHook);
365
366
626
  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
2504
  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
2504
  FORCE_SET_TARGET_FIELD(target,
394
                         "async_id_fields",
395
                         env->async_hooks()->async_id_fields().GetJSArray());
396
397
2504
  FORCE_SET_TARGET_FIELD(target,
398
                         "execution_async_resources",
399
                         env->async_hooks()->js_execution_async_resources());
400
401
626
  target->Set(context,
402
              env->async_ids_stack_string(),
403
1878
              env->async_hooks()->async_ids_stack().GetJSArray()).Check();
404
405
626
  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
2504
  SET_HOOKS_CONSTANT(kInit);
411
2504
  SET_HOOKS_CONSTANT(kBefore);
412
2504
  SET_HOOKS_CONSTANT(kAfter);
413
2504
  SET_HOOKS_CONSTANT(kDestroy);
414
2504
  SET_HOOKS_CONSTANT(kPromiseResolve);
415
2504
  SET_HOOKS_CONSTANT(kTotals);
416
2504
  SET_HOOKS_CONSTANT(kCheck);
417
2504
  SET_HOOKS_CONSTANT(kExecutionAsyncId);
418
2504
  SET_HOOKS_CONSTANT(kTriggerAsyncId);
419
2504
  SET_HOOKS_CONSTANT(kAsyncIdCounter);
420
2504
  SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
421
2504
  SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource);
422
2504
  SET_HOOKS_CONSTANT(kStackLength);
423
#undef SET_HOOKS_CONSTANT
424
1252
  FORCE_SET_TARGET_FIELD(target, "constants", constants);
425
426
626
  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
109550
  NODE_ASYNC_PROVIDER_TYPES(V)
431
#undef V
432
1878
  FORCE_SET_TARGET_FIELD(target, "Providers", async_providers);
433
434
#undef FORCE_SET_TARGET_FIELD
435
436
626
  env->set_async_hooks_init_function(Local<Function>());
437
626
  env->set_async_hooks_before_function(Local<Function>());
438
626
  env->set_async_hooks_after_function(Local<Function>());
439
626
  env->set_async_hooks_destroy_function(Local<Function>());
440
626
  env->set_async_hooks_promise_resolve_function(Local<Function>());
441
626
  env->set_async_hooks_callback_trampoline(Local<Function>());
442
626
  env->set_async_hooks_binding(target);
443
626
}
444
445
4946
void AsyncWrap::RegisterExternalReferences(
446
    ExternalReferenceRegistry* registry) {
447
4946
  registry->Register(SetupHooks);
448
4946
  registry->Register(SetCallbackTrampoline);
449
4946
  registry->Register(PushAsyncContext);
450
4946
  registry->Register(PopAsyncContext);
451
4946
  registry->Register(ExecutionAsyncResource);
452
4946
  registry->Register(ClearAsyncIdStack);
453
4946
  registry->Register(QueueDestroyAsyncId);
454
4946
  registry->Register(SetPromiseHooks);
455
4946
  registry->Register(RegisterDestroyHook);
456
4946
  registry->Register(AsyncWrap::GetAsyncId);
457
4946
  registry->Register(AsyncWrap::AsyncReset);
458
4946
  registry->Register(AsyncWrap::GetProviderType);
459
4946
}
460
461
199819
AsyncWrap::AsyncWrap(Environment* env,
462
                     Local<Object> object,
463
                     ProviderType provider,
464
199819
                     double execution_async_id)
465
199819
    : AsyncWrap(env, object, provider, execution_async_id, false) {}
466
467
199819
AsyncWrap::AsyncWrap(Environment* env,
468
                     Local<Object> object,
469
                     ProviderType provider,
470
                     double execution_async_id,
471
199819
                     bool silent)
472
199819
    : AsyncWrap(env, object) {
473
199819
  CHECK_NE(provider, PROVIDER_NONE);
474
199819
  provider_type_ = provider;
475
476
  // Use AsyncReset() call to execute the init() callbacks.
477
199819
  AsyncReset(object, execution_async_id, silent);
478
199819
  init_hook_ran_ = true;
479
199819
}
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
203972
AsyncWrap::AsyncWrap(Environment* env, Local<Object> object)
491
203972
  : BaseObject(env, object) {
492
203972
}
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
202210
bool AsyncWrap::IsDoneInitializing() const {
516
202210
  return init_hook_ran_;
517
}
518
519
406038
AsyncWrap::~AsyncWrap() {
520
406038
  EmitTraceEventDestroy();
521
406038
  EmitDestroy(true /* from gc */);
522
}
523
524
209117
void AsyncWrap::EmitTraceEventDestroy() {
525














209117
  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


























































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

433342
  if (env->async_hooks()->fields()[AsyncHooks::kDestroy] == 0 ||
541
120428
      !env->can_call_into_js()) {
542
192656
    return;
543
  }
544
545
120258
  if (env->destroy_async_id_list()->empty()) {
546
24225
    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
120258
  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
120258
  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
206571
void AsyncWrap::AsyncReset(Local<Object> resource, double execution_async_id,
569
                           bool silent) {
570
206571
  CHECK_NE(provider_type(), PROVIDER_NONE);
571
572
206571
  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
206571
  async_id_ = execution_async_id == kInvalidAsyncId ? env()->new_async_id()
581
                                                     : execution_async_id;
582
206571
  trigger_async_id_ = env()->get_default_trigger_async_id();
583
584
  {
585
413142
    HandleScope handle_scope(env()->isolate());
586
206571
    Local<Object> obj = object();
587
206571
    CHECK(!obj.IsEmpty());
588
206571
    if (resource != obj) {
589
13504
      USE(obj->Set(env()->context(), env()->resource_symbol(), resource));
590
    }
591
  }
592
593














206571
  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























































































206630
    NODE_ASYNC_PROVIDER_TYPES(V)
610
#undef V
611
    default:
612
      UNREACHABLE();
613
  }
614
615
206571
  if (silent) return;
616
617
413142
  EmitAsyncInit(env(), resource,
618
206571
                env()->async_hooks()->provider_string(provider_type()),
619
                async_id_, trigger_async_id_);
620
}
621
622
623
207124
void AsyncWrap::EmitAsyncInit(Environment* env,
624
                              Local<Object> object,
625
                              Local<String> type,
626
                              double async_id,
627
                              double trigger_async_id) {
628
207124
  CHECK(!object.IsEmpty());
629
207124
  CHECK(!type.IsEmpty());
630
207124
  AsyncHooks* async_hooks = env->async_hooks();
631
632
  // Nothing to execute, so can continue normally.
633
207124
  if (async_hooks->fields()[AsyncHooks::kInit] == 0) {
634
189260
    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
356895
MaybeLocal<Value> AsyncWrap::MakeCallback(const Local<Function> cb,
653
                                          int argc,
654
                                          Local<Value>* argv) {
655
356895
  EmitTraceEventBefore();
656
657
356895
  ProviderType provider = provider_type();
658
356895
  async_context context { get_async_id(), get_trigger_async_id() };
659
  MaybeLocal<Value> ret = InternalMakeCallback(
660
356895
      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
356756
  EmitTraceEventAfter(provider, context.async_id);
665
666
356756
  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
5007
NODE_MODULE_CONTEXT_AWARE_INTERNAL(async_wrap, node::AsyncWrap::Initialize)
702
4946
NODE_MODULE_EXTERNAL_REFERENCE(async_wrap,
703
                               node::AsyncWrap::RegisterExternalReferences)