Skip to content

chore: Update compiler flags for security enhancements#447

Merged
deepin-bot[bot] merged 1 commit intolinuxdeepin:masterfrom
wangrong1069:pr0130
Jan 31, 2026
Merged

chore: Update compiler flags for security enhancements#447
deepin-bot[bot] merged 1 commit intolinuxdeepin:masterfrom
wangrong1069:pr0130

Conversation

@wangrong1069
Copy link
Contributor

@wangrong1069 wangrong1069 commented Jan 30, 2026

As title

Log: Update compiler flags for security enhancements
Bug: https://pms.uniontech.com/bug-view-342665.html

Summary by Sourcery

Strengthen compiler and linker configuration for more secure and consistent release builds.

Build:

  • Enable additional hardening compiler and linker flags for Release builds at the top-level CMake configuration.
  • Adjust per-architecture C and C++ flag settings in src CMakeLists to append to existing flags instead of overwriting them.

As title

Log: Update compiler flags for security enhancements
Bug: https://pms.uniontech.com/bug-view-342665.html
@sourcery-ai
Copy link

sourcery-ai bot commented Jan 30, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Configures additional compiler and linker hardening flags for release builds and adjusts existing C/C++ flag settings to append to, rather than overwrite, previously defined flags, with special handling for mips64 vs other architectures.

Flow diagram for CMake release build hardening flags configuration

flowchart TD
    A[Configure_project] --> B{CMAKE_BUILD_TYPE STREQUAL Release}
    B -- Yes --> C[Print Enable build hardening]
    C --> D[Enable CMAKE_VERBOSE_MAKEFILE]
    D --> E[Define HARDENING_FLAGS
-Wdate-time
-D_FORTIFY_SOURCE=2
-g
-O2
-ffile-prefix-map
-fstack-protector-strong
-fstack-clash-protection
-Wformat
-Werror=format-security]
    E --> F[Append HARDENING_FLAGS to CMAKE_CXX_FLAGS]
    F --> G[Append HARDENING_FLAGS to CMAKE_C_FLAGS]
    G --> H[Append -Wl,-z,relro -Wl,-z,now to CMAKE_EXE_LINKER_FLAGS]
    B -- No --> I[Use existing compiler and linker flags]
    H --> J[Invoke add_subdirectory src]
    I --> J
Loading

File-Level Changes

Change Details Files
Enable security hardening flags for Release builds at the top-level CMake configuration.
  • Gate new hardening configuration behind a check for CMAKE_BUILD_TYPE equal to Release.
  • Enable verbose makefile output for Release builds to make flags visible during compilation.
  • Define a HARDENING_FLAGS variable that includes fortify, stack protection, stack clash protection, format string warnings-as-errors, and related GCC security options.
  • Append HARDENING_FLAGS to both CMAKE_CXX_FLAGS and CMAKE_C_FLAGS instead of replacing existing contents.
  • Augment executable linker flags with RELRO and immediate binding (-z relro -z now) for hardened binaries.
CMakeLists.txt
Change per-architecture C/C++ flag configuration to append to existing flags instead of overwriting them.
  • For mips64 builds, prepend existing CMAKE_CXX_FLAGS/CMAKE_C_FLAGS before environment-provided flags and optimization/tuning options, ensuring prior flags (including hardening) are preserved.
  • For non-mips64 builds, similarly append to existing CMAKE_CXX_FLAGS/CMAKE_C_FLAGS instead of setting them solely from environment variables and basic flags.
  • Keep PIE and linker flags configuration unchanged while ensuring they combine with top-level flags.
