Skip to content

Commit 7c079d1

Browse files
committed
async_hooks: skip runtime checks when disabled
PR-URL: #15454 Ref: #14387 Ref: #14722 Ref: #14717 Ref: #15448 Reviewed-By: Refael Ackermann <refack@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net>
1 parent f8ef2e2 commit 7c079d1

15 files changed

+192
-87
lines changed

doc/api/cli.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,14 @@ added: v2.1.0
208208
Prints a stack trace whenever synchronous I/O is detected after the first turn
209209
of the event loop.
210210

211+
### `--force-async-hooks-checks`
212+
<!-- YAML
213+
added: REPLACEME
214+
-->
215+
216+
Enables runtime checks for `async_hooks`. These can also be enabled dynamically
217+
by enabling one of the `async_hooks` hooks.
218+
211219
### `--trace-events-enabled`
212220
<!-- YAML
213221
added: v7.7.0

doc/node.1

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ Write process warnings to the given file instead of printing to stderr.
152152
Print a stack trace whenever synchronous I/O is detected after the first turn
153153
of the event loop.
154154

155+
.TP
156+
.BR \-\-force\-async\-hooks\-checks
157+
Enables runtime checks for `async_hooks`. These can also be enabled dynamically
158+
by enabling one of the `async_hooks` hooks.
159+
155160
.TP
156161
.BR \-\-trace\-events\-enabled
157162
Enables the collection of trace event tracing information.

lib/_http_outgoing.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,15 @@ function _writeRaw(data, encoding, callback) {
262262
this._flushOutput(conn);
263263
} else if (!data.length) {
264264
if (typeof callback === 'function') {
265-
nextTick(this.socket[async_id_symbol], callback);
265+
let socketAsyncId = this.socket[async_id_symbol];
266+
// If the socket was set directly it won't be correctly initialized
267+
// with an async_id_symbol.
268+
// TODO(AndreasMadsen): @trevnorris suggested some more correct
269+
// solutions in:
270+
// https://github.com/nodejs/node/pull/14389/files#r128522202
271+
if (socketAsyncId === undefined) socketAsyncId = null;
272+
273+
nextTick(socketAsyncId, callback);
266274
}
267275
return true;
268276
}

lib/async_hooks.js

Lines changed: 28 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ const active_hooks = {
6060
// async execution. These are tracked so if the user didn't include callbacks
6161
// for a given step, that step can bail out early.
6262
const { kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,
63-
kExecutionAsyncId, kTriggerAsyncId, kAsyncIdCounter,
63+
kCheck, kExecutionAsyncId, kTriggerAsyncId, kAsyncIdCounter,
6464
kInitTriggerAsyncId } = async_wrap.constants;
6565

6666
// Symbols used to store the respective ids on both AsyncResource instances and
@@ -156,8 +156,10 @@ class AsyncHook {
156156
hook_fields[kPromiseResolve] += +!!this[promise_resolve_symbol];
157157
hooks_array.push(this);
158158

159-
if (prev_kTotals === 0 && hook_fields[kTotals] > 0)
159+
if (prev_kTotals === 0 && hook_fields[kTotals] > 0) {
160160
enablePromiseHook();
161+
hook_fields[kCheck] += 1;
162+
}
161163

162164
return this;
163165
}
@@ -180,8 +182,10 @@ class AsyncHook {
180182
hook_fields[kPromiseResolve] -= +!!this[promise_resolve_symbol];
181183
hooks_array.splice(index, 1);
182184

183-
if (prev_kTotals > 0 && hook_fields[kTotals] === 0)
185+
if (prev_kTotals > 0 && hook_fields[kTotals] === 0) {
184186
disablePromiseHook();
187+
hook_fields[kCheck] -= 1;
188+
}
185189

186190
return this;
187191
}
@@ -243,6 +247,15 @@ function triggerAsyncId() {
243247
return async_id_fields[kTriggerAsyncId];
244248
}
245249

250+
function validateAsyncId(asyncId, type) {
251+
// Skip validation when async_hooks is disabled
252+
if (async_hook_fields[kCheck] <= 0) return;
253+
254+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
255+
fatalError(new errors.RangeError('ERR_INVALID_ASYNC_ID', type, asyncId));
256+
}
257+
}
258+
246259

247260
// Embedder API //
248261

