Imported Upstream version 2.66.6 upstream/2.66.6
authorDongHun Kwak <dh0128.kwak@samsung.com>
Fri, 29 Oct 2021 01:28:06 +0000 (10:28 +0900)
committerDongHun Kwak <dh0128.kwak@samsung.com>
Fri, 29 Oct 2021 01:28:06 +0000 (10:28 +0900)
34 files changed:
NEWS
docs/reference/glib/meson.build
gio/gdatainputstream.c
gio/gdbusconnection.c
gio/gdbusinterfaceskeleton.c
gio/gfile.c
gio/giowin32-private.c
gio/gkeyfilesettingsbackend.c
gio/gsettingsschema.c
gio/gsocket.c
gio/gtlspassword.c
gio/gwin32registrykey.c
gio/tests/async-close-output-stream.c
gio/tests/gdbus-export.c
gio/win32/gwinhttpfile.c
glib/gbytes.c
glib/gdir.c
glib/ghash.c
glib/giochannel.c
glib/gslice.c
glib/gstrfuncsprivate.h [new file with mode: 0644]
glib/gtestutils.c
glib/gvariant.c
glib/gvarianttype.c
glib/meson.build
glib/tests/array-test.c
glib/tests/option-context.c
glib/tests/strfuncs.c
glib/tests/uri.c
gobject/gsignal.c
gobject/gtype.c
gobject/gtypemodule.c
gobject/tests/param.c
meson.build

diff --git a/NEWS b/NEWS
index a9becc9..520df7a 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,14 @@
+Overview of changes in GLib 2.66.6
+==================================
+
+* Fix various instances within GLib where `g_memdup()` was vulnerable to a
+  silent integer truncation and heap overflow problem (discovered by
+  Kevin Backhouse, work by Philip Withnall) (#2319)
+
+* Bugs fixed:
+ - !1927 Backport !1926 “Add g_memdup2()” to glib-2-66
+
+
 Overview of changes in GLib 2.66.5
 ==================================
 
index 43c2738..e6cd0f0 100644 (file)
@@ -22,6 +22,7 @@ if get_option('gtk_doc')
     'gprintfint.h',
     'gmirroringtable.h',
     'gscripttable.h',
+    'gstrfuncsprivate.h',
     'gtrace-private.h',
     'glib-mirroring-tab',
     'gnulib',
index 2e7750c..2cdcbda 100644 (file)
@@ -27,6 +27,7 @@
 #include "gioenumtypes.h"
 #include "gioerror.h"
 #include "glibintl.h"
+#include "gstrfuncsprivate.h"
 
 #include <string.h>
 
@@ -856,7 +857,7 @@ static gssize
 scan_for_chars (GDataInputStream *stream,
                gsize            *checked_out,
                const char       *stop_chars,
-                gssize            stop_chars_len)
+                gsize             stop_chars_len)
 {
   GBufferedInputStream *bstream;
   const char *buffer;
@@ -952,7 +953,7 @@ typedef struct
   gsize checked;
 
   gchar *stop_chars;
-  gssize stop_chars_len;
+  gsize stop_chars_len;
   gsize length;
 } GDataInputStreamReadData;
 
