GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: async_wrap.cc Lines: 284 305 93.1 %
Date: 2022-01-15 04:15:29 Branches: 793 1408 56.3 %

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

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














355204
  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


























































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














355067
  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


























































719210
    NODE_ASYNC_PROVIDER_TYPES(V)
140
#undef V
141
    default:
142
      UNREACHABLE();
143
  }
144
355067
}
145
146
147
494463
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
494463
  Emit(env, async_id, AsyncHooks::kAfter,
151
       env->async_hooks_after_function());
152
494463
}
153
154
// TODO(addaleax): Remove once we're on C++17.
155
constexpr double AsyncWrap::kInvalidAsyncId;
156
157
616
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
158
616
  Environment* env = Environment::GetCurrent(args);
159
160
616
  CHECK(args[0]->IsObject());
161
162
  // All of init, before, after, destroy, and promise_resolve are supplied by
163
  // async_hooks internally, so this should only ever be called once. At which
164
  // time all the functions should be set. Detect this by checking if
165
  // init !IsEmpty().
166
1232
  CHECK(env->async_hooks_init_function().IsEmpty());
167
168
1232
  Local<Object> fn_obj = args[0].As<Object>();
169
170
#define SET_HOOK_FN(name)                                                      \
171
  do {                                                                         \
172
    Local<Value> v =                                                           \
173
        fn_obj->Get(env->context(),                                            \
174
                    FIXED_ONE_BYTE_STRING(env->isolate(), #name))              \
175
            .ToLocalChecked();                                                 \
176
    CHECK(v->IsFunction());                                                    \
177
    env->set_async_hooks_##name##_function(v.As<Function>());                  \
178
  } while (0)
179
180
3080
  SET_HOOK_FN(init);
181
2464
  SET_HOOK_FN(before);
182
2464
  SET_HOOK_FN(after);
183
2464
  SET_HOOK_FN(destroy);
184
2464
  SET_HOOK_FN(promise_resolve);
185
#undef SET_HOOK_FN
186
616
}
187
188
16844
static void SetPromiseHooks(const FunctionCallbackInfo<Value>& args) {
189
16844
  Environment* env = Environment::GetCurrent(args);
190
191


93058
  env->async_hooks()->SetJSPromiseHooks(
192
25682
    args[0]->IsFunction() ? args[0].As<Function>() : Local<Function>(),
193
25421
    args[1]->IsFunction() ? args[1].As<Function>() : Local<Function>(),
194
25133
    args[2]->IsFunction() ? args[2].As<Function>() : Local<Function>(),
195
17068
    args[3]->IsFunction() ? args[3].As<Function>() : Local<Function>());
196
16844
}
197
198
class DestroyParam {
199
 public:
200
  double asyncId;
201
  Environment* env;
202
  Global<Object> target;
203
  Global<Object> propBag;
204
};
205
206
154
static void DestroyParamCleanupHook(void* ptr) {
207
154
  delete static_cast<DestroyParam*>(ptr);
208
154
}
209
210
24656
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
211
24656
  HandleScope scope(info.GetIsolate());
212
213
24656
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
214
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
215
24656
                                                      p->propBag);
216
  Local<Value> val;
217
218
24656
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
219
220
49312
  if (!prop_bag->Get(p->env->context(), p->env->destroyed_string())
221
24656
        .ToLocal(&val)) {
222
    return;
223
  }
224
225
24656
  if (val->IsFalse()) {
226
24651
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
227
  }
228
  // unique_ptr goes out of scope here and pointer is deleted.
229
}
230
231
232
25595
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
233
25595
  CHECK(args[0]->IsObject());
234
25595
  CHECK(args[1]->IsNumber());
235
25595
  CHECK(args[2]->IsObject());
236
237
25595
  Isolate* isolate = args.GetIsolate();
238
25595
  DestroyParam* p = new DestroyParam();
239
51190
  p->asyncId = args[1].As<Number>()->Value();
240
25595
  p->env = Environment::GetCurrent(args);
241
76785
  p->target.Reset(isolate, args[0].As<Object>());
242
76785
  p->propBag.Reset(isolate, args[2].As<Object>());
243
25595
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
244
25595
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
245
25595
}
246
247
96925
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
248
  AsyncWrap* wrap;
