Skip to content

fix: resolve signed shift UB in escape parsing - #596

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:release/eaglefrom
liyigang1:agent/bugfix/383495
Nov 24, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:release/eaglefrom
liyigang1:agent/bugfix/383495

Conversation

@liyigang1

@liyigang1 liyigang1 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Root Cause Analysis

SettingIO::unescapedString() used signed int for escapeVal, and the hex/octal escape parsing loop performed escapeVal <<= 4/<<= 3 without iteration limits, causing signed integer overflow UB (CWE-190/CWE-758) on long escape sequences. utf8MultiByteCount()'s LeftBitFunc lambda took char parameter — on x86_64 char is signed, so UTF-8 leading bytes (≥0x80) became negative, and data <<= 1 on a negative value is UB. Both confirmed via UBSan independent verifiers.

Fix

Changed escapeVal from int to unsigned int and added range checks (> 0x0FFFFFFF for hex, > 0x1FFFFFFF for octal) before shift operations to prevent overflow. Changed LeftBitFunc parameter from char to unsigned char to eliminate negative left-shift UB.

Change Safety Assessment

Code Safety

  • Risk Level: Low
  • Type change to unsigned is standard overflow mitigation; no API/ABI change
  • Both functions are internal helpers — unescapedString() only called by config I/O; utf8MultiByteCount() only called within Gb18030→UTF-8 transcoding path

Business Impact Scope

  • Terminal config file read/write with escape sequences
  • UTF-8 multi-byte character detection (Gb18030→UTF-8 transcoding)
  • No behavior change for valid inputs; only eliminates undefined behavior

Verification Suggestion

Test terminal config file read/write with common escape sequences; test UTF-8 encoding detection with high bytes; verify no regression in existing escape parsing.


根因分析

SettingIO::unescapedString() 使用有符号 int 存储 escapeVal,十六进制/八进制转义解析循环 escapeVal <<= 4/<<= 3 无迭代上限,超长转义序列触发有符号整数溢出 UB(CWE-190/CWE-758)。utf8MultiByteCount() 的 LeftBitFunc lambda 参数为有符号 char,UTF-8 首字节 ≥ 0x80 时为负值,data <<= 1 对负值左移为 UB。两处 UB 均通过 UBSan 独立验证器复现确认。

修复方案

将 escapeVal 从 int 改为 unsigned int,在 hex/octal 左移前增加范围检查(> 0x0FFFFFFF / > 0x1FFFFFFF)防止溢出。将 LeftBitFunc 参数从 char 改为 unsigned char,消除负值左移 UB。

改动安全评估

代码安全评估

  • 风险等级: 低风险
  • 类型改为无符号为标准溢出缓解措施,无 API/ABI 变化
  • 两处均为内部辅助函数——unescapedString() 仅被配置 I/O 调用;utf8MultiByteCount() 仅被 Gb18030→UTF-8 转码路径调用

业务影响范围

  • 终端配置文件含转义字符的读写
  • UTF-8 多字节字符编码检测(Gb18030→UTF-8 转码)
  • 合法输入路径行为无变化,仅消除未定义行为

验证建议

测试终端配置文件含常见转义字符的读写功能;测试含高字节 UTF-8 字符的编码检测功能;验证现有转义解析行为无回归。

PMS: BUG-383495

Summary by Sourcery

Prevent undefined behavior in escape parsing and UTF-8 detection while preserving valid-input behavior.

Bug Fixes:

  • Eliminate undefined behavior in escape-sequence parsing and UTF-8 byte detection for oversized values and high-bit input bytes.

Enhancements:

  • Extract UTF-8 multibyte counting into a reusable source and header implementation.

Build:

  • Include the extracted UTF-8 multibyte counter in the terminal widget and test builds.

Tests:

  • Add coverage for UTF-8 byte classification, boundary cases, and escape decoding including overflow protection.

@liyigang1
liyigang1 marked this pull request as draft November 19, 2026 13:30
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Make the UTF-8 byte classifier shift an unsigned value to avoid undefined behavior on high-bit bytes.

  • 3rdparty/terminalwidget/lib/encodes/utf8multibytecount.cpp L1-61

Accumulate hexadecimal and octal escape values as unsigned integers and guard shifts to prevent overflow.

  • src/common/settingio.cpp L366-369, L387-390 (+2 small edits)

Extract the UTF-8 byte-count helper from detectcode.cpp into its own implementation and include its declaration for the existing caller.

  • 3rdparty/terminalwidget/lib/encodes/detectcode.cpp L1, L15, L488 (removed lines)

Configuration

Add the extracted UTF-8 byte-count implementation to the terminal widget build and test source lists.

  • 3rdparty/terminalwidget/CMakeLists.txt L110
  • tests/CMakeLists.txt L1, L66, L92

Tests

Add focused tests for UTF-8 byte classification, including high-bit bytes and boundary inputs.

  • tests/src/3rdparty/terminalwidget/lib/ut_utf8multibytecount_test.cpp L1-140

Cover common, oversized, invalid, and mixed escape parsing behavior in SettingIO.

  • tests/src/common/ut_settingio_test.cpp L2, L97-213

