修复:解决严格别名(Strict Aliasing)违规问题,提升 -O2 优化下的稳定性 #131
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
修复:解决严格别名(Strict Aliasing)违规问题,提升 -O2 优化下的稳定性
关联 Issue: NJU-ProjectN/ics-pa#35
概述
本次 Pull Request 系统性地解决了 NEMU 代码库中存在的严格别名(Strict Aliasing)违规问题。主要目标是增强代码在高级别编译器优化(如
-O2)下的稳定性和行为可预测性。主要修复内容
修正
new_space函数签名new_space函数的返回值从uint8_t*修正为更通用的void*。这使其与标准内存分配函数(如malloc)的行为保持一致,解决了最明显的类型安全隐患,允许调用者在不违反别名规则的情况下安全地进行类型转换。使用
memcpy替代不安全的指针类型转换\([\w\s]+\s*\*+\s*\))和人工代码审查,定位并重构了多处违反严格别名规则的指针类型强转(Type Punning)代码。char*与uint8_t*之外,所有直接的内存重解释操作(如*(uint32_t*)addr)均被替换为memcpy,以确保安全地以不同类型访问内存区域。重要说明
本次提交中对
tools/kvm-diff/src/kvm.c文件的修改,主要是为了遵循严格别名规则以消除潜在风险。由于缺乏相应的 KVM 测试环境,这些变更尚未经过实际运行测试,其功能正确性有待进一步验证。关于
-Wstrict-aliasing编译警告的说明在修复过程中,曾尝试添加
-fstrict-aliasing -Wstrict-aliasing=3编译选项以辅助定位问题。g++) 代码中能够有效工作并报告部分违规。gcc) 代码中,无论设置何种优化等级,此警告均未能按预期触发。鉴于该警告在 C 语言环境中并不可靠,本次 PR 并未将相关编译选项添加到构建系统中。
补充说明
此外, abstract-machine 的代码库中也存在大量严格别名违规。由于本人目前对该am代码的理解尚不深入,暂时不参与修复。