util/cbfstool: Prevent overflow when sorting fit table entries

If fit_table_entries() fails, it returns zero, but the sort loop
subtracts 1 from that value before comparing for the loop termination.
Since the value is unsigned, this results in wraparound overflow,
effectively causing an infinite loop. To mitigate this, store the
number of FIT entries as an int, and use that for the loop exit
condition check. Use int type for the loop counters as well to
avoid the compiler complaining about an signed/unsigned comparison.

BUG=CID 1612099

Change-Id: Id0a16bdb86d075ec6c322b44fd782f81d15ca6a7
Signed-off-by: Martin Roth <gaumless@gmail.com>
Signed-off-by: Matt DeVillier <matt.devillier@gmail.com>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/88324
Reviewed-by: Angel Pons <th3fanbus@gmail.com>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
This commit is contained in:
Martin Roth 2025-07-05 16:19:09 -06:00 committed by Matt DeVillier
commit 480ac15044

View file

@ -165,13 +165,14 @@ static inline size_t fit_free_space(struct fit_table *fit,
static void sort_fit_table(struct fit_table *fit)
{
struct fit_entry tmp;
size_t i, j;
int swapped;
int i, j, num_entries, swapped;
num_entries = fit_table_entries(fit);
/* Bubble sort entries */
for (j = 0; j < fit_table_entries(fit) - 1; j++) {
for (j = 0; j < num_entries - 1; j++) {
swapped = 0;
for (i = 0; i < fit_table_entries(fit) - j - 1; i++) {
for (i = 0; i < num_entries - j - 1; i++) {
if (fit->entries[i].type_checksum_valid <=
fit->entries[i + 1].type_checksum_valid)
continue;