[binutils-gdb] check bfd_alloc/bfd_malloc return in elflink.c

Alan Modra via Binutils-cvs <[email protected]> Sat, 13 Jun 2026 06:49:21 +0000 (GMT)
Newsgroups gmane.comp.gnu.binutils.cvs
Message-ID <[email protected]>
https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=e0fe0e3abde305a34de82134b7d8a7fa153d1897

commit e0fe0e3abde305a34de82134b7d8a7fa153d1897
Author: Alan Modra <[email protected]>
Date:   Fri Jun 12 23:23:48 2026 +0930

    check bfd_alloc/bfd_malloc return in elflink.c
    
    Add checks in a couple of places for a non-NULL return.  While we're
    at it, don't use sprintf to concatenate two strings.
    
            * elflink.c (bfd_elf_link_record_dynamic_symbol): Check than
            bfd_malloc returns non-NULL.
            (get_dynamic_reloc_section_name): Similarly check bfd_alloc.
            Replace sprintf with two memcpys.  Remove old_name NULL check.

Diff:
---
 bfd/elflink.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/bfd/elflink.c b/bfd/elflink.c
index 3c4332b549a..290fc5f2031 100644
--- a/bfd/elflink.c
+++ b/bfd/elflink.c
@@ -653,6 +653,8 @@ bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
       if (p != NULL)
 	{
 	  unversioned_name = bfd_malloc (p - name + 1);
+	  if (unversioned_name == NULL)
+	    return false;
 	  memcpy (unversioned_name, name, p - name);
 	  unversioned_name[p - name] = 0;
 	  name = unversioned_name;
@@ -15569,16 +15571,16 @@ get_dynamic_reloc_section_name (bfd *       abfd,
 				asection *  sec,
 				bool is_rela)
 {
-  char *name;
-  const char *old_name = bfd_section_name (sec);
   const char *prefix = is_rela ? ".rela" : ".rel";
-
-  if (old_name == NULL)
+  size_t plen = is_rela ? 5 : 4;
+  const char *old_name = bfd_section_name (sec);
+  size_t nlen = strlen (old_name);
+  char *name = bfd_alloc (abfd, plen + nlen + 1);
+  if (name == NULL)
     return NULL;
 
-  name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
-  sprintf (name, "%s%s", prefix, old_name);
-
+  memcpy (name, prefix, plen);
+  memcpy (name + plen, old_name, nlen + 1);
   return name;
 }