# HG changeset patch
# Parent  a84c8fe05da6097efaa00d8dee8a07b5816ae84e
Don't assume that argv is allocated as a single flat buffer.
While this is how the kernel behaves it is not a portable assumption.
The assumption may also be violated if getopt_long(3) permutes arguments.
Found by Qualys.

--- a/src/parse_args.c
+++ b/src/parse_args.c
@@ -591,16 +591,16 @@ parse_args(int argc, char **argv, int *o
 	if (argc != 0) {
 	    /* shell -c "command" */
 	    char *src, *dst;
-	    size_t cmnd_size = (size_t) (argv[argc - 1] - argv[0]) +
-		strlen(argv[argc - 1]) + 1;
+	    size_t size = 0;
 
-	    cmnd = dst = reallocarray(NULL, cmnd_size, 2);
-	    if (cmnd == NULL)
+	    for (av = argv; *av != NULL; av++)
+		size += strlen(*av) + 1;
+	    if (size == 0 || (cmnd = reallocarray(NULL, size, 2)) == NULL)
 		sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
 	    if (!gc_add(GC_PTR, cmnd))
 		exit(EXIT_FAILURE);
 
-	    for (av = argv; *av != NULL; av++) {
+	    for (dst = cmnd, av = argv; *av != NULL; av++) {
 		for (src = *av; *src != '\0'; src++) {
 		    /* quote potential meta characters */
 		    if (!isalnum((unsigned char)*src) && *src != '_' && *src != '-' && *src != '$')
