Skip to content

Commit 5bbbb28

Browse files
committed
buffer: random-fill Buffer(num) and new Buffer(num)
Selects a random byte and fills Buffer(num) and new Buffer(num) automatically using the randomly selected value. Why random-fill vs. zero-fill? Prior to this commit, the uninitialized Buffer allocation would be potentially filled with non-zeroed data. By filling with a randomly selected value, we eliminate the possibility of leaking uninitialized data but we preserve the need for users to completely over-write the Buffer contents in order for it to be useful. Zero-filling by default would *potentially* put users at risk if module developers assume that the Buffer instance will always be zero-filled (which will not be the case on older versions of Node.js). The cost, however, is that filling with a randomly selected value is a bit less performant than zero-filling on allocation. Note that Buffer.allocUnsafe() and Buffer.alloc() are *not* affected by this change. Buffer.allocUnsafe() will returns a Buffer with uninitialized data and Buffer.alloc() returns *zero-filled* data.
1 parent ab2d49b commit 5bbbb28

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

lib/buffer.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,14 @@
2222
'use strict';
2323

2424
const binding = process.binding('buffer');
25+
const config = process.binding('config');
2526
const { compare: compare_, compareOffset } = binding;
2627
const { isArrayBuffer, isSharedArrayBuffer, isUint8Array } =
2728
process.binding('util');
2829
const bindingObj = {};
2930
const internalUtil = require('internal/util');
31+
const zeroFillBuffers = !!config.zeroFillBuffers;
32+
const randomFill = zeroFillBuffers ? 0 : Math.floor(Math.random() * 256);
3033

3134
class FastBuffer extends Uint8Array {
3235
constructor(arg1, arg2, arg3) {
@@ -102,7 +105,7 @@ function Buffer(arg, encodingOrOffset, length) {
102105
'If encoding is specified then the first argument must be a string'
103106
);
104107
}
105-
return Buffer.allocUnsafe(arg);
108+
return Buffer.allocUnsafe(arg).fill(randomFill);
106109
}
107110
return Buffer.from(arg, encodingOrOffset, length);
108111
}

src/node_config.cc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "node.h"
2+
#include "node_buffer.h"
23
#include "node_i18n.h"
34
#include "env.h"
45
#include "env-inl.h"
@@ -49,6 +50,9 @@ void InitConfig(Local<Object> target,
4950
if (config_preserve_symlinks)
5051
READONLY_BOOLEAN_PROPERTY("preserveSymlinks");
5152

53+
if (zero_fill_all_buffers)
54+
READONLY_BOOLEAN_PROPERTY("zeroFillBuffers");
55+
5256
if (!config_warning_file.empty()) {
5357
Local<String> name = OneByteString(env->isolate(), "warningFile");
5458
Local<String> value = String::NewFromUtf8(env->isolate(),

0 commit comments

Comments
 (0)