e2ec8a
From 9b9b6d8c7b10c069d36f85bd17f144011282cb58 Mon Sep 17 00:00:00 2001
e2ec8a
From: Michal Sekletar <msekleta@redhat.com>
e2ec8a
Date: Tue, 22 Jan 2019 14:29:50 +0100
e2ec8a
Subject: [PATCH] process-util: don't use overly large buffer to store process
e2ec8a
 command line
e2ec8a
e2ec8a
Allocate new string as a return value and free our "scratch pad"
e2ec8a
buffer that is potentially much larger than needed (up to
e2ec8a
_SC_ARG_MAX).
e2ec8a
e2ec8a
Fixes #11502
e2ec8a
e2ec8a
(cherry-picked from commit eb1ec489eef8a32918bbfc56a268c9d10464584d)
e2ec8a
e2ec8a
Related: #1664976
e2ec8a
---
e2ec8a
 src/basic/process-util.c | 18 ++++++++++++++----
e2ec8a
 1 file changed, 14 insertions(+), 4 deletions(-)
e2ec8a
e2ec8a
diff --git a/src/basic/process-util.c b/src/basic/process-util.c
e2ec8a
index a20f1e3ccf..aa3eff779a 100644
e2ec8a
--- a/src/basic/process-util.c
e2ec8a
+++ b/src/basic/process-util.c
e2ec8a
@@ -101,7 +101,8 @@ int get_process_comm(pid_t pid, char **ret) {
e2ec8a
 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
e2ec8a
         _cleanup_fclose_ FILE *f = NULL;
e2ec8a
         bool space = false;
e2ec8a
-        char *k, *ans = NULL;
e2ec8a
+        char *k;
e2ec8a
+        _cleanup_free_ char *ans = NULL;
e2ec8a
         const char *p;
e2ec8a
         int c;
e2ec8a
 
e2ec8a
@@ -142,7 +143,7 @@ int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char *
e2ec8a
                 if (!ans)
e2ec8a
                         return -ENOMEM;
e2ec8a
 
e2ec8a
-                *line = ans;
e2ec8a
+                *line = TAKE_PTR(ans);
e2ec8a
                 return 0;
e2ec8a
 
e2ec8a
         } else {
e2ec8a
@@ -207,7 +208,7 @@ int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char *
e2ec8a
                 _cleanup_free_ char *t = NULL;
e2ec8a
                 int h;
e2ec8a
 
e2ec8a
-                free(ans);
e2ec8a
+                ans = mfree(ans);
e2ec8a
 
e2ec8a
                 if (!comm_fallback)
e2ec8a
                         return -ENOENT;
e2ec8a
@@ -240,9 +241,18 @@ int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char *
e2ec8a
                         if (!ans)
e2ec8a
                                 return -ENOMEM;
e2ec8a
                 }
e2ec8a
+
e2ec8a
+                *line = TAKE_PTR(ans);
e2ec8a
+                return 0;
e2ec8a
         }
e2ec8a
 
e2ec8a
-        *line = ans;
e2ec8a
+        k = realloc(ans, strlen(ans) + 1);
e2ec8a
+        if (!k)
e2ec8a
+                return -ENOMEM;
e2ec8a
+
e2ec8a
+        ans = NULL;
e2ec8a
+        *line = k;
e2ec8a
+
e2ec8a
         return 0;
e2ec8a
 }
e2ec8a