GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: async_wrap.cc Lines: 287 308 93.2 %
Date: 2022-09-22 04:22:24 Branches: 817 1422 57.5 %

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

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














376843
  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


























































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














376680
  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


























































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


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

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

50928
  CHECK(args.Length() == 2 || args[2]->IsObject());
234
235
48041
  Isolate* isolate = args.GetIsolate();
236
48041
  DestroyParam* p = new DestroyParam();
237
96082
  p->asyncId = args[1].As<Number>()->Value();
238
48041
  p->env = Environment::GetCurrent(args);
239
192164
  p->target.Reset(isolate, args[0].As<Object>());
240
48041
  if (args.Length() > 2) {
241
11548
    p->propBag.Reset(isolate, args[2].As<Object>());
242
  }
243
48041
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
244
48041
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
245
48041
}
246
247
100947
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
248
  AsyncWrap* wrap;
249
201894
  args.GetReturnValue().Set(kInvalidAsyncId);
250
100947
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
251
201852
  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
2406
void AsyncWrap::ExecutionAsyncResource(
273
    const FunctionCallbackInfo<Value>& args) {
274
2406
  Environment* env = Environment::GetCurrent(args);
275
  uint32_t index;
276
4812
  if (!args[0]->Uint32Value(env->context()).To(&index)) return;
277
4812
  args.GetReturnValue().Set(
278
      env->async_hooks()->native_execution_async_resource(index));
279
}
280
281
282
1259
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
283
1259
  Environment* env = Environment::GetCurrent(args);
284
1259
  env->async_hooks()->clear_async_id_stack();
285
1259
}
286
287
288
343
void AsyncWrap::AsyncReset(const FunctionCallbackInfo<Value>& args) {
289
343
  CHECK(args[0]->IsObject());
290
291
  AsyncWrap* wrap;
292
343
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
293
294
686
  Local<Object> resource = args[0].As<Object>();
295
  double execution_async_id =
296
343
      args[1]->IsNumber() ? args[1].As<Number>()->Value() : kInvalidAsyncId;
297
343
  wrap->AsyncReset(resource, execution_async_id);
298
}
299
300
301
343
void AsyncWrap::GetProviderType(const FunctionCallbackInfo<Value>& args) {
302
  AsyncWrap* wrap;
303
686
  args.GetReturnValue().Set(AsyncWrap::PROVIDER_NONE);
304
343
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
305
686
  args.GetReturnValue().Set(wrap->provider_type());
306
}
307
308
309
217666
void AsyncWrap::EmitDestroy(bool from_gc) {
310
217666
  AsyncWrap::EmitDestroy(env(), async_id_);
311
  // Ensure no double destroy is emitted via AsyncReset().
312
217666
  async_id_ = kInvalidAsyncId;
313
314

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














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


























































447576
    NODE_ASYNC_PROVIDER_TYPES(V)
538
  #undef V
539
    default:
540
      UNREACHABLE();
541
  }
542
217126
}
543
544
330946
void AsyncWrap::EmitDestroy(Environment* env, double async_id) {
545

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














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























































































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

8152
                  env->owner_symbol()).ToLocal(&owner) ||
696
2038
        !owner->IsObject()) {
697
1026
      return handle_scope.Escape(obj);
698
    }
699
700
1012
    obj = owner.As<Object>();
701
1012
  }
702
}
703
704
}  // namespace node
705
706
5595
NODE_MODULE_CONTEXT_AWARE_INTERNAL(async_wrap, node::AsyncWrap::Initialize)
707
5525
NODE_MODULE_EXTERNAL_REFERENCE(async_wrap,
708
                               node::AsyncWrap::RegisterExternalReferences)