Is life-before-main / `#[ctor]` safe?

未关闭
#598 36 条评论 3 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
25/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
冷清
技术栈
rust

调研方向

Start by reading the examples and safety assumptions in this issue, then compare the behavior of the ctor and inventory crates with Rust's configure_builtins.rs. Review the linked rust-ctor issue and unsafe-code-guidelines issue 397 for existing discussion. Done means reaching a documented consensus on whether pre-main constructors require unsafe and what safety requirements apply.

由索引模型根据 Issue 内容生成。

描述

Rust does not provide facilities for doing work before fn main(), but we can achieve it anyhow on a lot of platforms using linker tricks and global constructors, as done in ctor, inventory and the standard library itself.

Is this safe to do, or should it require unsafe? If so, what are the safety requirements that one needs to uphold inside a global constructor?


In isolation, this feature seems to be safe (?), but one reason to define it as unsafe could be to allow libraries to rely on never being used in a constructor themselves? Consider the following library:

static mut FOO: i32 = 0;

/// Do some "heavy" work to initialize `FOO`.
#[ctor]
fn setup_foo() {
    // SAFETY: `get_foo` is not running at the same time as this constructor, so an unsynchronized write is fine.
    unsafe { FOO = 42 };
}

/// Get the value from `FOO`.
pub fn get_foo() -> NonZero<i32> {
    // SAFETY: The constructor has run before `get_foo`
    let foo = unsafe { FOO };

    // SAFETY: The variable was initialized to a non-zero value.
    unsafe { NonZero::new_unchecked(foo) }
}

The safety comments here rely on:

  1. The constructor not executing concurrently with anything else.
  2. The constructor executing before get_foo.

But those assumptions are actually false, since the user may write:

#[ctor]
fn user_constructor() {
    std::thread::spawn(|| {
        get_foo();
    });
}

And, depending on linker ordering, user_constructor may be run first (unless we can somehow guarantee that setup_foo runs before user_constructor?), in which case the unsynchronized read+write is not actually okay, and the variable may not actually be initialized to a non-zero value.

The correct way to write it then would be:

static FOO: AtomicI32 = AtomicI32::new(0);

#[ctor]
fn setup_foo() {
    // Must use atomics.
    FOO.store(42, Ordering::Relaxed);
}

pub fn get_foo() -> NonZero<i32> {
    let foo = FOO.load(Ordering::Relaxed);

    // Must check that the variable is actually initialized.
    NonZero::new(foo).unwrap()
}

Though this does decrease the utility of #[ctor] by a fair margin as the performance improvements of using a global constructor decreases, and you'd probably just want to use OnceLock now instead.

One noteworthy tidbit is that when using dynamic libraries (e.g. linking libc or libX11), this is a non-issue, as constructors are executed in libraries first, so any global constructors that a dynamic library has are guaranteed to be executed before any code that depends on that dynamic library.


For context, I'm opening this because the ctor crate has made the #[ctor] attribute require unsafe, see https://github.com/mmastrac/rust-ctor/issues/159, but deciding "running code before main is unsafe for xyz reason" is a decision that affects more than just ctor (e.g. it affects inventory as well), so I thought it might be something that t-opsem / the UCG has opinions on?

See also https://github.com/rust-lang/unsafe-code-guidelines/issues/397.

主要语言
没有语言数据
星标
760
派生
68
PR 合并指标
30 天内没有已合并 PR

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

rust-lang/unsafe-code-guidelines 的其他 Issue

查看 rust-lang/unsafe-code-guidelines 的全部 Issue

相似的 Issue

更多 Compilers Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。