When parsing target attributes, if an invalid architecture string is
provided, the function parse_single_ext may return nullptr. The existing
code does not check for this case, leading to a nullptr dereference when
attempting to access the returned pointer. This patch adds a check to
ensure that the returned pointer is not nullptr before dereferencing it.
If it is nullptr, an appropriate error message is generated.

Fixes: aa8e2de78cae ("RISC-V: Rewrite target attribute handling")
Signed-off-by: Yangyu Chen <[email protected]>

gcc/ChangeLog:

        * 
config/riscv/riscv-target-attr.cc(riscv_target_attr_parser::parse_arch): Fix 
nullptr dereference when parsing invalid arch string.

gcc/testsuite/ChangeLog:

        * gcc.target/riscv/target-attr-bad-11.c: New test.
---
Note: This patch need to be backported to GCC 14 and 15 branches as well.

This is also an subset of another patch:
https://patchwork.sourceware.org/project/gcc/patch/[email protected]/
---
 gcc/config/riscv/riscv-target-attr.cc               | 2 +-
 gcc/testsuite/gcc.target/riscv/target-attr-bad-11.c | 8 ++++++++
 2 files changed, 9 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/gcc.target/riscv/target-attr-bad-11.c

diff --git a/gcc/config/riscv/riscv-target-attr.cc 
b/gcc/config/riscv/riscv-target-attr.cc
index 99af5308fea4..683b2a02f807 100644
--- a/gcc/config/riscv/riscv-target-attr.cc
+++ b/gcc/config/riscv/riscv-target-attr.cc
@@ -156,7 +156,7 @@ riscv_target_attr_parser::parse_arch (const char *str)
 
          const char *result = m_subset_list->parse_single_ext (token + 1);
          /* Check parse_single_ext has consume all string.  */
-         if (*result != '\0')
+         if (result == nullptr || *result != '\0')
            {
              if (m_loc)
                error_at (*m_loc, "unexpected arch for %<target()%> "
diff --git a/gcc/testsuite/gcc.target/riscv/target-attr-bad-11.c 
b/gcc/testsuite/gcc.target/riscv/target-attr-bad-11.c
new file mode 100644
index 000000000000..92da82ffc97c
--- /dev/null
+++ b/gcc/testsuite/gcc.target/riscv/target-attr-bad-11.c
@@ -0,0 +1,8 @@
+/* { dg-do compile } */
+/* { dg-skip-if "" { *-*-* } { "-fno-fat-lto-objects" } } */
+/* { dg-options "-march=rv64gc -O2 -mabi=lp64" } */
+
+long foo(long a, long b) __attribute__((target("arch=+randomstring"))); /* { 
dg-error "unexpected arch for 'target\\(\\)' attribute: bad string found 
'\\+randomstring'" } */
+long foo(long a, long b){
+  return a + (b * 2);
+}
-- 
2.51.0

Reply via email to