diff --git a/MODULE.bazel b/MODULE.bazel index a9f5588..94e709c 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 51ea98b..31aacb9 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 74bd636..c5d6b75 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 `String::from_utf8_lossy` +// (matching Node.js and SWC). 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 0000000..58108e0 --- /dev/null +++ b/maldoca/js/ir/utf16.rs @@ -0,0 +1,158 @@ +// 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 via +/// `String::from_utf8_lossy` + `str::encode_utf16`. +/// +/// Every UTF-8 byte produces at most one UTF-16 code unit, so `dst_cap >= +/// src_len` always fits the entire result without truncation. Returns `0` if +/// `src_len == 0` or `dst_cap < src_len`; otherwise returns the number of +/// UTF-16 code units written into `dst`. +/// +/// # Safety +/// The caller must ensure that, for the entire duration of this call: +/// - If `src_len > 0` and `dst_cap >= src_len`, `src` is non-null, +/// `src_len <= isize::MAX as usize`, the entire byte range +/// `[src, src + src_len)` lies within a single live allocated object, all +/// `src_len` bytes are initialized `u8` values valid for reads, and the +/// memory in `[src, src + src_len)` is not mutated through any alias or +/// concurrent thread. +/// - If `src_len > 0` and `dst_cap >= src_len`, `dst` is non-null, properly +/// aligned for `u16`, +/// `dst_cap <= (isize::MAX as usize) / mem::size_of::()`, the entire +/// `u16` range `[dst, dst + dst_cap)` lies within a single live allocated +/// object valid for writes (elements need not be initialized), and +/// `[dst, dst + dst_cap)` is exclusively accessed (neither read nor written +/// through any other pointer, alias, or concurrent thread, and does not +/// overlap with `[src, src + src_len)`). +// 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() + || isize::try_from(src_len).is_err() + || dst_cap < src_len + || dst.is_null() + || !dst.is_aligned() + || dst_cap + .checked_mul(mem::size_of::()) + .and_then(|bytes| isize::try_from(bytes).ok()) + .is_none() + { + return 0; + } + // SAFETY: The guard above checks `src_len > 0`, `!src.is_null()`, and + // `src_len <= isize::MAX as usize`, and `mem::align_of::() == 1`. By + // the `# Safety` contract, `[src, src + src_len)` lies within a single + // live allocation of `src_len` initialized `u8` bytes valid for reads and + // is not mutated through any alias or concurrent thread for the duration + // of this call. + let input = unsafe { slice::from_raw_parts(src, src_len) }; + // SAFETY: The guard above checks `dst_cap >= src_len > 0`, + // `!dst.is_null()`, `dst.is_aligned()` for `u16`, and + // `dst_cap * mem::size_of::() <= isize::MAX as usize`. + // `MaybeUninit` has the same size and alignment as `u16` and imposes + // no initialization requirement. By the `# Safety` contract, + // `[dst, dst + dst_cap)` lies within a single live allocation valid for + // writes and is exclusively accessed (non-overlapping with `input` and not + // read or written through any other pointer or thread) for the duration of + // this call. + let output = unsafe { slice::from_raw_parts_mut(dst.cast::>(), dst_cap) }; + + let mut written = 0; + for (slot, unit) in output.iter_mut().zip(String::from_utf8_lossy(input).encode_utf16()) { + slot.write(unit); + 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_and_guard_conditions() { + assert_eq!(decode(b""), Vec::::new()); + let mut buf = [0u16; 2]; + // SAFETY: Insufficient capacity, null pointers, and overflow lengths + // are rejected by the entry guard without dereferencing. + unsafe { + assert_eq!(maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), 4, buf.as_mut_ptr(), 2), 0); + assert_eq!(maldoca_utf8_to_utf16_lossy(std::ptr::null(), 4, buf.as_mut_ptr(), 4), 0); + assert_eq!( + maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), 4, std::ptr::null_mut(), 4), + 0 + ); + assert_eq!(maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), 4, buf.as_mut_ptr(), 0), 0); + assert_eq!( + maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), usize::MAX, buf.as_mut_ptr(), 4), + 0 + ); + assert_eq!( + maldoca_utf8_to_utf16_lossy(b"abcd".as_ptr(), 4, buf.as_mut_ptr(), usize::MAX), + 0 + ); + assert_eq!( + maldoca_utf8_to_utf16_lossy( + b"abcd".as_ptr(), + 4, + buf.as_mut_ptr(), + (isize::MAX as usize) / 2 + 1 + ), + 0 + ); + } + } +}