From 9226190d73a2fe1d47ca0c1d71ceb5039d116be4 Mon Sep 17 00:00:00 2001 From: liyigang Date: Mon, 23 Nov 2026 15:09:17 +0800 Subject: [PATCH] fix: prevent integer overflow and division by zero in size utils MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Additionally, when Utils::ceilSize()'s numerator addition overflows and roundingSize does not divide LLONG_MAX, the saturated value would round down to a multiple below the requested size. PartedCore:: eraseFilesystemSignatures() used that truncated value to compute the end of an erase range, leaving trailing bytes unerased. ceilSize() now reports the overflow through a bool *overflow output parameter and eraseFilesystemSignatures() aborts with failure instead of writing a truncated range. Add unit tests in test/ut_diskoperation/ut_utils.cpp covering formatSize() unit boundaries and overflow saturation, floorSize()/ ceilSize() normal values, zero/negative rounding guards, and the unrepresentable ceiling size failure path. 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 4. Test partition formatting and signature erase on normal disks 5. Verify erase reports failure rather than truncating when the ceiling size is unrepresentable (near LLONG_MAX) 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. 影响:正常值路径行为不变;极值/零值输入从崩溃或未定义行为 变为安全返回 另外,当 Utils::ceilSize() 的分子加法溢出且 roundingSize 不能整除 LLONG_MAX 时,饱和值会被向下取整到小于请求大小的倍数。 PartedCore::eraseFilesystemSignatures() 用该截断值计算擦除范围的 末尾,会遗漏尾随字节。ceilSize() 现在通过 bool *overflow 出参报告 溢出,eraseFilesystemSignatures() 检测到后中止并返回失败,不再写入 截断范围。 在 test/ut_diskoperation/ut_utils.cpp 中新增单元测试,覆盖 formatSize() 各单位边界与溢出饱和、floorSize()/ceilSize() 正常取值、零值/负值 舍入保护,以及不可表示的向上取整失败路径。 Influence: 1. 测试各单位阈值档位下的正常磁盘容量显示 2. 测试标准对齐粒度(如 4096)下的分区大小取整 3. 验证极值(接近 LLONG_MAX)和零值 roundingSize 下不崩溃 4. 测试正常磁盘的分区格式化与签名擦除 5. 验证擦除范围无法表示时返回失败而非截断写入 PMS: BUG-383517 --- basestruct/utils.cpp | 32 ++++- basestruct/utils.h | 5 +- service/diskoperation/partedcore.cpp | 14 +- test/CMakeLists.txt | 3 + test/ut_diskoperation/ut_partedcore_erase.cpp | 75 ++++++++++ test/ut_diskoperation/ut_utils.cpp | 136 ++++++++++++++++++ 6 files changed, 254 insertions(+), 11 deletions(-) create mode 100644 test/ut_diskoperation/ut_partedcore_erase.cpp create mode 100644 test/ut_diskoperation/ut_utils.cpp diff --git a/basestruct/utils.cpp b/basestruct/utils.cpp index fa637c0a..3dc0c5e7 100644 --- a/basestruct/utils.cpp +++ b/basestruct/utils.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -579,16 +580,20 @@ QString Utils::formatSize(Sector sectors, Byte_Value sectorSize) { qCDebug(baseLog) << "Utils::formatSize - Formatting size for sectors:" << sectors << "sectorSize:" << sectorSize; QString res; - if ((sectors * sectorSize) < KIBIBYTE) { + Byte_Value totalBytes; + if (__builtin_mul_overflow(sectors, sectorSize, &totalBytes)) { + totalBytes = LLONG_MAX; + } + if (totalBytes < KIBIBYTE) { res = res.setNum(sectorToUnit(sectors, sectorSize, UNIT_BYTE), 'f', 2); res.append(" B"); - } else if ((sectors * sectorSize) < MEBIBYTE) { + } else if (totalBytes < MEBIBYTE) { res = res.setNum(sectorToUnit(sectors, sectorSize, UNIT_KIB), 'f', 2); res.append(" KiB"); - } else if ((sectors * sectorSize) < GIBIBYTE) { + } else if (totalBytes < GIBIBYTE) { res = res.setNum(sectorToUnit(sectors, sectorSize, UNIT_MIB), 'f', 2); res.append(" MiB"); - } else if ((sectors * sectorSize) < TEBIBYTE) { + } else if (totalBytes < TEBIBYTE) { res = res.setNum(sectorToUnit(sectors, sectorSize, UNIT_GIB), 'f', 2); res.append(" GiB"); } else { @@ -647,13 +652,28 @@ int Utils::getMaxPartitionNameLength(QString &tableType) Byte_Value Utils::floorSize(Byte_Value value, Byte_Value roundingSize) { // qCInfo(baseLog) << "Utils::floorSize - value:" << value << "roundingSize:" << roundingSize; + if (roundingSize <= 0) + return value; return value / roundingSize * roundingSize; } -Byte_Value Utils::ceilSize(Byte_Value value, Byte_Value roundingSize) +Byte_Value Utils::ceilSize(Byte_Value value, Byte_Value roundingSize, bool *overflow) { // qCInfo(baseLog) << "Utils::ceilSize - value:" << value << "roundingSize:" << roundingSize; - return (value + roundingSize - 1LL) / roundingSize * roundingSize; + if (overflow) + *overflow = false; + if (roundingSize <= 0) + return value; + Byte_Value numerator; + if (__builtin_add_overflow(value, roundingSize - 1LL, &numerator)) { + // 加法溢出说明向上取整结果无法用 Byte_Value 表示,不能 + // 静默回退到一个更小的倍数(会让擦除范围末尾遗漏尾随字节)。 + // 置位 overflow 并返回饱和值,由调用方报告失败。 + if (overflow) + *overflow = true; + return LLONG_MAX; + } + return numerator / roundingSize * roundingSize; } QString Utils::createUuid() diff --git a/basestruct/utils.h b/basestruct/utils.h index 3fba7a71..19e6f8d1 100644 --- a/basestruct/utils.h +++ b/basestruct/utils.h @@ -167,9 +167,10 @@ class Utils * @brief 计算上偏移量 * @param value:大小 * @param roundingSize:舍入值 - * @return 上偏移量 + * @param overflow:输出参数,加法溢出(结果无法用 Byte_Value 表示)时置 true + * @return 上偏移量;溢出时返回 LLONG_MAX,调用方应通过 overflow 判定失败 */ - static Byte_Value ceilSize(Byte_Value value, Byte_Value roundingSize); + static Byte_Value ceilSize(Byte_Value value, Byte_Value roundingSize, bool *overflow = nullptr); /** * @brief 创建UUID diff --git a/service/diskoperation/partedcore.cpp b/service/diskoperation/partedcore.cpp index 517ddfd7..54f9677a 100644 --- a/service/diskoperation/partedcore.cpp +++ b/service/diskoperation/partedcore.cpp @@ -3288,16 +3288,24 @@ bool PartedCore::eraseFilesystemSignatures(const Partition &partition) for (unsigned int i = 0; overallSuccess && i < sizeof(ranges) / sizeof(ranges[0]); i++) { //Rounding is performed in multiples of the sector size because writes are in whole sectors. - Byte_Value roundingSize = Utils::ceilSize(ranges[i].rounding, lpDevice->sector_size); + bool roundingOverflow = false; + Byte_Value roundingSize = Utils::ceilSize(ranges[i].rounding, lpDevice->sector_size, &roundingOverflow); Byte_Value byteOffset; Byte_Value byteLen; if (ranges[i].offset >= 0LL) { byteOffset = Utils::floorSize(ranges[i].offset, roundingSize); - byteLen = Utils::ceilSize(ranges[i].offset + ranges[i].length, lpDevice->sector_size) - byteOffset; + byteLen = Utils::ceilSize(ranges[i].offset + ranges[i].length, lpDevice->sector_size, &roundingOverflow) - byteOffset; } else { //Negative offsets Byte_Value notionalOffset = Utils::floorSize(partition.getByteLength() + ranges[i].offset, ranges[i].rounding); byteOffset = Utils::floorSize(notionalOffset, roundingSize); - byteLen = Utils::ceilSize(notionalOffset + ranges[i].length, lpDevice->sector_size) - byteOffset; + byteLen = Utils::ceilSize(notionalOffset + ranges[i].length, lpDevice->sector_size, &roundingOverflow) - byteOffset; + } + if (roundingOverflow) { + // 向上取整结果无法用 Byte_Value 表示,不能使用截断后的 + // 范围继续擦除,否则会遗漏尾随字节。报告失败。 + qCWarning(serviceLog) << __FUNCTION__ << "ceiling overflow computing erase range" << i << "for" << partition.getPath(); + overallSuccess = false; + break; } //Limit range to partition size. if (byteOffset + byteLen <= 0LL) { diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index e4a9d55e..a361a1a1 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -8,6 +8,9 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) +# 可访问 private 成员(与 tests/CMakeLists.txt 保持一致,用于测试内部工具函数) +ADD_COMPILE_OPTIONS(-fno-access-control) + #include(../cmake/googletest.cmake) #fetch_googletest( diff --git a/test/ut_diskoperation/ut_partedcore_erase.cpp b/test/ut_diskoperation/ut_partedcore_erase.cpp new file mode 100644 index 00000000..8dac8250 --- /dev/null +++ b/test/ut_diskoperation/ut_partedcore_erase.cpp @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-only + +#include "gtest/gtest.h" + +#include "../../service/diskoperation/partedcore.h" +#include "../../service/diskoperation/partition.h" +#include "../../basestruct/commondef.h" + +using namespace DiskManager; + +/** + * @brief PartedCore::eraseFilesystemSignatures() 单元测试 + * + * 该函数在 PMS BUG-383517 修复中新增了 ceilSize() 溢出检测: + * 当擦除范围的上取整结果无法用 Byte_Value 表示时,必须中止并报告失败, + * 而不是用截断后的范围继续擦除(否则会遗漏尾随字节)。 + * + * 说明:函数内部 ranges 为局部常量、且依赖真实块设备才能走到写入 + * 循环,溢出分支在正常输入下不可达。这里覆盖无需真实设备的确定性分支: + * - 打开中的 LUKS 加密分区应直接失败早退; + * - 设备不存在/无法打开时应安全返回失败而不崩溃。 + */ +class ut_partedcore_erase : public ::testing::Test +{ +protected: + void SetUp() override {} + void TearDown() override {} +}; + +TEST_F(ut_partedcore_erase, luks_busy_partition_returns_false) +{ + // 打开中的 LUKS 加密分区不允许在仅擦除签名的步骤中处理, + // 应直接返回 false 早退(不访问任何设备)。 + PartedCore core; + Partition partition; + partition.m_fstype = FS_LUKS; + partition.m_busy = true; + + EXPECT_FALSE(core.eraseFilesystemSignatures(partition)); +} + +TEST_F(ut_partedcore_erase, nonexistent_device_returns_false_without_crash) +{ + // 设备路径不存在时 getDevice() 失败,overallSuccess 保持 false, + // 函数应安全返回 false,既不崩溃也不写入任何数据。 + PartedCore core; + Partition partition; + partition.m_fstype = FS_EXT4; + partition.m_busy = false; + partition.m_devicePath = "/dev/__ut_nonexistent_device_383517__"; + partition.m_type = TYPE_PRIMARY; + partition.m_sectorStart = 2048; + partition.m_sectorEnd = 4096; + partition.m_sectorSize = 512; + + EXPECT_FALSE(core.eraseFilesystemSignatures(partition)); +} + +TEST_F(ut_partedcore_erase, unpartitioned_nonexistent_device_returns_false) +{ + // 未分区(虚拟整盘)类型 + 不存在设备:overallSuccess 曾先被置 true, + // 但 deviceIsOpen 为 false 后仍应整体返回 false。 + PartedCore core; + Partition partition; + partition.m_fstype = FS_UNALLOCATED; + partition.m_busy = false; + partition.m_devicePath = "/dev/__ut_nonexistent_device_383517__"; + partition.m_type = TYPE_UNPARTITIONED; + partition.m_sectorSize = 512; + partition.m_sectorStart = 0; + + EXPECT_FALSE(core.eraseFilesystemSignatures(partition)); +} diff --git a/test/ut_diskoperation/ut_utils.cpp b/test/ut_diskoperation/ut_utils.cpp new file mode 100644 index 00000000..ec2a86e6 --- /dev/null +++ b/test/ut_diskoperation/ut_utils.cpp @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: 2022 - 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-only + +#include "gtest/gtest.h" + +#include + +#include "../../basestruct/utils.h" +#include "../../basestruct/commondef.h" + +/** + * @brief 尺寸工具函数(formatSize / floorSize / ceilSize)单元测试 + * + * 覆盖 PMS BUG-383517 修复的场景: + * - formatSize() 的 sectors * sectorSize 乘法溢出 + * - floorSize()/ceilSize() 的 roundingSize 零值/负值除零 + * - ceilSize() 分子加法溢出及「向上取整结果不可表示」的失败上报 + */ +class ut_utils : public ::testing::Test +{ +protected: + void SetUp() override {} + void TearDown() override {} +}; + +/* -------------------- formatSize 正常单位换算 -------------------- */ + +TEST_F(ut_utils, formatSize_byte_unit) +{ + // 小于 1 KiB 的走 B 分支 + EXPECT_EQ(Utils::formatSize(0, 512), QString("0.00 B")); + EXPECT_EQ(Utils::formatSize(1, 512), QString("512.00 B")); +} + +TEST_F(ut_utils, formatSize_kib_unit) +{ + // 512 字节扇区,2 扇区 = 1024 字节 = 1 KiB + EXPECT_EQ(Utils::formatSize(2, 512), QString("1.00 KiB")); +} + +TEST_F(ut_utils, formatSize_mib_unit) +{ + // 2048 扇区 * 512 = 1 MiB + EXPECT_EQ(Utils::formatSize(2048, 512), QString("1.00 MiB")); +} + +TEST_F(ut_utils, formatSize_gib_unit) +{ + // 2097152 扇区 * 512 = 1 GiB + EXPECT_EQ(Utils::formatSize(2097152, 512), QString("1.00 GiB")); +} + +TEST_F(ut_utils, formatSize_tib_unit) +{ + // 2147483648 扇区 * 512 = 1 TiB + EXPECT_EQ(Utils::formatSize(2147483648LL, 512), QString("1.00 TiB")); +} + +TEST_F(ut_utils, formatSize_overflow_no_crash) +{ + // sectors * sectorSize 溢出时不能崩溃/未定义行为; + // 结果饱和到 LLONG_MAX 后落入 TiB 分支 + QString res = Utils::formatSize(LLONG_MAX, 512); + EXPECT_FALSE(res.isEmpty()); + EXPECT_TRUE(res.endsWith("TiB")); +} + +/* -------------------- floorSize -------------------- */ + +TEST_F(ut_utils, floorSize_normal) +{ + EXPECT_EQ(Utils::floorSize(13, 4), 12); // 向下取整到 4 的倍数 + EXPECT_EQ(Utils::floorSize(16, 4), 16); // 已是倍数保持不变 + EXPECT_EQ(Utils::floorSize(4099, 4096), 4096); + EXPECT_EQ(Utils::floorSize(0, 4096), 0); +} + +TEST_F(ut_utils, floorSize_zero_rounding) +{ + // roundingSize 为 0 时不应 SIGFPE,直接返回原值 + EXPECT_EQ(Utils::floorSize(12345, 0), 12345); + // 负值同样安全返回 + EXPECT_EQ(Utils::floorSize(12345, -4), 12345); +} + +/* -------------------- ceilSize -------------------- */ + +TEST_F(ut_utils, ceilSize_normal) +{ + bool overflow = true; + EXPECT_EQ(Utils::ceilSize(13, 4, &overflow), 16); // 向上取整到 4 的倍数 + EXPECT_FALSE(overflow); + EXPECT_EQ(Utils::ceilSize(16, 4, &overflow), 16); // 已是倍数保持不变 + EXPECT_FALSE(overflow); + EXPECT_EQ(Utils::ceilSize(4097, 4096, &overflow), 8192); + EXPECT_FALSE(overflow); + EXPECT_EQ(Utils::ceilSize(0, 4096, &overflow), 0); + EXPECT_FALSE(overflow); +} + +TEST_F(ut_utils, ceilSize_zero_rounding) +{ + // roundingSize 为 0 时不应 SIGFPE,直接返回原值 + bool overflow = true; + EXPECT_EQ(Utils::ceilSize(12345, 0, &overflow), 12345); + EXPECT_FALSE(overflow); + // 负值同样安全返回 + EXPECT_EQ(Utils::ceilSize(12345, -4, &overflow), 12345); + EXPECT_FALSE(overflow); +} + +TEST_F(ut_utils, ceilSize_no_overflow_default_param) +{ + // 不传 overflow 出参时仍可正常使用(默认参数) + EXPECT_EQ(Utils::ceilSize(13, 4), 16); +} + +TEST_F(ut_utils, ceilSize_overflow_reports_failure) +{ + // 分子加法溢出:value 接近 LLONG_MAX 且 roundingSize 不整除 LLONG_MAX。 + // 应报告 overflow=true 并返回饱和值 LLONG_MAX,而不是向下取整到更小倍数。 + bool overflow = false; + Byte_Value res = Utils::ceilSize(LLONG_MAX, 4, &overflow); + EXPECT_TRUE(overflow); + EXPECT_EQ(res, LLONG_MAX); +} + +TEST_F(ut_utils, ceilSize_boundary_no_overflow) +{ + // LLONG_MAX-1 加 1 恰好等于 LLONG_MAX,不构成溢出 + bool overflow = true; + Byte_Value res = Utils::ceilSize(LLONG_MAX - 1, 2, &overflow); + EXPECT_FALSE(overflow); + EXPECT_EQ(res, LLONG_MAX - 1); // (LLONG_MAX-1) 是 2 的倍数 +}