249
193850
  args.GetReturnValue().Set(kInvalidAsyncId);
250
96925
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
251
193808
  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
1252
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
283
1252
  Environment* env = Environment::GetCurrent(args);
284
1252
  env->async_hooks()->clear_async_id_stack();
285
1252
}
286
287
288
234
void AsyncWrap::AsyncReset(const FunctionCallbackInfo<Value>& args) {
289
234
  CHECK(args[0]->IsObject());
290
291
  AsyncWrap* wrap;
292
234
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
293
294
468
  Local<Object> resource = args[0].As<Object>();
295
  double execution_async_id =
296
234
      args[1]->IsNumber() ? args[1].As<Number>()->Value() : kInvalidAsyncId;
297
234
  wrap->AsyncReset(resource, execution_async_id);
298
}
299
300
301
234
void AsyncWrap::GetProviderType(const FunctionCallbackInfo<Value>& args) {
302
  AsyncWrap* wrap;
303
468
  args.GetReturnValue().Set(AsyncWrap::PROVIDER_NONE);
304
234
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
305
468
  args.GetReturnValue().Set(wrap->provider_type());
306
}
307
308
309
207884
void AsyncWrap::EmitDestroy(bool from_gc) {
310
207884
  AsyncWrap::EmitDestroy(env(), async_id_);
311
  // Ensure no double destroy is emitted via AsyncReset().
312
207884
  async_id_ = kInvalidAsyncId;
313
314

207884
  if (!persistent().IsEmpty() && !from_gc) {
315
6356
    HandleScope handle_scope(env()->isolate());
316
25424
    USE(object()->Set(env()->context(), env()->resource_symbol(), object()));
317
  }
318
207884
}
319
320
75931
void AsyncWrap::QueueDestroyAsyncId(const FunctionCallbackInfo<Value>& args) {
321
75931
  CHECK(args[0]->IsNumber());
322
75931
  AsyncWrap::EmitDestroy(
323
      Environment::GetCurrent(args),
324
151862
      args[0].As<Number>()->Value());
325
75931
}
326
327
623
void AsyncWrap::SetCallbackTrampoline(const FunctionCallbackInfo<Value>& args) {
328
623
  Environment* env = Environment::GetCurrent(args);
329
330
623
  if (args[0]->IsFunction()) {
331
912
    env->set_async_hooks_callback_trampoline(args[0].As<Function>());
332
  } else {
333
167
    env->set_async_hooks_callback_trampoline(Local<Function>());
334
  }
335
623
}
336
337
130854
Local<FunctionTemplate> AsyncWrap::GetConstructorTemplate(Environment* env) {
338
130854
  Local<FunctionTemplate> tmpl = env->async_wrap_ctor_template();
339
130854
  if (tmpl.IsEmpty()) {
340
616
    tmpl = env->NewFunctionTemplate(nullptr);
341
616
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "AsyncWrap"));
342
616
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
343
616
    env->SetProtoMethod(tmpl, "getAsyncId", AsyncWrap::GetAsyncId);
344
616
    env->SetProtoMethod(tmpl, "asyncReset", AsyncWrap::AsyncReset);
345
616
    env->SetProtoMethod(tmpl, "getProviderType", AsyncWrap::GetProviderType);
346
616
    env->set_async_wrap_ctor_template(tmpl);
347
  }
348
130854
  return tmpl;
349
}
350
351
616
void AsyncWrap::Initialize(Local<Object> target,
352
                           Local<Value> unused,
353
                           Local<Context> context,
354
                           void* priv) {
355
616
  Environment* env = Environment::GetCurrent(context);
356
616
  Isolate* isolate = env->isolate();
357
1232
  HandleScope scope(isolate);
358
359
616
  env->SetMethod(target, "setupHooks", SetupHooks);
360
616
  env->SetMethod(target, "setCallbackTrampoline", SetCallbackTrampoline);
361
616
  env->SetMethod(target, "pushAsyncContext", PushAsyncContext);
362
616
  env->SetMethod(target, "popAsyncContext", PopAsyncContext);
363
616
  env->SetMethod(target, "executionAsyncResource", ExecutionAsyncResource);
364
616
  env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack);
