Detect buffer underflow in get_th()
authorPeter Eisentraut <[email protected]>
Mon, 18 Aug 2025 09:03:22 +0000 (11:03 +0200)
committerPeter Eisentraut <[email protected]>
Mon, 18 Aug 2025 09:03:22 +0000 (11:03 +0200)
Input with zero length can result in a buffer underflow when
accessing *(num + (len - 1)), as (len - 1) would produce a negative
index.  Add an assertion for zero-length input to prevent it.

This was found by ALT Linux Team.

Reviewing the call sites shows that get_th() currently cannot be
applied to an empty string: it is always called on a string containing
a number we've just printed.  Therefore, an assertion rather than a
user-facing error message is sufficient.

Co-authored-by: Alexander Kuznetsov <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/e22df993-cdb4-4d0a-b629-42211ebed582@altlinux.org

src/backend/utils/adt/formatting.c

index 1d05481181db7d94eeb62e4e7f829c86bd914ce2..7ad453314c307b276d5f518eefb735ab5d70726f 100644 (file)
@@ -1565,6 +1565,8 @@ get_th(char *num, int type)
    int         len = strlen(num),
                last;
 
+   Assert(len > 0);
+
    last = *(num + (len - 1));
    if (!isdigit((unsigned char) last))
        ereport(ERROR,