Skip to content

Clamp UTF-8 length in ConvertToUnicodeAlignment - #1231

Merged
taku910 merged 1 commit into
google:masterfrom
Alearner12:fix/convert-to-unicode-alignment-oob
May 8, 2026
Merged

taku910 merged 1 commit into
google:masterfrom
Alearner12:fix/convert-to-unicode-alignment-oob

Conversation

@Alearner12

Copy link
Copy Markdown
Contributor

Clamp UTF-8 length in ConvertToUnicodeAlignment

Fixes #1230

Description

This PR fixes a heap out-of-bounds write vulnerability in ConvertToUnicodeAlignment (src/sentencepiece_trainer.cc).

When processing malformed or truncated UTF-8 input strings (e.g., a single 0xF0 byte), the loop relies on string_util::OneCharLen(str.data()) to determine the multi-byte sequence length (mblen). Since OneCharLen only inspects the lead byte and does not validate against the actual remaining string length, a truncated sequence results in an mblen that exceeds str.size().

This causes two issues:

  1. The inner loop writes out-of-bounds into the utf8_to_unicode heap-allocated std::vector.
  2. str.remove_prefix(mblen) underflows the absl::string_view's size, leading to unbounded reads/writes in subsequent loop iterations.

The Fix

This PR mirrors the identical fix applied in commit d14bab4 for the sibling function ConvertToUnicodeSpansInternal. We wrap the existing std::max logic with a clamp against str.size():

const size_t mblen = std::min(
    str.size(),
    static_cast<size_t>(
        std::max<int>(1, string_util::OneCharLen(str.data()))));

Testing

  • Added regression tests in src/sentencepiece_trainer_test.cc that specifically test 2-byte, 3-byte, and 4-byte truncated UTF-8 sequences as single-byte inputs.
  • Built and tested with AddressSanitizer (-fsanitize=address) — confirmed that ASan catches the heap-buffer-overflow on the unpatched code, and passes successfully with this PR.

@google-cla

google-cla Bot commented May 8, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

This change adds a clamp against str.size() so a truncated UTF-8 lead byte (e.g. 0xF0 alone) cannot produce an mblen larger than the remaining buffer, preventing heap out-of-bounds writes.

Mirrors the fix applied in d14bab4 for ConvertToUnicodeSpansInternal.
@Alearner12
Alearner12 force-pushed the fix/convert-to-unicode-alignment-oob branch from 02984d4 to 0baaece Compare May 8, 2026 16:50
@taku910
taku910 merged commit c6caa60 into google:master May 8, 2026
48 checks passed
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
sentencepiece 0.2.2

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre># Release Notes v0.2.2

This release contains major updates, including the migration of the Python wrapper to pybind11, native NumPy support, enhanced offset mapping, performance optimizations, security hardening, and internal code modernization.

## 1. Python Wrapper (pybind11 Migration & Features)
- **SWIG to pybind11 Migration**: Fully migrated the Python wrapper from SWIG to pybind11, enabling better performance, safer memory management, and cleaner code integration ([#1266](google/sentencepiece#1266), Commit `528dc9e`).
-  **Native NumPy Support**: 
    * direct encode/decoder from/to numpy object
- **Enhanced Offset Mapping**:
    * Added new offset mapping features supporting both Unicode character offsets and raw byte offsets.
    * Added bounds checking to prevent OOB reads in offset mapping (Commit `c5b0ce0`).
    * Fixed crash issues and OOB spans in alignment conversions ([#1231](google/sentencepiece#1231), [#1211](google/sentencepiece#1211)).
- **Type Stubs (PEP 561)**: Added inline type stubs (`.pyi` files) and packaged PEP 561 marker to provide auto-completion and static type safety in IDEs ([#1258](google/sentencepiece#1258), Commit `8b7f97b`).
- **Parallel Encoding API**: Introduced `parallel_encode` and `ThreadPool` APIs, allowing Python users to tokenize single large documents across multiple CPU cores in parallel ([#1254](google/sentencepiece#1254), Commit `3c37c39`).
- **Direct Proto Loading**: Added support for loading processors and normalizers directly from in-memory Proto instances (Commit `12788ba`).
- **Concurrency Enhancements**: Added GIL release during C++ execution to improve multi-threaded Python performance ([#1251](google/sentencepiece#1251), Commit `0a044ae`).
- **BOS/EOS Behavior Hardening**: Aligned BOS/EOS adding behavior with C++ constraints, raising explicit `ValueError` instead of silent failures or crashes (Commit `780618a`).

## 2. Performance Optimizations
- **BPE Training Optimization**: Ported O(log n) lazy priority queue update optimization to BPE trainer to speed up training (Commit `8db9878`).
- **Encode/Decode Optimizations**: Decoding/Encoding optimization for integer/string input case by skipping `SentencePieceText` conversion, resulting in ~2x speedup (Commit `4b9231b`).
- **Unigram Pruning**: Improved unigram pruning using token-normalized frequency calculations ([#1135](google/sentencepiece#1135), Commit `1cd0c59`).

## 3. Security & Hardening
- **Trie Validation at Load**: Added verification of `darts-clone` trie offsets when loading models to prevent segfaults on corrupted or malicious model files ([#1224](google/sentencepiece#1224), Commit `6b2f05d`).
- **Bounds Checking in Maps**: Added bounds checks to piece accessors and validated value offsets in `DecompileCharsMap` ([#1265](google/sentencepiece#1265), Commit `82b7c6d`).
- **Crash Prevention**: Replaced internal `CHECK` macros with `DCHECK` or returned errors to prevent host application crashes on invalid inputs (Commit `66b2587`).
- **Null Character Disallowment**: Explicitly disallow vocabulary pieces containing null characters (Commit `eb3ba49`).
- **NBest Timeout**: Implemented a global timeout for NBest A* search to prevent hangs on pathological inputs (Commit `ba57749`).

## 4. C++ API & Internals Modernization
- **Abseil Migration**: Extensively migrated from custom utilities to Abseil primitives ([#1270]
- **Normalizer Maps**: Supported loading normalizer from raw maps in C++ ([#1273](google/sentencepiece#1273), Commit `e476e5e`).

## 5. Build & Packaging
- **Deprecate Win32 Wheels**: Stopped support and distribution of 32-bit Windows wheels (win32) (Commit `24fd00c`).
- **Modernized Python builds**: Switched from calling `setup.py` directly to the standard `pypa/build` PEP 517 frontend ([#1167](google/sentencepiece#1167), Commit `f300c7d`).
- **PEP 639 License**: Added PEP 639 license metadata to `pyproject.toml` ([#1173](google/sentencepiece#1173)).

## 6. Documentation
- **API Cheat Sheet**: Added comparison tables, zero-copy, and sampling comparison guides.
- **Refactored Options**: Fully reorganized `options.md` and `special_symbols.md` with verified code examples.
</pre>
  <p>View the full release notes at <a href="https://github.com/google/sentencepiece/releases/tag/v0.2.2">https://github.com/google/sentencepiece/releases/tag/v0.2.2</a>.</p>
</details>
<hr>

See merge request: Harmonybrew/homebrew-core!14138
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Heap out-of-bounds write in ConvertToUnicodeAlignment on truncated UTF-8

2 participants