Skip to content

Commit

Permalink
(size_trunc_len): fix Undefined Binary Operator Result.
Browse files Browse the repository at this point in the history
lib/util.c:493:28: warning: The left operand of '!=' is a garbage value due to array index out of bounds [clang-analyzer-core.UndefinedBinaryOperatorResult]
  493 |     for (j = units; sfx[j] != NULL; j++)
      |                     ~~~~~~ ^

 - verify and limit input 'units' value

Found by Clang-19 Static Analyzer.

Reported-by: Andreas Mohr <[email protected]>
Signed-off-by: Andrew Borodin <vmail.ru>
  • Loading branch information
Andrew Borodin authored and aborodin committed Dec 22, 2024
1 parent a4063fc commit 3475da7
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -459,9 +459,19 @@ size_trunc_len (char *buffer, unsigned int len, uintmax_t size, int units, gbool
{ "", "k", "m", "g", "t", "p", "e", "z", "y", "r", "q", NULL };
/* *INDENT-ON* */

static int sfx_last = -1;

const char *const *sfx = use_si ? suffix_lc : suffix;
int j = 0;

if (sfx_last < 0)
{
for (sfx_last = 0; sfx[sfx_last] != NULL; sfx_last++)
;

sfx_last--;
}

if (len == 0)
len = 9;
#if SIZEOF_UINTMAX_T == 8
Expand All @@ -474,13 +484,15 @@ size_trunc_len (char *buffer, unsigned int len, uintmax_t size, int units, gbool
len = 9;
#endif

const int units_safe = MIN (units, sfx_last);

/*
* recalculate from 1024 base to 1000 base if units>0
* We can't just multiply by 1024 - that might cause overflow
* if uintmax_t type is too small
*/
if (use_si)
for (j = 0; j < units; j++)
for (j = 0; j < units_safe; j++)
{
uintmax_t size_remain;

Expand All @@ -490,7 +502,7 @@ size_trunc_len (char *buffer, unsigned int len, uintmax_t size, int units, gbool
size += size_remain; /* Re-add remainder lost by division/multiplication */
}

for (j = units; sfx[j] != NULL; j++)
for (j = units_safe; sfx[j] != NULL; j++)
{
if (size == 0)
{
Expand Down

0 comments on commit 3475da7

Please sign in to comment.