Skip to content

fix: resolve silent truncation on non-EILSEQ iconv errors - #762

Merged
pengfeixx merged 1 commit into
linuxdeepin:masterfrom
pengfeixx:agent/bugfix/384499
Dec 1, 2026
Merged

pengfeixx merged 1 commit into
linuxdeepin:masterfrom
pengfeixx:agent/bugfix/384499

Conversation

@pengfeixx

@pengfeixx pengfeixx commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

fix: resolve silent truncation on non-EILSEQ iconv errors

  1. Root cause: In ChangeFileEncodingFormat(), the iconv do-while loop's
    else branch (for non-EILSEQ errors like EINVAL) performed a silent
    break, truncating all remaining content after the error byte
  2. Fix: replace the break with the same recovery strategy used by the
    EILSEQ branch — skip the current input byte, append '?' to the output
    buffer, and continue the conversion loop instead of aborting
  3. Impact: files containing invalid byte sequences (e.g. kern.log with
    53263 lines showing only 1034) now load completely with '?' replacing
    invalid bytes instead of being silently truncated

fix: 修复编码转换中非EILSEQ的iconv错误导致文件内容静默截断

  1. 根因:ChangeFileEncodingFormat()的iconv循环中,else分支(处理EINVAL等
    非EILSEQ错误)直接break,导致错误字节之后的所有内容被静默截断
  2. 方案:将break替换为与EILSEQ分支相同的恢复策略——跳过当前输入字节、
    在输出缓冲区追加'?'、继续循环而非中止转换
  3. 影响:包含非法字节序列的文件(如kern.log 53263行仅显示1034行)
    现在能完整加载,非法字节以'?'替代而非静默截断

Log: Fixed file content truncation when encountering invalid byte sequences during encoding conversion
Influence:

  • Test opening files with invalid byte sequences to verify complete content display
  • Verify normal encoding files load without regression
  • Test UTF-8 to GB18030 and reverse conversion with mixed valid/invalid bytes
    Log: 修复包含非法字节序列的文件在编码转换时内容被静默截断的问题
    Influence:
  • 测试打开含非法字节的文件,验证内容完整显示
  • 验证正常编码文件加载无回归
  • 测试UTF-8与GB18030互转场景下混合有效/非法字节的处理
    PMS: BUG-384499

Summary by Sourcery

Preserve file contents during encoding conversion when iconv encounters non-EILSEQ errors.

Bug Fixes:

  • Prevent encoding conversion from silently truncating file contents after non-EILSEQ iconv errors by replacing invalid bytes with '?' and continuing conversion.

Tests:

  • Update the truncated UTF-8 conversion test to verify the invalid trailing byte is replaced with '?'.

1. Root cause: In ChangeFileEncodingFormat(), the iconv do-while loop's
   else branch (for non-EILSEQ errors like EINVAL) performed a silent
   break, truncating all remaining content after the error byte
2. Fix: replace the break with the same recovery strategy used by the
   EILSEQ branch — skip the current input byte, append '?' to the output
   buffer, and continue the conversion loop instead of aborting
3. Impact: files containing invalid byte sequences (e.g. kern.log with
   53263 lines showing only 1034) now load completely with '?' replacing
   invalid bytes instead of being silently truncated

fix: 修复编码转换中非EILSEQ的iconv错误导致文件内容静默截断

1. 根因:ChangeFileEncodingFormat()的iconv循环中,else分支(处理EINVAL等
   非EILSEQ错误)直接break,导致错误字节之后的所有内容被静默截断
2. 方案:将break替换为与EILSEQ分支相同的恢复策略——跳过当前输入字节、
   在输出缓冲区追加'?'、继续循环而非中止转换
3. 影响:包含非法字节序列的文件(如kern.log 53263行仅显示1034行)
   现在能完整加载,非法字节以'?'替代而非静默截断

Log: Fixed file content truncation when encountering invalid byte sequences during encoding conversion
Influence:
  - Test opening files with invalid byte sequences to verify complete content display
  - Verify normal encoding files load without regression
  - Test UTF-8 to GB18030 and reverse conversion with mixed valid/invalid bytes
Log: 修复包含非法字节序列的文件在编码转换时内容被静默截断的问题
Influence:
  - 测试打开含非法字节的文件,验证内容完整显示
  - 验证正常编码文件加载无回归
  - 测试UTF-8与GB18030互转场景下混合有效/非法字节的处理
