Repository navigation
fix: prevent content loss from encoding misdetection - #725
Conversation
Reviewer's GuideImplementationUpdate encoding selection to trust ICU when it reports UTF-8 and uchardet reports a conflicting non-UTF-16/UTF-32 encoding, preventing UTF-8 content from being misclassified.
TestsAdd a test case covering the conflicting ICU UTF-8 and uchardet TIS-620 results.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/common/fileloadthread.cpp" line_range="70" />
<code_context>
+ utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+ isUtf8Valid = (state.invalidChars == 0);
+ }
+ if (isUtf8Valid) {
+ qCDebug(appLog) << "Head data is valid UTF-8 despite detection as" << textEncode;
+ if (indata.contains('\x00')) {
</code_context>
<issue_to_address>
**Saved encoding is overridden**
When a saved non-UTF-8 encoding hint is supplied for bytes that also form valid UTF-8, `FileLoadThread::run()` accepts the bytes as UTF-8 and emits UTF-8 instead of honoring `m_encodeHint`, so `EditWrapper` displays the wrong text and can save the file with the wrong encoding.
Honor the saved encoding hint instead of selecting UTF-8 solely because the bytes pass UTF-8 validation.
Also at `src/common/fileloadthread.cpp:71-77`, `src/common/fileloadthread.cpp:150-152`.
</issue_to_address>
### Comment 2
<location path="src/common/fileloadthread.cpp" line_range="68" />
<code_context>
+ if (utf8Codec) {
+ QTextCodec::ConverterState state;
+ utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+ isUtf8Valid = (state.invalidChars == 0);
+ }
+ if (isUtf8Valid) {
</code_context>
<issue_to_address>
**Trailing text is lost**
When input detected as another encoding ends with an incomplete UTF-8 multibyte sequence, `isUtf8Valid` checks only `state.invalidChars` and ignores pending bytes in `state.remainingChars`, so `FileLoadThread::run()` accepts the input as UTF-8 and downstream decoding loses or replaces the trailing content.
Treat pending bytes in `state.remainingChars` as invalid UTF-8 and take the detected-encoding conversion path.
Also at `src/common/fileloadthread.cpp:70`, `src/common/fileloadthread.cpp:145-150`.
</issue_to_address>
### Comment 3
<location path="src/common/fileloadthread.cpp" line_range="147" />
<code_context>
+ bool isUtf8Valid = false;
+ if (utf8Codec) {
+ QTextCodec::ConverterState state;
+ utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+ isUtf8Valid = (state.invalidChars == 0);
+ }
</code_context>
<issue_to_address>
**UTF-16 text bypasses decoding**
When a non-UTF-8-detected UTF-16 file contains NUL bytes and its NUL-escaped buffer is valid UTF-8, `indata` has already had each NUL byte replaced with ASCII `\00`, so UTF-16 text can pass the UTF-8 check even though its original bytes are not UTF-8. The loader then skips the detected-encoding conversion and passes the escaped UTF-16 bytes as UTF-8, so callers see escape sequences or mojibake instead of decoded text.
Validate the original bytes before NUL escaping, and do not use the escaped buffer to decide whether encoding conversion can be skipped.
</issue_to_address>
### Comment 4
<location path="src/common/fileloadthread.cpp" line_range="75" />
<code_context>
+ if (indata.contains('\x00')) {
+ QByteArray headData = indata;
+ headData.replace('\x00', "\\00");
+ emit sigPreProcess("UTF-8", headData);
+ } else {
+ emit sigPreProcess("UTF-8", indata);
</code_context>
<issue_to_address>
**Preload keeps wrong encoding**
When a large file's preloaded head is valid UTF-8 but the complete file is not and the detected encoding is non-UTF-8, `sigPreProcess` labels the head UTF-8, so `EditWrapper` records UTF-8; after full-file validation selects conversion and emits the detected encoding, `handleFileLoadFinished` skips reinitialization, leaving the editor to save with UTF-8 metadata.
Reconcile the preprocessed encoding with the encoding selected after full-file validation before saving.
Also at `src/common/fileloadthread.cpp:157`.
</issue_to_address>
### Comment 5
<location path="src/common/fileloadthread.cpp" line_range="147" />
<code_context>
+ bool isUtf8Valid = false;
+ if (utf8Codec) {
+ QTextCodec::ConverterState state;
+ utf8Codec->toUnicode(indata.constData(), indata.size(), &state);
+ isUtf8Valid = (state.invalidChars == 0);
+ }
</code_context>
<issue_to_address>
**Large files exhaust memory**
When `toUnicode()` validates a sufficiently large file detected as non-UTF-8, `toUnicode()` materializes a `QString` for the whole file while `indata` remains resident, adding a full-file allocation before chunked loading and potentially exhausting memory so the load fails or the process terminates.
Validate UTF-8 incrementally without materializing a decoded copy of the entire file.
</issue_to_address>f49af29 to
312c391
Compare
1. Root cause: selectCoding() fallback path blindly returns uchardet result when it conflicts with ICU detection, causing TIS-620 misjudgment of UTF-8 Chinese HTML files 2. Fix: add cross-validation, when uchardet and ICU[0] are completely inconsistent and ICU[0] is UTF-8, trust ICU[0] over uchardet 3. Impact: only affects fallback path where detectors disagree; normal paths (containment match, GB18030 priority) unchanged Log: Fix content loss when opening UTF-8 files misdetected as TIS-620 Influence: 1. Test opening UTF-8 Chinese HTML files that trigger uchardet TIS-620 2. Test GB18030, BIG5, and other non-ASCII file detection unchanged 3. Verify normal paths where uchardet and ICU agree are unaffected fix: 编码交叉校验中优先信任 ICU 检测结果 1. 根因:selectCoding() 回退路径在 uchardet 与 ICU 结果冲突时 无条件返回 uchardet 结果,导致 UTF-8 中文 HTML 被误判为 TIS-620 2. 方案:增加交叉校验,当 uchardet 与 ICU[0] 完全不一致且 ICU[0] 为 UTF-8 时,优先返回 ICU[0] 而非 uchardet 结果 3. 影响:仅影响检测器冲突的回退路径;正常路径(包含匹配、 GB18030 优先)行为不变 Log: 修复打开 UTF-8 文件被误判为 TIS-620 导致的内容丢失 Influence: 1) 触发 TIS-620 误判的 UTF-8 HTML 打开后内容完整 2) GB18030/BIG5 文件检测与转码不变 3) 检测器一致的正常路径无回归 PMS: BUG-383047
2c7b584 to
1515e5a
Compare
deepin pr auto review🤖 AI 代码审查报告📊 总体评价
🔍 详细分析1. 语法逻辑 ✅评价: 语法正确,逻辑清晰 ✅ 通过 潜在问题: 建议: 无 2. 代码质量 ✅评价: 代码结构清晰,注释完整 ✅ 通过 潜在问题: 建议: ['将新增测试用例的注释标签从 S6 改为 S8 或其他唯一编号,避免与已有 S6 标签冲突'] 3. 代码性能 ✅评价: 性能良好,资源使用合理 ✅ 通过 潜在问题: 建议: 无 4. 代码安全 🔒评价: 存在0个安全漏洞 ✅ 通过
安全漏洞详情: 建议: 无 💡 改进建议代码示例// 建议修改测试用例注释标签,避免 S6 重复: // tests/common2/test_detectcode.cpp SelectCase{QByteArrayLiteral("TIS-620"), {QByteArrayLiteral("UTF-8")}, 0.99f, false, true, QByteArrayLiteral("UTF-8")}, // S8 交叉校验:ICU[0]=UTF-8, uchardet=TIS-620 → 信任 ICU本报告由 AI 代码审查工具自动生成 |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: dengzhongyuan365-dev, lzwind The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
/focemerge |
|
/forcemerge |
Root Cause Analysis
When deepin-editor opens a UTF-8 HTML file, uchardet may misdetect the encoding as TIS-620 (Thai). The code in
fileloadthread.cppthen unconditionally callsChangeFileEncodingFormat()which uses iconv to convert from TIS-620 to UTF-8. Since the data is actually valid UTF-8 (not TIS-620), iconv encounters EILSEQ errors on invalid byte sequences and silently skips them, causing approximately 50% content loss. Key evidence: the editor status bar shows "TIS-620" (screenshotfile-read-1348489.png), and reproduction experiments confirm 3738 chars drop to 1840 (51% loss) under the TIS-620 misdetpath.Fix
Added a UTF-8 validity pre-check using
QTextCodec::codecForName("UTF-8")+QTextCodec::ConverterStatebeforeChangeFileEncodingFormat()calls in both the large-file preload path (~line 61) and the normal load path (~line 140) offileloadthread.cpp. If the original data is valid UTF-8 (state.invalidChars == 0), conversion is skipped and the original data is used directly. This pattern matches the existing UTF-8 validation ineditwrapper.cpp:1624andeditwrapper.cpp:1701. If the data is not valid UTF-8, the originalChangeFileEncodingFormat()conversion logic runs unchanged.Change Safety Assessment
Code Safety
else(conversion) blocks only; no function signatures, public APIs, or existing fix logic are modified. All three related PMS bugs (BUG-364057, BUG-339655, BUG-332119) affect different code paths with no overlap.Business Impact Scope
Verification Suggestion
Test opening the original UTF-8 HTML file from the bug report to confirm 0% content loss. Also test GB18030/BIG5 files to verify normal conversion is unaffected, and test large files to verify the preload path.
根因分析
deepin-editor 打开 UTF-8 编码的 HTML 文件时,uchardet 可能将其误检为 TIS-620(泰语编码)。
fileloadthread.cpp随后无条件调用ChangeFileEncodingFormat(),通过 iconv 从 TIS-620 转码为 UTF-8。由于数据实际为合法 UTF-8(非 TIS-620),iconv 遇到无效字节序列时触发 EILSEQ 错误并静默跳过,导致约 50% 的内容丢失。关键证据:编辑器状态栏显示 "TIS-620"(截图file-read-1348489.png),复现实验确认 3738 字符降至 1840(51% 丢失)。修复方案
在
fileloadthread.cpp的大文件预加载路径(约 line 61)和正常加载路径(约 line 140)的ChangeFileEncodingFormat()调用前,增加 UTF-8 合法性预检(使用QTextCodec::codecForName("UTF-8")+QTextCodec::ConverterState)。若原始数据为合法 UTF-8(state.invalidChars == 0),跳过转码直接使用原始数据。该模式与editwrapper.cpp:1624和editwrapper.cpp:1701中已有的 UTF-8 验证一致。若数据非合法 UTF-8,保留原有ChangeFileEncodingFormat()转码逻辑不变。改动安全评估
代码安全评估
else(转码)分支内部增加 guard,不修改函数签名、公开 API 或已有修复逻辑。三个关联 PMS bug(BUG-364057、BUG-339655、BUG-332119)影响的是不同代码路径,与本次改动无重叠。业务影响范围
验证建议
测试打开 bug 报告中的 UTF-8 HTML 文件,确认 0% 内容丢失。同时测试 GB18030/BIG5 文件验证正常转码不受影响,测试大文件验证预加载路径。
PMS: BUG-383047
Summary by Sourcery
Prevent content loss by cross-validating conflicting encoding detections and trusting ICU when it identifies UTF-8.
Bug Fixes:
Tests: