Skip to content

Commit

Permalink
buffer: validate UTF8 on fast path
Browse files Browse the repository at this point in the history
Fast API handles invalid UTF differently than the slow API.

Fixes: #54521
PR-URL: #54525
  • Loading branch information
ronag committed Aug 23, 2024
1 parent d5dc540 commit a930ad4
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,30 @@ uint32_t FastWriteString(Local<Value> receiver,

static v8::CFunction fast_write_string(v8::CFunction::Make(FastWriteString));

uint32_t FastWriteStringUTF8(Local<Value> receiver,
const v8::FastApiTypedArray<uint8_t>& dst,
const v8::FastOneByteString& src,
uint32_t offset,
uint32_t max_length) {
uint8_t* dst_data;
CHECK(dst.getStorageIfAligned(&dst_data));
CHECK(offset <= dst.length());
CHECK(dst.length() - offset <= std::numeric_limits<uint32_t>::max());

const auto size = std::min(
{static_cast<uint32_t>(dst.length() - offset), max_length, src.length});

if (simdutf::validate_utf8(src.data, size)) {
memcpy(dst_data + offset, src.data, size);
} else {
// TODO (fix): Fallback to SlowWriteString
}

return size;
}

static v8::CFunction fast_write_string_utf8(v8::CFunction::Make(FastWriteStringUTF8));

void Initialize(Local<Object> target,
Local<Value> unused,
Local<Context> context,
Expand Down Expand Up @@ -1568,7 +1592,7 @@ void Initialize(Local<Object> target,
target,
"utf8WriteStatic",
SlowWriteString<UTF8>,
&fast_write_string);
&fast_write_string_utf8);

SetMethod(context, target, "getZeroFillToggle", GetZeroFillToggle);
}
Expand Down Expand Up @@ -1615,6 +1639,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(SlowWriteString<UTF8>);
registry->Register(fast_write_string.GetTypeInfo());
registry->Register(FastWriteString);
registry->Register(fast_write_string_utf8.GetTypeInfo());
registry->Register(FastWriteStringUTF8);
registry->Register(StringWrite<ASCII>);
registry->Register(StringWrite<BASE64>);
registry->Register(StringWrite<BASE64URL>);
Expand Down

0 comments on commit a930ad4

Please sign in to comment.