Re: [PATCH 1/2] rust: sync: refactor static_lock_class!() macro
From: Boqun Feng
Date: Wed Jul 23 2025 - 16:58:49 EST
On Wed, Jul 23, 2025 at 10:41:18PM +0200, Benno Lossin wrote:
[...]
> >> >> > is in a static segment it uses different behavior?
> >> >> >
> >> >> > Because from the safety requirements on this function, I could just do
> >> >> > this:
> >> >> >
> >> >> > // SAFETY: we leak the box below, so the destructor never runs.
> >> >> > let class = KBox::new(unsafe { LockClassKey::new_static() });
> >> >> > let class = Pin::static_ref(KBox::leak(class));
> >> >> > let lock = SpinLock::new(42, c_str!("test"), class);
> >> >
> >> > This will trigger a runtime error because `class` is not static, but
> >> > technically, it won't trigger UB, at least lockdep should be able to
> >> > handle this case.
> >>
> >> Could you go into more details? What is the "technically it won't
> >> trigger UB" part about?
> >>
> >
> > If a dynamic key is not registered, lockdep will simply just skip the
> > initialization of locks, report an error and disable itself entirely. So
> > it won't cause UB.
>
> So the code above would trigger lockdep to disable itself?
>
Yes.
> And how does it detect that the class isn't registered? By checking for
> the address in the hash list?
Right, in is_dynamice_key(), the hash list is scanned to see the key has
been registered.
> Otherwise it would be UB, right? Could there be a hash collision that
> induces UB?
>
I don't think a hash collision will cause an UB, because the checking
only uses the address of the key, so even the key is uninitialized, it's
fine.
Regards,
Boqun
> ---
> Cheers,
> Benno