Skip to content

Commit e8a4e56

Browse files
Qardruyadorno
authored andcommitted
async_hooks: fix leak in AsyncLocalStorage exit
If exit is called and then run or enterWith are called within the exit function, the als instace should not be added to the storageList additional times. The correct behaviour is to remove the instance from the storageList before executing the exit handler and then to restore it after. PR-URL: #35779 Reviewed-By: Vladimir de Turckheim <[email protected]> Reviewed-By: Michael Dawson <[email protected]> Reviewed-By: Gerhard Stöbich <[email protected]> Reviewed-By: Andrey Pechkurov <[email protected]> Reviewed-By: Rich Trott <[email protected]>
1 parent 427968d commit e8a4e56

File tree

2 files changed

+36
-7
lines changed

2 files changed

+36
-7
lines changed

lib/async_hooks.js

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,14 @@ class AsyncLocalStorage {
268268
}
269269
}
270270

271+
_enable() {
272+
if (!this.enabled) {
273+
this.enabled = true;
274+
storageList.push(this);
275+
storageHook.enable();
276+
}
277+
}
278+
271279
// Propagate the context from a parent resource to a child one
272280
_propagate(resource, triggerResource) {
273281
const store = triggerResource[this.kResourceStore];
@@ -277,11 +285,7 @@ class AsyncLocalStorage {
277285
}
278286

279287
enterWith(store) {
280-
if (!this.enabled) {
281-
this.enabled = true;
282-
storageList.push(this);
283-
storageHook.enable();
284-
}
288+
this._enable();
285289
const resource = executionAsyncResource();
286290
resource[this.kResourceStore] = store;
287291
}
@@ -305,11 +309,11 @@ class AsyncLocalStorage {
305309
if (!this.enabled) {
306310
return callback(...args);
307311
}
308-
this.enabled = false;
312+
this.disable();
309313
try {
310314
return callback(...args);
311315
} finally {
312-
this.enabled = true;
316+
this._enable();
313317
}
314318
}
315319

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { AsyncLocalStorage } = require('async_hooks');
5+
6+
const als = new AsyncLocalStorage();
7+
8+
// Make sure _propagate function exists.
9+
assert.ok(typeof als._propagate === 'function');
10+
11+
// The als instance should be getting removed from the storageList in
12+
// lib/async_hooks.js when exit(...) is called, therefore when the nested runs
13+
// are called there should be no copy of the als in the storageList to run the
14+
// _propagate method on.
15+
als._propagate = common.mustNotCall('_propagate() should not be called');
16+
17+
const done = common.mustCall();
18+
19+
function run(count) {
20+
if (count === 0) return done();
21+
als.run({}, () => {
22+
als.exit(run, --count);
23+
});
24+
}
25+
run(100);

0 commit comments

Comments
 (0)