GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/async_wrap.cc Lines: 430 466 92.3 %
Date: 2021-05-03 04:13:35 Branches: 867 1481 58.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::Just;
43
using v8::Local;
44
using v8::Maybe;
45
using v8::MaybeLocal;
46
using v8::Name;
47
using v8::Nothing;
48
using v8::Number;
49
using v8::Object;
50
using v8::ObjectTemplate;
51
using v8::Promise;
52
using v8::PromiseHookType;
53
using v8::PropertyAttribute;
54
using v8::PropertyCallbackInfo;
55
using v8::ReadOnly;
56
using v8::String;
57
using v8::Undefined;
58
using v8::Value;
59
using v8::WeakCallbackInfo;
60
using v8::WeakCallbackType;
61
62
using TryCatchScope = node::errors::TryCatchScope;
63
64
namespace node {
65
66
static const char* const provider_names[] = {
67
#define V(PROVIDER)                                                           \
68
  #PROVIDER,
69
  NODE_ASYNC_PROVIDER_TYPES(V)
70
#undef V
71
};
72
73
23248
void AsyncWrap::DestroyAsyncIdsCallback(Environment* env) {
74
23248
  Local<Function> fn = env->async_hooks_destroy_function();
75
76
46494
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
77
78

23248
  do {
79
46498
    std::vector<double> destroy_async_id_list;
80
23250
    destroy_async_id_list.swap(*env->destroy_async_id_list());
81
23250
    if (!env->can_call_into_js()) return;
82

136130
    for (auto async_id : destroy_async_id_list) {
83
      // Want each callback to be cleaned up after itself, instead of cleaning
84
      // them all up after the while() loop completes.
85
225762
      HandleScope scope(env->isolate());
86
112882
      Local<Value> async_id_value = Number::New(env->isolate(), async_id);
87
      MaybeLocal<Value> ret = fn->Call(
88
338646
          env->context(), Undefined(env->isolate()), 1, &async_id_value);
89
90
112880
      if (ret.IsEmpty())
91
        return;
92
    }
93
23248
  } while (!env->destroy_async_id_list()->empty());
94
}
95
96
151423
void Emit(Environment* env, double async_id, AsyncHooks::Fields type,
97
          Local<Function> fn) {
98
151423
  AsyncHooks* async_hooks = env->async_hooks();
99
100

151423
  if (async_hooks->fields()[type] == 0 || !env->can_call_into_js())
101
146795
    return;
102
103
9256
  HandleScope handle_scope(env->isolate());
104
4628
  Local<Value> async_id_value = Number::New(env->isolate(), async_id);
105
9256
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
106
13884
  USE(fn->Call(env->context(), Undefined(env->isolate()), 1, &async_id_value));
107
}
108
109
110
23364
void AsyncWrap::EmitPromiseResolve(Environment* env, double async_id) {
111
23364
  Emit(env, async_id, AsyncHooks::kPromiseResolve,
112
23364
       env->async_hooks_promise_resolve_function());
113
23364
}
114
115
116
347564
void AsyncWrap::EmitTraceEventBefore() {
117














347564
  switch (provider_type()) {
118
#define V(PROVIDER)                                                           \
119
    case PROVIDER_ ## PROVIDER:                                               \
120
      TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(                                      \
121
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
122
        #PROVIDER "_CALLBACK", static_cast<int64_t>(get_async_id()));         \
123
      break;
124






















































695068
    NODE_ASYNC_PROVIDER_TYPES(V)
125
#undef V
126
    default:
127
      UNREACHABLE();
128
  }
129
347534
}
130
131
132
64024
void AsyncWrap::EmitBefore(Environment* env, double async_id) {
133
64024
  Emit(env, async_id, AsyncHooks::kBefore,
134
64024
       env->async_hooks_before_function());
135
64024
}
136
137
138
347481
void AsyncWrap::EmitTraceEventAfter(ProviderType type, double async_id) {
139














347481
  switch (type) {
140
#define V(PROVIDER)                                                           \
141
    case PROVIDER_ ## PROVIDER:                                               \
142
      TRACE_EVENT_NESTABLE_ASYNC_END0(                                        \
143
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
144
        #PROVIDER "_CALLBACK", static_cast<int64_t>(async_id));               \
145
      break;
146






















































694948
    NODE_ASYNC_PROVIDER_TYPES(V)
147
#undef V
148
    default:
149
      UNREACHABLE();
150
  }
151
347474
}
152
153
154
64035
void AsyncWrap::EmitAfter(Environment* env, double async_id) {
155
  // If the user's callback failed then the after() hooks will be called at the
156
  // end of _fatalException().
157
64035
  Emit(env, async_id, AsyncHooks::kAfter,
158
64035
       env->async_hooks_after_function());
159
64035
}
160
161
// TODO(addaleax): Remove once we're on C++17.
162
constexpr double AsyncWrap::kInvalidAsyncId;
163
164
343
static Maybe<double> GetAssignedPromiseAsyncId(Environment* env,
165
                                               Local<Promise> promise,
166
                                               Local<Value> id_symbol) {
167
  Local<Value> maybe_async_id;
168

1029
  if (!promise->Get(env->context(), id_symbol).ToLocal(&maybe_async_id)) {
169
    return Nothing<double>();
170
  }
171
343
  return maybe_async_id->IsNumber()
172
258
      ? maybe_async_id->NumberValue(env->context())
173
472
      : Just(AsyncWrap::kInvalidAsyncId);
174
}
175
176
43634
class PromiseWrap : public AsyncWrap {
177
 public:
178
23089
  PromiseWrap(Environment* env, Local<Object> object, bool silent)
179
23089
      : AsyncWrap(env, object, PROVIDER_PROMISE, kInvalidAsyncId, silent) {
180
23089
    MakeWeak();
181
23089
  }
182
183
  PromiseWrap(Environment* env, Local<Object> object, double asyncId,
184
    double triggerAsyncId)
185
      : AsyncWrap(env, object, PROVIDER_PROMISE, asyncId, triggerAsyncId) {
186
    MakeWeak();
187
  }
188
189
5
  SET_NO_MEMORY_INFO()
190
5
  SET_MEMORY_INFO_NAME(PromiseWrap)
191
5
  SET_SELF_SIZE(PromiseWrap)
192
193
  static PromiseWrap* New(Environment* env,
194
                          Local<Promise> promise,
195
                          bool silent);
196
  static void GetAsyncId(Local<Name> property,
197
                         const PropertyCallbackInfo<Value>& args);
198
  static void GetTriggerAsyncId(Local<Name> property,
199
                                const PropertyCallbackInfo<Value>& args);
200
201
  static void Initialize(Environment* env);
202
};
203
204
23089
PromiseWrap* PromiseWrap::New(Environment* env,
205
                              Local<Promise> promise,
206
                              bool silent) {
207
23089
  Local<Context> context = env->context();
208
209
  Local<Object> obj;
210
69267
  if (!env->promise_wrap_template()->NewInstance(context).ToLocal(&obj))
211
    return nullptr;
212
213
46178
  CHECK_NULL(promise->GetAlignedPointerFromInternalField(0));
214
23089
  promise->SetInternalField(0, obj);
215
216
  // Skip for init events
217
23089
  if (silent) {
218
    double async_id;
219
    double trigger_async_id;
220
318
    if (!GetAssignedPromiseAsyncId(env, promise, env->async_id_symbol())
221
106
            .To(&async_id)) return nullptr;
222
318
    if (!GetAssignedPromiseAsyncId(env, promise, env->trigger_async_id_symbol())
223
106
            .To(&trigger_async_id)) return nullptr;
224
225

106
    if (async_id != AsyncWrap::kInvalidAsyncId &&
226
        trigger_async_id != AsyncWrap::kInvalidAsyncId) {
227
      return new PromiseWrap(
228
          env, obj, async_id, trigger_async_id);
229
    }
230
  }
231
232
23089
  return new PromiseWrap(env, obj, silent);
233
}
234
235
19
void PromiseWrap::GetAsyncId(Local<Name> property,
236
                             const PropertyCallbackInfo<Value>& info) {
237
19
  Isolate* isolate = info.GetIsolate();
238
38
  HandleScope scope(isolate);
239
240
19
  PromiseWrap* wrap = Unwrap<PromiseWrap>(info.Holder());
241
19
  double value = wrap->get_async_id();
242
243
57
  info.GetReturnValue().Set(Number::New(isolate, value));
244
19
}
245
246
19
void PromiseWrap::GetTriggerAsyncId(Local<Name> property,
247
                                    const PropertyCallbackInfo<Value>& info) {
248
19
  Isolate* isolate = info.GetIsolate();
249
38
  HandleScope scope(isolate);
250
251
19
  PromiseWrap* wrap = Unwrap<PromiseWrap>(info.Holder());
252
19
  double value = wrap->get_trigger_async_id();
253
254
57
  info.GetReturnValue().Set(Number::New(isolate, value));
255
19
}
256
257
470
void PromiseWrap::Initialize(Environment* env) {
258
470
  Isolate* isolate = env->isolate();
259
940
  HandleScope scope(isolate);
260
261
470
  Local<FunctionTemplate> ctor = FunctionTemplate::New(isolate);
262
940
  ctor->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "PromiseWrap"));
263
264
470
  Local<ObjectTemplate> promise_wrap_template = ctor->InstanceTemplate();
265
470
  env->set_promise_wrap_template(promise_wrap_template);
266
267
470
  promise_wrap_template->SetInternalFieldCount(
268
470
      PromiseWrap::kInternalFieldCount);
269
270
1410
  promise_wrap_template->SetAccessor(
271
      env->async_id_symbol(),
272
470
      PromiseWrap::GetAsyncId);
273
274
1410
  promise_wrap_template->SetAccessor(
275
      env->trigger_async_id_symbol(),
276
470
      PromiseWrap::GetTriggerAsyncId);
277
470
}
278
279
82575
static PromiseWrap* extractPromiseWrap(Local<Promise> promise) {
280
  // This check is imperfect. If the internal field is set, it should
281
  // be an object. If it's not, we just ignore it. Ideally v8 would
282
  // have had GetInternalField returning a MaybeLocal but this works
283
  // for now.
284
165150
  Local<Value> obj = promise->GetInternalField(0);
285
142061
  return obj->IsObject() ? Unwrap<PromiseWrap>(obj.As<Object>()) : nullptr;
286
}
287
288
147
static uint16_t ToAsyncHooksType(PromiseHookType type) {
289

147
  switch (type) {
290
131
    case PromiseHookType::kInit:    return AsyncHooks::kInit;
291
6
    case PromiseHookType::kBefore:  return AsyncHooks::kBefore;
292
6
    case PromiseHookType::kAfter:   return AsyncHooks::kAfter;
293
4
    case PromiseHookType::kResolve: return AsyncHooks::kPromiseResolve;
294
  }
295
  UNREACHABLE();
296
}
297
298
// Simplified JavaScript hook fast-path for when there is no destroy hook
299
354
static void FastPromiseHook(PromiseHookType type, Local<Promise> promise,
300
                            Local<Value> parent) {
301
708
  Local<Context> context = promise->GetCreationContext().ToLocalChecked();
302
354
  Environment* env = Environment::GetCurrent(context);
303
561
  if (env == nullptr) return;
304
305

757
  if (type == PromiseHookType::kBefore &&
306
403
      env->async_hooks()->fields()[AsyncHooks::kBefore] == 0) {
307
    double async_id;
308
    double trigger_async_id;
309
132
    if (!GetAssignedPromiseAsyncId(env, promise, env->async_id_symbol())
310
87
            .To(&async_id)) return;
311
132
    if (!GetAssignedPromiseAsyncId(env, promise, env->trigger_async_id_symbol())
312
44
            .To(&trigger_async_id)) return;
313
314

87
    if (async_id != AsyncWrap::kInvalidAsyncId &&
315
43
        trigger_async_id != AsyncWrap::kInvalidAsyncId) {
316
86
      env->async_hooks()->push_async_context(
317
86
          async_id, trigger_async_id, promise);
318
43
      return;
319
    }
320
  }
321
322

671
  if (type == PromiseHookType::kAfter &&
323
360
      env->async_hooks()->fields()[AsyncHooks::kAfter] == 0) {
324
    double async_id;
325
129
    if (!GetAssignedPromiseAsyncId(env, promise, env->async_id_symbol())
326
86
            .To(&async_id)) return;
327
328
43
    if (async_id != AsyncWrap::kInvalidAsyncId) {
329
43
      if (env->execution_async_id() == async_id) {
330
        // This condition might not be true if async_hooks was enabled during
331
        // the promise callback execution.
332
41
        env->async_hooks()->pop_async_context(async_id);
333
      }
334
43
      return;
335
    }
336
  }
337
338

661
  if (type == PromiseHookType::kResolve &&
339
393
      env->async_hooks()->fields()[AsyncHooks::kPromiseResolve] == 0) {
340
121
    return;
341
  }
342
343
  // Getting up to this point means either init type or
344
  // that there are active hooks of another type.
345
  // In both cases fast-path JS hook should be called.
346
347
  Local<Value> argv[] = {
348
147
    Integer::New(env->isolate(), ToAsyncHooksType(type)),
349
    promise,
350
    parent
351
588
  };
352
353
286
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
354
147
  Local<Function> promise_hook = env->promise_hook_handler();
355
294
  USE(promise_hook->Call(context, Undefined(env->isolate()), 3, argv));
356
}
357
358
70748
static void FullPromiseHook(PromiseHookType type, Local<Promise> promise,
359
                            Local<Value> parent) {
360
141496
  Local<Context> context = promise->GetCreationContext().ToLocalChecked();
361
362
70748
  Environment* env = Environment::GetCurrent(context);
363
70748
  if (env == nullptr) return;
364
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
365
141496
                              "EnvPromiseHook", env);
366
367
70748
  PromiseWrap* wrap = extractPromiseWrap(promise);
368

70748
  if (type == PromiseHookType::kInit || wrap == nullptr) {
369
23065
    bool silent = type != PromiseHookType::kInit;
370
371
    // set parent promise's async Id as this promise's triggerAsyncId
372
23065
    if (parent->IsPromise()) {
373
      // parent promise exists, current promise
374
      // is a chained promise, so we set parent promise's id as
375
      // current promise's triggerAsyncId
376
11827
      Local<Promise> parent_promise = parent.As<Promise>();
377
11827
      PromiseWrap* parent_wrap = extractPromiseWrap(parent_promise);
378
11827
      if (parent_wrap == nullptr) {
379
24
        parent_wrap = PromiseWrap::New(env, parent_promise, true);
380
24
        if (parent_wrap == nullptr) return;
381
      }
382
383
23654
      AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent_wrap);
384
11827
      wrap = PromiseWrap::New(env, promise, silent);
385
    } else {
386
11238
      wrap = PromiseWrap::New(env, promise, silent);
387
    }
388
  }
