[pushed] Fix ubsan error in opts-global.cc

Message ID d13f6bf4-0c06-a7ec-c1b9-f8760bf65c3d@suse.cz
State Committed
Commit ec69db6be6912e45fa5f54f2d231d56e52612f1d
Headers
Series [pushed] Fix ubsan error in opts-global.cc |

Commit Message

Martin Liška May 16, 2022, 7:52 a.m. UTC
  Fixes:
opts-global.cc:75:15: runtime error: store to address 0x00000bc9be70 with insufficient space for an object of type 'char'
which happens when mask == 0, len == 0 and we allocate zero elements.
Eventually, result[0] is called which triggers the UBSAN.

It's newly discovered after the Siddhesh's recent patch.

Cheers,
Martin

gcc/ChangeLog:

	* opts-global.cc (write_langs): Allocate at least one byte.
---
 gcc/opts-global.cc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
  

Comments

Richard Biener May 16, 2022, 9:01 a.m. UTC | #1
On Mon, May 16, 2022 at 9:53 AM Martin Liška <mliska@suse.cz> wrote:
>
> Fixes:
> opts-global.cc:75:15: runtime error: store to address 0x00000bc9be70 with insufficient space for an object of type 'char'
> which happens when mask == 0, len == 0 and we allocate zero elements.
> Eventually, result[0] is called which triggers the UBSAN.
>
> It's newly discovered after the Siddhesh's recent patch.
>
> Cheers,
> Martin
>
> gcc/ChangeLog:
>
>         * opts-global.cc (write_langs): Allocate at least one byte.
> ---
>  gcc/opts-global.cc | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/gcc/opts-global.cc b/gcc/opts-global.cc
> index a18c76940f9..4f5f8cdcb98 100644
> --- a/gcc/opts-global.cc
> +++ b/gcc/opts-global.cc
> @@ -61,7 +61,7 @@ write_langs (unsigned int mask)
>      if (mask & (1U << n))
>        len += strlen (lang_name) + 1;
>
> -  result = XNEWVEC (char, len);
> +  result = XNEWVEC (char, MAX (1, len));

Does it not fail to allocate space for the '\0' it terminates the
list with even when there's a language?  Ah, it "re-uses" the
byte it allocates for the '/' of the first element.

Can you add a comment?

OK with that change.

Richard.

>    len = 0;
>    for (n = 0; (lang_name = lang_names[n]) != 0; n++)
>      if (mask & (1U << n))
> --
> 2.36.1
>
  

Patch

diff --git a/gcc/opts-global.cc b/gcc/opts-global.cc
index a18c76940f9..4f5f8cdcb98 100644
--- a/gcc/opts-global.cc
+++ b/gcc/opts-global.cc
@@ -61,7 +61,7 @@  write_langs (unsigned int mask)
     if (mask & (1U << n))
       len += strlen (lang_name) + 1;
 
-  result = XNEWVEC (char, len);
+  result = XNEWVEC (char, MAX (1, len));
   len = 0;
   for (n = 0; (lang_name = lang_names[n]) != 0; n++)
     if (mask & (1U << n))