From dadb60237e42971aa5abdca8422045b64f76cd92 Mon Sep 17 00:00:00 2001 From: Google JSIR Bot Date: Wed, 25 Nov 2026 01:08:20 -0800 Subject: [PATCH] No public description PiperOrigin-RevId: 1029703877 --- MODULE.bazel | 3 + maldoca/js/ir/BUILD | 13 ++++ maldoca/js/ir/utf16.cc | 37 +++++++++-- maldoca/js/ir/utf16.rs | 139 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 186 insertions(+), 6 deletions(-) create mode 100644 maldoca/js/ir/utf16.rs diff --git a/MODULE.bazel b/MODULE.bazel index a9f5588a..94e709c6 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -14,6 +14,9 @@ bazel_dep(name = "platforms", version = "1.1.0") # https://registry.bazel.build/modules/rules_cc bazel_dep(name = "rules_cc", version = "0.2.0") +# https://registry.bazel.build/modules/rules_rust +bazel_dep(name = "rules_rust", version = "0.75.0") + # https://registry.bazel.build/modules/rules_shell # Required by llvm-project's BUILD files. bazel_dep(name = "rules_shell", version = "0.8.0") diff --git a/maldoca/js/ir/BUILD b/maldoca/js/ir/BUILD index 51ea98b0..31aacb95 100644 --- a/maldoca/js/ir/BUILD +++ b/maldoca/js/ir/BUILD @@ -16,6 +16,7 @@ load("@llvm-project//mlir:tblgen.bzl", "gentbl_cc_library", "td_library") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_python//python:defs.bzl", "py_binary") +load("@rules_rust//rust:defs.bzl", "rust_static_library", "rust_test") load("//maldoca/js:allowed_users.bzl", "JSIR_ALLOWED_USERS") licenses(["notice"]) @@ -270,12 +271,24 @@ cc_library( ], ) +rust_static_library( + name = "utf16_rs", + srcs = ["utf16.rs"], + edition = "2021", +) + +rust_test( + name = "utf16_rs_test", + crate = ":utf16_rs", +) + cc_library( name = "utf16", srcs = ["utf16.cc"], hdrs = ["utf16.h"], visibility = ["//maldoca/js:__subpackages__"], deps = [ + ":utf16_rs", "@abseil-cpp//absl/strings:string_view", "@llvm-project//llvm:Support", ], diff --git a/maldoca/js/ir/utf16.cc b/maldoca/js/ir/utf16.cc index 74bd6364..9884085f 100644 --- a/maldoca/js/ir/utf16.cc +++ b/maldoca/js/ir/utf16.cc @@ -14,6 +14,8 @@ #include "maldoca/js/ir/utf16.h" +#include +#include #include #include @@ -24,15 +26,38 @@ #include "absl/strings/string_view.h" namespace maldoca { +namespace { + +// LINT.IfChange(maldoca_utf8_to_utf16_lossy_ffi) +extern "C" { +size_t maldoca_utf8_to_utf16_lossy(const uint8_t* src, size_t src_len, + char16_t* dst, size_t dst_cap); +} +// LINT.ThenChange(utf16.rs:maldoca_utf8_to_utf16_lossy_ffi) + +// Lossy UTF-8 -> UTF-16 decoding via Rust's `utf8_chunks()` (matching +// `String::from_utf8_lossy` and Node.js). Every UTF-8 byte produces at most +// one UTF-16 code unit, so `src.size()` is always a sufficient output bound. +std::u16string Utf8ToUtf16Lossy(absl::string_view src) { + std::u16string out(src.size(), u'\0'); + size_t len = + maldoca_utf8_to_utf16_lossy(reinterpret_cast(src.data()), + src.size(), out.data(), out.size()); + out.resize(len); + return out; +} + +} // namespace std::u16string Utf8ToUtf16(absl::string_view src) { - llvm::StringRef src_ref(src.data(), src.size()); - llvm::SmallVector dst; - if (!llvm::convertUTF8ToUTF16String(src_ref, dst)) { - return u""; + { + llvm::StringRef src_ref(src.data(), src.size()); + llvm::SmallVector dst; + if (llvm::convertUTF8ToUTF16String(src_ref, dst)) { + return std::u16string(dst.begin(), dst.end()); + } } - return std::u16string(reinterpret_cast(dst.data()), - dst.size()); + return Utf8ToUtf16Lossy(src); } std::string Utf16ToUtf8(std::u16string_view src) { diff --git a/maldoca/js/ir/utf16.rs b/maldoca/js/ir/utf16.rs new file mode 100644 index 00000000..3d4b9152 --- /dev/null +++ b/maldoca/js/ir/utf16.rs @@ -0,0 +1,139 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::mem::{self, MaybeUninit}; +use std::slice; + +/// Lossily decodes UTF-8 bytes into UTF-16 code units using Unicode +/// maximal-subpart `U+FFFD` replacement (matching `String::from_utf8_lossy` +/// and Node.js), writing at most `dst_cap` code units into `dst`. +/// +/// Every UTF-8 byte produces at most one UTF-16 code unit, so `dst_cap >= +/// src_len` always suffices without truncation. When `dst_cap` is smaller, +/// decoding stops before writing a character whose UTF-16 encoding would not +/// fit (avoiding unpaired surrogates). Returns the number of UTF-16 code units +/// written. +/// +/// # Safety +/// - If `src_len > 0`, `src` must be non-null and valid for reads of `src_len` +/// bytes, and `src_len <= isize::MAX as usize`. +/// - If `dst_cap > 0`, `dst` must be non-null, properly aligned for `u16`, and +/// valid for writes of `dst_cap` `u16`s (need not be initialized), with +/// `dst_cap <= (isize::MAX as usize) / mem::size_of::()`. +/// - `src` and `dst` must not overlap. +// LINT.IfChange(maldoca_utf8_to_utf16_lossy_ffi) +#[no_mangle] +pub unsafe extern "C" fn maldoca_utf8_to_utf16_lossy( + src: *const u8, + src_len: usize, + dst: *mut u16, + dst_cap: usize, +) -> usize { + // LINT.ThenChange(utf16.cc:maldoca_utf8_to_utf16_lossy_ffi) + if src_len == 0 + || src.is_null() + || src_len > isize::MAX as usize + || dst_cap == 0 + || dst.is_null() + || !dst.is_aligned() + || dst_cap > (isize::MAX as usize) / mem::size_of::() + { + return 0; + } + // SAFETY: Validated non-null, aligned, and within `isize::MAX` byte bounds + // above; caller guarantees read/write validity and non-overlap. Using + // `MaybeUninit` allows `dst` to point to uninitialized memory. + let input = unsafe { slice::from_raw_parts(src, src_len) }; + let output = unsafe { slice::from_raw_parts_mut(dst.cast::>(), dst_cap) }; + + let mut written = 0; + let mut utf16_char_buf = [0u16; 2]; + for chunk in input.utf8_chunks() { + for ch in chunk.valid().chars() { + let encoded = ch.encode_utf16(&mut utf16_char_buf); + if written + encoded.len() > output.len() { + return written; + } + for &u in encoded.iter() { + output[written].write(u); + written += 1; + } + } + if !chunk.invalid().is_empty() { + if written >= output.len() { + return written; + } + output[written].write(0xFFFD); + written += 1; + } + } + written +} + +#[cfg(test)] +mod tests { + use super::*; + + fn decode(bytes: &[u8]) -> Vec { + let mut out = vec![MaybeUninit::::uninit(); bytes.len()]; + // SAFETY: `bytes` and `out` are valid, aligned, non-overlapping slices. + let n = unsafe { + maldoca_utf8_to_utf16_lossy( + bytes.as_ptr(), + bytes.len(), + out.as_mut_ptr().cast::(), + out.len(), + ) + }; + // SAFETY: `maldoca_utf8_to_utf16_lossy` initialized the first `n` slots. + out[..n].iter().map(|slot| unsafe { slot.assume_init() }).collect() + } + + #[test] + fn test_lossy_latin1_and_surrogate_pair() { + let input = b"caf\xe9 \xc3\xa9 \xe4\xb8\xad \xf0\x9f\x98\x80"; + let expected: Vec = "caf\u{FFFD} \u{00E9} \u{4E2D} \u{1F600}".encode_utf16().collect(); + assert_eq!(decode(input), expected); + } + + #[test] + fn test_truncated_sequences_maximal_subpart() { + assert_eq!(decode(b"\xc3"), vec![0xFFFD]); + assert_eq!(decode(b"\xe4\xb8"), vec![0xFFFD]); + assert_eq!(decode(b"\xf0\x9f\x98"), vec![0xFFFD]); + assert_eq!(decode(b"\xf0\x9f"), vec![0xFFFD]); + assert_eq!(decode(b"\xff\xff\xff"), vec![0xFFFD, 0xFFFD, 0xFFFD]); + } + + #[test] + fn test_empty_small_cap_and_no_unpaired_surrogate() { + assert_eq!(decode(b""), Vec::::new()); + let mut small = [0u16; 2]; + // SAFETY: Valid non-overlapping buffers. + let n = unsafe { maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), 4, small.as_mut_ptr(), 2) }; + assert_eq!(n, 2); + assert_eq!(small, [b'a' as u16, b'b' as u16]); + + // Capacity 2 for "a" (1 unit) + U+1F600 (2 units) must stop at 1 unit + // rather than emitting an unpaired high surrogate. + let emoji = "a\u{1F600}".as_bytes(); + let mut buf = [0u16; 2]; + // SAFETY: Valid non-overlapping buffers. + let written = unsafe { + maldoca_utf8_to_utf16_lossy(emoji.as_ptr(), emoji.len(), buf.as_mut_ptr(), buf.len()) + }; + assert_eq!(written, 1); + assert_eq!(buf[0], b'a' as u16); + } +}