389
390
70748
  if (wrap == nullptr) return;
391
392
70748
  if (type == PromiseHookType::kBefore) {
393
12189
    env->async_hooks()->push_async_context(wrap->get_async_id(),
394
12189
      wrap->get_trigger_async_id(), wrap->object());
395
12189
    wrap->EmitTraceEventBefore();
396
12189
    AsyncWrap::EmitBefore(wrap->env(), wrap->get_async_id());
397
58559
  } else if (type == PromiseHookType::kAfter) {
398
12212
    wrap->EmitTraceEventAfter(wrap->provider_type(), wrap->get_async_id());
399
12212
    AsyncWrap::EmitAfter(wrap->env(), wrap->get_async_id());
400
12212
    if (env->execution_async_id() == wrap->get_async_id()) {
401
      // This condition might not be true if async_hooks was enabled during
402
      // the promise callback execution.
403
      // Popping it off the stack can be skipped in that case, because it is
404
      // known that it would correspond to exactly one call with
405
      // PromiseHookType::kBefore that was not witnessed by the PromiseHook.
406
12187
      env->async_hooks()->pop_async_context(wrap->get_async_id());
407
    }
408
46347
  } else if (type == PromiseHookType::kResolve) {
409
23364
    AsyncWrap::EmitPromiseResolve(wrap->env(), wrap->get_async_id());
410
  }