365
616
  env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId);
366
616
  env->SetMethod(target, "setPromiseHooks", SetPromiseHooks);
367
616
  env->SetMethod(target, "registerDestroyHook", RegisterDestroyHook);
368
369
616
  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
2464
  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
2464
  FORCE_SET_TARGET_FIELD(target,
397
                         "async_id_fields",
398
                         env->async_hooks()->async_id_fields().GetJSArray());
399
400
2464
  FORCE_SET_TARGET_FIELD(target,
401
                         "execution_async_resources",
402
                         env->async_hooks()->js_execution_async_resources());
403
404
616
  target->Set(context,
405
              env->async_ids_stack_string(),
406
1848
              env->async_hooks()->async_ids_stack().GetJSArray()).Check();
407
408
616
  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
2464
  SET_HOOKS_CONSTANT(kInit);
414
2464
  SET_HOOKS_CONSTANT(kBefore);
415
2464
  SET_HOOKS_CONSTANT(kAfter);
416
2464
  SET_HOOKS_CONSTANT(kDestroy);
417
2464
  SET_HOOKS_CONSTANT(kPromiseResolve);
418
2464
  SET_HOOKS_CONSTANT(kTotals);
419
2464
  SET_HOOKS_CONSTANT(kCheck);
420
2464
  SET_HOOKS_CONSTANT(kExecutionAsyncId);
421
2464
  SET_HOOKS_CONSTANT(kTriggerAsyncId);
422
2464
  SET_HOOKS_CONSTANT(kAsyncIdCounter);
423
2464
  SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
424
2464
  SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource);
425
2464
  SET_HOOKS_CONSTANT(kStackLength);
426
#undef SET_HOOKS_CONSTANT
427
1232
  FORCE_SET_TARGET_FIELD(target, "constants", constants);
428
429
616
  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
107800
  NODE_ASYNC_PROVIDER_TYPES(V)
434
#undef V
435
1848
  FORCE_SET_TARGET_FIELD(target, "Providers", async_providers);
436
437
#undef FORCE_SET_TARGET_FIELD
438
439
616
  env->set_async_hooks_init_function(Local<Function>());
440
616
  env->set_async_hooks_before_function(Local<Function>());
441
616
  env->set_async_hooks_after_function(Local<Function>());
442
616
  env->set_async_hooks_destroy_function(Local<Function>());
443
616
  env->set_async_hooks_promise_resolve_function(Local<Function>());
444
616
  env->set_async_hooks_callback_trampoline(Local<Function>());
445
616
  env->set_async_hooks_binding(target);
446
616
}
447
448
4914
void AsyncWrap::RegisterExternalReferences(
449
    ExternalReferenceRegistry* registry) {
450
4914
  registry->Register(SetupHooks);
451
4914
  registry->Register(SetCallbackTrampoline);
452
4914
  registry->Register(PushAsyncContext);
453
4914
  registry->Register(PopAsyncContext);
454
4914
  registry->Register(ExecutionAsyncResource);
455
4914
  registry->Register(ClearAsyncIdStack);
456
4914
  registry->Register(QueueDestroyAsyncId);
457
4914
  registry->Register(SetPromiseHooks);
458
4914
  registry->Register(RegisterDestroyHook);
459
4914
  registry->Register(AsyncWrap::GetAsyncId);
460
4914
  registry->Register(AsyncWrap::AsyncReset);
461
4914
  registry->Register(AsyncWrap::GetProviderType);
462
4914
}
463
464
198814
AsyncWrap::AsyncWrap(Environment* env,
465
                     Local<Object> object,
466
                     ProviderType provider,
467
198814
                     double execution_async_id)
468
198814
    : AsyncWrap(env, object, provider, execution_async_id, false) {}
469
470
198814
AsyncWrap::AsyncWrap(Environment* env,
471
                     Local<Object> object,
472
                     ProviderType provider,
473
                     double execution_async_id,
474
198814
                     bool silent)
