-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
std::ptr::copy() can read from uninitialized statics (unsound) #142532
Copy link
Copy link
Closed
Labels
A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)Area: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.Category: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-highHigh priorityHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language teamRelevant to the language team
Metadata
Metadata
Assignees
Labels
A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)Area: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.Category: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-highHigh priorityHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language teamRelevant to the language team
Type
Fields
Give feedbackNo fields configured for issues without a type.
It is possible to create references to statics while you're still initializing it. Normally, attempting to read from such a reference will cause a compile-time error, with the message "encountered static that tried to initialize itself with itself". However, reading from such a reference with
std::ptr::copy()(and alsostd::ptr::copy_nonoverlapping()andstd::ptr::read_unaligned(), but notstd::ptr::read()) does not cause this error. For example:This code compiles fine, and leaves
X.1as an uninitialized value.This can cause supposedly-sound API using unsafe code to become unsound. For example:
Example unsoundness
In this code, the
YesInittype exposes an API that I think should be sound. However, the weirdness withstd::ptr::copymeans that this API can be used to cause undefined behavior. Running this code with Miri reports: "error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory" inside theto_inner()call, which happens at run time, not compile time.See also #142404 for shenanigans with uninitialized statics.
Meta
Reproducible on the playground with
1.89.0-nightly (2025-06-11 e703dff8fe220b78195c)@rustbot labels +I-unsound +A-const-eval