411
}
412
413
470
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
414
470
  Environment* env = Environment::GetCurrent(args);
415
416
940
  CHECK(args[0]->IsObject());
417
418
  // All of init, before, after, destroy, and promise_resolve are supplied by
419
  // async_hooks internally, so this should only ever be called once. At which
420
  // time all the functions should be set. Detect this by checking if
421
  // init !IsEmpty().
422
940
  CHECK(env->async_hooks_init_function().IsEmpty());
423
424
940
  Local<Object> fn_obj = args[0].As<Object>();
425
426
#define SET_HOOK_FN(name)                                                      \
427
  do {                                                                         \
428
    Local<Value> v =                                                           \
429
        fn_obj->Get(env->context(),                                            \
430
                    FIXED_ONE_BYTE_STRING(env->isolate(), #name))              \
431
            .ToLocalChecked();                                                 \
432
    CHECK(v->IsFunction());                                                    \
433
    env->set_async_hooks_##name##_function(v.As<Function>());                  \
434
  } while (0)
435
436
2820
  SET_HOOK_FN(init);
437
2820
  SET_HOOK_FN(before);
438
2820
  SET_HOOK_FN(after);
439
2820
  SET_HOOK_FN(destroy);
440
2820
  SET_HOOK_FN(promise_resolve);
441
#undef SET_HOOK_FN
442
470
}
443
444
344
static void EnablePromiseHook(const FunctionCallbackInfo<Value>& args) {
445
344
  Environment* env = Environment::GetCurrent(args);
446
447
688
  if (args[0]->IsFunction()) {
448
128
    env->set_promise_hook_handler(args[0].As<Function>());
449
64
    args.GetIsolate()->SetPromiseHook(FastPromiseHook);
450
  } else {
451
280
    args.GetIsolate()->SetPromiseHook(FullPromiseHook);
452
  }
453
344
}
454
455
456
64
static void DisablePromiseHook(const FunctionCallbackInfo<Value>& args) {
457
64
  Environment* env = Environment::GetCurrent(args);
458
64
  env->set_promise_hook_handler(Local<Function>());
459
460
  // The per-Isolate API provides no way of knowing whether there are multiple
461
  // users of the PromiseHook. That hopefully goes away when V8 introduces
462
  // a per-context API.
463
64
  args.GetIsolate()->SetPromiseHook(nullptr);
464
64
}
465
466
467
14931
class DestroyParam {
468
 public:
469
  double asyncId;
470
  Environment* env;
471
  Global<Object> target;
472
  Global<Object> propBag;
473
};
474
475
11
static void DestroyParamCleanupHook(void* ptr) {
476
11
  delete static_cast<DestroyParam*>(ptr);
477
11
}
478
479
2477
void AsyncWrap::WeakCallback(const WeakCallbackInfo<DestroyParam>& info) {
480
4954
  HandleScope scope(info.GetIsolate());
481
482
4954
  std::unique_ptr<DestroyParam> p{info.GetParameter()};
483
  Local<Object> prop_bag = PersistentToLocal::Default(info.GetIsolate(),
484
4954
                                                      p->propBag);
485
  Local<Value> val;
486
487
2477
  p->env->RemoveCleanupHook(DestroyParamCleanupHook, p.get());
488
489
9908
  if (!prop_bag->Get(p->env->context(), p->env->destroyed_string())
490
2477
        .ToLocal(&val)) {
491
    return;
492
  }
493
494
2477
  if (val->IsFalse()) {
495
2472
    AsyncWrap::EmitDestroy(p->env, p->asyncId);
496
  }
497
  // unique_ptr goes out of scope here and pointer is deleted.
498
}
499
500
501
2489
static void RegisterDestroyHook(const FunctionCallbackInfo<Value>& args) {
502
4978
  CHECK(args[0]->IsObject());
503
4978
  CHECK(args[1]->IsNumber());
504
4978
  CHECK(args[2]->IsObject());
505
506
2489
  Isolate* isolate = args.GetIsolate();
507
2489
  DestroyParam* p = new DestroyParam();
508
7467
  p->asyncId = args[1].As<Number>()->Value();
509
2489
  p->env = Environment::GetCurrent(args);
510
7467
  p->target.Reset(isolate, args[0].As<Object>());
511
7467
  p->propBag.Reset(isolate, args[2].As<Object>());
512
2489
  p->target.SetWeak(p, AsyncWrap::WeakCallback, WeakCallbackType::kParameter);
513
2489
  p->env->AddCleanupHook(DestroyParamCleanupHook, p);
514
2489
}
515
516
96017
void AsyncWrap::GetAsyncId(const FunctionCallbackInfo<Value>& args) {
517
  AsyncWrap* wrap;
518
192034
  args.GetReturnValue().Set(kInvalidAsyncId);
519
96017
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
520
287988
  args.GetReturnValue().Set(wrap->get_async_id());
521
}
522
523
524
10
void AsyncWrap::PushAsyncContext(const FunctionCallbackInfo<Value>& args) {
525
10
  Environment* env = Environment::GetCurrent(args);
526
  // No need for CHECK(IsNumber()) on args because if FromJust() doesn't fail
527
  // then the checks in push_async_ids() and pop_async_id() will.
528
40
  double async_id = args[0]->NumberValue(env->context()).FromJust();
529
40
  double trigger_async_id = args[1]->NumberValue(env->context()).FromJust();
530
10
  env->async_hooks()->push_async_context(async_id, trigger_async_id, {});
531
10
}
532
533
534
3
void AsyncWrap::PopAsyncContext(const FunctionCallbackInfo<Value>& args) {
535
3
  Environment* env = Environment::GetCurrent(args);
536
12
  double async_id = args[0]->NumberValue(env->context()).FromJust();
537
3
  args.GetReturnValue().Set(env->async_hooks()->pop_async_context(async_id));
538
}
539
540
541
278
void AsyncWrap::ExecutionAsyncResource(
542
    const FunctionCallbackInfo<Value>& args) {
543
278
  Environment* env = Environment::GetCurrent(args);
544
  uint32_t index;
545
1112
  if (!args[0]->Uint32Value(env->context()).To(&index)) return;
546
834
  args.GetReturnValue().Set(
547
      env->async_hooks()->native_execution_async_resource(index));
548
}
549
550
551
1232
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
552
1232
  Environment* env = Environment::GetCurrent(args);
553
1232
  env->async_hooks()->clear_async_id_stack();
554
1232
}
555
556
557
284
void AsyncWrap::AsyncReset(const FunctionCallbackInfo<Value>& args) {
558
568
  CHECK(args[0]->IsObject());
559
560
  AsyncWrap* wrap;
561
284
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
562
563
568
  Local<Object> resource = args[0].As<Object>();
564
  double execution_async_id =
565
568
      args[1]->IsNumber() ? args[1].As<Number>()->Value() : kInvalidAsyncId;
566
284
  wrap->AsyncReset(resource, execution_async_id);
567
}
568
569
570
284
void AsyncWrap::GetProviderType(const FunctionCallbackInfo<Value>& args) {
571
  AsyncWrap* wrap;
572
568
  args.GetReturnValue().Set(AsyncWrap::PROVIDER_NONE);
573
284
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
574
852
  args.GetReturnValue().Set(wrap->provider_type());
575
}
576
577
578
219590
void AsyncWrap::EmitDestroy(bool from_gc) {
579
219590
  AsyncWrap::EmitDestroy(env(), async_id_);
580
  // Ensure no double destroy is emitted via AsyncReset().
581
219590
  async_id_ = kInvalidAsyncId;
582
583

439180
  if (!persistent().IsEmpty() && !from_gc) {
584
12814
    HandleScope handle_scope(env()->isolate());
585
25628
    USE(object()->Set(env()->context(), env()->resource_symbol(), object()));
586
  }
587
219590
}
588
589
72473
void AsyncWrap::QueueDestroyAsyncId(const FunctionCallbackInfo<Value>& args) {
590
144946
  CHECK(args[0]->IsNumber());
591
72473
  AsyncWrap::EmitDestroy(
592
      Environment::GetCurrent(args),
593
217419
      args[0].As<Number>()->Value());
594
72473
}
595
596
470
void AsyncWrap::SetCallbackTrampoline(const FunctionCallbackInfo<Value>& args) {
597
470
  Environment* env = Environment::GetCurrent(args);
598
599
940
  CHECK(args[0]->IsFunction());
600
601
940
  env->set_async_hooks_callback_trampoline(args[0].As<Function>());
602
470
}
603
604
123523
Local<FunctionTemplate> AsyncWrap::GetConstructorTemplate(Environment* env) {
605
123523
  Local<FunctionTemplate> tmpl = env->async_wrap_ctor_template();
606
123523
  if (tmpl.IsEmpty()) {
607
470
    tmpl = env->NewFunctionTemplate(nullptr);
608
940
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "AsyncWrap"));
609
940
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
610
470
    env->SetProtoMethod(tmpl, "getAsyncId", AsyncWrap::GetAsyncId);
