Skip to content

Commit

Permalink
qom: assert integer does not overflow
Browse files Browse the repository at this point in the history
QOM reference counting is not designed with an infinite amount of
references in mind, trying to take a reference in a loop without
dropping a reference will overflow the integer.

It is generally a symptom of a reference leak (a missing deref, commonly
as part of error handling - such as one fixed here:
https://lore.kernel.org/r/20220228095058.27899-1-sgarzare%40redhat.com ).

All this can lead to either freeing the object too early (memory
corruption) or never freeing it (memory leak).

If we happen to dereference at just the right time (when it's wrapping
around to 0), we might eventually assert when dereferencing, but the
real problem is an extra object_ref so let's assert there to make such
issues cleaner and easier to debug.

Some micro-benchmarking shows using fetch and add this is essentially
free on x86.

Since multiple threads could be incrementing in parallel, we assert
around INT_MAX to make sure none of these approach the wrap around
point: this way we get a memory leak and not a memory corruption, the
former is generally easier to debug.

Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
  • Loading branch information
mstsirkin committed Mar 4, 2022
1 parent 6629bf7 commit e368287
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion qom/object.c
Expand Up @@ -1167,10 +1167,14 @@ GSList *object_class_get_list_sorted(const char *implements_type,
Object *object_ref(void *objptr)
{
Object *obj = OBJECT(objptr);
uint32_t ref;

if (!obj) {
return NULL;
}
qatomic_inc(&obj->ref);
ref = qatomic_fetch_inc(&obj->ref);
/* Assert waaay before the integer overflows */
g_assert(ref < INT_MAX);
return obj;
}

Expand Down

0 comments on commit e368287

Please sign in to comment.