Skip to content

fix: prevent integer overflow and division by zero in size utils - #262

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:release/1071from
liyigang1:agent/bugfix/383517
Nov 23, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:release/1071from
liyigang1:agent/bugfix/383517

Conversation

@liyigang1

@liyigang1 liyigang1 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Root Cause Analysis

Three integer safety defects exist in basestruct/utils.cpp:

  1. ceilSize() (utils.cpp:541) — CWE-190 + CWE-369: The expression (value + roundingSize - 1LL) / roundingSize * roundingSize overflows when value is near LLONG_MAX, and divides by zero when roundingSize=0.
  2. floorSize() (utils.cpp:536) — CWE-369: value / roundingSize * roundingSize divides by zero when roundingSize=0, causing SIGFPE.
  3. formatSize() (utils.cpp:473) — CWE-190: sectors * sectorSize multiplication overflows for large sector counts, evaluated 5 times in if/else branches.

Both Sector and Byte_Value are typedef long long (64-bit signed). UBSan detected 5 signed integer overflow points; divide-by-zero test exited with SIGFPE (code 136).

Fix Approach

  • floorSize()/ceilSize(): Added roundingSize <= 0 early return (returns value), eliminating CWE-369.
  • ceilSize(): Used __builtin_add_overflow to safely compute value + roundingSize - 1LL, capping to LLONG_MAX on overflow.
  • formatSize(): Used __builtin_mul_overflow to safely compute sectors * sectorSize once, capping to LLONG_MAX on overflow, replacing 5 inline overflow-prone multiplications.

Change Safety Assessment

Code Safety

  • Risk Level: Low
  • Target lines are not products of historical bug fixes; this change does not revert any existing fix.
  • All three functions are internal utility functions; normal-value paths produce identical results.

Business Impact Scope

  • Disk size display: formatSize() formats sector count + sector size to human-readable string. Normal display behavior unchanged.
  • Partition alignment: floorSize()/ceilSize() round partition sizes to alignment boundaries. Normal alignment behavior unchanged.
  • Extreme/zero-value inputs now return safely instead of crashing or producing undefined behavior.

Verification Suggestion

Test disk size display across all unit thresholds (B/KiB/MiB/GiB/TiB) and partition alignment with standard rounding sizes. Verify no crash on extreme values and zero roundingSize.


根因分析

basestruct/utils.cpp 中存在三个整数安全缺陷:

  1. ceilSize() (utils.cpp:541) — CWE-190 + CWE-369:表达式 (value + roundingSize - 1LL) / roundingSize * roundingSize 在 value 接近 LLONG_MAX 时加法溢出,roundingSize=0 时除零。
  2. floorSize() (utils.cpp:536) — CWE-369:value / roundingSize * roundingSize 在 roundingSize=0 时除零,导致 SIGFPE。
  3. formatSize() (utils.cpp:473) — CWE-190:sectors * sectorSize 乘法在大扇区数时溢出,在 if/else 分支中重复求值 5 次。

Sector 和 Byte_Value 均为 typedef long long(64 位有符号)。UBSan 检出 5 处有符号整数溢出;除零测试退出码 136(SIGFPE)。

修复方案

  • floorSize()/ceilSize():添加 roundingSize <= 0 提前返回(返回 value),消除 CWE-369。
  • ceilSize():使用 __builtin_add_overflow 安全计算 value + roundingSize - 1LL,溢出时 cap 到 LLONG_MAX。
  • formatSize():使用 __builtin_mul_overflow 安全计算 sectors * sectorSize,溢出时 cap 到 LLONG_MAX,替换 5 处内联溢出乘法。

改动安全评估

代码安全评估

  • 风险等级: 低风险
  • 目标行非历史修复产物,本次改动不撤销任何已有修复。
  • 三个函数均为内部工具函数,正常值路径结果完全一致。

业务影响范围

  • 磁盘空间显示:formatSize() 将扇区数+扇区大小格式化为可读字符串,正常显示行为不变。
  • 分区大小对齐:floorSize()/ceilSize() 对分区大小取整对齐,正常对齐行为不变。
  • 极值/零值输入从崩溃或未定义行为变为安全返回。

验证建议

测试各单位阈值档位下的磁盘容量显示和标准对齐粒度下的分区取整。验证极值和零值 roundingSize 下不崩溃。

Summary by Sourcery

Harden size formatting and alignment utilities against integer overflow and invalid rounding inputs.

Bug Fixes:

  • Prevent size formatting from overflowing on large sector counts.
  • Handle zero or negative rounding sizes without division-by-zero failures.
  • Prevent ceiling-size calculations from overflowing near the maximum signed integer value.

Enhancements:

  • Reuse safely computed total byte values when selecting human-readable size units.