@@ -337,10 +350,16 @@ function setInitTriggerId(triggerAsyncId) {
337350

338351

339352
function emitInitScript(asyncId, type, triggerAsyncId, resource) {
353+
validateAsyncId(asyncId, 'asyncId');
354+
if (triggerAsyncId !== null)
355+
validateAsyncId(triggerAsyncId, 'triggerAsyncId');
356+
if (async_hook_fields[kCheck] > 0 &&
357+
(typeof type !== 'string' || type.length <= 0)) {
358+
throw new errors.TypeError('ERR_ASYNC_TYPE', type);
359+
}
360+
340361
// Short circuit all checks for the common case. Which is that no hooks have
341362
// been set. Do this to remove performance impact for embedders (and core).
342-
// Even though it bypasses all the argument checks. The performance savings
343-
// here is critical.
344363
if (async_hook_fields[kInit] === 0)
345364
return;
346365

@@ -354,18 +373,6 @@ function emitInitScript(asyncId, type, triggerAsyncId, resource) {
354373
async_id_fields[kInitTriggerAsyncId] = 0;
355374
}
356375

357-
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
358-
throw new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId);
359-
}
360-
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
361-
throw new errors.RangeError('ERR_INVALID_ASYNC_ID',
362-
'triggerAsyncId',
363-
triggerAsyncId);
364-
}
365-
if (typeof type !== 'string' || type.length <= 0) {
366-
throw new errors.TypeError('ERR_ASYNC_TYPE', type);
367-
}
368-
369376
emitInitNative(asyncId, type, triggerAsyncId, resource);
370377
}
371378

@@ -411,15 +418,8 @@ function emitBeforeScript(asyncId, triggerAsyncId) {
411418
// Validate the ids. An id of -1 means it was never set and is visible on the
412419
// call graph. An id < -1 should never happen in any circumstance. Throw
413420
// on user calls because async state should still be recoverable.
414-
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
415-
fatalError(
416-
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
417-
}
418-
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
419-
fatalError(new errors.RangeError('ERR_INVALID_ASYNC_ID',
420-
'triggerAsyncId',
421-
triggerAsyncId));
422-
}
421+
validateAsyncId(asyncId, 'asyncId');
422+
validateAsyncId(triggerAsyncId, 'triggerAsyncId');
423423

424424
pushAsyncIds(asyncId, triggerAsyncId);
425425

@@ -429,10 +429,7 @@ function emitBeforeScript(asyncId, triggerAsyncId) {
429429

430430

431431
function emitAfterScript(asyncId) {
432-
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
433-
fatalError(
434-
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
435-
}
432+
validateAsyncId(asyncId, 'asyncId');
436433

437434
if (async_hook_fields[kAfter] > 0)
438435
emitAfterNative(asyncId);
@@ -442,10 +439,7 @@ function emitAfterScript(asyncId) {
442439

443440

444441
function emitDestroyScript(asyncId) {
445-
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
446-
fatalError(
447-
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
448-
}
442+
validateAsyncId(asyncId, 'asyncId');
449443

450444
// Return early if there are no destroy callbacks, or invalid asyncId.
451445
if (async_hook_fields[kDestroy] === 0 || asyncId <= 0)

lib/internal/process/next_tick.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ function setupNextTick() {
281281
if (process._exiting)
282282
return;
283283

284-
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId <= 0) {
284+
if (triggerAsyncId === null) {
285285
triggerAsyncId = async_hooks.initTriggerId();
286286
}
287287

src/async-wrap.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,7 @@ void AsyncWrap::Initialize(Local<Object> target,
526526
SET_HOOKS_CONSTANT(kDestroy);
527527
SET_HOOKS_CONSTANT(kPromiseResolve);
528528
SET_HOOKS_CONSTANT(kTotals);
529+
SET_HOOKS_CONSTANT(kCheck);
529530
SET_HOOKS_CONSTANT(kExecutionAsyncId);
530531
SET_HOOKS_CONSTANT(kTriggerAsyncId);
531532
SET_HOOKS_CONSTANT(kAsyncIdCounter);

src/env-inl.h

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,19 @@ inline v8::Local<v8::String> Environment::AsyncHooks::provider_string(int idx) {
129129
return providers_[idx].Get(isolate_);
130130
}
131131

132+
inline void Environment::AsyncHooks::force_checks() {
133+
// fields_ does not have the += operator defined
134+
fields_[kCheck] = fields_[kCheck] + 1;
135+
}
136+
132137
inline void Environment::AsyncHooks::push_async_ids(double async_id,
133138
double trigger_async_id) {
134-
CHECK_GE(async_id, -1);
135-
CHECK_GE(trigger_async_id, -1);
139+
// Since async_hooks is experimental, do only perform the check
140+
// when async_hooks is enabled.
141+
if (fields_[kCheck] > 0) {
142+
CHECK_GE(async_id, -1);
143+
CHECK_GE(trigger_async_id, -1);
144+
}
136145

137146
async_ids_stack_.push({ async_id_fields_[kExecutionAsyncId],
138147
async_id_fields_[kTriggerAsyncId] });
@@ -145,9 +154,11 @@ inline bool Environment::AsyncHooks::pop_async_id(double async_id) {
145154
// stack was multiple MakeCallback()'s deep.
146155
if (async_ids_stack_.empty()) return false;
147156

148-
// Ask for the async_id to be restored as a sanity check that the stack
157+
// Ask for the async_id to be restored as a check that the stack
149158
// hasn't been corrupted.
150-
if (async_id_fields_[kExecutionAsyncId] != async_id) {
159+
// Since async_hooks is experimental, do only perform the check
160+
// when async_hooks is enabled.
161+
if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
151162
fprintf(stderr,
152163
"Error: async hook stack has become corrupted ("
153164
"actual: %.f, expected: %.f)\n",
@@ -185,7 +196,9 @@ inline Environment::AsyncHooks::InitScope::InitScope(
185196
Environment* env, double init_trigger_async_id)
186197
: env_(env),
187198
async_id_fields_ref_(env->async_hooks()->async_id_fields()) {
188-
CHECK_GE(init_trigger_async_id, -1);
199+
if (env_->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
200+
CHECK_GE(init_trigger_async_id, -1);
201+
}
189202
env->async_hooks()->push_async_ids(
190203
async_id_fields_ref_[AsyncHooks::kExecutionAsyncId],
191204
init_trigger_async_id);

src/env.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,7 @@ class Environment {
387387
kDestroy,
388388
kPromiseResolve,
389389
kTotals,
390+
kCheck,
390391
kFieldsCount,
391392
};
392393

@@ -408,6 +409,8 @@ class Environment {
408409

409410
inline v8::Local<v8::String> provider_string(int idx);
410411

412+
inline void force_checks();
413+
411414
inline void push_async_ids(double async_id, double trigger_async_id);
412415
inline bool pop_async_id(double async_id);
413416
inline size_t stack_size();

src/node.cc

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ static bool syntax_check_only = false;
173173
static bool trace_deprecation = false;
174174
static bool throw_deprecation = false;
175175
static bool trace_sync_io = false;
176+
static bool force_async_hooks_checks = false;
176177
static bool track_heap_objects = false;
177178
static const char* eval_string = nullptr;
178179
static std::vector<std::string> preload_modules;
@@ -1440,8 +1441,10 @@ void InternalCallbackScope::Close() {
14401441

14411442
// Make sure the stack unwound properly. If there are nested MakeCallback's
14421443
// then it should return early and not reach this code.
1443-
CHECK_EQ(env_->execution_async_id(), 0);
1444-
CHECK_EQ(env_->trigger_async_id(), 0);
1444+
if (env_->async_hooks()->fields()[AsyncHooks::kTotals]) {
1445+
CHECK_EQ(env_->execution_async_id(), 0);
1446+
CHECK_EQ(env_->trigger_async_id(), 0);
1447+
}
14451448

14461449
Local<Object> process = env_->process_object();
14471450

@@ -1450,8 +1453,10 @@ void InternalCallbackScope::Close() {
14501453
return;
14511454
}
14521455

1453-
CHECK_EQ(env_->execution_async_id(), 0);
1454-
CHECK_EQ(env_->trigger_async_id(), 0);
1456+
if (env_->async_hooks()->fields()[AsyncHooks::kTotals]) {
1457+
CHECK_EQ(env_->execution_async_id(), 0);
1458+
CHECK_EQ(env_->trigger_async_id(), 0);
1459+
}
14551460

14561461
if (env_->tick_callback_function()->Call(process, 0, nullptr).IsEmpty()) {
14571462
failed_ = true;
@@ -3894,6 +3899,8 @@ static void PrintHelp() {
38943899
" stderr\n"
38953900
" --trace-sync-io show stack trace when use of sync IO\n"
38963901
" is detected after the first tick\n"
3902+
" --force-async-hooks-checks\n"
3903+
" enables checks for async_hooks\n"
38973904
" --trace-events-enabled track trace events\n"
38983905
" --trace-event-categories comma separated list of trace event\n"
38993906
" categories to record\n"
@@ -4019,6 +4026,7 @@ static void CheckIfAllowedInEnv(const char* exe, bool is_env,
40194026
"--trace-warnings",
40204027
"--redirect-warnings",
40214028
"--trace-sync-io",
4029+
"--force-async-hooks-checks",
40224030
"--trace-events-enabled",
40234031
"--trace-events-categories",
40244032
"--track-heap-objects",
@@ -4157,6 +4165,8 @@ static void ParseArgs(int* argc,
41574165
trace_deprecation = true;
41584166
} else if (strcmp(arg, "--trace-sync-io") == 0) {
41594167
trace_sync_io = true;
4168+
} else if (strcmp(arg, "--force-async-hooks-checks") == 0) {
4169+
force_async_hooks_checks = true;
41604170
} else if (strcmp(arg, "--trace-events-enabled") == 0) {
41614171
trace_enabled = true;
41624172
} else if (strcmp(arg, "--trace-event-categories") == 0) {
@@ -4805,6 +4815,10 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data,
48054815

48064816
env.set_abort_on_uncaught_exception(abort_on_uncaught_exception);
48074817

4818+
if (force_async_hooks_checks) {
4819+
env.async_hooks()->force_checks();
4820+
}
4821+
48084822
{
48094823
Environment::AsyncCallbackScope callback_scope(&env);
48104824
env.async_hooks()->push_async_ids(1, 0);

test/async-hooks/test-emit-init.js

Lines changed: 35 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@
22

33
const common = require('../common');
44
const assert = require('assert');
5+
const spawnSync = require('child_process').spawnSync;
56
const async_hooks = require('async_hooks');
67
const initHooks = require('./init-hooks');
78

8-
// Verify that if there is no registered hook, then those invalid parameters
9-
// won't be checked.
10-
assert.doesNotThrow(() => async_hooks.emitInit());
11-
129
const expectedId = async_hooks.newUid();
1310
const expectedTriggerId = async_hooks.newUid();
1411
const expectedType = 'test_emit_init_type';
@@ -25,24 +22,40 @@ const hooks1 = initHooks({
2522

2623
hooks1.enable();
2724

28-
assert.throws(() => {
29-
async_hooks.emitInit();
30-
}, common.expectsError({
31-
code: 'ERR_INVALID_ASYNC_ID',
32-
type: RangeError,
33-
}));
34-
assert.throws(() => {
35-
async_hooks.emitInit(expectedId);
36-
}, common.expectsError({
37-
code: 'ERR_INVALID_ASYNC_ID',
38-
type: RangeError,
39-
}));
40-
assert.throws(() => {
41-
async_hooks.emitInit(expectedId, expectedType, -2);
42-
}, common.expectsError({
43-
code: 'ERR_INVALID_ASYNC_ID',
44-
type: RangeError,
45-
}));
25+
switch (process.argv[2]) {
26+
case 'test_invalid_async_id':
27+
async_hooks.emitInit();
28+
return;
29+
case 'test_invalid_trigger_id':
30+
async_hooks.emitInit(expectedId);
31+
return;
32+
case 'test_invalid_trigger_id_negative':
33+
async_hooks.emitInit(expectedId, expectedType, -2);
34+
return;
35+
}
36+
assert.ok(!process.argv[2]);
37+
38+
39+
const c1 = spawnSync(process.execPath, [__filename, 'test_invalid_async_id']);
40+
assert.strictEqual(
41+
c1.stderr.toString().split(/[\r\n]+/g)[0],
42+
'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: undefined');
43+
assert.strictEqual(c1.status, 1);
44+
45+
const c2 = spawnSync(process.execPath, [__filename, 'test_invalid_trigger_id']);
46+
assert.strictEqual(
47+
c2.stderr.toString().split(/[\r\n]+/g)[0],
48+
'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: undefined');
49+
assert.strictEqual(c2.status, 1);
50+
51+
const c3 = spawnSync(process.execPath, [
52+
__filename, 'test_invalid_trigger_id_negative'
53+
]);
54+
assert.strictEqual(
55+
c3.stderr.toString().split(/[\r\n]+/g)[0],
56+
'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2');
57+
assert.strictEqual(c3.status, 1);
58+
4659

4760
async_hooks.emitInit(expectedId, expectedType, expectedTriggerId,
4861
expectedResource);

0 commit comments

Comments
 (0)