buffer: fix transcode for single-byte enc to ucs2

Fix `buffer.transcode()` for transcoding from single-byte character
encodings to UCS2.

These would previously perform out-of-bounds reads due to an
incorrect `sizeof()` expression.

Fixes: https://github.com/nodejs/node/issues/9834
PR-URL: https://github.com/nodejs/node/pull/9838
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Anna Henningsen 2016-11-29 05:22:40 -06:00
parent 18cf668d40
commit 69b1a76ddd
No known key found for this signature in database
GPG Key ID: D8B9F5AEAE84E4CF
2 changed files with 11 additions and 1 deletions

View File

@ -179,7 +179,7 @@ MaybeLocal<Object> TranscodeToUcs2(Isolate* isolate,
MaybeLocal<Object> ret; MaybeLocal<Object> ret;
MaybeStackBuffer<UChar> destbuf(source_length); MaybeStackBuffer<UChar> destbuf(source_length);
Converter from(fromEncoding); Converter from(fromEncoding);
const size_t length_in_chars = source_length * sizeof(*destbuf); const size_t length_in_chars = source_length * sizeof(UChar);
ucnv_toUChars(from.conv, *destbuf, length_in_chars, ucnv_toUChars(from.conv, *destbuf, length_in_chars,
source, source_length, status); source, source_length, status);
if (U_SUCCESS(*status)) if (U_SUCCESS(*status))

View File

@ -46,3 +46,13 @@ assert.throws(
() => buffer.transcode(Buffer.from('a'), 'uf8', 'b'), () => buffer.transcode(Buffer.from('a'), 'uf8', 'b'),
/Unable to transcode Buffer \[U_ILLEGAL_ARGUMENT_ERROR\]/ /Unable to transcode Buffer \[U_ILLEGAL_ARGUMENT_ERROR\]/
); );
assert.deepStrictEqual(
buffer.transcode(Buffer.from('hi', 'ascii'), 'ascii', 'utf16le'),
Buffer.from('hi', 'utf16le'));
assert.deepStrictEqual(
buffer.transcode(Buffer.from('hi', 'latin1'), 'latin1', 'utf16le'),
Buffer.from('hi', 'utf16le'));
assert.deepStrictEqual(
buffer.transcode(Buffer.from('hä', 'latin1'), 'latin1', 'utf16le'),
Buffer.from('hä', 'utf16le'));