Skip to content

Commit 062beb0

Browse files
trevnorrisaddaleax
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 d441c7f commit 062beb0

9 files changed

+124
-51
lines changed

lib/async_hooks.js

Lines changed: 44 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
const async_wrap = process.binding('async_wrap');
4+
const errors = require('internal/errors');
45
/* async_hook_fields is a Uint32Array wrapping the uint32_t array of
56
* Environment::AsyncHooks::fields_[]. Each index tracks the number of active
67
* hooks for each type.
@@ -108,13 +109,13 @@ function fatalError(e) {
108109
class AsyncHook {
109110
constructor({ init, before, after, destroy }) {
110111
if (init !== undefined && typeof init !== 'function')
111-
throw new TypeError('init must be a function');
112+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'init');
112113
if (before !== undefined && typeof before !== 'function')
113-
throw new TypeError('before must be a function');
114+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'before');
114115
if (after !== undefined && typeof after !== 'function')
115-
throw new TypeError('after must be a function');
116+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'before');
116117
if (destroy !== undefined && typeof destroy !== 'function')
117-
throw new TypeError('destroy must be a function');
118+
throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'before');
118119

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

241245
this[async_id_symbol] = ++async_uid_fields[kAsyncUidCntr];
242246
this[trigger_id_symbol] = triggerAsyncId;
@@ -330,14 +334,17 @@ function emitInitScript(asyncId, type, triggerAsyncId, resource) {
330334
async_uid_fields[kInitTriggerId] = 0;
331335
}
332336

333-
// TODO(trevnorris): I'd prefer allowing these checks to not exist, or only
334-
// throw in a debug build, in order to improve performance.
335-
if (!Number.isSafeInteger(asyncId) || asyncId < 0)
336-
throw new RangeError('asyncId must be an unsigned integer');
337-
if (typeof type !== 'string' || type.length <= 0)
338-
throw new TypeError('type must be a string with length > 0');
339-
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < 0)
340-
throw new RangeError('triggerAsyncId must be an unsigned integer');
337+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
338+
throw new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId);
339+
}
340+
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
341+
throw new errors.RangeError('ERR_INVALID_ASYNC_ID',
342+
'triggerAsyncId',
343+
triggerAsyncId);
344+
}
345+
if (typeof type !== 'string' || type.length <= 0) {
346+
throw new errors.TypeError('ERR_ASYNC_TYPE', type);
347+
}
341348

342349
emitInitNative(asyncId, type, triggerAsyncId, resource);
343350
}
@@ -381,13 +388,17 @@ function emitHookFactory(symbol, name) {
381388

382389

383390
function emitBeforeScript(asyncId, triggerAsyncId) {
384-
// CHECK(Number.isSafeInteger(asyncId) && asyncId > 0)
385-
// CHECK(Number.isSafeInteger(triggerAsyncId) && triggerAsyncId > 0)
386-
387-
// Validate the ids.
388-
if (asyncId < 0 || triggerAsyncId < 0) {
389-
fatalError('before(): asyncId or triggerAsyncId is less than zero ' +
390-
`(asyncId: ${asyncId}, triggerAsyncId: ${triggerAsyncId})`);
391+
// Validate the ids. An id of -1 means it was never set and is visible on the
392+
// call graph. An id < -1 should never happen in any circumstance. Throw
393+
// on user calls because async state should still be recoverable.
394+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
395+
fatalError(
396+
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
397+
}
398+
if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
399+
fatalError(new errors.RangeError('ERR_INVALID_ASYNC_ID',
400+
'triggerAsyncId',
401+
triggerAsyncId));
391402
}
392403

393404
pushAsyncIds(asyncId, triggerAsyncId);
@@ -398,6 +409,11 @@ function emitBeforeScript(asyncId, triggerAsyncId) {
398409

399410

400411
function emitAfterScript(asyncId) {
412+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
413+
fatalError(
414+
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
415+
}
416+
401417
if (async_hook_fields[kAfter] > 0)
402418
emitAfterNative(asyncId);
403419

@@ -406,9 +422,13 @@ function emitAfterScript(asyncId) {
406422

407423

408424
function emitDestroyScript(asyncId) {
409-
// Return early if there are no destroy callbacks, or on attempt to emit
410-
// destroy on the void.
411-
if (async_hook_fields[kDestroy] === 0 || asyncId === 0)
425+
if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
426+
fatalError(
427+
new errors.RangeError('ERR_INVALID_ASYNC_ID', 'asyncId', asyncId));
428+
}
429+
430+
// Return early if there are no destroy callbacks, or invalid asyncId.
431+
if (async_hook_fields[kDestroy] === 0 || asyncId <= 0)
412432
return;
413433
async_wrap.addIdToDestroyList(asyncId);
414434
}

lib/internal/errors.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ module.exports = exports = {
101101
// Note: Please try to keep these in alphabetical order
102102
E('ERR_ARG_NOT_ITERABLE', '%s must be iterable');
103103
E('ERR_ASSERTION', '%s');
104+
E('ERR_ASYNC_CALLBACK', (name) => `${name} must be a function`);
105+
E('ERR_ASYNC_TYPE', (s) => `Invalid name for async "type": ${s}`);
104106
E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds);
105107
E('ERR_CHILD_CLOSED_BEFORE_REPLY', 'Child closed before reply received');
106108
E('ERR_CONSOLE_WRITABLE_STREAM',
@@ -188,6 +190,7 @@ E('ERR_INVALID_ARRAY_LENGTH',
188190
assert.strictEqual(typeof actual, 'number');
189191
return `The array "${name}" (length ${actual}) must be of length ${len}.`;
190192
});
193+
E('ERR_INVALID_ASYNC_ID', (type, id) => `Invalid ${type} value: ${id}`);
191194
E('ERR_INVALID_BUFFER_SIZE', 'Buffer size must be a multiple of %s');
192195
E('ERR_INVALID_CALLBACK', 'Callback must be a function');
193196
E('ERR_INVALID_CHAR', invalidChar);

src/env-inl.h

Lines changed: 5 additions & 2 deletions
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] });
@@ -177,6 +177,7 @@ inline Environment::AsyncHooks::InitScope::InitScope(
177177
Environment* env, double init_trigger_id)
178178
: env_(env),
179179
uid_fields_ref_(env->async_hooks()->uid_fields()) {
180+
CHECK_GE(init_trigger_id, -1);
180181
env->async_hooks()->push_ids(uid_fields_ref_[AsyncHooks::kCurrentAsyncId],
181182
init_trigger_id);
182183
}
@@ -190,6 +191,8 @@ inline Environment::AsyncHooks::ExecScope::ExecScope(
190191
: env_(env),
191192
async_id_(async_id),
192193
disposed_(false) {
194+
CHECK_GE(async_id, -1);
195+
CHECK_GE(trigger_id, -1);
193196
env->async_hooks()->push_ids(async_id, trigger_id);
194197
}
195198

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

Lines changed: 12 additions & 4 deletions
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

Lines changed: 8 additions & 8 deletions
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

Lines changed: 18 additions & 6 deletions
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);
Lines changed: 17 additions & 5 deletions
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+
}));
Lines changed: 5 additions & 2 deletions
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
}

test/parallel/test-internal-errors.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,15 @@ assert.strictEqual(
260260
errors.message('ERR_UNESCAPED_CHARACTERS', ['Request path']),
261261
'Request path contains unescaped characters'
262262
);
263+
264+
265+
// Test error messages for async_hooks
266+
assert.strictEqual(
267+
errors.message('ERR_ASYNC_CALLBACK', ['init']),
268+
'init must be a function');
269+
assert.strictEqual(
270+
errors.message('ERR_ASYNC_TYPE', [{}]),
271+
'Invalid name for async "type": [object Object]');
272+
assert.strictEqual(
273+
errors.message('ERR_INVALID_ASYNC_ID', ['asyncId', undefined]),
274+
'Invalid asyncId value: undefined');

0 commit comments

Comments
 (0)