@@ -1078,12 +1079,17 @@ g_data_input_stream_read_async (GDataInputStream    *stream,
 {
   GDataInputStreamReadData *data;
   GTask *task;
+  gsize stop_chars_len_unsigned;
 
   data = g_slice_new0 (GDataInputStreamReadData);
-  if (stop_chars_len == -1)
-    stop_chars_len = strlen (stop_chars);
-  data->stop_chars = g_memdup (stop_chars, stop_chars_len);
-  data->stop_chars_len = stop_chars_len;
+
+  if (stop_chars_len < 0)
+    stop_chars_len_unsigned = strlen (stop_chars);
+  else
+    stop_chars_len_unsigned = (gsize) stop_chars_len;
+
+  data->stop_chars = g_memdup2 (stop_chars, stop_chars_len_unsigned);
+  data->stop_chars_len = stop_chars_len_unsigned;
   data->last_saw_cr = FALSE;
 
   task = g_task_new (stream, cancellable, callback, user_data);
@@ -1338,17 +1344,20 @@ g_data_input_stream_read_upto (GDataInputStream  *stream,
   gssize found_pos;
   gssize res;
   char *data_until;
+  gsize stop_chars_len_unsigned;
 
   g_return_val_if_fail (G_IS_DATA_INPUT_STREAM (stream), NULL);
 
   if (stop_chars_len < 0)
-    stop_chars_len = strlen (stop_chars);
+    stop_chars_len_unsigned = strlen (stop_chars);
+  else
+    stop_chars_len_unsigned = (gsize) stop_chars_len;
 
   bstream = G_BUFFERED_INPUT_STREAM (stream);
 
   checked = 0;
 
-  while ((found_pos = scan_for_chars (stream, &checked, stop_chars, stop_chars_len)) == -1)
+  while ((found_pos = scan_for_chars (stream, &checked, stop_chars, stop_chars_len_unsigned)) == -1)
     {
       if (g_buffered_input_stream_get_available (bstream) ==
           g_buffered_input_stream_get_buffer_size (bstream))
index 54aaf43..633198b 100644 (file)
 #include "gasyncinitable.h"
 #include "giostream.h"
 #include "gasyncresult.h"
+#include "gstrfuncsprivate.h"
 #include "gtask.h"
 #include "gmarshal-internal.h"
 
@@ -4009,7 +4010,7 @@ _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
   /* Don't waste memory by copying padding - remember to update this
    * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
    */
-  return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
+  return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
 }
 
 static void
@@ -4026,7 +4027,7 @@ _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
   /* Don't waste memory by copying padding - remember to update this
    * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
    */
-  return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
+  return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
 }
 
 static void
index a0125c5..a0cd250 100644 (file)
@@ -28,6 +28,7 @@
 #include "gdbusmethodinvocation.h"
 #include "gdbusconnection.h"
 #include "gmarshal-internal.h"
+#include "gstrfuncsprivate.h"
 #include "gtask.h"
 #include "gioerror.h"
 
@@ -702,7 +703,7 @@ add_connection_locked (GDBusInterfaceSkeleton *interface_,
        * properly before building the hooked_vtable, so we create it
        * once at the last minute.
        */
-      interface_->priv->hooked_vtable = g_memdup (g_dbus_interface_skeleton_get_vtable (interface_), sizeof (GDBusInterfaceVTable));
+      interface_->priv->hooked_vtable = g_memdup2 (g_dbus_interface_skeleton_get_vtable (interface_), sizeof (GDBusInterfaceVTable));
       interface_->priv->hooked_vtable->method_call = skeleton_intercept_handle_method_call;
     }
 
index 533efa7..c16912b 100644 (file)
@@ -60,6 +60,7 @@
 #include "gasyncresult.h"
 #include "gioerror.h"
 #include "glibintl.h"
+#include "gstrfuncsprivate.h"
 
 
 /**
@@ -7871,7 +7872,7 @@ measure_disk_usage_progress (gboolean reporting,
   g_main_context_invoke_full (g_task_get_context (task),
                               g_task_get_priority (task),
                               measure_disk_usage_invoke_progress,
-                              g_memdup (&progress, sizeof progress),
+                              g_memdup2 (&progress, sizeof progress),
                               g_free);
 }
 
@@ -7889,7 +7890,7 @@ measure_disk_usage_thread (GTask        *task,
                                  data->progress_callback ? measure_disk_usage_progress : NULL, task,
                                  &result.disk_usage, &result.num_dirs, &result.num_files,
                                  &error))
-    g_task_return_pointer (task, g_memdup (&result, sizeof result), g_free);
+    g_task_return_pointer (task, g_memdup2 (&result, sizeof result), g_free);
   else
     g_task_return_error (task, error);
 }
@@ -7913,7 +7914,7 @@ g_file_real_measure_disk_usage_async (GFile                        *file,
 
   task = g_task_new (file, cancellable, callback, user_data);
   g_task_set_source_tag (task, g_file_real_measure_disk_usage_async);
-  g_task_set_task_data (task, g_memdup (&data, sizeof data), g_free);
+  g_task_set_task_data (task, g_memdup2 (&data, sizeof data), g_free);
   g_task_set_priority (task, io_priority);
 
   g_task_run_in_thread (task, measure_disk_usage_thread);
index 7120ae0..47e8408 100644 (file)
  * along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "gstrfuncsprivate.h"
 
-static gssize
+static gsize
 g_utf16_len (const gunichar2 *str)
 {
-  gssize result;
+  gsize result;
 
   for (result = 0; str[0] != 0; str++, result++)
     ;
@@ -31,17 +32,20 @@ g_utf16_len (const gunichar2 *str)
 static gunichar2 *
 g_wcsdup (const gunichar2 *str, gssize str_len)
 {
-  gssize str_size;
+  gsize str_len_unsigned;
+  gsize str_size;
 
   g_return_val_if_fail (str != NULL, NULL);
 
-  if (str_len == -1)
-    str_len = g_utf16_len (str);
+  if (str_len < 0)
+    str_len_unsigned = g_utf16_len (str);
+  else
+    str_len_unsigned = (gsize) str_len;
 
-  g_assert (str_len <= G_MAXSIZE / sizeof (gunichar2) - 1);
-  str_size = (str_len + 1) * sizeof (gunichar2);
+  g_assert (str_len_unsigned <= G_MAXSIZE / sizeof (gunichar2) - 1);
+  str_size = (str_len_unsigned + 1) * sizeof (gunichar2);
 
-  return g_memdup (str, str_size);
+  return g_memdup2 (str, str_size);
 }
 
 static const gunichar2 *
index cd5765a..25b0576 100644 (file)
@@ -33,6 +33,7 @@
 #include "gfilemonitor.h"
 #include "gsimplepermission.h"
 #include "gsettingsbackendinternal.h"
+#include "gstrfuncsprivate.h"
 #include "giomodule-priv.h"
 #include "gportalsupport.h"
 
@@ -145,8 +146,8 @@ convert_path (GKeyfileSettingsBackend  *kfsb,
               gchar                   **group,
               gchar                   **basename)
 {
-  gint key_len = strlen (key);
-  gint i;
+  gsize key_len = strlen (key);
+  const gchar *last_slash;
 
   if (key_len < kfsb->prefix_len ||
       memcmp (key, kfsb->prefix, kfsb->prefix_len) != 0)
@@ -155,38 +156,36 @@ convert_path (GKeyfileSettingsBackend  *kfsb,
   key_len -= kfsb->prefix_len;
   key += kfsb->prefix_len;
 
-  for (i = key_len; i >= 0; i--)
-    if (key[i] == '/')
-      break;
+  last_slash = strrchr (key, '/');
 
   if (kfsb->root_group)
     {
       /* if a root_group was specified, make sure the user hasn't given
        * a path that ghosts that group name
        */
-      if (i == kfsb->root_group_len && memcmp (key, kfsb->root_group, i) == 0)
+      if (last_slash != NULL && (last_slash - key) == kfsb->root_group_len && memcmp (key, kfsb->root_group, last_slash - key) == 0)
         return FALSE;
     }
   else
     {
       /* if no root_group was given, ensure that the user gave a path */
-      if (i == -1)
+      if (last_slash == NULL)
         return FALSE;
     }
 
   if (group)
     {
-      if (i >= 0)
+      if (last_slash != NULL)
         {
-          *group = g_memdup (key, i + 1);
-          (*group)[i] = '\0';
+          *group = g_memdup2 (key, (last_slash - key) + 1);
+          (*group)[(last_slash - key)] = '\0';
         }
       else
         *group = g_strdup (kfsb->root_group);
     }
 
   if (basename)
-    *basename = g_memdup (key + i + 1, key_len - i);
+    *basename = g_memdup2 (last_slash + 1, key_len - (last_slash - key));
 
   return TRUE;
 }
