Skip to content

Commit f46952e

Browse files
ChALkeRMyles Borins
authored and
Myles Borins
committed
buffer: safeguard against accidental kNoZeroFill
This makes sure that `kNoZeroFill` flag is not accidentally set by moving the all the flag operations directly inside `createBuffer()`. It safeguards against logical errors like #6006. This also ensures that `kNoZeroFill` flag is always restored to 0 using a try-finally block, as it could be not restored to 0 in cases of failed or zero-size `Uint8Array` allocation. It safeguards against errors like #2930. It also makes the `size > 0` check not needed there. PR-URL: https://github.com/nodejs/node-private/pull/30 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Trevor Norris <[email protected]>
1 parent 4f1c82f commit f46952e

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

lib/buffer.js

+12-14
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,20 @@ binding.setupBufferJS(Buffer.prototype, bindingObj);
1919
const flags = bindingObj.flags;
2020
const kNoZeroFill = 0;
2121

22-
function createBuffer(size) {
23-
const ui8 = new Uint8Array(size);
24-
Object.setPrototypeOf(ui8, Buffer.prototype);
25-
return ui8;
22+
function createBuffer(size, noZeroFill) {
23+
flags[kNoZeroFill] = noZeroFill ? 1 : 0;
24+
try {
25+
const ui8 = new Uint8Array(size);
26+
Object.setPrototypeOf(ui8, Buffer.prototype);
27+
return ui8;
28+
} finally {
29+
flags[kNoZeroFill] = 0;
30+
}
2631
}
2732

2833
function createPool() {
2934
poolSize = Buffer.poolSize;
30-
if (poolSize > 0)
31-
flags[kNoZeroFill] = 1;
32-
allocPool = createBuffer(poolSize);
35+
allocPool = createBuffer(poolSize, true);
3336
poolOffset = 0;
3437
}
3538
createPool();
@@ -65,13 +68,10 @@ function Buffer(arg, encoding) {
6568
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
6669
Object.setPrototypeOf(Buffer, Uint8Array);
6770

68-
6971
function SlowBuffer(length) {
7072
if (+length != length)
7173
length = 0;
72-
if (length > 0)
73-
flags[kNoZeroFill] = 1;
74-
return createBuffer(+length);
74+
return createBuffer(+length, true);
7575
}
7676

7777
Object.setPrototypeOf(SlowBuffer.prototype, Uint8Array.prototype);
@@ -93,9 +93,7 @@ function allocate(size) {
9393
// Even though this is checked above, the conditional is a safety net and
9494
// sanity check to prevent any subsequent typed array allocation from not
9595
// being zero filled.
96-
if (size > 0)
97-
flags[kNoZeroFill] = 1;
98-
return createBuffer(size);
96+
return createBuffer(size, true);
9997
}
10098
}
10199

0 commit comments

Comments
 (0)