Skip to content

Commit 58b5a61

Browse files
joyeecheungrvagg
authored andcommitted
util: implement util.getSystemErrorName()
Reimplement uv.errname() as internal/util.getSystemErrorName() to avoid the memory leaks caused by unknown error codes and avoid calling into C++ for the error names. Also expose it as a public API for external use. Backport-PR-URL: #19191 PR-URL: #18186 Refs: http://docs.libuv.org/en/v1.x/errors.html#c.uv_err_name Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent c39b002 commit 58b5a61

File tree

9 files changed

+85
-13
lines changed

9 files changed

+85
-13
lines changed

doc/api/util.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,25 @@ without any formatting.
217217
util.format('%% %s'); // '%% %s'
218218
```
219219

220+
## util.getSystemErrorName(err)
221+
<!-- YAML
222+
added: REPLACEME
223+
-->
224+
225+
* `err` {number}
226+
* Returns: {string}
227+
228+
Returns the string name for a numeric error code that comes from a Node.js API.
229+
The mapping between error codes and error names is platform-dependent.
230+
See [Common System Errors][] for the names of common errors.
231+
232+
```js
233+
fs.access('file/that/does/not/exist', (err) => {
234+
const name = util.getSystemErrorName(err.errno);
235+
console.error(name); // ENOENT
236+
});
237+
```
238+
220239
## util.inherits(constructor, superConstructor)
221240
<!-- YAML
222241
added: v0.3.0
@@ -1196,6 +1215,7 @@ Deprecated predecessor of `console.log`.
11961215
[`console.log()`]: console.html#console_console_log_data_args
11971216
[`util.inspect()`]: #util_util_inspect_object_options
11981217
[`util.promisify()`]: #util_util_promisify_original
1218+
[Common System Errors]: errors.html#errors_common_system_errors
11991219
[Custom inspection functions on Objects]: #util_custom_inspection_functions_on_objects
12001220
[Custom promisified functions]: #util_custom_promisified_functions
12011221
[Customizing `util.inspect` colors]: #util_customizing_util_inspect_colors

lib/child_process.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,14 @@
2222
'use strict';
2323

2424
const util = require('util');
25-
const { deprecate, convertToValidSignal } = require('internal/util');
25+
const {
26+
deprecate, convertToValidSignal, getSystemErrorName
27+
} = require('internal/util');
2628
const { isUint8Array } = require('internal/util/types');
2729
const { createPromise,
2830
promiseResolve, promiseReject } = process.binding('util');
2931
const debug = util.debuglog('child_process');
3032

31-
const uv = process.binding('uv');
3233
const spawn_sync = process.binding('spawn_sync');
3334
const { Buffer } = require('buffer');
3435
const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap');
@@ -274,7 +275,7 @@ exports.execFile = function(file /*, args, options, callback*/) {
274275
if (!ex) {
275276
ex = new Error('Command failed: ' + cmd + '\n' + stderr);
276277
ex.killed = child.killed || killed;
277-
ex.code = code < 0 ? uv.errname(code) : code;
278+
ex.code = code < 0 ? getSystemErrorName(code) : code;
278279
ex.signal = signal;
279280
}
280281

lib/internal/util.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
const errors = require('internal/errors');
44
const binding = process.binding('util');
55
const { signals } = process.binding('constants').os;
6-
76
const { createPromise, promiseResolve, promiseReject } = binding;
7+
const { errmap } = process.binding('uv');
88

99
const kArrowMessagePrivateSymbolIndex = binding.arrow_message_private_symbol;
1010
const kDecoratedPrivateSymbolIndex = binding.decorated_private_symbol;
@@ -201,6 +201,16 @@ function getConstructorOf(obj) {
201201
return null;
202202
}
203203

204+
function getSystemErrorName(err) {
205+
if (typeof err !== 'number' || err >= 0 || !Number.isSafeInteger(err)) {
206+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'err',
207+
'negative number');
208+
}
209+
210+
const entry = errmap.get(err);
211+
return entry ? entry[0] : `Unknown system error ${err}`;
212+
}
213+
204214
const kCustomPromisifiedSymbol = Symbol('util.promisify.custom');
205215
const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs');
206216

@@ -286,6 +296,7 @@ module.exports = {
286296
emitExperimentalWarning,
287297
filterDuplicateStrings,
288298
getConstructorOf,
299+
getSystemErrorName,
289300
isError,
290301
join,
291302
normalizeEncoding,

lib/util.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ const errors = require('internal/errors');
2525
const { TextDecoder, TextEncoder } = require('internal/encoding');
2626
const { isBuffer } = require('buffer').Buffer;
2727

28-
const { errname } = process.binding('uv');
29-
3028
const {
3129
getPromiseDetails,
3230
getProxyDetails,
@@ -52,6 +50,7 @@ const {
5250
customInspectSymbol,
5351
deprecate,
5452
getConstructorOf,
53+
getSystemErrorName,
5554
isError,
5655
promisify,
5756
join
@@ -985,7 +984,7 @@ function error(...args) {
985984
}
986985

987986
function _errnoException(err, syscall, original) {
988-
var name = errname(err);
987+
const name = getSystemErrorName(err);
989988
var message = `${syscall} ${name}`;
990989
if (original)
991990
message += ` ${original}`;
@@ -1075,6 +1074,7 @@ module.exports = exports = {
10751074
debuglog,
10761075
deprecate,
10771076
format,
1077+
getSystemErrorName,
10781078
inherits,
10791079
inspect,
10801080
isArray: Array.isArray,

src/uv.cc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ using v8::String;
3939
using v8::Value;
4040

4141

42+
// TODO(joyeecheung): deprecate this function in favor of
43+
// lib/util.getSystemErrorName()
4244
void ErrName(const FunctionCallbackInfo<Value>& args) {
4345
Environment* env = Environment::GetCurrent(args);
4446
int err = args[0]->Int32Value();

test/parallel/test-child-process-execfile.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
'use strict';
2+
23
const common = require('../common');
34
const assert = require('assert');
45
const execFile = require('child_process').execFile;
5-
const uv = process.binding('uv');
6+
const { getSystemErrorName } = require('util');
67
const fixtures = require('../common/fixtures');
78

89
const fixture = fixtures.path('exit.js');
@@ -27,7 +28,7 @@ const execOpts = { encoding: 'utf8', shell: true };
2728
const code = -1;
2829
const callback = common.mustCall((err, stdout, stderr) => {
2930
assert.strictEqual(err.toString().trim(), errorString);
30-
assert.strictEqual(err.code, uv.errname(code));
31+
assert.strictEqual(err.code, getSystemErrorName(code));
3132
assert.strictEqual(err.killed, true);
3233
assert.strictEqual(err.signal, null);
3334
assert.strictEqual(err.cmd, process.execPath);

test/parallel/test-net-server-listen-handle.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const common = require('../common');
44
const assert = require('assert');
55
const net = require('net');
66
const fs = require('fs');
7-
const uv = process.binding('uv');
7+
const { getSystemErrorName } = require('util');
88
const { TCP, constants: TCPConstants } = process.binding('tcp_wrap');
99
const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap');
1010

@@ -47,9 +47,10 @@ function randomHandle(type) {
4747
handleName = `pipe ${path}`;
4848
}
4949

50-
if (errno < 0) { // uv.errname requires err < 0
51-
assert(errno >= 0, `unable to bind ${handleName}: ${uv.errname(errno)}`);
50+
if (errno < 0) {
51+
assert.fail(`unable to bind ${handleName}: ${getSystemErrorName(errno)}`);
5252
}
53+
5354
if (!common.isWindows) { // fd doesn't work on windows
5455
// err >= 0 but fd = -1, should not happen
5556
assert.notStrictEqual(handle.fd, -1,

test/parallel/test-uv-errno.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const {
6+
getSystemErrorName,
7+
_errnoException
8+
} = require('util');
9+
10+
const uv = process.binding('uv');
11+
const keys = Object.keys(uv);
12+
13+
keys.forEach((key) => {
14+
if (!key.startsWith('UV_'))
15+
return;
16+
17+
assert.doesNotThrow(() => {
18+
const err = _errnoException(uv[key], 'test');
19+
const name = uv.errname(uv[key]);
20+
assert.strictEqual(getSystemErrorName(uv[key]), name);
21+
assert.strictEqual(err.code, name);
22+
assert.strictEqual(err.code, err.errno);
23+
assert.strictEqual(err.message, `test ${name}`);
24+
});
25+
});
26+
27+
[0, 1, 'test', {}, [], Infinity, -Infinity, NaN].forEach((key) => {
28+
common.expectsError(
29+
() => _errnoException(key),
30+
{
31+
code: 'ERR_INVALID_ARG_TYPE',
32+
type: TypeError,
33+
message: 'The "err" argument must be of type negative number'
34+
});
35+
});

test/sequential/test-async-wrap-getasyncid.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const net = require('net');
77
const providers = Object.assign({}, process.binding('async_wrap').Providers);
88
const fixtures = require('../common/fixtures');
99
const tmpdir = require('../common/tmpdir');
10+
const { getSystemErrorName } = require('util');
1011

1112
// Make sure that all Providers are tested.
1213
{
@@ -214,7 +215,7 @@ if (common.hasCrypto) { // eslint-disable-line crypto-check
214215
// Use a long string to make sure the write happens asynchronously.
215216
const err = handle.writeLatin1String(wreq, 'hi'.repeat(100000));
216217
if (err)
217-
throw new Error(`write failed: ${process.binding('uv').errname(err)}`);
218+
throw new Error(`write failed: ${getSystemErrorName(err)}`);
218219
testInitialized(wreq, 'WriteWrap');
219220
});
220221
req.address = common.localhostIPv4;

0 commit comments

Comments
 (0)