Blob Blame History Raw
From f0e34498a2f2e2ec6644a3af47c1b56ac5b6dec3 Mon Sep 17 00:00:00 2001
From: Ernestas Kulik <ernestask@gnome.org>
Date: Thu, 2 Aug 2018 22:29:03 +0300
Subject: [PATCH] clipboard: Prevent crash when selection data is empty

Somehow, magically, it can happen that the clipboard contains an empty
string, which wreaks havoc in convert_selection_data_to_str_list(),
since the loop counter goes from 0 to the number of lines in the data
string minus one. This commit adds a check for the number of lines and
returns early. Additionally, this introduces automatic cleanup for a
variable and fixes mismatched types.
---
 src/nautilus-clipboard.c | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/src/nautilus-clipboard.c b/src/nautilus-clipboard.c
index 752ff131f..2a77cf28f 100644
--- a/src/nautilus-clipboard.c
+++ b/src/nautilus-clipboard.c
@@ -42,23 +42,29 @@ typedef struct
 static GList *
 convert_selection_data_to_str_list (const gchar *data)
 {
-    int i;
+    g_auto (GStrv) lines;
+    guint number_of_lines;
     GList *result;
-    size_t number_of_lines;
-    gchar **lines;
 
     lines = g_strsplit (data, "\n", 0);
-    result = NULL;
     number_of_lines = g_strv_length (lines);
+    if (number_of_lines == 0)
+    {
+        /* An empty string will result in g_strsplit() returning an empty
+         * array, so, naturally, 0 - 1 = UINT32_MAX and we read all sorts
+         * of invalid memory.
+         */
+        return NULL;
+    }
+    result = NULL;
+
     /* Also, this skips the last line, since it would be an
      * empty string from the split */
-    for (i = 0; i < number_of_lines - 1; i++)
+    for (guint i = 0; i < number_of_lines - 1; i++)
     {
         result = g_list_prepend (result, g_strdup (lines[i]));
     }
 
-    g_strfreev (lines);
-
     return g_list_reverse (result);
 }
 
-- 
2.17.2