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

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














353373
  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


























































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














353236
  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


























































715520
    NODE_ASYNC_PROVIDER_TYPES(V)
140
#undef V
141
    default:
142
      UNREACHABLE();
143
  }
144
353236
}
145
146
147
492203
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
492203
  Emit(env, async_id, AsyncHooks::kAfter,
151
       env->async_hooks_after_function());
152
492203
}
153
154
// TODO(addaleax): Remove once we're on C++17.
155
constexpr double AsyncWrap::kInvalidAsyncId;
156
157
615
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
158
615
  Environment* env = Environment::GetCurrent(args);
159
160
615
  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
1230
  CHECK(env->async_hooks_init_function().IsEmpty());
167
168
1230
  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
3075
  SET_HOOK_FN(init);
181
2460
  SET_HOOK_FN(before);
182
2460
  SET_HOOK_FN(after);
183
2460
  SET_HOOK_FN(destroy);
184
2460
  SET_HOOK_FN(promise_resolve);
185
#undef SET_HOOK_FN
186
615
}
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
157
static void DestroyParamCleanupHook(void* ptr) {
207
157
  delete static_cast<DestroyParam*>(ptr);
208
157
}
209
210
24702
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
211
24702
  HandleScope scope(info.GetIsolate());
212
213
24702
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
214
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
215
24702
                                                      p->propBag);
216
  Local<Value> val;
217
218
24702
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
219
220
49404
  if (!prop_bag->Get(p->env->context(), p->env->destroyed_string())
221
24702
        .ToLocal(&val)) {
222
    return;
223
  }
224
225
24702
  if (val->IsFalse()) {
226
24697
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
227
  }
228
  // unique_ptr goes out of scope here and pointer is deleted.
229
}
230
231
232
25596
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
233
25596
  CHECK(args[0]->IsObject());
234
25596
  CHECK(args[1]->IsNumber());
235
25596
  CHECK(args[2]->IsObject());
236
237
25596
  Isolate* isolate = args.GetIsolate();
238
25596
  DestroyParam* p = new DestroyParam();
239
51192
  p->asyncId = args[1].As<Number>()->Value();
240
25596
  p->env = Environment::GetCurrent(args);
241
76788
  p->target.Reset(isolate, args[0].As<Object>());
242
76788
  p->propBag.Reset(isolate, args[2].As<Object>());
243
25596
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
244
25596
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
245
25596
}
246
247
96474
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
248
  AsyncWrap* wrap;
249
192948
  args.GetReturnValue().Set(kInvalidAsyncId);
250
96474
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
251
192906
  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
206727
void AsyncWrap::EmitDestroy(bool from_gc) {
310
206727
  AsyncWrap::EmitDestroy(env(), async_id_);
311
  // Ensure no double destroy is emitted via AsyncReset().
312
206727
  async_id_ = kInvalidAsyncId;
313
314

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














206298
  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


























































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

425827
  if (env->async_hooks()->fields()[AsyncHooks::kDestroy] == 0 ||
544
117882
      !env->can_call_into_js()) {
545
190230
    return;
546
  }
547
548
117715
  if (env->destroy_async_id_list()->empty()) {
549
23853
    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
117715
  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
117715
  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
204122
void AsyncWrap::AsyncReset(Local<Object> resource, double execution_async_id,
572
                           bool silent) {
573
204122
  CHECK_NE(provider_type(), PROVIDER_NONE);
574
575
204122
  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
204122
  async_id_ = execution_async_id == kInvalidAsyncId ? env()->new_async_id()
584
                                                     : execution_async_id;
585
204122
  trigger_async_id_ = env()->get_default_trigger_async_id();
586
587
  {
588
408244
    HandleScope handle_scope(env()->isolate());
589
204122
    Local<Object> obj = object();
590
204122
    CHECK(!obj.IsEmpty());
591
204122
    if (resource != obj) {
592
13102
      USE(obj->Set(env()->context(), env()->resource_symbol(), resource));
593
    }
594
  }
595
596














204122
  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























































































204181
    NODE_ASYNC_PROVIDER_TYPES(V)
613
#undef V
614
    default:
615
      UNREACHABLE();
616
  }
617
618
204122
  if (silent) return;
619
620
408244
  EmitAsyncInit(env(), resource,
621
204122
                env()->async_hooks()->provider_string(provider_type()),
622
                async_id_, trigger_async_id_);
623
}
624
625
626
204675
void AsyncWrap::EmitAsyncInit(Environment* env,
627
                              Local<Object> object,
628
                              Local<String> type,
629
                              double async_id,
630
                              double trigger_async_id) {
631
204675
  CHECK(!object.IsEmpty());
632
204675
  CHECK(!type.IsEmpty());
633
204675
  AsyncHooks* async_hooks = env->async_hooks();
634
635
  // Nothing to execute, so can continue normally.
636
204675
  if (async_hooks->fields()[AsyncHooks::kInit] == 0) {
637
187237
    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
353373
MaybeLocal<Value> AsyncWrap::MakeCallback(const Local<Function> cb,
656
                                          int argc,
657
                                          Local<Value>* argv) {
658
353373
  EmitTraceEventBefore();
659
660
353373
  ProviderType provider = provider_type();
661
353373
  async_context context { get_async_id(), get_trigger_async_id() };
662
  MaybeLocal<Value> ret = InternalMakeCallback(
663
353373
      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
353236
  EmitTraceEventAfter(provider, context.async_id);
668
669
353236
  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
947
Local<Object> AsyncWrap::GetOwner() {
682
947
  return GetOwner(env(), object());
683
}
684
685
947
Local<Object> AsyncWrap::GetOwner(Environment* env, Local<Object> obj) {
686
947
  EscapableHandleScope handle_scope(env->isolate());
687
947
  CHECK(!obj.IsEmpty());
688
689
947
  TryCatchScope ignore_exceptions(env);
690
  while (true) {
691
    Local<Value> owner;
692
5640
    if (!obj->Get(env->context(),
693

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