src/CMakeLists.txt

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

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • Relying on if(CMAKE_BUILD_TYPE STREQUAL "Release") means these hardening flags won't be applied for multi-config generators (e.g. Ninja Multi-Config, Visual Studio); consider using configuration-specific compile/link options instead of checking CMAKE_BUILD_TYPE directly.
  • Enabling CMAKE_VERBOSE_MAKEFILE ON unconditionally for Release builds can make normal build logs very noisy; it might be better to leave this under a developer toggle or only enable it for debugging specific issues.
  • Appending hardening options by modifying CMAKE_C_FLAGS/CMAKE_CXX_FLAGS directly (including -g -O2) can override or conflict with user/toolchain-provided flags; using add_compile_options()/add_link_options() scoped to targets or configurations would be more robust and composable.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Relying on `if(CMAKE_BUILD_TYPE STREQUAL "Release")` means these hardening flags won't be applied for multi-config generators (e.g. Ninja Multi-Config, Visual Studio); consider using configuration-specific compile/link options instead of checking `CMAKE_BUILD_TYPE` directly.
- Enabling `CMAKE_VERBOSE_MAKEFILE ON` unconditionally for Release builds can make normal build logs very noisy; it might be better to leave this under a developer toggle or only enable it for debugging specific issues.
- Appending hardening options by modifying `CMAKE_C_FLAGS`/`CMAKE_CXX_FLAGS` directly (including `-g -O2`) can override or conflict with user/toolchain-provided flags; using `add_compile_options()`/`add_link_options()` scoped to targets or configurations would be more robust and composable.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@deepin-ci-robot
Copy link

deepin pr auto review

这份 CMakeLists.txt 的修改主要目的是引入编译器加固选项和修正标志变量的追加方式。以下是对语法逻辑、代码质量、代码性能和代码安全方面的详细审查与改进建议:

1. 语法逻辑审查

  • 变量追加方式修正 (src/CMakeLists.txt):
    • 现状: 修改前使用 SET(CMAKE_CXX_FLAGS "$ENV{CXXFLAGS} ..."),这会覆盖掉之前设置的 CMAKE_CXX_FLAGS(例如根目录 CMakeLists.txt 中设置的 HARDENING_FLAGS)。
    • 改进: 修改后使用 SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} $ENV{CXXFLAGS} ..."),正确地将新标志追加到已有变量之后。这是非常关键的逻辑修复,确保了根目录的安全标志不会被后续的特定架构优化标志清除。

2. 代码质量审查

  • CMAKE_VERBOSE_MAKEFILE (根 CMakeLists.txt):
    • 现状: 在 Release 模式下设置了 set(CMAKE_VERBOSE_MAKEFILE ON)
    • 意见: 通常 VERBOSE_MAKEFILE 用于调试构建过程,会在编译时打印大量详细信息。在 Release 模式下开启它可能会让构建日志变得冗长且难以阅读。
    • 建议: 除非是为了在 CI/CD 流水线中排查编译问题,否则建议移除此行,或者通过命令行参数 cmake --verbose ... 按需开启。
  • 大小写一致性:
    • 现状: 根目录使用小写 setsrc 目录使用大写 SET
    • 建议: CMake 对命令大小写不敏感,但为了代码风格统一,建议全项目统一使用小写(现代 CMake 风格)或大写。推荐使用小写。

3. 代码性能审查

  • MIPS64 架构优化 (src/CMakeLists.txt):
    • 现状: 针对龙芯架构添加了 -O3 -ftree-vectorize -march=loongson3a 等激进的优化参数。
    • 意见: -O3 会增加代码体积并可能导致未定义行为的概率增加(尽管在成熟硬件上较少见)。针对特定 CPU 架构(如 loongson3a)的优化是合理的,能显著提升性能。
    • 注意: 确保目标运行环境确实匹配 loongson3a,否则二进制文件可能无法在其他 MIPS64 机器上运行。

