GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: async_wrap.cc Lines: 282 303 93.1 %
Date: 2021-09-18 04:12:33 Branches: 792 1408 56.2 %

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

336264
  if (async_hooks->fields()[type] == 0 || !env->can_call_into_js())
94
335939
    return;
95
96
650
  HandleScope handle_scope(env->isolate());
97
325
  Local<Value> async_id_value = Number::New(env->isolate(), async_id);
98
325
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
99
650
  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
352024
void AsyncWrap::EmitTraceEventBefore() {
110














352024
  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


























































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














351799
  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


























































712591
    NODE_ASYNC_PROVIDER_TYPES(V)
140
#undef V
141
    default:
142
      UNREACHABLE();
143
  }
144
351799
}
145
146
147
168126
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
168126
  Emit(env, async_id, AsyncHooks::kAfter,
151
       env->async_hooks_after_function());
152
168126
}
153
154
// TODO(addaleax): Remove once we're on C++17.
155
constexpr double AsyncWrap::kInvalidAsyncId;
156
157
622
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
158
622
  Environment* env = Environment::GetCurrent(args);
159
160
622
  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
1244
  CHECK(env->async_hooks_init_function().IsEmpty());
167
168
1244
  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
2488
  SET_HOOK_FN(init);
181
2488
  SET_HOOK_FN(before);
182
2488
  SET_HOOK_FN(after);
183
2488
  SET_HOOK_FN(destroy);
184
2488
  SET_HOOK_FN(promise_resolve);
185
#undef SET_HOOK_FN
186
622
}
187
188
2983
static void SetPromiseHooks(const FunctionCallbackInfo<Value>& args) {
189
2983
  Environment* env = Environment::GetCurrent(args);
190
191


17829
  env->async_hooks()->SetJSPromiseHooks(
192
5897
    args[0]->IsFunction() ? args[0].As<Function>() : Local<Function>(),
193
5907
    args[1]->IsFunction() ? args[1].As<Function>() : Local<Function>(),
194
5907
    args[2]->IsFunction() ? args[2].As<Function>() : Local<Function>(),
195
3050
    args[3]->IsFunction() ? args[3].As<Function>() : Local<Function>());
196
2983
}
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
24613
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
211
24613
  HandleScope scope(info.GetIsolate());
212
213
24613
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
214
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
215
24613
                                                      p->propBag);
216
  Local<Value> val;
217
218
24613
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
219
220
49226
  if (!prop_bag->Get(p->env->context(), p->env->destroyed_string())
221
24613
        .ToLocal(&val)) {
222
    return;
223
  }
224
225
24613
  if (val->IsFalse()) {
226
24608
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
227
  }
228
  // unique_ptr goes out of scope here and pointer is deleted.
229
}
230
231
232
25592
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
233
25592
  CHECK(args[0]->IsObject());
234
25592
  CHECK(args[1]->IsNumber());
235
25592
  CHECK(args[2]->IsObject());
236
237
25592
  Isolate* isolate = args.GetIsolate();
238
25592
  DestroyParam* p = new DestroyParam();
239
51184
  p->asyncId = args[1].As<Number>()->Value();
240
25592
  p->env = Environment::GetCurrent(args);
241
76776
  p->target.Reset(isolate, args[0].As<Object>());
242
76776
  p->propBag.Reset(isolate, args[2].As<Object>());
243
25592
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
244
25592
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
245
25592
}
246
247
96399
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
248
  AsyncWrap* wrap;
249
192798
  args.GetReturnValue().Set(kInvalidAsyncId);
250
96399
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
251
192756
  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
2402
void AsyncWrap::ExecutionAsyncResource(
273
    const FunctionCallbackInfo<Value>& args) {
274
2402
  Environment* env = Environment::GetCurrent(args);
275
  uint32_t index;
276
4804
  if (!args[0]->Uint32Value(env->context()).To(&index)) return;
277
4804
  args.GetReturnValue().Set(
278
      env->async_hooks()->native_execution_async_resource(index));
279
}
280
281
282
1247
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
283
1247
  Environment* env = Environment::GetCurrent(args);
284
1247
  env->async_hooks()->clear_async_id_stack();
285
1247
}
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
204137
void AsyncWrap::EmitDestroy(bool from_gc) {
310
204137
  AsyncWrap::EmitDestroy(env(), async_id_);
311
  // Ensure no double destroy is emitted via AsyncReset().
312
204137
  async_id_ = kInvalidAsyncId;
313
314

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














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


























































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

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














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























































































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

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