Repository navigation
Description
New high-level explanation of this issue, also covering #85873
Fuse<T> and Zip<T, U> have optimizations relying on specialization if their type parameters implement a trait (FusedIterator or TrustedRandomAccess, respectively).
These optimizations fundamentally change the way the iterator operates.
All type arguments are covariant. Coercing e.g. Fuse<T> to Fuse<U> if U is a subtype of T can “switch between” these fundamentally different ways of operation if T: !FusedIterator and U: FusedIterator which can bring the iterator into an invalid state that can cause UB; the same kind of problem exists for Zip.
For Zip, this problem can be avoided if TrustedRandomAccess never differs between types and subtypes. Copy-dependent impls for e.g. vec::IntoIter have to be removed (PR #85874).
Regarding Fuse: FusedIterator is a safe public trait, this is problematic. Some possible fixes: Either change Fuse to not get into a UB-causing invalid state by such a coercion (which kills some (or perhaps most) of the optimization offered by Fuse), or make Fuse invariant (but that’s a breaking change!). Here’s another possible approach, but this one requires new language features and could be done in the future if an immediate fix that just makes Fuse less performant is taken now.
Specialization not differentiating between e.g. Foo<'a> and Foo<'b> made this issue harder to spot.
But fn(&()) (that is, for<'a> fn(&'a ())) is a supertype [edited:] subtype of fn(&'static ()) and those are entirely different types.
Previous start of issue description
use std::{
iter::{Fuse, FusedIterator},
marker::PhantomData,
};
struct MyEmptyIterator<T>(PhantomData<T>, &'static str);
impl<T> Iterator for MyEmptyIterator<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
println!("called next, {}", self.1);
None
}
}
impl FusedIterator for MyEmptyIterator<fn(&'static ())> {}
fn main() {
let mut f = MyEmptyIterator::<fn(&())>(PhantomData, "Hello, World").fuse();
f.next();
let mut f = f as Fuse<MyEmptyIterator<fn(&'static ())>>;
f.next();
} Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.74s
Running `target/debug/playground`
timeout: the monitored command dumped core
/playground/tools/entrypoint.sh: line 11: 8 Segmentation fault timeout --signal=KILL ${timeout} "$@"
Standard Output
called next, Hello, World
@rustbot label T-libs, T-libs-impl, T-compiler, A-specialization, A-iterators, A-typesystem, A-lifetimes, A-traits, C-bug
someone please add the unsound label thanks
Explanation
The types for<'a> fn(&'a ()) (i.e. fn(&())) and fn(&'static ()) do seem to be distinguished by rust’s specialization. (I.e. the difference between the two types is not erased before the trait impl for specializing on FusedIterator is chosen.) But it’s also possible to convert Fuse<MyEmptyIterator<fn(&i32)>> into Fuse<MyEmptyIterator<fn(&'static i32)>>. This way, the first call to .next() will use unspecialized code and write a None value into the field of Fuse, whereas the second call will use the specialized version that uses intrinsics::unreachable() to unwrap the contained Option.
I haven’t tested it, but I’d guess that the same thing might be possible using HRTB trait objects instead of function pointers. (See comment below.)
Possible fixes
This soundness issue would probably go away if, somehow, specialization would also consider types such as fn(&()) and fn(&'static ()) to be “the same type”. Edit2: I don’t think that this approach is reasonable, and it’s probably even impossible.
The easiest / fastest fix for now would probably be to remove all the intrinsics::unreachable() assertions in the implementation of Fuse and replace them either with panics (which results in unexpected panicking but at least no unsoundness), or replace them with code that “properly” handles the None case as the iterator being empty. In either case, performance benefits from FusedIterator implementations could probably somewhat be retained by somehow marking the Some case as the hot path and the None case as a cold path. (In the approach with the None case panicking, this would probably be automatically considered the cold path due to the panic.)
Edit: Yet another alternative fix is to make Fuse<T> invariant over T.
Activity
the8472 commentedon May 31, 2021
I think this is a known hole see #68970 on rustc_unsafe_specialization_marker.
Copyis similar in that regard.steffahn commentedon May 31, 2021
@the8472 That section also says
This issue is a way to “cause use after frees with purely safe code” (not 100% a “use after free” with the current example code, but it can certainly be turned into “use-after-free” UB, too). So it is not a known hole AFAICT. I mean, sure, the fact that
FusedIteratoris a bit questionable in general and that implementing it for something likeMyIterator<'static>will have the same fact as implementing it for allMyIterator<'a>is weird/questionable/perhaps-technically-UB. This issue is about the fact that the way that specialization handles HRTB-fn-pointers combined with the covariance ofiter::Fusemakes for some practical unsoundness.On a similar note, there are no other open
I-unsound 💥+A-specializationissues that aren’trequires-nightly, further demonstrating the relevance of this issue.steffahn commentedon Jun 1, 2021
@the8472
Funny that you mentioned
Copy, now I’ve also found an issue involving specialization onCopy: #85873Maybe your remark even helped me a little bit in finding it. (I’m always unable to accurately recall afterwards how exactly I found such a soundness issue, so I’m not sure.)
cuviper commentedon Jun 1, 2021
Wouldn't that be a breaking API change?
20 remaining items
workingjubilee commentedon Jun 30, 2021
I am having trouble following this conversation, so I won't claim to have a deep opinion, but since there is a lot of confusion about which way the variance goes &etc., more cleanly expressing the subtype/supertype relationships seems desirable if we're going to expand the syntax for universal quantification. This is largely aside from the point, though.
cuviper commentedon Jun 30, 2021
I opened #86765 and #86766 with reduced and eliminated specialization, so we can compare performance.
I also considered just changing those
intrinsics::unreachable()tounreachable!()panics, but I think that's a bad move. It would avoid the unsound case, but it still implies that the user did something wrong, which isn't really true.danielhenrymantilla commentedon Jul 1, 2021
A diagram with some subtyping relationships
To recap, here is a hopefully illustrative diagram summarizing the basic subtyping relationships:
source
Playground
I have greyed out the types there that are necessarily / known to be
'static.My personal view of the situation
I believe the "surprising thing" here is that some of us may have intuitively thought (I personally did!) that subtyping necessarily involved variance, and thus, involved there being different lifetimes. Or, in other words, some of us may have intuitively thought that a
: 'staticbound disabled strict subtyping (by strict I mean there beingT : UwithT ≠ U). That is, that there would not be distinct and yet greyed out nodes in that graph that happened to be connected by an arrow.But there are: it turns out that a higher order
fnpointer –which is currently distinct, type-level-wise, from any non-higher order fn pointer (this may change, IIRC, so thatimpl<A> … for fn(A)would coverfn(&()), for instance)– does feature a subtyping relationship with any "concrete / fixed choice of its higher-order lifetime parameter(s)", so thatfn(&()) : fn(&'static ())holds, and both of these types are: 'static.Thus, not specializing over lifetimes does not prevent specializing over {sub,super}types.
This, however, in and of itself, is not a problem (≠ specializing over lifetimes, which is definitely a problem even without
unsafecode).Indeed, specialization itself is not to blame, here. There could have been two non-generic impls, one for
Fuse<…fn(&())>, and one forFuse<…fn(&'static ())>, and the problem would have still been there. Specialization has just made leading to this situation easier.The problem stems from
unsafecode inside one of these two impls (it happens to be the specialized one), which relied on a very specific state machine to uphold the invariants: it assumed full control of the "entrypoint" to this state machine. But it turns out subtyping makes it possible to start transitioning within the state machine for thefn(&())impl, and then suddenly hop onto the middle of the state machine for thefn(&'static ())impl, with the expected invariants thus not upheld. Hence the issue.This is no different to some oversight regarding some
.into()or.to_owned()conversion allowing something along the same lines (in that regard, coercions, a very close friend to subtyping, are also something to be mindful of: depending on the internals ofFuse, we could imagine it allowing an unsize coercion, and we'd have the same issue).In practice
The short answer is to say that that impl for
Fuse<impl FusedIterator>is unsound, because of this conversion. A middle ground could be to replace theunreachable_uncheckedwith anunreachable!(), and this would make a lot of sense if somebody had had to call.clone()/.into()in some weird fashion just to trigger that code path.But the issue here is that the type conversion is very sneaky, since it's a subtyping conversion, which can happen at any point under our feet. So I agree with @cuviper that
panic!-king may not be ideal.For the case of
Fusespecifically:since we can't specialize over lifetimes,
since unsized coercions are not possible either (I think? Somebody double check this)
this only leaves the
fn(…)-shenanigans to perform this subtyping issue.Thus, rather than a whole
for<U : T>quantification (which seems like a big deal to implement; but I'm not against it either), there is a way to weasel out of this issue, to keep the optimized impl and avoid the soundness issue, at the cost of a tiny bit of lang magic: to have some unsafe auto trait which is unimplemented for all function pointer types (that's the only thing that requires lang magic). Let's call this auto traitBikeshedContainsNoFnPointersThen, if we have
T : BikeshedContainsNoFnPointers, and thanks to there not being specialization over lifetimes,Fuse<impl FusedIterator + BikeshedContainsNoFnPointers>could still feature the optimized impl.Fusespecialized impls, to feature two distinct and yet convertible types (other form of subtypes? unsized coercion? some other way to construct aFusemid-way?).steffahn commentedon Jul 1, 2021
@danielhenrymantilla I believe that writing “outlives” as “⊇” also has potential for confusion. It might be useful if you’re thinking of lifetimes as a set of lines/places in your source code, but I wouldn’t necessarily want to introduce it as actual notation, because a correspondence between supersets (“⊇”) and subtypes – both using
:and both being strongly related due to reference types – seems suboptimal. You’re writing “subtypes” explicitly in your diagram, so writing “outlives” explicitly, too, seems like the best option to me.cuviper commentedon Jul 1, 2021
That diagram would be a great addition to the reference!
https://doc.rust-lang.org/reference/subtyping.html
the8472 commentedon Jul 1, 2021
steffahn commentedon Jul 1, 2021
@the8472 The original example works just as well with a generic
instead of just
The former kind of
implis not prohibited even for “#[rustc_specialization_trait]”. This means: even though “#[rustc_specialization_trait]” has more restriction, does in fact still fully supportthe8472 commentedon Jul 1, 2021
Objection retracted.
steffahn commentedon Jul 2, 2021
A day later, I still think that moving back to a
done-flag design is the best way of fixing this issue. Especially, if it really doesn't come with any significant performance impact.cuviper commentedon Jul 2, 2021
The other downside of the
doneflag is that it addsalign_of::<I>()bytes, whereasOption<I>may use a niche.The performance of #86765 looks stable enough that this would be my preference, although it does lose in-place iteration.
Auto merge of rust-lang#86765 - cuviper:fuse-less-specialized, r=josh…
QuineDot commentedon Aug 11, 2021
The current direction is for them to remain distinct types. See
I'm not sure within
Fusespecifically, butdyn for<'a> Trait<'a>anddyn Trait<'bound>exhibit the same behavior.