611
470
    env->SetProtoMethod(tmpl, "asyncReset", AsyncWrap::AsyncReset);
612
470
    env->SetProtoMethod(tmpl, "getProviderType", AsyncWrap::GetProviderType);
613
470
    env->set_async_wrap_ctor_template(tmpl);
614
  }
615
123523
  return tmpl;
616
}
617
618
470
void AsyncWrap::Initialize(Local<Object> target,
619
                           Local<Value> unused,
620
                           Local<Context> context,
621
                           void* priv) {
622
470
  Environment* env = Environment::GetCurrent(context);
623
470
  Isolate* isolate = env->isolate();
624
940
  HandleScope scope(isolate);
625
626
470
  env->SetMethod(target, "setupHooks", SetupHooks);
627
470
  env->SetMethod(target, "setCallbackTrampoline", SetCallbackTrampoline);
628
470
  env->SetMethod(target, "pushAsyncContext", PushAsyncContext);
629
470
  env->SetMethod(target, "popAsyncContext", PopAsyncContext);
630
470
  env->SetMethod(target, "executionAsyncResource", ExecutionAsyncResource);
631
470
  env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack);
632
470
  env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId);
633
470
  env->SetMethod(target, "enablePromiseHook", EnablePromiseHook);
634
470
  env->SetMethod(target, "disablePromiseHook", DisablePromiseHook);
