GeezerVison is showing github.com — vfs: do not reuse the path of a loaded memfd image · nodejs/node@422149f
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: src/node_binding.cc +26-1Lines changed: 26 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -475,6 +475,27 @@ bool WriteAllToFd(int fd, const char* data, size_t len) { | 475 | 475 | int NodeMemfdCreate(const char* name, unsigned int flags) { | 476 | 476 | return static_cast<int>(syscall(SYS_memfd_create, name, flags)); | 477 | 477 | } | | 478 | + | | 479 | +// The dynamic loader knows a loaded object by the path it was opened with, and | | 480 | +// hands back the object already loaded under a path instead of opening the | | 481 | +// file again. An image is loaded through /proc/self/fd/N and its fd is closed | | 482 | +// right after, so the kernel can hand N to the next image while the first is | | 483 | +// still loaded. So ask the loader, and move to a higher number while the path | | 484 | +// is taken. Holding the fd from here through the load keeps anyone else from | | 485 | +// taking the path in between, and an object that has really been unloaded gives | | 486 | +// its number back, so only images loaded at the same time compete for numbers. | | 487 | +int MoveFdToFreeImagePath(int fd) { | | 488 | + while (true) { | | 489 | + const std::string path = "/proc/self/fd/" + std::to_string(fd); | | 490 | + void* loaded = dlopen(path.c_str(), RTLD_LAZY | RTLD_NOLOAD); | | 491 | + if (loaded == nullptr) return fd; | | 492 | + dlclose(loaded); | | 493 | + const int moved = fcntl(fd, F_DUPFD_CLOEXEC, fd + 1); | | 494 | + close(fd); | | 495 | + if (moved == -1) return -1; | | 496 | + fd = moved; | | 497 | + } | | 498 | +} | 478 | 499 | #endif // __linux__ | 479 | 500 | #else // _WIN32 | 480 | 501 |
| @@ -635,7 +656,8 @@ bool AddonImage::Materialize(const char* data, size_t len) { | 635 | 656 | // reaches the filesystem, so there is no temp file to secure, unlink, or | 636 | 657 | // leak, and no noexec-mount problem. Request an executable memfd (MFD_EXEC, | 637 | 658 | // Linux 6.3+); retry without it on older kernels that reject the flag, then | 638 | | - // fall back to a temp file if memfd is unavailable entirely. | | 659 | + // fall back to a temp file if memfd is unavailable entirely, or if so many | | 660 | + // images are loaded that no fd number is left to load another through. | 639 | 661 | #ifndef MFD_CLOEXEC | 640 | 662 | #define MFD_CLOEXEC 0x0001U | 641 | 663 | #endif | @@ -653,6 +675,9 @@ bool AddonImage::Materialize(const char* data, size_t len) { | 653 | 675 | fd_ = -1; | 654 | 676 | return false; | 655 | 677 | } | | 678 | + fd_ = MoveFdToFreeImagePath(fd_); | | 679 | + } | | 680 | + if (fd_ != -1) { | 656 | 681 | path_ = "/proc/self/fd/" + std::to_string(fd_); | 657 | 682 | return true; | 658 | 683 | } | |
Collapse file Copy file name to clipboardExpand all lines: src/node_binding.h +3-1Lines changed: 3 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -176,7 +176,9 @@ void DLOpenBinary(const v8::FunctionCallbackInfo<v8::Value>& args); | 176 | 176 | // dlopen()/LoadLibrary() can load, with the smallest, most private on-disk | 177 | 177 | // footprint each platform allows: | 178 | 178 | // Linux: an anonymous in-memory memfd, loaded via /proc/self/fd/N - | 179 | | -// the bytes never touch the filesystem. | | 179 | +// the bytes never touch the filesystem. The fd is closed right | | 180 | +// after the load, and a number whose path still names a loaded | | 181 | +// object is skipped (the loader would return that object). | 180 | 182 | // other POSIX: a 0700 mkdtemp() directory plus an O_EXCL|O_NOFOLLOW file, | 181 | 183 | // unlink()ed right after the load (the mapping keeps it alive). | 182 | 184 | // Windows: a temp file, written and closed before the load because the | |
Collapse file Copy file name to clipboardExpand all lines: test/ffi/test-ffi-vfs.js +115-3Lines changed: 115 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 3 | 3 | const common = require('../common'); | 4 | 4 | common.skipIfFFIMissing(); | 5 | 5 | const assert = require('node:assert'); | | 6 | +const { spawnSync } = require('node:child_process'); | 6 | 7 | const fs = require('node:fs'); | 7 | 8 | const os = require('node:os'); | 8 | 9 | const path = require('node:path'); | 9 | 10 | const { test } = require('node:test'); | | 11 | +const tmpdir = require('../common/tmpdir'); | 10 | 12 | const ffi = require('node:ffi'); | 11 | 13 | const vfs = require('node:vfs'); | 12 | 14 | const { fixtureSymbols, libraryPath } = require('./ffi-test-common'); | @@ -21,8 +23,12 @@ myVfs.writeFileSync(`/${libraryName}`, fs.readFileSync(libraryPath)); | 21 | 23 | const mountPoint = myVfs.mount(); | 22 | 24 | const virtualPath = path.join(mountPoint, libraryName); | 23 | 25 |
| | 26 | +// Images land in TMPDIR, which other tests loading libraries share. Point it at | | 27 | +// a directory this test owns, so their images cannot pass for a leak here. | | 28 | +tmpdir.refresh(); | | 29 | +process.env.TMPDIR = tmpdir.path; | | 30 | + | 24 | 31 | test('ffi.dlopen() loads a library from a mounted VFS', () => { | 25 | | - const before = new Set(fs.readdirSync(os.tmpdir())); | 26 | 32 | const { lib, functions } = ffi.dlopen(virtualPath, { | 27 | 33 | add_i32: fixtureSymbols.add_i32, | 28 | 34 | }); | @@ -40,12 +46,64 @@ test('ffi.dlopen() loads a library from a mounted VFS', () => { | 40 | 46 | // filesystem; on other POSIX it is unlinked right after loading. | 41 | 47 | // (Windows keeps a delete-on-close file until exit, so skip there.) | 42 | 48 | if (!common.isWindows) { | 43 | | - const leaked = fs.readdirSync(os.tmpdir()) | 44 | | - .filter((f) => f.startsWith('node-addon') && !before.has(f)); | | 49 | + const leaked = fs.readdirSync(tmpdir.path) | | 50 | + .filter((f) => f.startsWith('node-addon')); | 45 | 51 | assert.deepStrictEqual(leaked, [], `image not cleaned up: ${leaked}`); | 46 | 52 | } | 47 | 53 | }); | 48 | 54 |
| | 55 | +test('library images leave no file descriptor behind', { skip: !common.isLinux }, () => { | | 56 | + const images = () => fs.readdirSync('/proc/self/fd').filter((fd) => { | | 57 | + try { | | 58 | + return fs.readlinkSync(`/proc/self/fd/${fd}`).startsWith('/memfd:node-addon'); | | 59 | + } catch { | | 60 | + return false; | | 61 | + } | | 62 | + }); | | 63 | + | | 64 | + const { lib, functions } = ffi.dlopen(virtualPath, { | | 65 | + add_i32: fixtureSymbols.add_i32, | | 66 | + }); | | 67 | + try { | | 68 | + assert.deepStrictEqual(images(), []); | | 69 | + assert.strictEqual(functions.add_i32(40, 2), 42); | | 70 | + } finally { | | 71 | + lib.close(); | | 72 | + } | | 73 | + assert.deepStrictEqual(images(), []); | | 74 | +}); | | 75 | + | | 76 | +test('closed library images give their fd numbers back', { skip: !common.isLinux }, () => { | | 77 | + // More loads than the limit allows fds, one at a time. There is no usable | | 78 | + // temporary directory, so this only works if each stays an in-memory image. | | 79 | + const limit = 128; | | 80 | + const child = ` | | 81 | + const assert = require('node:assert'); | | 82 | + const fs = require('node:fs'); | | 83 | + const path = require('node:path'); | | 84 | + const ffi = require('node:ffi'); | | 85 | + const vfs = require('node:vfs'); | | 86 | + const myVfs = vfs.create(); | | 87 | + myVfs.writeFileSync('/lib.so', fs.readFileSync(${JSON.stringify(libraryPath)})); | | 88 | + const libPath = path.join(myVfs.mount(), 'lib.so'); | | 89 | + for (let i = 0; i < ${limit * 4}; i++) { | | 90 | + const { lib, functions } = ffi.dlopen(libPath, { | | 91 | + add_i32: ${JSON.stringify(fixtureSymbols.add_i32)}, | | 92 | + }); | | 93 | + assert.strictEqual(functions.add_i32(40, 2), 42); | | 94 | + lib.close(); | | 95 | + } | | 96 | + `; | | 97 | + const { status, stderr } = spawnSync('/bin/sh', [ | | 98 | + '-c', `ulimit -n ${limit} && exec "$0" "$@"`, | | 99 | + process.execPath, '--experimental-vfs', '--disable-warning=ExperimentalWarning', '-e', child, | | 100 | + ], { | | 101 | + encoding: 'utf8', | | 102 | + env: { ...process.env, TMPDIR: path.join(os.tmpdir(), 'no-such-directory') }, | | 103 | + }); | | 104 | + assert.strictEqual(status, 0, stderr); | | 105 | +}); | | 106 | + | 49 | 107 | test('new ffi.DynamicLibrary() loads from a mounted VFS', () => { | 50 | 108 | const lib = new ffi.DynamicLibrary(virtualPath); | 51 | 109 |
| @@ -92,3 +150,57 @@ test('a library loaded from a VFS outlives the mount', () => { | 92 | 150 | lib.close(); | 93 | 151 | } | 94 | 152 | }); | | 153 | + | | 154 | +const addonPath = (name) => path.join( | | 155 | + __dirname, '..', 'addons', name, 'build', common.buildType, 'binding.node'); | | 156 | + | | 157 | +test('an addon loaded after a VFS library is its own module', (t) => { | | 158 | + const helloPath = addonPath('hello-world'); | | 159 | + if (!fs.existsSync(helloPath)) { | | 160 | + t.skip('the hello-world addon is not built'); | | 161 | + return; | | 162 | + } | | 163 | + const seqVfs = vfs.create(); | | 164 | + seqVfs.writeFileSync(`/${libraryName}`, fs.readFileSync(libraryPath)); | | 165 | + seqVfs.writeFileSync('/hello.node', fs.readFileSync(helloPath)); | | 166 | + const seqMount = seqVfs.mount(); | | 167 | + const { lib, functions } = ffi.dlopen(path.join(seqMount, libraryName), { | | 168 | + add_i32: fixtureSymbols.add_i32, | | 169 | + }); | | 170 | + | | 171 | + try { | | 172 | + // Resolved to the library, the addon would fail with "Module did not | | 173 | + // self-register". | | 174 | + const addon = require(path.join(seqMount, 'hello.node')); | | 175 | + assert.strictEqual(addon.hello(), 'world'); | | 176 | + assert.strictEqual(functions.add_i32(20, 22), 42); | | 177 | + } finally { | | 178 | + lib.close(); | | 179 | + seqVfs.unmount(); | | 180 | + } | | 181 | +}); | | 182 | + | | 183 | +test('a VFS library loaded after an addon is its own library', (t) => { | | 184 | + const functionPath = addonPath('hello-world-function-export'); | | 185 | + if (!fs.existsSync(functionPath)) { | | 186 | + t.skip('the hello-world-function-export addon is not built'); | | 187 | + return; | | 188 | + } | | 189 | + const seqVfs = vfs.create(); | | 190 | + seqVfs.writeFileSync('/function.node', fs.readFileSync(functionPath)); | | 191 | + seqVfs.writeFileSync(`/${libraryName}`, fs.readFileSync(libraryPath)); | | 192 | + const seqMount = seqVfs.mount(); | | 193 | + const addon = require(path.join(seqMount, 'function.node')); | | 194 | + assert.strictEqual(addon(), 'world'); | | 195 | + | | 196 | + // Resolved to the addon, the library would have no add_i32 to look up. | | 197 | + const { lib, functions } = ffi.dlopen(path.join(seqMount, libraryName), { | | 198 | + add_i32: fixtureSymbols.add_i32, | | 199 | + }); | | 200 | + try { | | 201 | + assert.strictEqual(functions.add_i32(40, 2), 42); | | 202 | + } finally { | | 203 | + lib.close(); | | 204 | + seqVfs.unmount(); | | 205 | + } | | 206 | +}); |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-dlopen-binary-image-cleanup.js +33-13Lines changed: 33 additions & 13 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 7 | 7 | // this checks both halves of the contract: | 8 | 8 | // | 9 | 9 | // Linux: an anonymous memfd loaded through /proc/self/fd - nothing ever | 10 | | -// reaches the filesystem, and AfterOpen() closes the descriptor | 11 | | -// once the load owns its mapping, so repeated loads must not | 12 | | -// accumulate open descriptors. | | 10 | +// reaches the filesystem, and the fd is closed right after the | | 11 | +// load, whether or not it worked. | 13 | 12 | // other POSIX: a mkdtemp() directory unlinked and rmdir()ed right after the | 14 | 13 | // load, so nothing is left even while the process runs. | 15 | 14 | // Windows: the loader maps the file by path for the DLL's lifetime, so | @@ -45,27 +44,48 @@ const child = ` | 45 | 44 | // the load can only come from the bytes and their materialized image. | 46 | 45 | const virtualPath = ${JSON.stringify(path.join(addonPath, '..', 'nowhere', 'binding.node'))}; | 47 | 46 |
| 48 | | - // On Linux the image is a descriptor rather than a file, so count them: each | 49 | | - // load must hand its fd to the mapping and close it, leaving no growth. | | 47 | + // On Linux the image is a memfd rather than a file, so count those: no load | | 48 | + // may keep one. | 50 | 49 | const fdDir = '/proc/self/fd'; | 51 | | - const countFds = () => { | 52 | | - try { return fs.readdirSync(fdDir).length; } catch { return -1; } | | 50 | + const imageFds = () => { | | 51 | + let fds; | | 52 | + try { fds = fs.readdirSync(fdDir); } catch { return null; } | | 53 | + return fds.filter((fd) => { | | 54 | + try { | | 55 | + return fs.readlinkSync(\`\${fdDir}/\${fd}\`).startsWith('/memfd:node-addon'); | | 56 | + } catch { return false; } | | 57 | + }); | 53 | 58 | }; | 54 | | - const before = countFds(); | 55 | 59 |
| 56 | 60 | // Load repeatedly: each load materializes its own image, so a leak of an | 57 | | - // image, a descriptor or a retained handle shows up as growth. | 58 | | - for (let i = 0; i < 5; i++) { | | 61 | + // image or a retained handle shows up as growth. | | 62 | + const loads = 5; | | 63 | + for (let i = 0; i < loads; i++) { | 59 | 64 | const m = { exports: {} }; | 60 | 65 | // flags undefined: keep the default dlopen(2) mode - 0 is not valid | 61 | 66 | // everywhere (glibc rejects it with EINVAL). | 62 | 67 | dlopenBinary(m, virtualPath, undefined, bytes); | 63 | 68 | if (m.exports.hello() !== 'world') throw new Error('addon did not load'); | 64 | 69 | } | | 70 | + const afterLoads = imageFds(); | 65 | 71 |
| 66 | | - const after = countFds(); | 67 | | - if (before !== -1 && after > before) { | 68 | | - throw new Error(\`descriptor leak: \${before} -> \${after} after 5 loads\`); | | 72 | + for (let i = 0; i < loads; i++) { | | 73 | + try { | | 74 | + dlopenBinary({ exports: {} }, virtualPath, undefined, Buffer.from('nope')); | | 75 | + throw new Error('loading garbage bytes did not fail'); | | 76 | + } catch (err) { | | 77 | + if (err.code !== 'ERR_DLOPEN_FAILED') throw err; | | 78 | + } | | 79 | + } | | 80 | + const afterFailures = imageFds(); | | 81 | +
| | 82 | + if (afterLoads !== null) { | | 83 | + if (afterLoads.length !== 0) { | | 84 | + throw new Error(\`loads kept images: \${afterLoads}\`); | | 85 | + } | | 86 | + if (afterFailures.length !== 0) { | | 87 | + throw new Error(\`failed loads kept images: \${afterFailures}\`); | | 88 | + } | 69 | 89 | } | 70 | 90 | process.exit(0); | 71 | 91 | `; | |
Collapse file Copy file name to clipboard +60Lines changed: 60 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +// Flags: --experimental-vfs --disable-warning=ExperimentalWarning | | 2 | +'use strict'; | | 3 | +const common = require('../common'); | | 4 | +const assert = require('node:assert'); | | 5 | +const { spawnSync } = require('node:child_process'); | | 6 | +const fs = require('node:fs'); | | 7 | +const path = require('node:path'); | | 8 | +const vfs = require('node:vfs'); | | 9 | + | | 10 | +const addonPath = (name) => path.join( | | 11 | + __dirname, '..', 'addons', name, 'build', common.buildType, 'binding.node'); | | 12 | +const helloPath = addonPath('hello-world'); | | 13 | +const functionPath = addonPath('hello-world-function-export'); | | 14 | +if (!fs.existsSync(helloPath) || !fs.existsSync(functionPath)) { | | 15 | + common.skip('the hello-world addons are not built'); | | 16 | +} | | 17 | + | | 18 | +const myVfs = vfs.create(); | | 19 | +myVfs.writeFileSync('/hello.node', fs.readFileSync(helloPath)); | | 20 | +myVfs.writeFileSync('/function.node', fs.readFileSync(functionPath)); | | 21 | +const mountPoint = myVfs.mount(); | | 22 | + | | 23 | +const hello = require(path.join(mountPoint, 'hello.node')); | | 24 | +assert.strictEqual(typeof hello, 'object'); | | 25 | +assert.strictEqual(hello.hello(), 'world'); | | 26 | + | | 27 | +// hello-world-function-export replaces its exports with a function. Resolved | | 28 | +// to the first image, this would be another { hello } object instead. | | 29 | +const fn = require(path.join(mountPoint, 'function.node')); | | 30 | +assert.strictEqual(typeof fn, 'function'); | | 31 | +assert.strictEqual(fn(), 'world'); | | 32 | +assert.notStrictEqual(fn, hello); | | 33 | + | | 34 | +myVfs.unmount(); | | 35 | + | | 36 | +// An addon on the main thread stays loaded and keeps the path it was loaded | | 37 | +// through, so enough of them leave no fd number to load another through. Loading | | 38 | +// has to carry on regardless, through the temp-file fallback. | | 39 | +if (common.isLinux) { | | 40 | + const limit = 128; | | 41 | + const child = ` | | 42 | + const assert = require('node:assert'); | | 43 | + const fs = require('node:fs'); | | 44 | + const path = require('node:path'); | | 45 | + const vfs = require('node:vfs'); | | 46 | + const myVfs = vfs.create(); | | 47 | + myVfs.writeFileSync('/function.node', fs.readFileSync(${JSON.stringify(functionPath)})); | | 48 | + const mountPoint = myVfs.mount(); | | 49 | + for (let i = 0; i < ${limit * 2}; i++) { | | 50 | + const addonPath = path.join(mountPoint, 'function.node'); | | 51 | + assert.strictEqual(require(addonPath)(), 'world'); | | 52 | + delete require.cache[addonPath]; | | 53 | + } | | 54 | + `; | | 55 | + const { status, stderr } = spawnSync('/bin/sh', [ | | 56 | + '-c', `ulimit -n ${limit} && exec "$0" "$@"`, | | 57 | + process.execPath, '--experimental-vfs', '--disable-warning=ExperimentalWarning', '-e', child, | | 58 | + ], { encoding: 'utf8' }); | | 59 | + assert.strictEqual(status, 0, stderr); | | 60 | +} |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-vfs-addon.js +8-4Lines changed: 8 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 3 | 3 | const common = require('../common'); | 4 | 4 | const assert = require('assert'); | 5 | 5 | const fs = require('fs'); | 6 | | -const os = require('os'); | 7 | 6 | const path = require('path'); | | 7 | +const tmpdir = require('../common/tmpdir'); | 8 | 8 | const vfs = require('node:vfs'); | 9 | 9 |
| 10 | 10 | const addonPath = path.join( | @@ -21,16 +21,20 @@ const myVfs = vfs.create(); | 21 | 21 | myVfs.writeFileSync('/binding.node', fs.readFileSync(addonPath)); | 22 | 22 | const mountPoint = myVfs.mount(); | 23 | 23 |
| 24 | | -const before = new Set(fs.readdirSync(os.tmpdir())); | | 24 | +// Images land in TMPDIR, which other tests loading addons share. Point it at a | | 25 | +// directory this test owns, so their images cannot pass for a leak here. | | 26 | +tmpdir.refresh(); | | 27 | +process.env.TMPDIR = tmpdir.path; | | 28 | + | 25 | 29 | const addon = require(path.join(mountPoint, 'binding.node')); | 26 | 30 | assert.strictEqual(addon.hello(), 'world'); | 27 | 31 |
| 28 | 32 | // On Linux the memfd path never touches the filesystem; on other POSIX the | 29 | 33 | // temp image is unlinked right after loading, so no addon temp file lingers. | 30 | 34 | // (Windows keeps a delete-on-close file until exit, so skip the check there.) | 31 | 35 | if (process.platform !== 'win32') { | 32 | | - const leaked = fs.readdirSync(os.tmpdir()) | 33 | | - .filter((f) => f.startsWith('node-addon') && !before.has(f)); | | 36 | + const leaked = fs.readdirSync(tmpdir.path) | | 37 | + .filter((f) => f.startsWith('node-addon')); | 34 | 38 | assert.deepStrictEqual(leaked, [], `addon temp not cleaned up: ${leaked}`); | 35 | 39 | } | 36 | 40 |
| |
|