PMS: BUG-384499
@pengfeixx
pengfeixx marked this pull request as draft December 1, 2026 06:09
@sourcery-ai

sourcery-ai Bot commented Dec 1, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Replace the non-EILSEQ error-path break with guarded replacement-character output and input advancement so conversion can continue.

  • src/encodes/detectcode.cpp L999-1018

Tests

Update the truncated UTF-8 regression test to expect the invalid trailing byte to be replaced while preserving the converted prefix.

  • tests/common2/test_detectcode.cpp L879-887

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 6 issues

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

## Individual Comments

### Comment 1
<location path="src/encodes/detectcode.cpp" line_range="999" />
<code_context>
                     } else {
-                        qCWarning(appLog) << "[DetectCode] iconv_open failed for conversion from" << fromCode << "to" << toCode;
-                        break;
+                        qCWarning(appLog) << "[DetectCode] iconv conversion error for" << fromCode << "to" << toCode << "errno:" << errorNum;
+                        if (outbytesleft == 0) {
+                            qCWarning(appLog) << "Output buffer exhausted, breaking conversion";
</code_context>
<issue_to_address>
**Valid text is lost on E2BIG**

When iconv returns E2BIG because the remaining output space cannot fit the next character, the error handler treats E2BIG as malformed input, writes '?', and advances `inbuf` past valid data instead of retrying; callers receive corrupted conversion output as success.

Handle E2BIG by providing more output space and retrying without consuming the unconverted input.

Also at `src/encodes/detectcode.cpp:1009-1017`.
</issue_to_address>

### Comment 2
<location path="src/encodes/detectcode.cpp" line_range="1009" />
<code_context>
+                            break;
+                        }
+                        outbytesleft -= 1;
+                        *outbuf = '?';
+                        outbuf += 1;
+                        qCDebug(appLog) << "Appended replacement char '?' for non-EILSEQ error, remaining outbytesleft:" << outbytesleft;
</code_context>
<issue_to_address>
**Replacement output is malformed**

When a non-EILSEQ error occurs while converting to a multibyte target such as UTF-16 or UTF-32, `ChangeFileEncodingFormat` writes `?` as a single raw byte instead of encoding it in `toCode`, so the result is malformed and callers can save or receive undecodable output.

Encode the replacement character in `toCode` before writing it to the output buffer.
</issue_to_address>

### Comment 3
<location path="src/encodes/detectcode.cpp" line_range="1017-1018" />
<code_context>
+                            inbytesleft = 0;
+                            break;
+                        }
+                        inbuf += 1;
+                        inbytesleft -= 1;
                     }
                 }
</code_context>
<issue_to_address>
**One truncated character becomes several**

When the input ends with a truncated multibyte character, the non-EILSEQ handler advances `inbuf` by one byte and retries, so each remaining byte of the incomplete character produces another `?` and the caller sees multiple replacements.

Treat the incomplete trailing sequence as one invalid character and emit only one replacement for it.
</issue_to_address>

### Comment 4
<location path="src/encodes/detectcode.cpp" line_range="1012-1015" />
<code_context>
+                        *outbuf = '?';
+                        outbuf += 1;
+                        qCDebug(appLog) << "Appended replacement char '?' for non-EILSEQ error, remaining outbytesleft:" << outbytesleft;
+                        if (inbytesleft <= 1) {
+                            inbuf += inbytesleft;
+                            inbytesleft = 0;
+                            break;
+                        }
+                        inbuf += 1;
</code_context>
<issue_to_address>
**Large-file boundary characters are corrupted**

When a file larger than 40 MiB uses a non-UTF-8 encoding and a multibyte character straddles the 1 MiB head boundary, `ChangeFileEncodingFormat` converts the head and remainder independently; it replaces each byte of an incomplete multibyte character at the head’s end, while conversion of the remainder replaces its continuation bytes too, so that character appears as multiple `?` characters.

Preserve incomplete trailing bytes for conversion with the remainder, or use a streaming converter that carries state across the boundary.
</issue_to_address>

### Comment 5
<location path="tests/common2/test_detectcode.cpp" line_range="887" />
<code_context>
+    // Assert: 'a' 已转换,非法尾部字节替换为 '?'
     EXPECT_TRUE(ok);
-    EXPECT_EQ(out, QByteArrayLiteral("a"));
+    EXPECT_EQ(out, QByteArrayLiteral("a?"));
 }

