[PATCH] Avoid potential NULL dereference in LIKE/ILIKE with C locale - Mailing list pgsql-hackers

From Eugeny Goryachev
Subject [PATCH] Avoid potential NULL dereference in LIKE/ILIKE with C locale
Date
Msg-id CABg3sZo30PKF-AYZ_eih=5snxqp73bVOGX7O_hBMqoFhcOWbjQ@mail.gmail.com
Whole thread Raw
Responses Re: [PATCH] Avoid potential NULL dereference in LIKE/ILIKE with C locale
List pgsql-hackers

Hi hackers,

While reviewing the MatchText function in backend/utils/adt/like_match.c, I noticed a potential NULL pointer dereference when using LIKE or ILIKE with the C locale.

The issue arises because the locale argument (of type pg_locale_t, which is a pointer) can be NULL when the C collation is in use. However, the GETCHAR macro unconditionally passes this locale to MATCH_LOWER, which - depending on its definition - may attempt to dereference it (e.g., to access locale->provider or other fields).

This can lead to a crash in builds or configurations where MATCH_LOWER is not safe to call with a NULL locale.

The proposed patch adds an explicit check for locale == NULL in the GETCHAR macro and falls back to pg_ascii_tolower() in that case, which is both safe and correct for the C locale (since no locale-specific case folding is needed).

The change aligns with existing patterns in the codebase (e.g., in text_cmp and other collation-aware functions) where NULL locale is treated as equivalent to C/POSIX behavior.

Best regards, Eugeny Goryachev.

Patch:

Subject: [PATCH] Avoid potential NULL dereference in LIKE/ILIKE with C locale

---
 src/backend/utils/adt/like_match.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/like_match.c b/src/backend/utils/adt/like_match.c
index 892f8a745ea..884edc7ff42 100644
--- a/src/backend/utils/adt/like_match.c
+++ b/src/backend/utils/adt/like_match.c
@@ -71,7 +71,8 @@
  */

 #ifdef MATCH_LOWER
-#define GETCHAR(t, locale) MATCH_LOWER(t, locale)
+#define GETCHAR(t, locale) \
+ ((locale) == 0 ? pg_ascii_tolower((unsigned char)(t)) : MATCH_LOWER(t, locale))
 #else
 #define GETCHAR(t, locale) (t)
 #endif
--
2.42.4



pgsql-hackers by date:

Previous
From: Amit Kapila
Date:
Subject: Re: Newly created replication slot may be invalidated by checkpoint
Next
From: Jim Jones
Date:
Subject: Re: ALTER TABLE: warn when actions do not recurse to partitions