From e63ad8aeb72c21a00397d2366cb89d65e638b39c Mon Sep 17 00:00:00 2001
From: "H.J. Lu" <hjl.tools@gmail.com>
Date: Sun, 30 Nov 2025 15:32:53 +0800
Subject: [PATCH] mips: Assert dynamic symbol counts only with dynamic sections

After

commit 54fbc12d6404b645363f901110a21f4410067df5
Author: H.J. Lu <hjl.tools@gmail.com>
Date:   Fri Nov 28 16:07:57 2025 +0800

    elf: Renumber local dynamic symbols only if needed

mips-linux got

FAIL: MIPS magic __ehdr_start symbol test 1 (o32)
FAIL: PR ld/21334 MIPS GOT16 relocation in static binary

with assertion failures on

BFD_ASSERT (hsd.max_local_dynindx <= htab->root.local_dynsymcount + 1);

Since there are dynamic symbols only if there are dynamic sections,
assert dynamic symbol counts only if there are dynamic sections.

	* elfxx-mips.c (mips_elf_sort_hash_table): Assert dynamic symbol
	counts only if there are dynamic sections.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
---
 bfd/elfxx-mips.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/bfd/elfxx-mips.c b/bfd/elfxx-mips.c
index e37c45fec15..fe896839d76 100644
--- a/bfd/elfxx-mips.c
+++ b/bfd/elfxx-mips.c
@@ -4034,12 +4034,15 @@ mips_elf_sort_hash_table (bfd *abfd, struct bfd_link_info *info)
     hsd.mipsxhash = NULL;
   mips_elf_link_hash_traverse (htab, mips_elf_sort_hash_table_f, &hsd);
 
-  /* There should have been enough room in the symbol table to
-     accommodate both the GOT and non-GOT symbols.  */
-  BFD_ASSERT (hsd.max_local_dynindx <= htab->root.local_dynsymcount + 1);
-  BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
-  BFD_ASSERT (hsd.max_unref_got_dynindx == htab->root.dynsymcount);
-  BFD_ASSERT (htab->root.dynsymcount - hsd.min_got_dynindx == g->global_gotno);
+  if (htab->root.dynamic_sections_created)
+    {
+      /* There should have been enough room in the symbol table to
+	 accommodate both the GOT and non-GOT symbols.  */
+      BFD_ASSERT (hsd.max_local_dynindx <= htab->root.local_dynsymcount + 1);
+      BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
+      BFD_ASSERT (hsd.max_unref_got_dynindx == htab->root.dynsymcount);
+      BFD_ASSERT (htab->root.dynsymcount - hsd.min_got_dynindx == g->global_gotno);
+    }
 
   /* Now we know which dynamic symbol has the lowest dynamic symbol
      table index in the GOT.  */
-- 
2.52.0