635
470
  env->SetMethod(target, "registerDestroyHook", RegisterDestroyHook);
636
637
  PropertyAttribute ReadOnlyDontDelete =
638
470
      static_cast<PropertyAttribute>(ReadOnly | DontDelete);
639
640
#define FORCE_SET_TARGET_FIELD(obj, str, field)                               \
641
  (obj)->DefineOwnProperty(context,                                           \
642
                           FIXED_ONE_BYTE_STRING(isolate, str),               \
643
                           field,                                             \
644
                           ReadOnlyDontDelete).FromJust()
645
646
  // Attach the uint32_t[] where each slot contains the count of the number of
647
  // callbacks waiting to be called on a particular event. It can then be
648
  // incremented/decremented from JS quickly to communicate to C++ if there are
649
  // any callbacks waiting to be called.
650
1880
  FORCE_SET_TARGET_FIELD(target,
651
                         "async_hook_fields",
652
                         env->async_hooks()->fields().GetJSArray());
653
654
  // The following v8::Float64Array has 5 fields. These fields are shared in
655
  // this way to allow JS and C++ to read/write each value as quickly as
656
  // possible. The fields are represented as follows:
657
  //
658
  // kAsyncIdCounter: Maintains the state of the next unique id to be assigned.
659
  //
660
  // kDefaultTriggerAsyncId: Write the id of the resource responsible for a
