Skip to content

Commit 0d8234e

Browse files
committed
Do not attempt to perform OOB write in writeCString
Include the nul terminator in the size computation. Otherwise, Node.js may throw an exception when `.writeUInt8` is called. Fixes: #40
1 parent 0b6bbb3 commit 0d8234e

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

lib/ref.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ exports.writeCString = function writeCString (buffer, offset, string, encoding)
578578
if (!encoding) {
579579
encoding = 'utf8';
580580
}
581-
const size = buffer.length - offset;
581+
const size = buffer.length - offset - 1;
582582
const len = buffer.write(string, offset, size, encoding);
583583
buffer.writeUInt8(0, offset + len); // NUL terminate
584584
}

test/string.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ describe('C string', function() {
3131
}
3232
assert.strictEqual(0, buf[str.length]);
3333
});
34+
35+
it('should not write the terminating 0 out of bounds', function() {
36+
const wholebuf = Buffer.alloc(20, 127);
37+
const buf = wholebuf.subarray(0, 10);
38+
const str = 'hello world';
39+
buf.writeCString(str);
40+
for (let i = 0; i < buf.length - 1; i++) {
41+
assert.strictEqual(str.charCodeAt(i), buf[i]);
42+
}
43+
assert.strictEqual(0, buf[buf.length - 1]);
44+
for (let i = buf.length; i < wholebuf.length; i++) {
45+
assert.strictEqual(127, wholebuf[i]);
46+
}
47+
});
3448
});
3549

3650
describe('allocCString()', function() {

0 commit comments

Comments
 (0)