Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <a3ed1efc-7a3e-4c69-b9c2-9ed6e9a97d69@ispras.ru>
Date: Fri, 10 Mar 2023 19:28:18 +0300 (MSK)
From: Alexander Monakov <amonakov@...ras.ru>
To: musl@...ts.openwall.com
Subject: Re: [PATCH] getopt: fix null pointer arithmetic ub

Hi,

On Fri, 10 Mar 2023, Alexey Izbyshev wrote:

> When an option that requires an argument is the last character of
> argv[argc-1], getopt computes argv[argc] + optpos. While optpos
> is always zero in this case, adding it to null pointer is still
> undefined.
> ---
>  src/misc/getopt.c | 3 ++-
>  1 file changed, 2 insertions(+), 1 deletion(-)
> 
> diff --git a/src/misc/getopt.c b/src/misc/getopt.c
> index c3f66995..af12973a 100644
> --- a/src/misc/getopt.c
> +++ b/src/misc/getopt.c
> @@ -87,7 +87,8 @@ int getopt(int argc, char * const argv[], const char *optstring)
>  	if (optstring[i] == ':') {
>  		optarg = 0;
>  		if (optstring[i+1] != ':' || optpos) {
> -			optarg = argv[optind++] + optpos;
> +			optarg = argv[optind++];
> +			if (optarg) optarg += optpos;

Can this be written as 'if (optpos) optarg += optpos;' instead? That will be
folded back into plain addition by the compiler.

(also (unlike the quoted variant) would allow undefined behavior
instrumentation to catch attempted NULL pointer arithmetic)

Alexander

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.