Description: This patch fixes a bug causing pgrep to fail with a large ulimit
 Changes to the kernel have caused the value of sysconf(_SC_ARG_MAX) to become
 larger than we can alloc. This patch sets the new size for the mallocs to a
 value between 4096 (POSIX_ARG_MAX) and 128kB. The upper limit was chosen
 to maintain similarity between xargs and other related libraries.
Origin: upstream, https://gitlab.com/procps-ng/procps/-/commit/bb96fc42956c9ed926a1b958ab715f8b4a663dec
Bug: https://gitlab.com/procps-ng/procps/-/issues/152
Bug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/procps/+bug/1874824
Last-Update: 2021-03-24
---
This patch header follows DEP-3: http://dep.debian.net/deps/dep3/
--- a/pgrep.c
+++ b/pgrep.c
@@ -485,6 +485,27 @@
 	return preg;
 }
 
+/*
+ * SC_ARG_MAX used to return the maximum size a command line can be
+ * however changes to the kernel mean this can be bigger than we can
+ * alloc. Clamp it to 128kB like xargs and friends do
+ * Should also not be smaller than POSIX_ARG_MAX which is 4096
+ */
+static size_t get_arg_max(void)
+{
+#define MIN_ARG_SIZE 4096u
+#define MAX_ARG_SIZE (128u * 1024u)
+
+    size_t val = sysconf(_SC_ARG_MAX);
+
+    if (val < MIN_ARG_SIZE)
+	val = MIN_ARG_SIZE;
+    if (val > MAX_ARG_SIZE)
+	val = MAX_ARG_SIZE;
+
+    return val;
+}
+
 static struct el * select_procs (int *num)
 {
 	PROCTAB *ptp;
@@ -497,7 +518,7 @@
 	regex_t *preg;
 	pid_t myself = getpid();
 	struct el *list = NULL;
-        long cmdlen = sysconf(_SC_ARG_MAX) * sizeof(char);
+        long cmdlen = get_arg_max() * sizeof(char);
 	char *cmdline = xmalloc(cmdlen);
 	char *cmdsearch = xmalloc(cmdlen);
 	char *cmdoutput = xmalloc(cmdlen);
