Commit 169bed74 authored by René Scharfe's avatar René Scharfe Committed by Junio C Hamano

parse-options: avoid arithmetic on pointer that's potentially NULL

parse_options_dup() counts the number of elements in the given array
without the end marker, allocates enough memory to hold all of them plus
an end marker, then copies them and terminates the new array.  The
counting part is done by advancing a pointer through the array, and the
original pointer is reconstructed using pointer subtraction before the
copy operation.

The function is also prepared to handle a NULL pointer passed to it.
None of its callers do that currently, but this feature was used by
46e91b66 ("checkout: split part of it to new command 'restore'",
2019-04-25); it seems worth keeping.

It ends up doing arithmetic on that NULL pointer, though, which is
undefined in standard C, when it tries to calculate "NULL - 0".  Better
avoid doing that by remembering the originally given pointer value.

There is another issue, though.  memcpy(3) does not support NULL
pointers, even for empty arrays.  Use COPY_ARRAY instead, which does
support such empty arrays.  Its call is also shorter and safer by
inferring the element type automatically.

Coccinelle and contrib/coccinelle/array.cocci did not propose to use
COPY_ARRAY because of the pointer subtraction and because the source is
const -- the semantic patch cautiously only considers pointers and array
references of the same type.
Signed-off-by: default avatarRené Scharfe <l.s.r@web.de>
Signed-off-by: default avatarJunio C Hamano <gitster@pobox.com>
parent 5fa0f523
......@@ -161,6 +161,7 @@ int parse_opt_tertiary(const struct option *opt, const char *arg, int unset)
struct option *parse_options_dup(const struct option *o)
{
const struct option *orig = o;
struct option *opts;
int nr = 0;
......@@ -170,7 +171,7 @@ struct option *parse_options_dup(const struct option *o)
}
ALLOC_ARRAY(opts, nr + 1);
memcpy(opts, o - nr, sizeof(*o) * nr);
COPY_ARRAY(opts, orig, nr);
memset(opts + nr, 0, sizeof(*opts));
opts[nr].type = OPTION_END;
return opts;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment