Skip to content

Commit b40105d

Browse files
trevnorrisMylesBorins
authored andcommitted
async_hooks: don't abort unnecessarily
* id values of -1 are allowed. They indicate that the id was never correctly assigned to the async resource. These will appear in any call graph, and will only be apparent to those using the async_hooks module, then reported in an issue. * ids < -1 are still not allowed and will cause the application to exit the process; because there is no scenario where this should ever happen. * Add asyncId range checks to emitAfterScript(). * Fix emitBeforeScript() range checks which should have been || not &&. * Replace errors with entries in internal/errors. * Fix async_hooks tests that check for exceptions to match new internal/errors entries. NOTE: emit{Before,After,Destroy}() must continue to exit the process because in the case of an exception during hook execution the state of the application is unknowable. For example, an exception could cause a memory leak: const id_map = new Map(); before(id) { id_map.set(id, /* data object or similar */); }, after(id) { throw new Error('id never dies!'); id_map.delete(id); } Allowing a recoverable exception may also cause an abort because of a stack check in Environment::AsyncHooks::pop_ids() that verifies the async id and pop'd ids match. This case would be more difficult to debug than if fatalError() (lib/async_hooks.js) was called immediately. try { async_hooks.emitBefore(null, NaN); } catch (e) { } // do something async_hooks.emitAfter(5); It also allows an edge case where emitBefore() could be called twice and not have the pop_ids() CHECK fail: try { async_hooks.emitBefore(5, NaN); } catch (e) { } async_hooks.emitBefore(5); // do something async_hooks.emitAfter(5); There is the option of allowing mismatches in the stack and ignoring the check if no async hooks are enabled, but I don't believe going this far is necessary. PR-URL: #14722 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Refael Ackermann <[email protected]>
1 parent 78a36e0 commit b40105d

8 files changed

+112
-51
lines changed

lib/async_hooks.js

+44-24
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
const internalUtil = require('internal/util');
44
const async_wrap = process.binding('async_wrap');
5+
const errors = require('internal/errors');
56
/* async_hook_fields is a Uint32Array wrapping the uint32_t array of
67
* Environment::AsyncHooks::fields_[]. Each index tracks the number of active
78
* hooks for each type.
@@ -109,13 +110,13 @@ function fatalError(e) {
109110
class AsyncHook {
110111
constructor({ init, before, after, destroy }) {
111112
if (init !== undefined && typeof init !== 'function')
112-
throw new TypeError('init must be a function');
113+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'init');
113114
if (before !== undefined && typeof before !== 'function')
114-
throw new TypeError('before must be a function');
115+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'before');
115116
if (after !== undefined && typeof after !== 'function')
116-
throw new TypeError('after must be a function');
117+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'before');
117118
if (destroy !== undefined && typeof destroy !== 'function')
118-
throw new TypeError('destroy must be a function');
119+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'before');
119120

120121
this[init_symbol] = init;
121122
this[before_symbol] = before;
@@ -236,8 +237,11 @@ class AsyncResource {
236237
constructor(type, triggerAsyncId = initTriggerId()) {
237238
// Unlike emitInitScript, AsyncResource doesn't supports null as the
238239
// triggerAsyncId.
239-
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < 0)
240-
throw new RangeError('triggerAsyncId must be an unsigned integer');
240+
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
241+
throw new errors.RangeError('ERR_INVALID_ASYNC_ID',
242+
'triggerAsyncId',
243+
triggerAsyncId);
244+
}
241245

242246
this[async_id_symbol] = ++async_uid_fields[kAsyncUidCntr];
243247
this[trigger_id_symbol] = triggerAsyncId;
@@ -342,14 +346,17 @@ function emitInitScript(asyncId, type, triggerAsyncId, resource) {
342346
async_uid_fields[kInitTriggerId] = 0;
343347
}
344348

345-
// TODO(trevnorris): I'd prefer allowing these checks to not exist, or only
346-
// throw in a debug build, in order to improve performance.
347-
if (!Number.isSafeInteger(asyncId) || asyncId < 0)
348-
throw new RangeError('asyncId must be an unsigned integer');
349-
if (typeof type !== 'string' || type.length <= 0)
350-
throw new TypeError('type must be a string with length > 0');
351-
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < 0)
352-
throw new RangeError('triggerAsyncId must be an unsigned integer');
349+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
350+
throw new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId);
351+
}
352+
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
353+
throw new errors.RangeError('ERR_INVALID_ASYNC_ID',
354+
'triggerAsyncId',
355+
triggerAsyncId);
356+
}
357+
if (typeof type !== 'string' || type.length <= 0) {
358+
throw new errors.TypeError('ERR_ASYNC_TYPE', type);
359+
}
353360

354361
emitInitNative(asyncId, type, triggerAsyncId, resource);
355362
}
@@ -393,13 +400,17 @@ function emitHookFactory(symbol, name) {
393400

394401

395402
function emitBeforeScript(asyncId, triggerAsyncId) {
396-
// CHECK(Number.isSafeInteger(asyncId) && asyncId > 0)
397-
// CHECK(Number.isSafeInteger(triggerAsyncId) && triggerAsyncId > 0)
398-
399-
// Validate the ids.
400-
if (asyncId < 0 || triggerAsyncId < 0) {
401-
fatalError('before(): asyncId or triggerAsyncId is less than zero ' +
402-
`(asyncId: ${asyncId}, triggerAsyncId: ${triggerAsyncId})`);
403+
// Validate the ids. An id of -1 means it was never set and is visible on the
404+
// call graph. An id < -1 should never happen in any circumstance. Throw
405+
// on user calls because async state should still be recoverable.
406+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
407+
fatalError(
408+
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
409+
}
410+
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
411+
fatalError(new errors.RangeError('ERR_INVALID_ASYNC_ID',
412+
'triggerAsyncId',
413+
triggerAsyncId));
403414
}
404415

405416
pushAsyncIds(asyncId, triggerAsyncId);
@@ -410,6 +421,11 @@ function emitBeforeScript(asyncId, triggerAsyncId) {
410421

411422

412423
function emitAfterScript(asyncId) {
424+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
425+
fatalError(
426+
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
427+
}
428+
413429
if (async_hook_fields[kAfter] > 0)
414430
emitAfterNative(asyncId);
415431

@@ -418,9 +434,13 @@ function emitAfterScript(asyncId) {
418434

419435

420436
function emitDestroyScript(asyncId) {
421-
// Return early if there are no destroy callbacks, or on attempt to emit
422-
// destroy on the void.
423-
if (async_hook_fields[kDestroy] === 0 || asyncId === 0)
437+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
438+
fatalError(
439+
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
440+
}
441+
442+
// Return early if there are no destroy callbacks, or invalid asyncId.
443+
if (async_hook_fields[kDestroy] === 0 || asyncId <= 0)
424444
return;
425445
async_wrap.addIdToDestroyList(asyncId);
426446
}

lib/internal/errors.js

+3
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ module.exports = exports = {
109109
// Note: Please try to keep these in alphabetical order
110110
E('ERR_ARG_NOT_ITERABLE', '%s must be iterable');
111111
E('ERR_ASSERTION', (msg) => msg);
112+
E('ERR_ASYNC_CALLBACK', (name) => `${name} must be a function`);
113+
E('ERR_ASYNC_TYPE', (s) => `Invalid name for async "type": ${s}`);
112114
E('ERR_ENCODING_INVALID_ENCODED_DATA',
113115
(enc) => `The encoded data was not valid for encoding ${enc}`);
114116
E('ERR_ENCODING_NOT_SUPPORTED',
@@ -184,6 +186,7 @@ E('ERR_HTTP2_UNSUPPORTED_PROTOCOL',
184186
(protocol) => `protocol "${protocol}" is unsupported.`);
185187
E('ERR_INDEX_OUT_OF_RANGE', 'Index out of range');
186188
E('ERR_INVALID_ARG_TYPE', invalidArgType);
189+
E('ERR_INVALID_ASYNC_ID', (type, id) => `Invalid ${type} value: ${id}`);
187190
E('ERR_INVALID_CALLBACK', 'callback must be a function');
188191
E('ERR_INVALID_FD', (fd) => `"fd" must be a positive integer: ${fd}`);
189192
E('ERR_INVALID_FILE_URL_HOST', 'File URL host %s');

src/env-inl.h

+5-2
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ inline v8::Local<v8::String> Environment::AsyncHooks::provider_string(int idx) {
127127

128128
inline void Environment::AsyncHooks::push_ids(double async_id,
129129
double trigger_id) {
130-
CHECK_GE(async_id, 0);
131-
CHECK_GE(trigger_id, 0);
130+
CHECK_GE(async_id, -1);
131+
CHECK_GE(trigger_id, -1);
132132

133133
ids_stack_.push({ uid_fields_[kCurrentAsyncId],
134134
uid_fields_[kCurrentTriggerId] });
@@ -181,6 +181,7 @@ inline Environment::AsyncHooks::InitScope::InitScope(
181181
Environment* env, double init_trigger_id)
182182
: env_(env),
183183
uid_fields_ref_(env->async_hooks()->uid_fields()) {
184+
CHECK_GE(init_trigger_id, -1);
184185
env->async_hooks()->push_ids(uid_fields_ref_[AsyncHooks::kCurrentAsyncId],
185186
init_trigger_id);
186187
}
@@ -194,6 +195,8 @@ inline Environment::AsyncHooks::ExecScope::ExecScope(
194195
: env_(env),
195196
async_id_(async_id),
196197
disposed_(false) {
198+
CHECK_GE(async_id, -1);
199+
CHECK_GE(trigger_id, -1);
197200
env->async_hooks()->push_ids(async_id, trigger_id);
198201
}
199202

test/async-hooks/test-embedder.api.async-resource.js

+12-4
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,18 @@ const { checkInvocations } = require('./hook-checks');
1212
const hooks = initHooks();
1313
hooks.enable();
1414

15-
assert.throws(() => new AsyncResource(),
16-
/^TypeError: type must be a string with length > 0$/);
17-
assert.throws(() => new AsyncResource('invalid_trigger_id', null),
18-
/^RangeError: triggerAsyncId must be an unsigned integer$/);
15+
assert.throws(() => {
16+
new AsyncResource();
17+
}, common.expectsError({
18+
code: 'ERR_ASYNC_TYPE',
19+
type: TypeError,
20+
}));
21+
assert.throws(() => {
22+
new AsyncResource('invalid_trigger_id', null);
23+
}, common.expectsError({
24+
code: 'ERR_INVALID_ASYNC_ID',
25+
type: RangeError,
26+
}));
1927

2028
assert.strictEqual(
2129
new AsyncResource('default_trigger_id').triggerAsyncId(),

test/async-hooks/test-emit-before-after.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,25 @@ const initHooks = require('./init-hooks');
88

99
switch (process.argv[2]) {
1010
case 'test_invalid_async_id':
11-
async_hooks.emitBefore(-1, 1);
11+
async_hooks.emitBefore(-2, 1);
1212
return;
1313
case 'test_invalid_trigger_id':
14-
async_hooks.emitBefore(1, -1);
14+
async_hooks.emitBefore(1, -2);
1515
return;
1616
}
1717
assert.ok(!process.argv[2]);
1818

1919

2020
const c1 = spawnSync(process.execPath, [__filename, 'test_invalid_async_id']);
21-
assert.strictEqual(c1.stderr.toString().split(/[\r\n]+/g)[0],
22-
'Error: before(): asyncId or triggerAsyncId is less than ' +
23-
'zero (asyncId: -1, triggerAsyncId: 1)');
21+
assert.strictEqual(
22+
c1.stderr.toString().split(/[\r\n]+/g)[0],
23+
'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: -2');
2424
assert.strictEqual(c1.status, 1);
2525

2626
const c2 = spawnSync(process.execPath, [__filename, 'test_invalid_trigger_id']);
27-
assert.strictEqual(c2.stderr.toString().split(/[\r\n]+/g)[0],
28-
'Error: before(): asyncId or triggerAsyncId is less than ' +
29-
'zero (asyncId: 1, triggerAsyncId: -1)');
27+
assert.strictEqual(
28+
c2.stderr.toString().split(/[\r\n]+/g)[0],
29+
'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2');
3030
assert.strictEqual(c2.status, 1);
3131

3232
const expectedId = async_hooks.newUid();

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

+18-6
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,24 @@ const hooks1 = initHooks({
2525

2626
hooks1.enable();
2727

28-
assert.throws(() => async_hooks.emitInit(),
29-
/^RangeError: asyncId must be an unsigned integer$/);
30-
assert.throws(() => async_hooks.emitInit(expectedId),
31-
/^TypeError: type must be a string with length > 0$/);
32-
assert.throws(() => async_hooks.emitInit(expectedId, expectedType, -1),
33-
/^RangeError: triggerAsyncId must be an unsigned integer$/);
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+
}));
3446

3547
async_hooks.emitInit(expectedId, expectedType, expectedTriggerId,
3648
expectedResource);
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
'use strict';
2-
require('../common');
32

43
// This tests that AsyncResource throws an error if bad parameters are passed
54

5+
const common = require('../common');
66
const assert = require('assert');
77
const async_hooks = require('async_hooks');
88
const { AsyncResource } = async_hooks;
@@ -14,16 +14,28 @@ async_hooks.createHook({
1414

1515
assert.throws(() => {
1616
return new AsyncResource();
17-
}, /^TypeError: type must be a string with length > 0$/);
17+
}, common.expectsError({
18+
code: 'ERR_ASYNC_TYPE',
19+
type: TypeError,
20+
}));
1821

1922
assert.throws(() => {
2023
new AsyncResource('');
21-
}, /^TypeError: type must be a string with length > 0$/);
24+
}, common.expectsError({
25+
code: 'ERR_ASYNC_TYPE',
26+
type: TypeError,
27+
}));
2228

2329
assert.throws(() => {
2430
new AsyncResource('type', -4);
25-
}, /^RangeError: triggerAsyncId must be an unsigned integer$/);
31+
}, common.expectsError({
32+
code: 'ERR_INVALID_ASYNC_ID',
33+
type: RangeError,
34+
}));
2635

2736
assert.throws(() => {
2837
new AsyncResource('type', Math.PI);
29-
}, /^RangeError: triggerAsyncId must be an unsigned integer$/);
38+
}, common.expectsError({
39+
code: 'ERR_INVALID_ASYNC_ID',
40+
type: RangeError,
41+
}));
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
'use strict';
2-
require('../common');
32

43
// This tests that using falsy values in createHook throws an error.
54

5+
const common = require('../common');
66
const assert = require('assert');
77
const async_hooks = require('async_hooks');
88

99
for (const badArg of [0, 1, false, true, null, 'hello']) {
1010
for (const field of ['init', 'before', 'after', 'destroy']) {
1111
assert.throws(() => {
1212
async_hooks.createHook({ [field]: badArg });
13-
}, new RegExp(`^TypeError: ${field} must be a function$`));
13+
}, common.expectsError({
14+
code: 'ERR_ASYNC_CALLBACK',
15+
type: TypeError,
16+
}));
1417
}
1518
}

0 commit comments

Comments
 (0)