Skip to content

Conversation

@illustriousness
Copy link
Contributor

拉取/合并请求描述:(PR description)

[
在使用RT_ALIGN时发现一个意外的现象
例如 RT_ALIGN( 17, 10 )=18

于是问了一下deepseek
#define RT_ALIGN(size, align) (((size) + (align) - 1) & ~((align) - 1))
为什么这个宏在非2字节对齐时存在风险

下面是deepseek的回答
该宏在非2的幂对齐时存在风险的核心原因在于二进制掩码生成逻辑,通过以下代码示例说明:

// 测试案例1:对齐值8(2^3)
RT_ALIGN(13, 8) => (13+7) & ~7 => 20 & 0xFFFFFFF8 = 16 ✔️

// 测试案例2:对齐值10(非2^n)
RT_ALIGN(13, 10) => (13+9) & ~9 => 22 & 0xFFFFFFF6 = 20 ✔️

// 测试案例3:危险案例
RT_ALIGN(15, 10) => (15+9) & ~9 => 24 & 0xFFFFFFF6 = 20 ❌
// 实际正确结果应为20(虽然结果正确,但掩码生成存在问题)

// 测试案例4:完全错误案例
RT_ALIGN(9, 6) => (9+5) & ~5 => 14 & 0xFFFFFFFA = 10 ❌
// 正确结果应为12(6的倍数)
DiffCopyInsert
风险本质分析:

掩码生成缺陷
当align=10(二进制1010)时:
align-1 = 9 (二进制 1001)
~(align-1) = 0xFFFF...F6 (二进制 ...11110110)
DiffCopyInsert
该掩码会将数值对齐到最近的8字节边界(8是小于10的最大2^n值),而非预期的10字节边界

位运算约束
按位与操作要求对齐值必须是2的幂,因为:
2^n的二进制特征:只有一个1(如8=1000)
2^n-1的二进制特征:全1(如7=0111)
DiffCopyInsert
数学矛盾
对于任意非2^n的align值:
~(align-1)≠ align的整数倍边界
DiffCopyInsert
这将导致计算结果无法保证是align的整数倍

修正建议方案:

// 安全的向上对齐实现(支持任意对齐值)
#define RT_ALIGN_SAFE(size, align)
((align) ? (((size) + (align) - 1) / (align)) * (align) : (size))

// 验证测试
RT_ALIGN_SAFE(15, 10) => ((15+9)/10)*10 = (24/10)10=210=20 ✔️
RT_ALIGN_SAFE(9, 6) => ((9+5)/6)*6 = (14/6)6=26=12 ✔️

建议在需要兼容非2^n对齐的场景中,采用除法优化的安全实现方案。

当前拉取/合并请求的状态 Intent for your PR

必须选择一项 Choose one (Mandatory):

  • 本拉取/合并请求是一个草稿版本 This PR is for a code-review and is intended to get feedback
  • 本拉取/合并请求是一个成熟版本 This PR is mature, and ready to be integrated into the repo

代码质量 Code Quality:

我在这个拉取/合并请求中已经考虑了 As part of this pull request, I've considered the following:

  • 已经仔细查看过代码改动的对比 Already check the difference between PR and old code
  • 代码风格正确,包括缩进空格,命名及其他风格 Style guide is adhered to, including spacing, naming and other styles
  • 没有垃圾代码,代码尽量精简,不包含#if 0代码,不包含已经被注释了的代码 All redundant code is removed and cleaned up
  • 所有变更均有原因及合理的,并且不会影响到其他软件组件代码或BSP All modifications are justified and not affect other components or BSP
  • 对难懂代码均提供对应的注释 I've commented appropriately where code is tricky
  • 代码是高质量的 Code in this PR is of high quality
  • 已经使用formatting 等源码格式化工具确保格式符合RT-Thread代码规范 This PR complies with RT-Thread code specification
  • 如果是新增bsp, 已经添加ci检查到.github/workflows/bsp_buildings.yml 详细请参考链接BSP自查

@Rbb666 Rbb666 requested a review from unicornx April 17, 2025 04:14
Copy link
Contributor

@unicornx unicornx left a comment

Choose a reason for hiding this comment

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

修改没有问题。

问题是这个 pr 的 commit 只需要一个。请使用 git rebase 命令 squash 后重新提交。

另外 commit 描述最好用 english,并加上签名。具体参考 https://github.com/plctlab/plct-rt-thread/blob/notes/0.notes/20241212-github-tips.md#2-how-to-write-git-commit-message

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.

2 participants