node/test/parallel/test-fs-filehandle-use-after-close.js
Anna Henningsen 7864c53629
fs: unset FileHandle fd after close
- Do not set the fd as a property on the native object.
- Use the already-existent `GetFD()` method to pass the
  fd from C++ to JS.
- Cache the fd in JS to avoid repeated accesses to the
  C++ getter.
- Set the fd to `-1` after close, thus reliably making
  subsequent calls using the `FileHandle` return `EBADF`.

Fixes: https://github.com/nodejs/node/issues/31361

PR-URL: https://github.com/nodejs/node/pull/31389
Reviewed-By: Richard Lau <riclau@uk.ibm.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Minwoo Jung <nodecorelab@gmail.com>
Reviewed-By: David Carlier <devnexen@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
2020-01-18 22:24:54 +01:00

26 lines
809 B
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs').promises;
(async () => {
const filehandle = await fs.open(__filename);
assert.notStrictEqual(filehandle.fd, -1);
await filehandle.close();
assert.strictEqual(filehandle.fd, -1);
// Open another file handle first. This would typically receive the fd
// that `filehandle` previously used. In earlier versions of Node.js, the
// .stat() call would then succeed because it still used the original fd;
// See https://github.com/nodejs/node/issues/31361 for more details.
const otherFilehandle = await fs.open(process.execPath);
assert.rejects(() => filehandle.stat(), {
code: 'EBADF',
syscall: 'fstat'
});
await otherFilehandle.close();
})().then(common.mustCall());