1. Root cause: ceilSize() and formatSize() performed unchecked
   arithmetic on 64-bit signed integers, causing CWE-190 overflow;
   floorSize() and ceilSize() divided by roundingSize without a
   zero-guard, causing CWE-369 division by zero (SIGFPE)
2. Fix: add roundingSize <= 0 early return in floorSize()/ceilSize();
   use __builtin_add_overflow in ceilSize() and __builtin_mul_overflow
   in formatSize() to detect overflow, capping to LLONG_MAX on overflow
3. Impact: normal-value paths unchanged; extreme/zero-value inputs now
   return safely instead of crashing or producing undefined behavior

Influence:
1. Test disk size display with normal values across all unit thresholds
2. Test partition alignment with standard rounding sizes (e.g. 4096)
3. Verify no crash on extreme values (near LLONG_MAX) and zero roundingSize

fix: 修复尺寸工具函数中的整数溢出与除零问题

1. 根因:ceilSize() 和 formatSize() 对 64 位有符号整数执行未检查的
   算术运算,导致 CWE-190 溢出;floorSize() 和 ceilSize() 未对
   roundingSize 做零值守卫即执行除法,导致 CWE-369 除零(SIGFPE)
2. 方案:在 floorSize()/ceilSize() 中添加 roundingSize <= 0 提前返回;
   ceilSize() 使用 __builtin_add_overflow、formatSize() 使用
   __builtin_mul_overflow 检测溢出,溢出时 cap 到 LLONG_MAX
3. 影响:正常值路径行为不变;极值/零值输入从崩溃或未定义行为
   变为安全返回

Influence:
1. 测试各单位阈值档位下的正常磁盘容量显示
2. 测试标准对齐粒度(如 4096)下的分区大小取整
3. 验证极值(接近 LLONG_MAX)和零值 roundingSize 下不崩溃

PMS: BUG-383517
@liyigang1
liyigang1 marked this pull request as draft November 19, 2026 13:27
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Review the overflow-safe byte calculation in formatSize() together with the LLONG_MAX definition it uses, ensuring the saturated total selects the correct display unit.

  • basestruct/utils.cpp L21, L477-490

Review the zero-or-negative rounding guards and overflow-safe numerator calculation in floorSize() and ceilSize(), including the behavior when the result saturates.

  • basestruct/utils.cpp L543-544, L550-556

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="basestruct/utils.cpp" line_range="556" />
<code_context>
+    if (__builtin_add_overflow(value, roundingSize - 1LL, &numerator)) {
+        numerator = LLONG_MAX;
+    }
+    return numerator / roundingSize * roundingSize;
 }

</code_context>
<issue_to_address>
**Trailing bytes remain unerased**

When the numerator addition overflows and `roundingSize` does not divide `LLONG_MAX`, `ceilSize` substitutes `LLONG_MAX` for the overflowing numerator, then division and multiplication round it down to a multiple below the requested value. When `PartedCore::eraseFilesystemSignatures()` uses that result to calculate the end of a write range, trailing bytes are not erased.

Detect an unrepresentable rounded-up size and report failure instead of returning a smaller multiple.
</issue_to_address>

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

Comment thread basestruct/utils.cpp
if (__builtin_add_overflow(value, roundingSize - 1LL, &numerator)) {
numerator = LLONG_MAX;
}
return numerator / roundingSize * roundingSize;

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 · Trailing bytes remain unerased

When the numerator addition overflows and roundingSize does not divide LLONG_MAX, ceilSize substitutes LLONG_MAX for the overflowing numerator, then division and multiplication round it down to a multiple below the requested value. When PartedCore::eraseFilesystemSignatures() uses that result to calculate the end of a write range, trailing bytes are not erased.

Detect an unrepresentable rounded-up size and report failure instead of returning a smaller multiple.

Prompt for AI agents
In `basestruct/utils.cpp` at line 556:

**Trailing bytes remain unerased**

When the numerator addition overflows and `roundingSize` does not divide `LLONG_MAX`, `ceilSize` substitutes `LLONG_MAX` for the overflowing numerator, then division and multiplication round it down to a multiple below the requested value. When `PartedCore::eraseFilesystemSignatures()` uses that result to calculate the end of a write range, trailing bytes are not erased.

Detect an unrepresentable rounded-up size and report failure instead of returning a smaller multiple.

@liyigang1
liyigang1 marked this pull request as ready for review November 23, 2026 05:35
@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 23, 2026

Copy link
Copy Markdown
Contributor

This pr force merged! (status: unstable)

@deepin-bot
deepin-bot Bot merged commit ac95791 into linuxdeepin:release/1071 Nov 23, 2026
19 of 20 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