Skip to content

Commit

Permalink
Type-checking container_of macro
Browse files Browse the repository at this point in the history
It is an error to invoke the container_of() macro with a
`ptr` parameter that is not of type pointer-to-`member`.
But the macro hides that error by ignoring the 'ptr' type.

Make the macro safer by requiring `ptr` to have the
correct type.

Also, rename it to er_container_of(), to avoid potential
name collisions with other container_of() macros.
  • Loading branch information
aiw-panasonic committed Feb 23, 2024
1 parent dbad9f5 commit 77e273e
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
12 changes: 8 additions & 4 deletions eventrouter/internal/defs.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
#define ER_UNUSED(statement) (void)(statement);

/// Returns the address of the structure containing the member.
#ifndef container_of
#define container_of(ptr, type, member) \

/// The "?:" conditional operator requires its second and third operands to
/// be of compatible type, so by writing "1 ? (ptr) : &((type *)0)->member"
/// instead of simply writing "(ptr)", we ensure that `ptr` actually does
/// point to a type compatible with `member` (compilation halts if it doesn't).

#define er_container_of(ptr, type, member) \
({ \
const typeof(((type *)0)->member) *__mptr = (ptr); \
void *__mptr = (1 ? (ptr) : &((type *)0)->member); \
(type *)((char *)__mptr - offsetof(type, member)); \
})
#endif

#endif /* EVENTROUTER_DEFS_H */
2 changes: 1 addition & 1 deletion eventrouter/internal/event.h
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ extern "C"
/// `a_event_p`. The developer must ensure that `a_type` is correct. This
/// macro returns the surrounding struct by value instead of by reference.
#define FROM_ER_EVENT(a_event_p, a_type) \
(*container_of(a_event_p, a_type, ER_EVENT_MEMBER))
(*er_container_of(a_event_p, a_type, ER_EVENT_MEMBER))

/// Initialize the event fields of a struct which mixes-in `ErEvent_t`
/// behavior. This differs from `ErEventInit_t` in that it can be used in
Expand Down
2 changes: 1 addition & 1 deletion eventrouter/internal/eventrouter_baremetal.c
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ ErEvent_t *ErGetEventToDeliver(void)
ErList_t *node = &s_context.m_events.m_deliver_now;
if (node->m_next != NULL)
{
ret = container_of(node->m_next, ErEvent_t, m_next);
ret = er_container_of(node->m_next, ErEvent_t, m_next);
node->m_next = node->m_next->m_next;
ret->m_next.m_next = NULL;
}
Expand Down

0 comments on commit 77e273e

Please sign in to comment.