Re: [TECH TOPIC] Rust for Linux

Wedson Almeida Filho
2021-07-08T13:54:43Z

On Thu, Jul 08, 2021 at 03:43:28PM +0200, Geert Uytterhoeven wrote:
> Hi Wedson,

Hey Geert,

> On Thu, Jul 8, 2021 at 3:42 PM Wedson Almeida Filho <wedsonaf@google.com> wrote:
> > On Thu, Jul 08, 2021 at 09:20:25AM +0200, Geert Uytterhoeven wrote:
> > > > Weak references need to upgraded to strong references before the underlying
> > > > objects can be accessed; upgrading may fail if the strong count has gone to
> > > > zero. It is, naturally, implemented as an increment that avoids going from 0 to
> > > > 1. It is safe to try to do it because the memory is kept alive while there are
> > > > weak references.
> > >
> > > What does "may fail" imply?
> >
> > Upgrading is essentially calling `refcount_inc_not_zero` on the strong count.
> > It succeeds when the count is already non-zero, it fails when the count is zero.
> >
> > So "may fail" here means "your attempt to upgrade came too late, the object is
> > gone". (The memory is still around so that attempts to upgrade don't cause UAF,
> > but the object is gone.)
>
> So what happens if this fails?

You move on the next element in your data structure. This one doesn't really
exist anymore; once you release it lock, the cleanup code will likely come and
remove it.

This is a common pattern, see for example (or search for uses of
`refcount_inc_not_zero` and `kref_get_unless_zero`):
https://elixir.bootlin.com/linux/latest/source/net/core/skbuff.c#L4738

The difference between the above and Rust is that in C, one can mistakenly use
the "object" even if the refcount is zero. Rust would prohibit it.

Cheers,
-Wedson