475
198814
    : AsyncWrap(env, object) {
476
198814
  CHECK_NE(provider, PROVIDER_NONE);
477
198814
  provider_type_ = provider;
478
479
  // Use AsyncReset() call to execute the init() callbacks.
480
198814
  AsyncReset(object, execution_async_id, silent);
481
198814
  init_hook_ran_ = true;
482
198814
}
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
202469
AsyncWrap::AsyncWrap(Environment* env, Local<Object> object)
494
202469
  : BaseObject(env, object) {
495
202469
}
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
203561
bool AsyncWrap::IsDoneInitializing() const {
519
203561
  return init_hook_ran_;
520
}
521
522
403056
AsyncWrap::~AsyncWrap() {
523
403056
  EmitTraceEventDestroy();
524
403056
  EmitDestroy(true /* from gc */);
525
}
526
527
207455
void AsyncWrap::EmitTraceEventDestroy() {
528














207455
  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


























































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

426810
  if (env->async_hooks()->fields()[AsyncHooks::kDestroy] == 0 ||
544
117795
      !env->can_call_into_js()) {
545
191387
    return;
546
  }
547
548
117628
  if (env->destroy_async_id_list()->empty()) {
549
23846
    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
117628
  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
117628
  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
205365
void AsyncWrap::AsyncReset(Local<Object> resource, double execution_async_id,
572
                           bool silent) {
573
205365
  CHECK_NE(provider_type(), PROVIDER_NONE);
574
575
205365
  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
429
    EmitDestroy();
580
  }
581
582
  // Now we can assign a new async_id_ to this instance.
583
205365
  async_id_ = execution_async_id == kInvalidAsyncId ? env()->new_async_id()
584
                                                     : execution_async_id;
585
205365
  trigger_async_id_ = env()->get_default_trigger_async_id();
586
587
  {
588
410730
    HandleScope handle_scope(env()->isolate());
589
205365
    Local<Object> obj = object();
590
205365
    CHECK(!obj.IsEmpty());
591
205365
    if (resource != obj) {
592
13102
      USE(obj->Set(env()->context(), env()->resource_symbol(), resource));
593
    }
594
  }
595
596














205365
  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























































































205424
    NODE_ASYNC_PROVIDER_TYPES(V)
613
#undef V
614
    default:
615
      UNREACHABLE();
616
  }
617
618
205365
  if (silent) return;
619
620
410730
  EmitAsyncInit(env(), resource,
621
205365
                env()->async_hooks()->provider_string(provider_type()),
622
                async_id_, trigger_async_id_);
623
}
624
625
626
205918
void AsyncWrap::EmitAsyncInit(Environment* env,
627
                              Local<Object> object,
628
                              Local<String> type,
629
                              double async_id,
630
                              double trigger_async_id) {
631
205918
  CHECK(!object.IsEmpty());
632
205918
  CHECK(!type.IsEmpty());
633
205918
  AsyncHooks* async_hooks = env->async_hooks();
634
635
  // Nothing to execute, so can continue normally.
636
205918
  if (async_hooks->fields()[AsyncHooks::kInit] == 0) {
637
188480
    return;
638
  }
639
640
34876
  HandleScope scope(env->isolate());
641
17438
  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
52314
  };
649
650
17438
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
651
17438
  USE(init_fn->Call(env->context(), object, arraysize(argv), argv));
652
}
653
654
655
355204
MaybeLocal<Value> AsyncWrap::MakeCallback(const Local<Function> cb,
656
                                          int argc,
657
                                          Local<Value>* argv) {
658
355204
  EmitTraceEventBefore();
659
660
355204
  ProviderType provider = provider_type();
661
355204
  async_context context { get_async_id(), get_trigger_async_id() };
662
  MaybeLocal<Value> ret = InternalMakeCallback(
663
355204
      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
355067
  EmitTraceEventAfter(provider, context.async_id);
668
669
355067
  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
1000
Local<Object> AsyncWrap::GetOwner() {
682
1000
  return GetOwner(env(), object());
683
}
684
685
1000
Local<Object> AsyncWrap::GetOwner(Environment* env, Local<Object> obj) {
686
1000
  EscapableHandleScope handle_scope(env->isolate());
687
1000
  CHECK(!obj.IsEmpty());
688
689
1000
  TryCatchScope ignore_exceptions(env);
690
  while (true) {
691
    Local<Value> owner;
692
5958
    if (!obj->Get(env->context(),
693

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