[PATCH] bfd: Validate common symbol alignment before bfd_log2 to avoid UB [PR binutils/34996]

Haolin Xue 762233433@qq.com
Fri Nov 20 03:35:30 GMT 2026


A malformed ELF object with a common symbol whose st_value is not a
power of two (e.g., 0xffffff000000ffff) causes bfd_log2 to return 64,
which then triggers undefined behavior at the 1 << alignment_power
shift (elflink.c:10992).

Add validation guards at both bfd_log2(isym->st_value) call sites in
elf_link_add_object_symbols:
  - elflink.c:5465 (initial common symbol alignment)
  - elflink.c:5593 (common alignment when overridden by normal definition)

Reject st_value that is zero, not a power of two, or >= 2^31,
reporting the offending object and symbol name.

The >= 2^31 bound avoids a second UB at elflink.c:10992 where
'1 << alignment_power' with alignment_power=31 would overflow int.
Both guards use goto error_free_vers to properly free isymbuf and
related allocations, consistent with other error paths in the function.

Based on the fix suggested by the bug reporter in PR binutils/34996
(text suggestion only; reporter did not attach a patch).
Extended to cover the second call site at line 5593.

	PR binutils/34996
	* elflink.c (elf_link_add_object_symbols): Validate isym->st_value
	before bfd_log2 at both call sites.  Use error_free_vers for cleanup.

Signed-off-by: Haolin Xue <xuehaolin@uniontech.com>
---
 bfd/elflink.c | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/bfd/elflink.c b/bfd/elflink.c
index 1eef868be49..98e7dc61826 100644
--- a/bfd/elflink.c
+++ b/bfd/elflink.c
@@ -5462,7 +5462,20 @@ elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
 	  unsigned int align;
 
 	  if (common)
-	    align = bfd_log2 (isym->st_value);
+	    {
+	      if (isym->st_value == 0
+		  || (isym->st_value & (isym->st_value - 1)) != 0
+		  || isym->st_value >= (bfd_vma) 1 << 31)
+		{
+		  _bfd_error_handler
+		    /* xgettext:c-format */
+		    (_("%pB: common symbol `%s' has invalid alignment 0x%lx"),
+		     abfd, name, (unsigned long) isym->st_value);
+		  bfd_set_error (bfd_error_bad_value);
+		  goto error_free_vers;
+		}
+	      align = bfd_log2 (isym->st_value);
+	    }
 	  else
 	    {
 	      /* The new symbol is a common symbol in a shared object.
@@ -5590,6 +5603,17 @@ elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
 		}
 	      else
 		{
+		  if (isym->st_value == 0
+		      || (isym->st_value & (isym->st_value - 1)) != 0
+		      || isym->st_value >= (bfd_vma) 1 << 31)
+		    {
+		      _bfd_error_handler
+			/* xgettext:c-format */
+			(_("%pB: common symbol `%s' has invalid alignment 0x%lx"),
+			 abfd, name, (unsigned long) isym->st_value);
+		      bfd_set_error (bfd_error_bad_value);
+		      goto error_free_vers;
+		    }
 		  common_align = bfd_log2 (isym->st_value);
 		  common_bfd = abfd;
 		  normal_bfd = old_bfd;
-- 
2.43.0



More information about the Binutils mailing list