From 0eef9aeb776a83cb58eae744ffdea81ad17622c8 Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Mon, 11 Aug 2025 22:31:09 +0200 Subject: [PATCH] gstrfuncs: Check parameter validity If string operations get the length G_MAXSIZE passed (which cannot ever be true because terminating NUL byte would not fit), return NULL instead of triggering out of boundary writes. --- glib/gstrfuncs.c | 4 ++++ glib/tests/strfuncs.c | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/glib/gstrfuncs.c b/glib/gstrfuncs.c index 7ac827619..9b76049a4 100644 --- a/glib/gstrfuncs.c +++ b/glib/gstrfuncs.c @@ -416,6 +416,8 @@ g_strndup (const gchar *str, if (str) { + g_return_val_if_fail (n < G_MAXSIZE, NULL); + new_str = g_new (gchar, n + 1); strncpy (new_str, str, n); new_str[n] = '\0'; @@ -441,6 +443,8 @@ g_strnfill (gsize length, { gchar *str; + g_return_val_if_fail (length < G_MAXSIZE, NULL); + str = g_new (gchar, length + 1); memset (str, (guchar)fill_char, length); str[length] = '\0'; diff --git a/glib/tests/strfuncs.c b/glib/tests/strfuncs.c index 05f08c0ac..3a6f745f2 100644 --- a/glib/tests/strfuncs.c +++ b/glib/tests/strfuncs.c @@ -571,6 +571,16 @@ test_strndup (void) g_assert_nonnull (str); g_assert_cmpstr (str, ==, "aa"); g_free (str); + + if (g_test_undefined ()) + { + /* Testing degenerated cases */ + g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, + "*assertion* < G_MAXSIZE*"); + g_assert_null ( + g_strndup ("aaaa", G_MAXSIZE)); + g_test_assert_expected_messages (); + } } /* Testing g_strdup_printf() function with various positive and negative cases */ @@ -616,6 +626,16 @@ test_strnfill (void) g_assert_nonnull (str); g_assert_cmpstr (str, ==, "aaaaa"); g_free (str); + + if (g_test_undefined ()) + { + /* Testing degenerated cases */ + g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, + "*assertion* < G_MAXSIZE*"); + g_assert_null ( + g_strnfill (G_MAXSIZE, 'a')); + g_test_assert_expected_messages (); + } } /* Testing g_strconcat() function with various positive and negative cases */