4. 代码安全审查

  • 加固选项 (根 CMakeLists.txt):
    • 现状: 引入了 -D_FORTIFY_SOURCE=2, -fstack-protector-strong, -fstack-clash-protection, -Wformat -Werror=format-security, -Wl,-z,relro -Wl,-z,now
    • 评价: 这些是非常标准且有效的安全加固选项,能够有效防御缓冲区溢出、栈破坏、格式化字符串漏洞以及攻击 GOT/PLT 表。这部分修改质量很高。
  • 非 MIPS 架构的 Release 模式冲突 (src/CMakeLists.txt):
    • 问题: 在 src/CMakeLists.txtelse() 分支(即非 MIPS64 架构)中,CMAKE_C_FLAGS 被设置为包含 -O3,而根目录 HARDENING_FLAGS 中包含 -O2
    • 冲突: 由于采用了追加模式,最终编译命令可能会同时出现 -O2-O3。虽然 GCC 通常会取最后一个出现的优化级别(即 -O3),但这依赖于编译器行为,且 -O2 的存在是多余的。
    • 建议: 根目录的 HARDENING_FLAGS 中包含了 -O2,而子目录针对非 MIPS 架构又追加了 -O3。建议统一管理优化级别。
      • 方案 A: 在根目录定义 OPTIMIZATION_LEVEL 变量(如 -O2-O3),子目录引用该变量而不是硬编码。
      • 方案 B: 如果非 MIPS 架构必须使用 -O3,则应在子目录显式移除之前的 -O2(较难操作),或者接受这种覆盖行为。
  • 环境变量的使用:
    • 现状: 引用了 $ENV{CXXFLAGS}$ENV{CFLAGS}
    • 风险: 如果环境变量中包含了与 HARDENING_FLAGS 冲突的参数(例如 -fno-stack-protector),可能会导致安全加固失效。
    • 建议: 信任构建环境是标准做法,但在高安全要求的场景下,需确保构建环境变量的清洁。

总结与改进建议代码

以下是综合上述建议的优化版本:

根目录 CMakeLists.txt:

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    message(STATUS "Enable build hardening.")
    # 移除 CMAKE_VERBOSE_MAKEFILE ON,保持构建日志简洁,如需调试可在外部开启

    # 定义基础优化级别,子目录可覆盖或追加
    set(OPTIMIZATION_FLAGS "-O2")
    
    set(HARDENING_FLAGS "-Wdate-time -D_FORTIFY_SOURCE=2 -g ${OPTIMIZATION_FLAGS} -ffile-prefix-map=${CMAKE_SOURCE_DIR}=. -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${HARDENING_FLAGS}")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${HARDENING_FLAGS}")
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,relro -Wl,-z,now")
endif()

src/CMakeLists.txt:

# 加速编译优化参数
if (CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "mips64")
    # 针对龙芯架构使用更激进的优化,覆盖之前的 -O2
    # 注意:这里直接追加 -O3,由于命令行顺序,GCC通常会使用最后一个 -O 选项
    set(ARCH_FLAGS "-O3 -ftree-vectorize -march=loongson3a -mhard-float -mno-micromips -mno-mips16 -flax-vector-conversions -mloongson-ext2 -mloongson-mmi")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} $ENV{CXXFLAGS} ${ARCH_FLAGS} -Wl,--as-needed -fPIE")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} $ENV{CFLAGS} ${ARCH_FLAGS} -Wl,--as-needed -fPIE")
    set(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} -pie")
else()
    # 通用架构:保留根目录的 -O2,或者如果需要更高性能可改为 -O3
    # 这里为了示例,我们显式使用 -O2,避免根目录 -O2 和这里可能的 -O3 混用
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} $ENV{CXXFLAGS} -Wl,--as-needed -fPIE")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} $ENV{CFLAGS} -Wl,--as-needed -fPIE")
    set(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} -pie")
endif()

主要变更点说明:

  1. 移除 VERBOSE_MAKEFILE: 减少不必要的输出。
  2. 提取 ARCH_FLAGS: 提高可读性,方便管理特定架构的编译参数。
  3. 统一命令大小写: 使用 setif 等小写命令。
  4. 优化级别管理: 明确区分了龙芯架构(-O3)和其他架构(默认 -O2)的优化策略,避免混淆。

@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: lzwind, wangrong1069

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

@wangrong1069
Copy link
Contributor Author

/forcemerge

@deepin-bot
Copy link
Contributor

deepin-bot bot commented Jan 31, 2026

This pr force merged! (status: unstable)

@deepin-bot deepin-bot bot merged commit eb083fd into linuxdeepin:master Jan 31, 2026
16 of 18 checks passed
@wangrong1069 wangrong1069 deleted the pr0130 branch January 31, 2026 05:10
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