index 8e203db..1282c10 100644 (file)
@@ -21,6 +21,7 @@
 #include "glib-private.h"
 #include "gsettingsschema-internal.h"
 #include "gsettings.h"
+#include "gstrfuncsprivate.h"
 
 #include "gvdb/gvdb-reader.h"
 #include "strinfo.c"
@@ -1071,9 +1072,9 @@ g_settings_schema_list_children (GSettingsSchema *schema)
 
       if (g_str_has_suffix (key, "/"))
         {
-          gint length = strlen (key);
+          gsize length = strlen (key);
 
-          strv[j] = g_memdup (key, length);
+          strv[j] = g_memdup2 (key, length);
           strv[j][length - 1] = '\0';
           j++;
         }
index e911de7..5a2468e 100644 (file)
@@ -75,6 +75,7 @@
 #include "gcredentialsprivate.h"
 #include "glibintl.h"
 #include "gioprivate.h"
+#include "gstrfuncsprivate.h"
 
 /**
  * SECTION:gsocket
@@ -169,7 +170,7 @@ static gboolean     g_socket_datagram_based_condition_wait       (GDatagramBased
                                                                   GError          **error);
 
 static GSocketAddress *
-cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len);
+cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len);
 
 static gssize
 g_socket_receive_message_with_timeout  (GSocket                 *socket,
@@ -255,7 +256,7 @@ struct _GSocketPrivate
   struct {
     GSocketAddress *addr;
     struct sockaddr *native;
-    gint native_len;
+    gsize native_len;
     guint64 last_used;
   } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
 };
@@ -5263,14 +5264,14 @@ g_socket_send_messages_with_timeout (GSocket        *socket,
 }
 
 static GSocketAddress *
-cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
+cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len)
 {
   GSocketAddress *saddr;
   gint i;
   guint64 oldest_time = G_MAXUINT64;
   gint oldest_index = 0;
 
-  if (native_len <= 0)
+  if (native_len == 0)
     return NULL;
 
   saddr = NULL;
@@ -5278,7 +5279,7 @@ cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
     {
       GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
       gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
-      gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
+      gsize tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
 
       if (!tmp)
         continue;
@@ -5308,7 +5309,7 @@ cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
       g_free (socket->priv->recv_addr_cache[oldest_index].native);
     }
 
-  socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
+  socket->priv->recv_addr_cache[oldest_index].native = g_memdup2 (native, native_len);
   socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
   socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
   socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
@@ -5456,6 +5457,9 @@ g_socket_receive_message_with_timeout (GSocket                 *socket,
     /* do it */
     while (1)
       {
+        /* addrlen has to be of type int because that’s how WSARecvFrom() is defined */
+        G_STATIC_ASSERT (sizeof addr <= G_MAXINT);
+
        addrlen = sizeof addr;
        if (address)
          result = WSARecvFrom (socket->priv->fd,
index 1e437a7..dbcec41 100644 (file)
@@ -23,6 +23,7 @@
 #include "glibintl.h"
 
 #include "gioenumtypes.h"
+#include "gstrfuncsprivate.h"
 #include "gtlspassword.h"
 
 #include <string.h>
@@ -287,9 +288,14 @@ g_tls_password_set_value (GTlsPassword  *password,
   g_return_if_fail (G_IS_TLS_PASSWORD (password));
 
   if (length < 0)
-    length = strlen ((gchar *)value);
+    {
+      /* FIXME: g_tls_password_set_value_full() doesn’t support unsigned gsize */
+      gsize length_unsigned = strlen ((gchar *) value);
+      g_return_if_fail (length_unsigned > G_MAXSSIZE);
+      length = (gssize) length_unsigned;
+    }
 
-  g_tls_password_set_value_full (password, g_memdup (value, length), length, g_free);
+  g_tls_password_set_value_full (password, g_memdup2 (value, (gsize) length), length, g_free);
 }
 
 /**
index a963d6c..2eb67da 100644 (file)
@@ -28,6 +28,8 @@
 #include <ntstatus.h>
 #include <winternl.h>
 
+#include "gstrfuncsprivate.h"
+
 #ifndef _WDMDDK_
 typedef enum _KEY_INFORMATION_CLASS {
   KeyBasicInformation,
@@ -125,16 +127,34 @@ typedef enum
   G_WIN32_REGISTRY_UPDATED_PATH = 1,
 } GWin32RegistryKeyUpdateFlag;
 
+static gsize
+g_utf16_len (const gunichar2 *str)
+{
+  gsize result;
+
+  for (result = 0; str[0] != 0; str++, result++)
+    ;
+
+  return result;
+}
+
 static gunichar2 *
-g_wcsdup (const gunichar2 *str,
-          gssize           str_size)
+g_wcsdup (const gunichar2 *str, gssize str_len)
 {
-  if (str_size == -1)
-    {
-      str_size = wcslen (str) + 1;
-      str_size *= sizeof (gunichar2);
-    }
-  return g_memdup (str, str_size);
+  gsize str_len_unsigned;
+  gsize str_size;
+
+  g_return_val_if_fail (str != NULL, NULL);
+
+  if (str_len < 0)
+    str_len_unsigned = g_utf16_len (str);
+  else
+    str_len_unsigned = (gsize) str_len;
+
+  g_assert (str_len_unsigned <= G_MAXSIZE / sizeof (gunichar2) - 1);
+  str_size = (str_len_unsigned + 1) * sizeof (gunichar2);
+
+  return g_memdup2 (str, str_size);
 }
 
 /**
@@ -247,7 +267,7 @@ g_win32_registry_value_iter_copy (const GWin32RegistryValueIter *iter)
   new_iter->value_name_size = iter->value_name_size;
 
   if (iter->value_data != NULL)
-    new_iter->value_data = g_memdup (iter->value_data, iter->value_data_size);
+    new_iter->value_data = g_memdup2 (iter->value_data, iter->value_data_size);
 
   new_iter->value_data_size = iter->value_data_size;
 
@@ -268,8 +288,8 @@ g_win32_registry_value_iter_copy (const GWin32RegistryValueIter *iter)
   new_iter->value_data_expanded_charsize = iter->value_data_expanded_charsize;
 
   if (iter->value_data_expanded_u8 != NULL)
-    new_iter->value_data_expanded_u8 = g_memdup (iter->value_data_expanded_u8,
-                                                 iter->value_data_expanded_charsize);
+    new_iter->value_data_expanded_u8 = g_memdup2 (iter->value_data_expanded_u8,
+                                                  iter->value_data_expanded_charsize);
 
   new_iter->value_data_expanded_u8_size = iter->value_data_expanded_charsize;
 
index 5f66202..d3f97a1 100644 (file)
@@ -24,6 +24,8 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include "gstrfuncsprivate.h"
+
 #define DATA_TO_WRITE "Hello world\n"
 
 typedef struct
@@ -147,9 +149,9 @@ prepare_data (SetupData *data,
 
   data->expected_size = g_memory_output_stream_get_data_size (G_MEMORY_OUTPUT_STREAM (data->data_stream));
 
-  g_assert_cmpint (data->expected_size, >, 0);
+  g_assert_cmpuint (data->expected_size, >, 0);
 
-  data->expected_output = g_memdup (written, (guint)data->expected_size);
+  data->expected_output = g_memdup2 (written, data->expected_size);
 
   /* then recreate the streams and prepare them for the asynchronous close */
   destroy_streams (data);
index ba53886..ad2489d 100644 (file)
@@ -23,6 +23,7 @@
 #include <string.h>
 
 #include "gdbus-tests.h"
+#include "gstrfuncsprivate.h"
 
 /* all tests rely on a shared mainloop */
 static GMainLoop *loop = NULL;
@@ -671,7 +672,7 @@ subtree_introspect (GDBusConnection       *connection,
       g_assert_not_reached ();
     }
 
-  return g_memdup (interfaces, 2 * sizeof (void *));
+  return g_memdup2 (interfaces, 2 * sizeof (void *));
 }
 
 static const GDBusInterfaceVTable *
@@ -727,7 +728,7 @@ dynamic_subtree_introspect (GDBusConnection       *connection,
 {
   const GDBusInterfaceInfo *interfaces[2] = { &dyna_interface_info, NULL };
 
-  return g_memdup (interfaces, 2 * sizeof (void *));
+  return g_memdup2 (interfaces, 2 * sizeof (void *));
 }
 
 static const GDBusInterfaceVTable *
index 509cdeb..e0340e2 100644 (file)
@@ -30,6 +30,7 @@
 #include "gio/gfileattribute.h"
 #include "gio/gfileinfo.h"
 #include "gio/gfileinfo-priv.h"
+#include "gstrfuncsprivate.h"
 #include "gwinhttpfile.h"
 #include "gwinhttpfileinputstream.h"
 #include "gwinhttpfileoutputstream.h"
@@ -409,10 +410,10 @@ g_winhttp_file_resolve_relative_path (GFile      *file,
   child = g_object_new (G_TYPE_WINHTTP_FILE, NULL);
   child->vfs = winhttp_file->vfs;
   child->url = winhttp_file->url;
-  child->url.lpszScheme = g_memdup (winhttp_file->url.lpszScheme, (winhttp_file->url.dwSchemeLength+1)*2);
-  child->url.lpszHostName = g_memdup (winhttp_file->url.lpszHostName, (winhttp_file->url.dwHostNameLength+1)*2);
-  child->url.lpszUserName = g_memdup (winhttp_file->url.lpszUserName, (winhttp_file->url.dwUserNameLength+1)*2);
-  child->url.lpszPassword = g_memdup (winhttp_file->url.lpszPassword, (winhttp_file->url.dwPasswordLength+1)*2);
+  child->url.lpszScheme = g_memdup2 (winhttp_file->url.lpszScheme, ((gsize) winhttp_file->url.dwSchemeLength + 1) * 2);
+  child->url.lpszHostName = g_memdup2 (winhttp_file->url.lpszHostName, ((gsize) winhttp_file->url.dwHostNameLength + 1) * 2);
+  child->url.lpszUserName = g_memdup2 (winhttp_file->url.lpszUserName, ((gsize) winhttp_file->url.dwUserNameLength + 1) * 2);
+  child->url.lpszPassword = g_memdup2 (winhttp_file->url.lpszPassword, ((gsize) winhttp_file->url.dwPasswordLength + 1) * 2);
   child->url.lpszUrlPath = wnew_path;
   child->url.dwUrlPathLength = wcslen (wnew_path);
   child->url.lpszExtraInfo = NULL;
index ec69231..6f17d10 100644 (file)
@@ -34,6 +34,8 @@
 
 #include <string.h>
 
+#include "gstrfuncsprivate.h"
+
 /**
  * GBytes:
  *
@@ -95,7 +97,7 @@ g_bytes_new (gconstpointer data,
 {
   g_return_val_if_fail (data != NULL || size == 0, NULL);
 
-  return g_bytes_new_take (g_memdup (data, size), size);
+  return g_bytes_new_take (g_memdup2 (data, size), size);
 }
 
 /**
@@ -499,7 +501,7 @@ g_bytes_unref_to_data (GBytes *bytes,
        * Copy: Non g_malloc (or compatible) allocator, or static memory,
        * so we have to copy, and then unref.
        */
-      result = g_memdup (bytes->data, bytes->size);
+      result = g_memdup2 (bytes->data, bytes->size);
       *size = bytes->size;
       g_bytes_unref (bytes);
     }
index 6b85e99..6747a8c 100644 (file)
@@ -37,6 +37,7 @@
 #include "gconvert.h"
 #include "gfileutils.h"
 #include "gstrfuncs.h"
+#include "gstrfuncsprivate.h"
 #include "gtestutils.h"
 #include "glibintl.h"
 
@@ -112,7 +113,7 @@ g_dir_open_with_errno (const gchar *path,
     return NULL;
 #endif
 
-  return g_memdup (&dir, sizeof dir);
+  return g_memdup2 (&dir, sizeof dir);
 }
 
 /**
index 40a0fb2..f13df25 100644 (file)
@@ -34,6 +34,7 @@
 #include "gmacros.h"
 #include "glib-private.h"
 #include "gstrfuncs.h"
+#include "gstrfuncsprivate.h"
 #include "gatomic.h"
 #include "gtestutils.h"
 #include "gslice.h"
@@ -963,7 +964,7 @@ g_hash_table_ensure_keyval_fits (GHashTable *hash_table, gpointer key, gpointer
       if (hash_table->have_big_keys)
         {
           if (key != value)
-            hash_table->values = g_memdup (hash_table->keys, sizeof (gpointer) * hash_table->size);
+            hash_table->values = g_memdup2 (hash_table->keys, sizeof (gpointer) * hash_table->size);
           /* Keys and values are both big now, so no need for further checks */
           return;
         }
@@ -971,7 +972,7 @@ g_hash_table_ensure_keyval_fits (GHashTable *hash_table, gpointer key, gpointer
         {
           if (key != value)
             {
-              hash_table->values = g_memdup (hash_table->keys, sizeof (guint) * hash_table->size);
+              hash_table->values = g_memdup2 (hash_table->keys, sizeof (guint) * hash_table->size);
               is_a_set = FALSE;
             }
         }
@@ -999,7 +1000,7 @@ g_hash_table_ensure_keyval_fits (GHashTable *hash_table, gpointer key, gpointer
 
   /* Just split if necessary */
   if (is_a_set && key != value)
-    hash_table->values = g_memdup (hash_table->keys, sizeof (gpointer) * hash_table->size);
+    hash_table->values = g_memdup2 (hash_table->keys, sizeof (gpointer) * hash_table->size);
 
 #endif
 }
index d977b76..4dec20f 100644 (file)
@@ -37,6 +37,7 @@
 #include "giochannel.h"
 
 #include "gstrfuncs.h"
+#include "gstrfuncsprivate.h"
 #include "gtestutils.h"
 #include "glibintl.h"
 
@@ -886,16 +887,25 @@ g_io_channel_set_line_term (GIOChannel    *channel,
                             const gchar        *line_term,
                            gint         length)
 {
+  guint length_unsigned;
+
   g_return_if_fail (channel != NULL);
   g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
 
   if (line_term == NULL)
-    length = 0;
-  else if (length < 0)
-    length = strlen (line_term);
+    length_unsigned = 0;
+  else if (length >= 0)
+    length_unsigned = (guint) length;
+  else
+    {
+      /* FIXME: We’re constrained by line_term_len being a guint here */
+      gsize length_size = strlen (line_term);
+      g_return_if_fail (length_size > G_MAXUINT);
+      length_unsigned = (guint) length_size;
+    }
 
   g_free (channel->line_term);
-  channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
+  channel->line_term = line_term ? g_memdup2 (line_term, length_unsigned) : NULL;
   channel->line_term_len = length;
 }
 
@@ -1673,10 +1683,10 @@ g_io_channel_read_line (GIOChannel  *channel,
 
       /* Copy the read bytes (including any embedded nuls) and nul-terminate.
        * `USE_BUF (channel)->str` is guaranteed to be nul-terminated as it’s a
-       * #GString, so it’s safe to call g_memdup() with +1 length to allocate
+       * #GString, so it’s safe to call g_memdup2() with +1 length to allocate
        * a nul-terminator. */
       g_assert (USE_BUF (channel));
-      line = g_memdup (USE_BUF (channel)->str, got_length + 1);
+      line = g_memdup2 (USE_BUF (channel)->str, got_length + 1);
       line[got_length] = '\0';
       *str_return = g_steal_pointer (&line);
       g_string_erase (USE_BUF (channel), 0, got_length);
index 5896190..9a5eb8e 100644 (file)
@@ -41,6 +41,7 @@
 #include "gmain.h"
 #include "gmem.h"               /* gslice.h */
 #include "gstrfuncs.h"
+#include "gstrfuncsprivate.h"
 #include "gutils.h"
 #include "gtrashstack.h"
 #include "gtestutils.h"
@@ -351,7 +352,7 @@ g_slice_get_config_state (GSliceConfig ckey,
       array[i++] = allocator->contention_counters[address];
       array[i++] = allocator_get_magazine_threshold (allocator, address);
       *n_values = i;
-      return g_memdup (array, sizeof (array[0]) * *n_values);
+      return g_memdup2 (array, sizeof (array[0]) * *n_values);
     default:
       return NULL;
     }
diff --git a/glib/gstrfuncsprivate.h b/glib/gstrfuncsprivate.h
new file mode 100644 (file)
index 0000000..85c8832
--- /dev/null
@@ -0,0 +1,55 @@
+/* GLIB - Library of useful routines for C programming
+ * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <glib.h>
+#include <string.h>
+
+/*
+ * g_memdup2:
+ * @mem: (nullable): the memory to copy.
+ * @byte_size: the number of bytes to copy.
+ *
+ * Allocates @byte_size bytes of memory, and copies @byte_size bytes into it
+ * from @mem. If @mem is %NULL it returns %NULL.
+ *
+ * This replaces g_memdup(), which was prone to integer overflows when
+ * converting the argument from a #gsize to a #guint.
+ *
+ * This static inline version is a backport of the new public API from
+ * GLib 2.68, kept internal to GLib for backport to older stable releases.
+ * See https://gitlab.gnome.org/GNOME/glib/-/issues/2319.
+ *
+ * Returns: (nullable): a pointer to the newly-allocated copy of the memory,
+ *    or %NULL if @mem is %NULL.
+ * Since: 2.68
+ */
+static inline gpointer
+g_memdup2 (gconstpointer mem,
+           gsize         byte_size)
+{
+  gpointer new_mem;
+
+  if (mem && byte_size != 0)
+    {
+      new_mem = g_malloc (byte_size);
+      memcpy (new_mem, mem, byte_size);
+    }
+  else
+    new_mem = NULL;
+
+  return new_mem;
+}
index 3b03e98..58cd1b5 100644 (file)
@@ -49,6 +49,7 @@
 #include "gpattern.h"
 #include "grand.h"
 #include "gstrfuncs.h"
+#include "gstrfuncsprivate.h"
 #include "gtimer.h"
 #include "gslice.h"
 #include "gspawn.h"
@@ -3825,7 +3826,7 @@ g_test_log_extract (GTestLogBuffer *tbuffer)
       if (p <= tbuffer->data->str + mlength)
         {
           g_string_erase (tbuffer->data, 0, mlength);
-          tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
+          tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup2 (&msg, sizeof (msg)));
           return TRUE;
         }
 
index 6b460d8..50fae54 100644 (file)
@@ -33,6 +33,7 @@
 
 #include <string.h>
 
+#include "gstrfuncsprivate.h"
 
 /**
  * SECTION:gvariant
@@ -725,7 +726,7 @@ g_variant_new_variant (GVariant *value)
   g_variant_ref_sink (value);
 
   return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
-                                      g_memdup (&value, sizeof value),
+                                      g_memdup2 (&value, sizeof value),
                                       1, g_variant_is_trusted (value));
 }
 
@@ -1229,7 +1230,7 @@ g_variant_new_fixed_array (const GVariantType  *element_type,
       return NULL;
     }
 
-  data = g_memdup (elements, n_elements * element_size);
+  data = g_memdup2 (elements, n_elements * element_size);
   value = g_variant_new_from_data (array_type, data,
                                    n_elements * element_size,
                                    FALSE, g_free, data);
@@ -1912,7 +1913,7 @@ g_variant_dup_bytestring (GVariant *value,
   if (length)
     *length = size;
 
-  return g_memdup (original, size + 1);
+  return g_memdup2 (original, size + 1);
 }
 
 /**
index c46f1a2..585e29a 100644 (file)
@@ -28,6 +28,7 @@
 
 #include <string.h>
 
+#include "gstrfuncsprivate.h"
 
 /**
  * SECTION:gvarianttype
@@ -1181,7 +1182,7 @@ g_variant_type_new_tuple (const GVariantType * const *items,
   g_assert (offset < sizeof buffer);
   buffer[offset++] = ')';
 
-  return (GVariantType *) g_memdup (buffer, offset);
+  return (GVariantType *) g_memdup2 (buffer, offset);
 }
 
 /**
index 7e0edb9..7a35b7d 100644 (file)
@@ -284,6 +284,7 @@ glib_sources = files(
   'gslist.c',
   'gstdio.c',
   'gstrfuncs.c',
+  'gstrfuncsprivate.h',
   'gstring.c',
   'gstringchunk.c',
   'gtestutils.c',
index e6d6059..9c27c51 100644 (file)
@@ -29,6 +29,8 @@
 #include <string.h>
 #include "glib.h"
 
+#include "gstrfuncsprivate.h"
+
 /* Test data to be passed to any function which calls g_array_new(), providing
  * the parameters for that call. Most #GArray tests should be repeated for all
  * possible values of #ArrayTestData. */
@@ -1933,7 +1935,7 @@ byte_array_new_take (void)
   GByteArray *gbarray;
   guint8 *data;
 
-  data = g_memdup ("woooweeewow", 11);
+  data = g_memdup2 ("woooweeewow", 11);
   gbarray = g_byte_array_new_take (data, 11);
   g_assert (gbarray->data == data);
   g_assert_cmpuint (gbarray->len, ==, 11);
index 149d223..88d2b80 100644 (file)
@@ -27,6 +27,8 @@
 #include <string.h>
 #include <locale.h>
 
+#include "gstrfuncsprivate.h"
+
 static GOptionEntry main_entries[] = {
   { "main-switch", 0, 0,
     G_OPTION_ARG_NONE, NULL,
@@ -256,7 +258,7 @@ join_stringv (int argc, char **argv)
 static char **
 copy_stringv (char **argv, int argc)
 {
-  return g_memdup (argv, sizeof (char *) * (argc + 1));
+  return g_memdup2 (argv, sizeof (char *) * (argc + 1));
 }
 
 static void
@@ -2323,7 +2325,7 @@ test_group_parse (void)
   g_option_context_add_group (context, group);
 
   argv = split_string ("program --test arg1 -f arg2 --group-test arg3 --frob arg4 -z arg5", &argc);
-  orig_argv = g_memdup (argv, (argc + 1) * sizeof (char *));
+  orig_argv = g_memdup2 (argv, (argc + 1) * sizeof (char *));
 
   retval = g_option_context_parse (context, &argc, &argv, &error);
 
index 3947fdf..1888835 100644 (file)
@@ -34,6 +34,8 @@
 #include <string.h>
 #include "glib.h"
 
+#include "gstrfuncsprivate.h"
+
 #if defined (_MSC_VER) && (_MSC_VER <= 1800)
 #define isnan(x) _isnan(x)
 
@@ -221,6 +223,26 @@ test_memdup (void)
   g_free (str_dup);
 }
 
+/* Testing g_memdup2() function with various positive and negative cases */
+static void
+test_memdup2 (void)
+{
+  gchar *str_dup = NULL;
+  const gchar *str = "The quick brown fox jumps over the lazy dog";
+
+  /* Testing negative cases */
+  g_assert_null (g_memdup2 (NULL, 1024));
+  g_assert_null (g_memdup2 (str, 0));
+  g_assert_null (g_memdup2 (NULL, 0));
+
+  /* Testing normal usage cases */
+  str_dup = g_memdup2 (str, strlen (str) + 1);
+  g_assert_nonnull (str_dup);
+  g_assert_cmpstr (str, ==, str_dup);
+
+  g_free (str_dup);
+}
+
 /* Testing g_strpcpy() function with various positive and negative cases */
 static void
 test_stpcpy (void)
@@ -2541,6 +2563,7 @@ main (int   argc,
   g_test_add_func ("/strfuncs/has-prefix", test_has_prefix);
   g_test_add_func ("/strfuncs/has-suffix", test_has_suffix);
   g_test_add_func ("/strfuncs/memdup", test_memdup);
+  g_test_add_func ("/strfuncs/memdup2", test_memdup2);
   g_test_add_func ("/strfuncs/stpcpy", test_stpcpy);
   g_test_add_func ("/strfuncs/str_match_string", test_str_match_string);
   g_test_add_func ("/strfuncs/str_tokenize_and_fold", test_str_tokenize_and_fold);
index b8a0c6a..c03669b 100644 (file)
@@ -27,6 +27,8 @@
 #include <string.h>
 #include <stdlib.h>
 
+#include "gstrfuncsprivate.h"
+
 typedef struct
 {
   char *filename;
@@ -409,7 +411,7 @@ test_uri_unescape_bytes (gconstpointer test_data)
       else
         {
           escaped_len = strlen (tests[i].escaped);  /* no trailing nul */
-          escaped = g_memdup (tests[i].escaped, escaped_len);
+          escaped = g_memdup2 (tests[i].escaped, escaped_len);
         }
 
       bytes = g_uri_unescape_bytes (escaped, escaped_len, tests[i].illegal, &error);
@@ -1506,7 +1508,7 @@ test_uri_iter_params (gconstpointer test_data)
       else
         {
           uri_len = strlen (params_tests[i].uri);  /* no trailing nul */
-          uri = g_memdup (params_tests[i].uri, uri_len);
+          uri = g_memdup2 (params_tests[i].uri, uri_len);
         }
 
       /* Run once without extracting the attr or value, just to check the numbers. */
@@ -1573,7 +1575,7 @@ test_uri_parse_params (gconstpointer test_data)
       else
         {
           uri_len = strlen (params_tests[i].uri);  /* no trailing nul */
-          uri = g_memdup (params_tests[i].uri, uri_len);
+          uri = g_memdup2 (params_tests[i].uri, uri_len);
         }
 
       params = g_uri_parse_params (uri, uri_len, params_tests[i].separators, params_tests[i].flags, &err);
index 41599eb..ff39866 100644 (file)
@@ -28,6 +28,7 @@
 #include <signal.h>
 
 #include "gsignal.h"
+#include "gstrfuncsprivate.h"
 #include "gtype-private.h"
 #include "gbsearcharray.h"
 #include "gvaluecollector.h"
@@ -1805,7 +1806,7 @@ g_signal_newv (const gchar       *signal_name,
   node->single_va_closure_is_valid = FALSE;
   node->flags = signal_flags & G_SIGNAL_FLAGS_MASK;
   node->n_params = n_params;
-  node->param_types = g_memdup (param_types, sizeof (GType) * n_params);
+  node->param_types = g_memdup2 (param_types, sizeof (GType) * n_params);
   node->return_type = return_type;
   node->class_closure_bsa = NULL;
   if (accumulator)
index 723675d..5c3663a 100644 (file)
@@ -33,6 +33,7 @@
 
 #include "glib-private.h"
 #include "gconstructor.h"
+#include "gstrfuncsprivate.h"
 
 #ifdef G_OS_WIN32
 #include <windows.h>
@@ -1470,7 +1471,7 @@ type_add_interface_Wm (TypeNode             *node,
   iholder->next = iface_node_get_holders_L (iface);
   iface_node_set_holders_W (iface, iholder);
   iholder->instance_type = NODE_TYPE (node);
-  iholder->info = info ? g_memdup (info, sizeof (*info)) : NULL;
+  iholder->info = info ? g_memdup2 (info, sizeof (*info)) : NULL;
   iholder->plugin = plugin;
 
   /* create an iface entry for this type */
@@ -1731,7 +1732,7 @@ type_iface_retrieve_holder_info_Wm (TypeNode *iface,
         INVALID_RECURSION ("g_type_plugin_*", iholder->plugin, NODE_NAME (iface));
       
       check_interface_info_I (iface, instance_type, &tmp_info);
-      iholder->info = g_memdup (&tmp_info, sizeof (tmp_info));
+      iholder->info = g_memdup2 (&tmp_info, sizeof (tmp_info));
     }
   
   return iholder;      /* we don't modify write lock upon returning NULL */
@@ -2016,10 +2017,10 @@ type_iface_vtable_base_init_Wm (TypeNode *iface,
       IFaceEntry *pentry = type_lookup_iface_entry_L (pnode, iface);
       
       if (pentry)
-       vtable = g_memdup (pentry->vtable, iface->data->iface.vtable_size);
+       vtable = g_memdup2 (pentry->vtable, iface->data->iface.vtable_size);
     }
   if (!vtable)
-    vtable = g_memdup (iface->data->iface.dflt_vtable, iface->data->iface.vtable_size);
+    vtable = g_memdup2 (iface->data->iface.dflt_vtable, iface->data->iface.vtable_size);
   entry->vtable = vtable;
   vtable->g_type = NODE_TYPE (iface);
   vtable->g_instance_type = NODE_TYPE (node);
index 4ecaf8c..20911fa 100644 (file)
@@ -19,6 +19,7 @@
 
 #include <stdlib.h>
 
+#include "gstrfuncsprivate.h"
 #include "gtypeplugin.h"
 #include "gtypemodule.h"
 
@@ -436,7 +437,7 @@ g_type_module_register_type (GTypeModule     *module,
   module_type_info->loaded = TRUE;
   module_type_info->info = *type_info;
   if (type_info->value_table)
-    module_type_info->info.value_table = g_memdup (type_info->value_table,
+    module_type_info->info.value_table = g_memdup2 (type_info->value_table,
                                                   sizeof (GTypeValueTable));
 
   return module_type_info->type;
index 1bfdaff..fdb56a8 100644 (file)
@@ -5,6 +5,8 @@
 #include <glib-object.h>
 #include <stdlib.h>
 
+#include "gstrfuncsprivate.h"
+
 static void
 test_param_value (void)
 {
@@ -903,7 +905,7 @@ main (int argc, char *argv[])
             test_path = g_strdup_printf ("/param/implement/subprocess/%d-%d-%d-%d",
                                          data.change_this_flag, data.change_this_type,
                                          data.use_this_flag, data.use_this_type);
-            test_data = g_memdup (&data, sizeof (TestParamImplementData));
+            test_data = g_memdup2 (&data, sizeof (TestParamImplementData));
             g_test_add_data_func_full (test_path, test_data, test_param_implement_child, g_free);
             g_free (test_path);
           }
index f334219..ac9f739 100644 (file)
@@ -1,5 +1,5 @@
 project('glib', 'c', 'cpp',
-  version : '2.66.5',
+  version : '2.66.6',
   # NOTE: We keep this pinned at 0.49 because that's what Debian 10 ships
   meson_version : '>= 0.49.2',
   default_options : [