</code_context>
<issue_to_address>
**Regression test bypasses iconv**

When the test suite runs this updated truncated-UTF-8 test, the updated test converts UTF-8 to GB18030, but `ChangeFileEncodingFormat()` routes any conversion involving GB18030 to `convertEncodingTextCodec()` before reaching the changed iconv branch; the test therefore passes without exercising the fix and cannot catch a regression there.

Add a truncated-input test using an encoding pair that reaches the iconv branch and assert the replacement and converted output.
</issue_to_address>

### Comment 6
<location path="tests/common2/test_detectcode.cpp" line_range="882" />
<code_context>
 {
-    // Arrange: E6 EINVAL(不完整多字节序列在末尾)→ 保留已转换前缀
+    // Arrange: E6 EINVAL(不完整多字节序列在末尾)→ 'a' 已转换,尾部 C3 替换为 '?'
     QByteArray in = QByteArrayLiteral("a") + QByteArray::fromHex("C3"), out;
     // Act
     const bool ok = DetectCode::ChangeFileEncodingFormat(in, out, QStringLiteral("UTF-8"), QStringLiteral("GB18030"));
</code_context>
<issue_to_address>
**Continuation is never verified**

When the conversion appends `?` for the incomplete trailing byte but incorrectly stops instead of resuming, the `ChangeEncoding_TruncatedUtf8_ReplacesInvalidByteAndContinues` test puts the invalid `C3` byte at the end of its input (line 882), so an implementation that appends `?` and then incorrectly stops still satisfies the `a?` assertion at line 887; the test does not verify that later content survives.

Add valid bytes after the incomplete sequence and assert that they appear after the replacement in the output.
</issue_to_address>

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

} else {
qCWarning(appLog) << "[DetectCode] iconv_open failed for conversion from" << fromCode << "to" << toCode;
break;
qCWarning(appLog) << "[DetectCode] iconv conversion error for" << fromCode << "to" << toCode << "errno:" << errorNum;

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 · Valid text is lost on E2BIG

When iconv returns E2BIG because the remaining output space cannot fit the next character, the error handler treats E2BIG as malformed input, writes '?', and advances inbuf past valid data instead of retrying; callers receive corrupted conversion output as success.

Handle E2BIG by providing more output space and retrying without consuming the unconverted input.

Also at src/encodes/detectcode.cpp:1009-1017.

Prompt for AI agents
In `src/encodes/detectcode.cpp` at line 999:

**Valid text is lost on E2BIG**

When iconv returns E2BIG because the remaining output space cannot fit the next character, the error handler treats E2BIG as malformed input, writes '?', and advances `inbuf` past valid data instead of retrying; callers receive corrupted conversion output as success.

Handle E2BIG by providing more output space and retrying without consuming the unconverted input.

Also at `src/encodes/detectcode.cpp:1009-1017`.

break;
}
outbytesleft -= 1;
*outbuf = '?';

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 · Replacement output is malformed

When a non-EILSEQ error occurs while converting to a multibyte target such as UTF-16 or UTF-32, ChangeFileEncodingFormat writes ? as a single raw byte instead of encoding it in toCode, so the result is malformed and callers can save or receive undecodable output.

Encode the replacement character in toCode before writing it to the output buffer.

Prompt for AI agents
In `src/encodes/detectcode.cpp` at line 1009:

**Replacement output is malformed**

When a non-EILSEQ error occurs while converting to a multibyte target such as UTF-16 or UTF-32, `ChangeFileEncodingFormat` writes `?` as a single raw byte instead of encoding it in `toCode`, so the result is malformed and callers can save or receive undecodable output.

Encode the replacement character in `toCode` before writing it to the output buffer.

Comment on lines +1017 to +1018
inbuf += 1;
inbytesleft -= 1;

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 · One truncated character becomes several

When the input ends with a truncated multibyte character, the non-EILSEQ handler advances inbuf by one byte and retries, so each remaining byte of the incomplete character produces another ? and the caller sees multiple replacements.

Treat the incomplete trailing sequence as one invalid character and emit only one replacement for it.

Prompt for AI agents
In `src/encodes/detectcode.cpp` at lines 1017-1018:

**One truncated character becomes several**

When the input ends with a truncated multibyte character, the non-EILSEQ handler advances `inbuf` by one byte and retries, so each remaining byte of the incomplete character produces another `?` and the caller sees multiple replacements.