661
  //   handle's creation just before calling the new handle's constructor.
662
  //   After the new handle is constructed kDefaultTriggerAsyncId is set back
663
  //   to kInvalidAsyncId.
664
1880
  FORCE_SET_TARGET_FIELD(target,
665
                         "async_id_fields",
666
                         env->async_hooks()->async_id_fields().GetJSArray());
667
668
1880
  FORCE_SET_TARGET_FIELD(target,
669
                         "execution_async_resources",
670
                         env->async_hooks()->js_execution_async_resources());
671
672
940
  target->Set(context,
673
              env->async_ids_stack_string(),
674
1880
              env->async_hooks()->async_ids_stack().GetJSArray()).Check();
675
676
470
  Local<Object> constants = Object::New(isolate);
677
#define SET_HOOKS_CONSTANT(name)                                              \
678
  FORCE_SET_TARGET_FIELD(                                                     \
679
      constants, #name, Integer::New(isolate, AsyncHooks::name))
680
681
1880
  SET_HOOKS_CONSTANT(kInit);
682
1880
  SET_HOOKS_CONSTANT(kBefore);
683
1880
  SET_HOOKS_CONSTANT(kAfter);
684
1880
  SET_HOOKS_CONSTANT(kDestroy);
685
1880
  SET_HOOKS_CONSTANT(kPromiseResolve);
686
1880
  SET_HOOKS_CONSTANT(kTotals);
687
1880
  SET_HOOKS_CONSTANT(kCheck);
688
1880
  SET_HOOKS_CONSTANT(kExecutionAsyncId);
689
1880
  SET_HOOKS_CONSTANT(kTriggerAsyncId);
690
1880
  SET_HOOKS_CONSTANT(kAsyncIdCounter);
691
1880
  SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
692
1880
  SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource);
693
1880
  SET_HOOKS_CONSTANT(kStackLength);
694
#undef SET_HOOKS_CONSTANT
695
1410
  FORCE_SET_TARGET_FIELD(target, "constants", constants);
696
697
470
  Local<Object> async_providers = Object::New(isolate);
698
#define V(p)                                                                  \
699
  FORCE_SET_TARGET_FIELD(                                                     \
700
      async_providers, #p, Integer::New(isolate, AsyncWrap::PROVIDER_ ## p));
701
54050
  NODE_ASYNC_PROVIDER_TYPES(V)
702
#undef V
703
4230
  FORCE_SET_TARGET_FIELD(target, "Providers", async_providers);
704
705
2820
#undef FORCE_SET_TARGET_FIELD
706
2820
707
2350
  env->set_async_hooks_init_function(Local<Function>());
708
1410
  env->set_async_hooks_before_function(Local<Function>());
709
3290
  env->set_async_hooks_after_function(Local<Function>());
710
2350
  env->set_async_hooks_destroy_function(Local<Function>());
711
1410
  env->set_async_hooks_promise_resolve_function(Local<Function>());
712
3290
  env->set_async_hooks_binding(target);
713
1880
714
940
  // TODO(qard): maybe this should be GetConstructorTemplate instead?
715
3290
  PromiseWrap::Initialize(env);
716
2350
}
717
940
718
7583
void AsyncWrap::RegisterExternalReferences(
719
1880
    ExternalReferenceRegistry* registry) {
720
5703
  registry->Register(SetupHooks);
721
7583
  registry->Register(SetCallbackTrampoline);
722
7583
  registry->Register(PushAsyncContext);
723
6643
  registry->Register(PopAsyncContext);
724
5703
  registry->Register(ExecutionAsyncResource);
725
7583
  registry->Register(ClearAsyncIdStack);
726
6643
  registry->Register(QueueDestroyAsyncId);
727
5703
  registry->Register(EnablePromiseHook);
728
7583
  registry->Register(DisablePromiseHook);
729
6643
  registry->Register(RegisterDestroyHook);
730
5703
  registry->Register(AsyncWrap::GetAsyncId);
731
7583
  registry->Register(AsyncWrap::AsyncReset);
732
7583
  registry->Register(AsyncWrap::GetProviderType);
733
4763
  registry->Register(PromiseWrap::GetAsyncId);
734
4763
  registry->Register(PromiseWrap::GetTriggerAsyncId);
735
4763
}
736
737
188672
AsyncWrap::AsyncWrap(Environment* env,
738
                     Local<Object> object,
739
                     ProviderType provider,
740
188672
                     double execution_async_id)
