Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 17 Mar 2023 10:23:57 +0000
From:      bugzilla-noreply@freebsd.org
To:        bugs@FreeBSD.org
Subject:   [Bug 270283] would like an even safer LIST_FOREACH_SAFE()
Message-ID:  <bug-270283-227@https.bugs.freebsd.org/bugzilla/>

next in thread | raw e-mail | index | archive | help
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=3D270283

            Bug ID: 270283
           Summary: would like an even safer LIST_FOREACH_SAFE()
           Product: Base System
           Version: CURRENT
          Hardware: Any
                OS: Any
            Status: New
          Severity: Affects Only Me
          Priority: ---
         Component: kern
          Assignee: bugs@FreeBSD.org
          Reporter: levon@movementarian.org

We hit the following situation:

 - we have a component with a list of callbacks.
 - those callbacks are themselves allowed to call back in and remove entries
from the list
 - LIST_FOREACH_SAFE() is used to safely protect against removal of the cur=
rent
item
 - however, a callback is also legitimately allowed to remove any other ite=
m on
the list

This falls down when a callback removes the *next* item on the list - the m=
acro
has already saved this in "tvar", so it will then try to use freed memory on
the next iteration.

We have fixed this with LIST_FOREACH_SAFER() / LIST_REMOVE_SAFER() variants:

#define LIST_FOREACH_SAFER(var, head, field, tvarp)     \=20=20=20=20=20=20=
=20
        for ((var) =3D LIST_FIRST((head));=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20
\
            (var) && ((*tvarp) =3D LIST_NEXT((var), field), 1);           \
            (var) =3D (*tvarp))

#define LIST_REMOVE_SAFER(elm, field, elmp) do {                \
        if (elmp =3D=3D elm) {=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20=20=20=20=20=20
        \
                elmp =3D LIST_NEXT(elm, field);                           \
        };=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20
                \
        LIST_REMOVE(elm, field);=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=20=
=20=20=20=20=20=20=20=20
\
} while (0)


Would like thoughts on whether this would be something more widely useful
before I prepare a PR and so on, thanks.

--=20
You are receiving this mail because:
You are the assignee for the bug.=



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?bug-270283-227>