Other changes

Files not grouped.

  • 3rdparty/terminalwidget/lib/encodes/utf8multibytecount.h L1-12

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/common/settingio.cpp" line_range="461-463" />
<code_context>
     }
     if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
         // qDebug() << "Branch: valid hex digit in sequence";
+        if (escapeVal > 0x0FFFFFFFu) {
+            stringResult += QChar(escapeVal);
+            goto normal;
+        }
         escapeVal <<= 4;
</code_context>
<issue_to_address>
**Oversized escapes split into text**

When a hex or octal escape has enough significant digits to exceed 32 bits, the guard appends only the accumulated prefix and jumps to `normal`, where the first excess digit is processed as ordinary text; a long escape such as `\x100000000` therefore becomes a code unit plus a literal suffix in the configuration value.

Define a consistent policy for oversized escapes, such as consuming the full sequence while safely bounding the value or rejecting it, rather than emitting a prefix and treating the rest as literal text.

Also at `src/common/settingio.cpp:485-488`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/common/settingio.cpp Outdated
Comment on lines +461 to +463
if (escapeVal > 0x0FFFFFFFu) {
stringResult += QChar(escapeVal);
goto normal;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Oversized escapes split into text

When a hex or octal escape has enough significant digits to exceed 32 bits, the guard appends only the accumulated prefix and jumps to normal, where the first excess digit is processed as ordinary text; a long escape such as \x100000000 therefore becomes a code unit plus a literal suffix in the configuration value.

Define a consistent policy for oversized escapes, such as consuming the full sequence while safely bounding the value or rejecting it, rather than emitting a prefix and treating the rest as literal text.

Also at src/common/settingio.cpp:485-488.

Prompt for AI agents
In `src/common/settingio.cpp` at lines 461-463:

**Oversized escapes split into text**

When a hex or octal escape has enough significant digits to exceed 32 bits, the guard appends only the accumulated prefix and jumps to `normal`, where the first excess digit is processed as ordinary text; a long escape such as `\x100000000` therefore becomes a code unit plus a literal suffix in the configuration value.

Define a consistent policy for oversized escapes, such as consuming the full sequence while safely bounding the value or rejecting it, rather than emitting a prefix and treating the rest as literal text.

Also at `src/common/settingio.cpp:485-488`.

@liyigang1
liyigang1 changed the base branch from master to release/eagle November 23, 2026 03:08
@liyigang1
liyigang1 marked this pull request as ready for review November 23, 2026 07:29
max-lvs
max-lvs previously approved these changes Nov 23, 2026
@liyigang1
liyigang1 marked this pull request as draft November 23, 2026 10:42
@liyigang1
liyigang1 marked this pull request as ready for review November 24, 2026 01:53
@liyigang1
liyigang1 marked this pull request as draft November 24, 2026 02:21
@liyigang1
liyigang1 marked this pull request as ready for review November 24, 2026 02:26
@liyigang1
liyigang1 marked this pull request as draft November 24, 2026 02:51
1. Root cause: SettingIO::unescapedString() used signed int for
   escapeVal, left-shift operations triggered signed integer
   overflow UB (CWE-190/CWE-758) when accumulating hex/octal values
2. Root cause: utf8MultiByteCount() LeftBitFunc lambda took char
   parameter, signed char implicit conversion caused UB on high
   bytes (>=0x80) during bit testing
3. Fix: change escapeVal to unsigned int and add range checks before
   shift operations; change LeftBitFunc parameter to unsigned char
4. Impact: eliminates undefined behavior, no behavior change for
   valid inputs, no API/ABI change

Influence:
1. Test terminal config read/write with common escape sequences
2. Test UTF-8 multi-byte character detection with high bytes
3. Verify no regression on existing escape parsing behavior

fix: 修复转义解析中的有符号移位未定义行为

1. 根因:SettingIO::unescapedString() 使用有符号 int 存储 escapeVal,
   左移操作在累积十六进制/八进制值时触发有符号整数溢出 UB
   (CWE-190/CWE-758)
2. 根因:utf8MultiByteCount() 的 LeftBitFunc lambda 参数为 char,
   有符号 char 在高字节(>=0x80)位测试时隐式转换导致 UB
3. 方案:escapeVal 改为 unsigned int 并在移位前增加范围检查;
   LeftBitFunc 参数改为 unsigned char
4. 影响:消除未定义行为,合法输入路径无行为变化,无 API/ABI 变化

Influence:
1. 测试终端配置文件含常见转义字符的读写
2. 测试含高字节 UTF-8 字符的编码检测
3. 验证现有转义解析行为无回归

Bug: #383495
PMS: BUG-383495
@liyigang1
liyigang1 marked this pull request as ready for review November 24, 2026 05:07
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: liyigang1, max-lvs

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@liyigang1

Copy link
Copy Markdown
Contributor Author

/forcemerge

@deepin-bot

deepin-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

This pr force merged! (status: unstable)

@deepin-bot
deepin-bot Bot merged commit cea82f2 into linuxdeepin:release/eagle Nov 24, 2026
12 of 14 checks passed
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.

3 participants