741
188672
    : AsyncWrap(env, object, provider, execution_async_id, false) {}
742
743
211761
AsyncWrap::AsyncWrap(Environment* env,
744
                     Local<Object> object,
745
                     ProviderType provider,
746
                     double execution_async_id,
747
211761
                     bool silent)
748
211761
    : AsyncWrap(env, object) {
749
211761
  CHECK_NE(provider, PROVIDER_NONE);
750
211761
  provider_type_ = provider;
751
752
  // Use AsyncReset() call to execute the init() callbacks.
753
211761
  AsyncReset(object, execution_async_id, silent);
754
211761
  init_hook_ran_ = true;
755
211761
}
756
757
AsyncWrap::AsyncWrap(Environment* env,
758
                     Local<Object> object,
759
                     ProviderType provider,
760
                     double execution_async_id,
761
                     double trigger_async_id)
762
    : AsyncWrap(env, object, provider, execution_async_id, true) {
763
  trigger_async_id_ = trigger_async_id;
764
}
765
766
215417
AsyncWrap::AsyncWrap(Environment* env, Local<Object> object)
767
215417
  : BaseObject(env, object) {
768
215417
}
769
770
// This method is necessary to work around one specific problem:
771
// Before the init() hook runs, if there is one, the BaseObject() constructor
772
// registers this object with the Environment for finalization and debugging
773
// purposes.
774
// If the Environment decides to inspect this object for debugging, it tries to
775
// call virtual methods on this object that are only (meaningfully) implemented
776
// by the subclasses of AsyncWrap.
777
// This could, with bad luck, happen during the AsyncWrap() constructor,
778
// because we run JS code as part of it and that in turn can lead to a heapdump
779
// being taken, either through the inspector or our programmatic API for it.
780
// The object being initialized is not fully constructed at that point, and
781
// in particular its virtual function table points to the AsyncWrap one
782
// (as the subclass constructor has not yet begun execution at that point).
783
// This means that the functions that are used for heap dump memory tracking
784
// are not yet available, and trying to call them would crash the process.
785
// We use this particular `IsDoneInitializing()` method to tell the Environment
786
// that such debugging methods are not yet available.
787
// This may be somewhat unreliable when it comes to future changes, because
788
// at this point it *only* protects AsyncWrap subclasses, and *only* for cases
789
// where heap dumps are being taken while the init() hook is on the call stack.
790
// For now, it seems like the best solution, though.
791
204848
bool AsyncWrap::IsDoneInitializing() const {
792
204848
  return init_hook_ran_;
793
}
794
795
426367
AsyncWrap::~AsyncWrap() {
796
213184
  EmitTraceEventDestroy();
797
213183
  EmitDestroy(true /* from gc */);
798
213183
}
799
800
219112
void AsyncWrap::EmitTraceEventDestroy() {
801














219112
  switch (provider_type()) {
802
  #define V(PROVIDER)                                                         \
803
    case PROVIDER_ ## PROVIDER:                                               \
804
      TRACE_EVENT_NESTABLE_ASYNC_END0(                                        \
805
        TRACING_CATEGORY_NODE1(async_hooks),                                  \
806
        #PROVIDER, static_cast<int64_t>(get_async_id()));                     \
807
      break;
808

























































438224
    NODE_ASYNC_PROVIDER_TYPES(V)
809
  #undef V
810
    default:
811
      UNREACHABLE();
812
  }
813
219112
}
814
815
295083
void AsyncWrap::EmitDestroy(Environment* env, double async_id) {
816

408824
  if (env->async_hooks()->fields()[AsyncHooks::kDestroy] == 0 ||
817
113741
      !env->can_call_into_js()) {
818
181709
    return;
819
  }
820
821
113375
  if (env->destroy_async_id_list()->empty()) {
822
23293
    env->SetImmediate(&DestroyAsyncIdsCallback, CallbackFlags::kUnrefed);
823
  }
824
825
  // If the list gets very large empty it faster using a Microtask.
826
  // Microtasks can't be added in GC context therefore we use an
827
  // interrupt to get this Microtask scheduled as fast as possible.
828
113375
  if (env->destroy_async_id_list()->size() == 16384) {
829
2
    env->RequestInterrupt([](Environment* env) {
830
4
      env->context()->GetMicrotaskQueue()->EnqueueMicrotask(
831
        env->isolate(),
832
3
        [](void* arg) {
833
1
          DestroyAsyncIdsCallback(static_cast<Environment*>(arg));
834
5
        }, env);
835
2
      });
836
  }
837
838
113375
  env->destroy_async_id_list()->push_back(async_id);
839
}
840
841
// Generalized call for both the constructor and for handles that are pooled
842
// and reused over their lifetime. This way a new uid can be assigned when
843
// the resource is pulled out of the pool and put back into use.
844
218362
void AsyncWrap::AsyncReset(Local<Object> resource, double execution_async_id,
845
                           bool silent) {
846
218362
  CHECK_NE(provider_type(), PROVIDER_NONE);
847
848
218362
  if (async_id_ != kInvalidAsyncId) {
849
    // This instance was in use before, we have already emitted an init with
850
    // its previous async_id and need to emit a matching destroy for that
851
    // before generating a new async_id.
852
478
    EmitDestroy();
853
  }
854
855
  // Now we can assign a new async_id_ to this instance.
856
218362
  async_id_ = execution_async_id == kInvalidAsyncId ? env()->new_async_id()
857
                                                     : execution_async_id;
858
218362
  trigger_async_id_ = env()->get_default_trigger_async_id();
859
860
  {
861
436724
    HandleScope handle_scope(env()->isolate());
862
218362
    Local<Object> obj = object();
863
218362
    CHECK(!obj.IsEmpty());
864
218362
    if (resource != obj) {
865
19803
      USE(obj->Set(env()->context(), env()->resource_symbol(), resource));
866
    }
867
  }
868
869














218362
  switch (provider_type()) {
870
#define V(PROVIDER)                                                           \
871
    case PROVIDER_ ## PROVIDER:                                               \
872
      if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(                        \
873
          TRACING_CATEGORY_NODE1(async_hooks))) {                             \
874
        auto data = tracing::TracedValue::Create();                           \
875
        data->SetInteger("executionAsyncId",                                  \
876
                         static_cast<int64_t>(env()->execution_async_id()));  \
877
        data->SetInteger("triggerAsyncId",                                    \
878
                         static_cast<int64_t>(get_trigger_async_id()));       \
879
        TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(                                    \
880
          TRACING_CATEGORY_NODE1(async_hooks),                                \
881
          #PROVIDER, static_cast<int64_t>(get_async_id()),                    \
882
          "data", std::move(data));                                           \
883
        }                                                                     \
884
      break;
885























































































52
    NODE_ASYNC_PROVIDER_TYPES(V)
886
#undef V
887
    default:
888
      UNREACHABLE();
889
  }
890
891
218361
  if (silent) return;
892
893
436511
  EmitAsyncInit(env(), resource,
894
218255
                env()->async_hooks()->provider_string(provider_type()),
895
218256
                async_id_, trigger_async_id_);
896
}
897
898
899
218808
void AsyncWrap::EmitAsyncInit(Environment* env,
900
                              Local<Object> object,
901
                              Local<String> type,
902
                              double async_id,
903
                              double trigger_async_id) {
904
218808
  CHECK(!object.IsEmpty());
905
218808
  CHECK(!type.IsEmpty());
906
218808
  AsyncHooks* async_hooks = env->async_hooks();
907
908
  // Nothing to execute, so can continue normally.
909
218808
  if (async_hooks->fields()[AsyncHooks::kInit] == 0) {
910
178683
    return;
911
  }
912
913
80250
  HandleScope scope(env->isolate());
914
40125
  Local<Function> init_fn = env->async_hooks_init_function();
915
916
  Local<Value> argv[] = {
917
    Number::New(env->isolate(), async_id),
918
    type,
919
    Number::New(env->isolate(), trigger_async_id),
920
    object,
921
200625
  };
922
923
80250
  TryCatchScope try_catch(env, TryCatchScope::CatchMode::kFatal);
924
120375
  USE(init_fn->Call(env->context(), object, arraysize(argv), argv));
925
}
926
927
928
335390
MaybeLocal<Value> AsyncWrap::MakeCallback(const Local<Function> cb,
929
                                          int argc,
930
                                          Local<Value>* argv) {
931
335390
  EmitTraceEventBefore();
932
933
335344
  ProviderType provider = provider_type();
934
335392
  async_context context { get_async_id(), get_trigger_async_id() };
935
  MaybeLocal<Value> ret = InternalMakeCallback(
936
335405
      env(), object(), object(), cb, argc, argv, context);
937
938
  // This is a static call with cached values because the `this` object may
939
  // no longer be alive at this point.
940
335276
  EmitTraceEventAfter(provider, context.async_id);
941
942
335280
  return ret;
943
}
944
945
std::string AsyncWrap::MemoryInfoName() const {
946
  return provider_names[provider_type()];
947
}
948
949
std::string AsyncWrap::diagnostic_name() const {
950
  return MemoryInfoName() + " (" + std::to_string(env()->thread_id()) + ":" +
951
      std::to_string(static_cast<int64_t>(async_id_)) + ")";
952
}
953
954
939
Local<Object> AsyncWrap::GetOwner() {
955
939
  return GetOwner(env(), object());
956
}
957
958
939
Local<Object> AsyncWrap::GetOwner(Environment* env, Local<Object> obj) {
959
939
  EscapableHandleScope handle_scope(env->isolate());
960
939
  CHECK(!obj.IsEmpty());
961
962
1878
  TryCatchScope ignore_exceptions(env);
963
  while (true) {
964
    Local<Value> owner;
965
7456
    if (!obj->Get(env->context(),
966

13048
                  env->owner_symbol()).ToLocal(&owner) ||
967
1864
        !owner->IsObject()) {
968
1878
      return handle_scope.Escape(obj);
969
    }
970
971
925
    obj = owner.As<Object>();
972
925
  }
973
}
974
975
}  // namespace node
976
977
4821
NODE_MODULE_CONTEXT_AWARE_INTERNAL(async_wrap, node::AsyncWrap::Initialize)
978

19250
NODE_MODULE_EXTERNAL_REFERENCE(async_wrap,
979
                               node::AsyncWrap::RegisterExternalReferences)