From 3597376414e7667dde0f415955c7222ef1194292 Mon Sep 17 00:00:00 2001 From: "Chao Li (Evan)" Date: Wed, 28 Oct 2026 09:17:17 +0800 Subject: [PATCH v1] Return INT_MAX or INT_MIN from strtoint() on overflow Previously, strtoint() set errno to ERANGE on overflow but returned the result of casting the long value to int. When the value is outside the range of int, this produces an implementation-defined result that cannot reliably indicate the direction of overflow. Check the bounds before casting and return INT_MAX or INT_MIN as appropriate, while retaining ERANGE. This makes the overflow behavior consistent with strtol() and allows callers to determine the overflow direction from the return value. All tests passed with "make check-world". Author: Chao Li --- src/common/string.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/common/string.c b/src/common/string.c index 41c74a1502d..6ba4a9be152 100644 --- a/src/common/string.c +++ b/src/common/string.c @@ -21,6 +21,8 @@ #include "postgres_fe.h" #endif +#include + #include "common/string.h" @@ -45,6 +47,8 @@ pg_str_endswith(const char *str, const char *end) /* * strtoint --- just like strtol, but returns int not long + * + * On overflow, returns INT_MAX or INT_MIN and sets errno to ERANGE. */ int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base) @@ -52,8 +56,16 @@ strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base) long val; val = strtol(str, endptr, base); - if (val != (int) val) + if (val > INT_MAX) + { errno = ERANGE; + return INT_MAX; + } + if (val < INT_MIN) + { + errno = ERANGE; + return INT_MIN; + } return (int) val; } -- 2.50.1 (Apple Git-155)