node/test/parallel/test-internal-module-wrap.js
Chengzhong Wu e55e0a7a98
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>
2025-07-29 12:17:52 +00:00

41 lines
1.3 KiB
JavaScript

// Flags: --expose-internals
'use strict';
const common = require('../common');
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);
(async () => {
const moduleRequests = foo.getModuleRequests();
assert.strictEqual(moduleRequests.length, 1);
assert.strictEqual(moduleRequests[0].specifier, 'bar');
foo.link([bar]);
foo.instantiate();
assert.strictEqual(await foo.evaluate(-1, false), undefined);
assert.strictEqual(foo.getNamespace().five, 5);
// Check that the module requests are the same after linking, instantiate, and evaluation.
assert.deepStrictEqual(moduleRequests, foo.getModuleRequests());
})().then(common.mustCall());