Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/string_bytes.cc
Original file line number Diff line number Diff line change
Expand Up @@ -723,8 +723,11 @@ MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
}
if (reinterpret_cast<uintptr_t>(buf) % 2 != 0) {
return EncodeTwoByteString(
isolate, str_len, [buf, buflen](uint16_t* dst) {
memcpy(dst, buf, buflen);
isolate, str_len, [buf, str_len](uint16_t* dst) {
// Copy whole code units only. buflen may be odd, but the
// destination holds str_len (== buflen / 2) uint16_t units, so
// copying buflen bytes would write one byte past it.
memcpy(dst, buf, str_len * sizeof(uint16_t));
});
}
return ExternTwoByteString::NewFromCopy(
Expand Down
17 changes: 17 additions & 0 deletions test/parallel/test-buffer-tostring-range.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,23 @@ assert.strictEqual(rangeBuffer.toString('ascii', 0, true), 'a');
);
}

// ucs2 slices of odd byte length at an odd (2-byte unaligned) start offset.
// The decoder keeps whole code units and drops the trailing odd byte, so an
// odd-length slice reads the same as the even-length slice one byte shorter.
// Regression for a one-byte out-of-bounds write in the unaligned copy path,
// where the full odd byte length was copied into a buffer sized for
// floor(len / 2) code units.
for (const nchars of [1, 200, 256, 300, 1024]) {
const bytes = nchars * 2 + 1; // odd
const src = Buffer.alloc(bytes + 2);
for (let i = 0; i < src.length; i++) src[i] = (i * 7 + 1) & 0xff;
// start = 1 makes the read pointer 2-byte unaligned; end - start is odd.
const odd = src.toString('ucs2', 1, 1 + bytes);
const even = src.toString('ucs2', 1, 1 + bytes - 1);
assert.strictEqual(odd.length, nchars);
assert.strictEqual(odd, even);
}

// Try toString() with an object as an encoding
assert.strictEqual(rangeBuffer.toString({ toString: function() {
return 'ascii';
Expand Down
Loading