glib-aux/prioq: assert for valid index in find_item() of NMPrioq

NMPrioq is taken from systemd's "prioq.c". It is a nice data structure,
that accepts and an index pointer, to directly access elements inside
the heap.

Previously, the API didn't require a consistent index, while the data is
not inside the heap. nm_prioq_{update,shuffle,remove}()) call find_item(),
which silently accepts wrong indexes and assumes the element is not in
the heap.

Keeping the index in sync with the data seems error prone. Accepting any
index without asserting may be convenient for the user (as the user is
not required to pre-initialize the index with NM_PRIOQ_IDX_NULL).
However, it also misses to catch potential bugs.

Now the index must be kept consistent, in particular also if the element
is not enqueued. This means, you must initialize them with
NM_PRIOQ_IDX_NULL.
This commit is contained in:
Thomas Haller 2023-03-10 15:13:18 +01:00
parent 78489e7cbb
commit d840ddd959
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 16 additions and 1 deletions

View file

@ -288,14 +288,28 @@ find_item(NMPrioq *q, void *data, unsigned *idx)
return NULL;
}
/* If the user however provides an "idx" pointer, then we assert that it is
* consistent. That is, if data is not in the queue, then we require that
* "*idx" is NM_PRIOQ_IDX_NULL, and otherwise we require that we really
* find "data" at index "*idx".
*
* This means, when the user calls nm_prioq_{remove,update,reshuffle}()
* with an "idx", then they must make sure that the index is consistent.
* Usually this means they are required to initialize the index to
* NM_PRIOQ_IDX_NULL while the data is not in the heap.
*
* This is done to assert more, and requires a stricter usage of the API
* (in the hope to find misuses of the index). */
if (*idx >= q->_priv.n_items) {
nm_assert(*idx == NM_PRIOQ_IDX_NULL);
return NULL;
}
i = &q->_priv.items[*idx];
if (i->data != data)
return NULL;
return nm_assert_unreachable_val(NULL);
return i;
}

View file

@ -735,6 +735,7 @@ nm_lldp_neighbor_new(size_t raw_size)
n->raw_size = raw_size;
n->ref_count = 1;
n->prioq_idx = NM_PRIOQ_IDX_NULL;
return n;
}