GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: async_wrap.cc Lines: 286 307 93.2 %
Date: 2022-04-09 04:14:47 Branches: 816 1422 57.4 %

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
23961
void AsyncWrap::DestroyAsyncIdsCallback(Environment* env) {
67
23961
  Local<Function> fn = env->async_hooks_destroy_function();
68
69
23961
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
70
71
2
  do {
72
23963
    std::vector<double> destroy_async_id_list;
73
23963
    destroy_async_id_list.swap(*env->destroy_async_id_list());
74
23963
    if (!env->can_call_into_js()) return;
75
143059
    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
119098
      HandleScope scope(env->isolate());
79
238196
      Local<Value> async_id_value = Number::New(env->isolate(), async_id);
80
      MaybeLocal<Value> ret = fn->Call(
81
238196
          env->context(), Undefined(env->isolate()), 1, &async_id_value);
82
83
119096
      if (ret.IsEmpty())
84
        return;
85
    }
86
23961
  } while (!env->destroy_async_id_list()->empty());
87
}
88
89
989831
void Emit(Environment* env, double async_id, AsyncHooks::Fields type,
90
          Local<Function> fn) {
91
989831
  AsyncHooks* async_hooks = env->async_hooks();
92
93

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














356486
  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


























































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














356259
  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


























































721701
    NODE_ASYNC_PROVIDER_TYPES(V)
140
#undef V
141
    default:
142
      UNREACHABLE();
143
  }
144
356259
}
145
146
147
494881
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
494881
  Emit(env, async_id, AsyncHooks::kAfter,
151
       env->async_hooks_after_function());
152
494881
}
153
154
623
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
155
623
  Environment* env = Environment::GetCurrent(args);
156
157
623
  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
1246
  CHECK(env->async_hooks_init_function().IsEmpty());
164
165
1246
  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
2492
  SET_HOOK_FN(init);
178
2492
  SET_HOOK_FN(before);
179
2492
  SET_HOOK_FN(after);
180
3115
  SET_HOOK_FN(destroy);
181
2492
  SET_HOOK_FN(promise_resolve);
182
#undef SET_HOOK_FN
183
623
}
184
185
17196
static void SetPromiseHooks(const FunctionCallbackInfo<Value>& args) {
186
17196
  Environment* env = Environment::GetCurrent(args);
187
188


94996
  env->async_hooks()->SetJSPromiseHooks(
189
26212
    args[0]->IsFunction() ? args[0].As<Function>() : Local<Function>(),
190
25950
    args[1]->IsFunction() ? args[1].As<Function>() : Local<Function>(),
191
25661
    args[2]->IsFunction() ? args[2].As<Function>() : Local<Function>(),
192
17421
    args[3]->IsFunction() ? args[3].As<Function>() : Local<Function>());
193
17196
}
194
195
class DestroyParam {
196
 public:
197
  double asyncId;
198
  Environment* env;
199
  Global<Object> target;
200
  Global<Object> propBag;
201
};
202
203
766
static void DestroyParamCleanupHook(void* ptr) {
204
766
  delete static_cast<DestroyParam*>(ptr);
205
766
}
206
207
24533
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
208
24533
  HandleScope scope(info.GetIsolate());
209
210
24533
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
211
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
212
24533
                                                      p->propBag);
213
  Local<Value> val;
214
215
24533
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
216
217
27062
  if (!prop_bag.IsEmpty() &&
218
29591
      !prop_bag->Get(p->env->context(), p->env->destroyed_string())
219
2529
        .ToLocal(&val)) {
220
    return;
221
  }
222
223

27062
  if (val.IsEmpty() || val->IsFalse()) {
224
24528
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
225
  }
226
  // unique_ptr goes out of scope here and pointer is deleted.
227
}
228
229
230
26260
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
231
26260
  CHECK(args[0]->IsObject());
232
26260
  CHECK(args[1]->IsNumber());
233

28900
  CHECK(args.Length() == 2 || args[2]->IsObject());
234
235
26260
  Isolate* isolate = args.GetIsolate();
236
26260
  DestroyParam* p = new DestroyParam();
237
52520
  p->asyncId = args[1].As<Number>()->Value();
238
26260
  p->env = Environment::GetCurrent(args);
239
105040
  p->target.Reset(isolate, args[0].As<Object>());
240
26260
  if (args.Length() > 2) {
241
10560
    p->propBag.Reset(isolate, args[2].As<Object>());
242
  }
