rev-parse --parseopt: detect missing opt-spec

After 2d893dff4c (rev-parse --parseopt: allow [*=?!] in argument hints, 2015-07-14) updated the parser, a line in parseopts's input can start with one of the flag characters and be erroneously parsed as a opt-spec where the short name of the option is the flag character itself and the long name is after the end of the string. This makes Git want to allocate SIZE_MAX bytes of memory at this line: o->long_name = xmemdupz(sb.buf + 2, s - sb.buf - 2); Since s and sb.buf are equal the second argument is -2 (except unsigned) and xmemdupz allocates len + 1 bytes, ie. -1 meaning SIZE_MAX. Avoid this by checking whether a flag character was found in the zeroth position. Reported-by: Ingy dot Net <ingy@ingy.net> Signed-off-by: Øystein Walle <oystwa@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Øystein Walle committed Sep 2, 2022 at 19:59 UTC f20b9c36d034fe37715d18ef67183cf5544227a7
2 files changed +10
builtin/rev-parse.c
+3
@@ -479,6 +479,9 @@ static int cmd_parseopt(int argc, const char **argv, const char *prefix)
479 if (!s)
480 s = help;
481
482 + if (s == sb.buf)
483 + die(_("missing opt-spec before option flags"));
484 +
485 if (s - sb.buf == 1) /* short option only */
486 o->short_name = *sb.buf;
487 else if (sb.buf[1] != ',') /* long option only */
t/t1502-rev-parse-parseopt.sh
+7
@@ -306,6 +306,13 @@ test_expect_success 'test --parseopt help output: "wrapped" options normal "or:"
306 test_cmp expect actual
307 '
308
309 +test_expect_success 'test --parseopt invalid opt-spec' '
310 + test_write_lines x -- "=, x" >spec &&
311 + echo "fatal: missing opt-spec before option flags" >expect &&
312 + test_must_fail git rev-parse --parseopt -- >out <spec 2>err &&
313 + test_cmp expect err
314 +'
315 +
316 test_expect_success 'test --parseopt help output: multi-line blurb after empty line' '
317 sed -e "s/^|//" >spec <<-\EOF &&
318 |cmd [--some-option]