src: clear all linked module caches once instantiated

There are two phases in module linking: link, and instantiate. These
two operations are required to be separated to allow cyclic
dependencies.

`v8::Module::InstantiateModule` is only required to be invoked on the
root module. The global references created by `ModuleWrap::Link` are
only cleared at `ModuleWrap::Instantiate`. So the global references
created for depended modules are usually not cleared because
`ModuleWrap::Instantiate` is not invoked for each of depended modules,
and caused memory leak.

The change references the linked modules in an object internal slot.

This is not an issue for Node.js ESM support as these modules can not be
off-loaded. However, this could be outstanding for `vm.Module`.

PR-URL: https://github.com/nodejs/node/pull/59117
Fixes: https://github.com/nodejs/node/issues/50113
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Chengzhong Wu 2025-07-29 13:17:52 +01:00 committed by GitHub
parent f904fa77f8
commit e55e0a7a98
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 136 additions and 90 deletions

View file

@ -6,6 +6,21 @@ const assert = require('assert');
const { internalBinding } = require('internal/test/binding');
const { ModuleWrap } = internalBinding('module_wrap');
const unlinked = new ModuleWrap('unlinked', undefined, 'export * from "bar";', 0, 0);
assert.throws(() => {
unlinked.instantiate();
}, {
code: 'ERR_VM_MODULE_LINK_FAILURE',
});
const dependsOnUnlinked = new ModuleWrap('dependsOnUnlinked', undefined, 'export * from "unlinked";', 0, 0);
dependsOnUnlinked.link([unlinked]);
assert.throws(() => {
dependsOnUnlinked.instantiate();
}, {
code: 'ERR_VM_MODULE_LINK_FAILURE',
});
const foo = new ModuleWrap('foo', undefined, 'export * from "bar";', 0, 0);
const bar = new ModuleWrap('bar', undefined, 'export const five = 5', 0, 0);
@ -22,4 +37,5 @@ const bar = new ModuleWrap('bar', undefined, 'export const five = 5', 0, 0);
// Check that the module requests are the same after linking, instantiate, and evaluation.
assert.deepStrictEqual(moduleRequests, foo.getModuleRequests());
})().then(common.mustCall());