pgsql: Fix right() with the most negative integer

From: Daniel Gustafsson <dgustafsson(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix right() with the most negative integer
Date: 2026-09-01 08:21:17
Message-ID: E1x1Jk4-000000030cn-33Ka@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Fix right() with the most negative integer

A negative n means "return all but the first |n| characters", so
text_right() negates n before clipping. Negating PG_INT32_MIN overflows;
with -fwrapv the result is PG_INT32_MIN again, still negative, and
pg_mbcharcliplen() then returns an offset of zero, so the whole string is
returned where the correct answer is an empty string:

SELECT right('abcdef', (-2147483648)::int4); -- 'abcdef', want ''
SELECT right('abcdef', -2147483647); -- '', correct

Clamp to PG_INT32_MAX instead. Any n whose absolute value is at least the
string's length skips all of it, and a text value cannot be longer than
PG_INT32_MAX, so this gives the same answer for every other input. Note
that erroring out, as text_format_string_conversion() does for a width of
INT_MIN a few hundred lines away, would not be right here: unlike a format
width, an out-of-range skip count has a well-defined result.

text_left() is not affected. Its negative case computes the character
length plus n rather than negating n, and since the length is non-negative
and bounded by the varlena size limit that sum cannot overflow.

Backpatch to all supported versions.

Author: Ewan Young <kdbase(dot)hack(at)gmail(dot)com>
Reviewed-by: Daniel Gustafsson <daniel(at)yesql(dot)se>
Reviewed-by: Dagfinn Ilmari Mannsåker <ilmari(at)ilmari(dot)org>
Reviewed-by: David Rowley <dgrowleyml(at)gmail(dot)com>
Reviewed-by: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAON2xHNnBz-AcPJgDmd5_39+8qR5AUKEZk4X3ZM-0zdsATn8kQ@mail.gmail.com
Backpatch-through: 14

Branch
------
REL_15_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/729bac9eb1042a722f21c6f6dfb5d0f6b0e6c67a

Modified Files
--------------
src/backend/utils/adt/varlena.c | 12 +++++++++++-
src/test/regress/expected/text.out | 8 ++++++++
src/test/regress/sql/text.sql | 3 +++
3 files changed, 22 insertions(+), 1 deletion(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Daniel Gustafsson 2026-09-01 08:21:29 pgsql: Handle PG_INT32_MIN negation overflow in right()
Previous Message Daniel Gustafsson 2026-09-01 08:21:05 pgsql: Handle PG_INT32_MIN negation overflow in right()