243
26260
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
244
26260
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
245
26260
}
246
247
97640
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
248
  AsyncWrap* wrap;
249
195280
  args.GetReturnValue().Set(kInvalidAsyncId);
250
97640
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
251
195238
  args.GetReturnValue().Set(wrap->get_async_id());
252
}
253
254
255
4
void AsyncWrap::PushAsyncContext(const FunctionCallbackInfo<Value>& args) {
256
4
  Environment* env = Environment::GetCurrent(args);
257
  // No need for CHECK(IsNumber()) on args because if FromJust() doesn't fail
258
  // then the checks in push_async_ids() and pop_async_id() will.
259
8
  double async_id = args[0]->NumberValue(env->context()).FromJust();
260
4
  double trigger_async_id = args[1]->NumberValue(env->context()).FromJust();
261
4
  env->async_hooks()->push_async_context(async_id, trigger_async_id, {});
262
4
}
263
264
265
3
void AsyncWrap::PopAsyncContext(const FunctionCallbackInfo<Value>& args) {
266
3
  Environment* env = Environment::GetCurrent(args);
267
6
  double async_id = args[0]->NumberValue(env->context()).FromJust();
268
3
  args.GetReturnValue().Set(env->async_hooks()->pop_async_context(async_id));
269
}
270
271
272
2401
void AsyncWrap::ExecutionAsyncResource(
273
    const FunctionCallbackInfo<Value>& args) {
274
2401
  Environment* env = Environment::GetCurrent(args);
275
  uint32_t index;
276
4802
  if (!args[0]->Uint32Value(env->context()).To(&index)) return;
277
4802
  args.GetReturnValue().Set(
278
      env->async_hooks()->native_execution_async_resource(index));
279
}
280
281
282
1261
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
283
1261
  Environment* env = Environment::GetCurrent(args);
284
1261
  env->async_hooks()->clear_async_id_stack();
285
1261
}
286
287
288
288
void AsyncWrap::AsyncReset(const FunctionCallbackInfo<Value>& args) {
289
288
  CHECK(args[0]->IsObject());
290
291
  AsyncWrap* wrap;
292
288
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
293
294
576
  Local<Object> resource = args[0].As<Object>();
295
  double execution_async_id =
296
288
      args[1]->IsNumber() ? args[1].As<Number>()->Value() : kInvalidAsyncId;
297
288
  wrap->AsyncReset(resource, execution_async_id);
298
}
299
300
301
288
void AsyncWrap::GetProviderType(const FunctionCallbackInfo<Value>& args) {
302
  AsyncWrap* wrap;
303
576
  args.GetReturnValue().Set(AsyncWrap::PROVIDER_NONE);
304
288
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
305
576
  args.GetReturnValue().Set(wrap->provider_type());
306
}
307
308
309
210457
void AsyncWrap::EmitDestroy(bool from_gc) {
310
210457
  AsyncWrap::EmitDestroy(env(), async_id_);
311
  // Ensure no double destroy is emitted via AsyncReset().
312
210457
  async_id_ = kInvalidAsyncId;
313
314

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














209974
  switch (provider_type()) {
529
  #define V(PROVIDER)                                                         \
530
    case PROVIDER_ ## PROVIDER:                                               \
531
      TRACE_EVENT_NESTABLE_ASYNC_END0(                                        \
532
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
533
        #PROVIDER, static_cast<int64_t>(get_async_id()));                     \
534
      break;
535


























































432089
    NODE_ASYNC_PROVIDER_TYPES(V)
536
  #undef V
537
    default:
538
      UNREACHABLE();
539
  }
540
209974
}
541
542
313305
void AsyncWrap::EmitDestroy(Environment* env, double async_id) {
543

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














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























































































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

8040
                  env->owner_symbol()).ToLocal(&owner) ||
694
2010
        !owner->IsObject()) {
695
1012
      return handle_scope.Escape(obj);
696
    }
697
698
998
    obj = owner.As<Object>();
699
998
  }
700
}
701
702
}  // namespace node
703
704
5042
NODE_MODULE_CONTEXT_AWARE_INTERNAL(async_wrap, node::AsyncWrap::Initialize)
705
4981
NODE_MODULE_EXTERNAL_REFERENCE(async_wrap,
706
                               node::AsyncWrap::RegisterExternalReferences)