Skip to content

Commit 029ea16

Browse files
QardBethGriggs
authored andcommittedDec 15, 2020
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 <vlad2t@hotmail.com> Reviewed-By: Michael Dawson <midawson@redhat.com> Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de> Reviewed-By: Andrey Pechkurov <apechkurov@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com>
1 parent e161249 commit 029ea16

File tree

2 files changed

+36
-7
lines changed

2 files changed

+36
-7
lines changed
 

‎lib/async_hooks.js

+11-7
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,14 @@ class AsyncLocalStorage {
271271
}
272272
}
273273

274+
_enable() {
275+
if (!this.enabled) {
276+
this.enabled = true;
277+
storageList.push(this);
278+
storageHook.enable();
279+
}
280+
}
281+
274282
// Propagate the context from a parent resource to a child one
275283
_propagate(resource, triggerResource) {
276284
const store = triggerResource[this.kResourceStore];
@@ -280,11 +288,7 @@ class AsyncLocalStorage {
280288
}
281289

282290
enterWith(store) {
283-
if (!this.enabled) {
284-
this.enabled = true;
285-
storageList.push(this);
286-
storageHook.enable();
287-
}
291+
this._enable();
288292
const resource = executionAsyncResource();
289293
resource[this.kResourceStore] = store;
290294
}
@@ -308,11 +312,11 @@ class AsyncLocalStorage {
308312
if (!this.enabled) {
309313
return callback(...args);
310314
}
311-
this.enabled = false;
315+
this.disable();
312316
try {
313317
return callback(...args);
314318
} finally {
315-
this.enabled = true;
319+
this._enable();
316320
}
317321
}
318322

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)
Please sign in to comment.