Treat the incomplete trailing sequence as one invalid character and emit only one replacement for it.

Comment on lines +1012 to +1015
if (inbytesleft <= 1) {
inbuf += inbytesleft;
inbytesleft = 0;
break;

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 · Large-file boundary characters are corrupted

When a file larger than 40 MiB uses a non-UTF-8 encoding and a multibyte character straddles the 1 MiB head boundary, ChangeFileEncodingFormat converts the head and remainder independently; it replaces each byte of an incomplete multibyte character at the head’s end, while conversion of the remainder replaces its continuation bytes too, so that character appears as multiple ? characters.

Preserve incomplete trailing bytes for conversion with the remainder, or use a streaming converter that carries state across the boundary.

Prompt for AI agents
In `src/encodes/detectcode.cpp` at lines 1012-1015:

**Large-file boundary characters are corrupted**

When a file larger than 40 MiB uses a non-UTF-8 encoding and a multibyte character straddles the 1 MiB head boundary, `ChangeFileEncodingFormat` converts the head and remainder independently; it replaces each byte of an incomplete multibyte character at the head’s end, while conversion of the remainder replaces its continuation bytes too, so that character appears as multiple `?` characters.

Preserve incomplete trailing bytes for conversion with the remainder, or use a streaming converter that carries state across the boundary.

// Assert: 'a' 已转换,非法尾部字节替换为 '?'
EXPECT_TRUE(ok);
EXPECT_EQ(out, QByteArrayLiteral("a"));
EXPECT_EQ(out, QByteArrayLiteral("a?"));

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 · Regression test bypasses iconv

When the test suite runs this updated truncated-UTF-8 test, the updated test converts UTF-8 to GB18030, but ChangeFileEncodingFormat() routes any conversion involving GB18030 to convertEncodingTextCodec() before reaching the changed iconv branch; the test therefore passes without exercising the fix and cannot catch a regression there.

Add a truncated-input test using an encoding pair that reaches the iconv branch and assert the replacement and converted output.

Prompt for AI agents
In `tests/common2/test_detectcode.cpp` at line 887:

**Regression test bypasses iconv**

When the test suite runs this updated truncated-UTF-8 test, the updated test converts UTF-8 to GB18030, but `ChangeFileEncodingFormat()` routes any conversion involving GB18030 to `convertEncodingTextCodec()` before reaching the changed iconv branch; the test therefore passes without exercising the fix and cannot catch a regression there.

Add a truncated-input test using an encoding pair that reaches the iconv branch and assert the replacement and converted output.

{
// Arrange: E6 EINVAL(不完整多字节序列在末尾)→ 保留已转换前缀
// Arrange: E6 EINVAL(不完整多字节序列在末尾)→ 'a' 已转换,尾部 C3 替换为 '?'
QByteArray in = QByteArrayLiteral("a") + QByteArray::fromHex("C3"), out;

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 · Continuation is never verified

When the conversion appends ? for the incomplete trailing byte but incorrectly stops instead of resuming, the ChangeEncoding_TruncatedUtf8_ReplacesInvalidByteAndContinues test puts the invalid C3 byte at the end of its input (line 882), so an implementation that appends ? and then incorrectly stops still satisfies the a? assertion at line 887; the test does not verify that later content survives.

Add valid bytes after the incomplete sequence and assert that they appear after the replacement in the output.

Prompt for AI agents
In `tests/common2/test_detectcode.cpp` at line 882:

**Continuation is never verified**

When the conversion appends `?` for the incomplete trailing byte but incorrectly stops instead of resuming, the `ChangeEncoding_TruncatedUtf8_ReplacesInvalidByteAndContinues` test puts the invalid `C3` byte at the end of its input (line 882), so an implementation that appends `?` and then incorrectly stops still satisfies the `a?` assertion at line 887; the test does not verify that later content survives.

Add valid bytes after the incomplete sequence and assert that they appear after the replacement in the output.

@pengfeixx
pengfeixx marked this pull request as ready for review December 1, 2026 08:29
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: lzwind, pengfeixx

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

@pengfeixx
pengfeixx merged commit d24ac83 into linuxdeepin:master Dec 1, 2026
19 of 20 checks passed
@pengfeixx
pengfeixx deleted the agent/bugfix/384499 branch December 1, 2026 08:32
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