[v7] MIPS: Reject branch absolute relocs for PIC for linking

Message ID 20240222065128.3693606-1-syq@gcc.gnu.org
State Accepted
Headers
Series [v7] MIPS: Reject branch absolute relocs for PIC for linking |

Checks

Context Check Description
snail/binutils-gdb-check success Github commit url

Commit Message

YunQiang Su Feb. 22, 2024, 6:51 a.m. UTC
  The asm code like:
	b	8
will emit absolute relocs like:
	R_MIPS_PC16	*ABS*

If they are included into PIC shared objects or PIE executables,
the branch target will be like 0x12340000, which will make the
programs crash.
---
 bfd/elfxx-mips.c                                | 9 +++++++++
 ld/testsuite/ld-mips-elf/mips-elf.exp           | 1 +
 ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.d | 5 +++++
 ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.s | 2 ++
 4 files changed, 17 insertions(+)
 create mode 100644 ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.d
 create mode 100644 ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.s
  

Patch

diff --git a/bfd/elfxx-mips.c b/bfd/elfxx-mips.c
index 69dd71419ff..8527a35010e 100644
--- a/bfd/elfxx-mips.c
+++ b/bfd/elfxx-mips.c
@@ -9258,6 +9258,15 @@  _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info,
 		   (h) ? h->root.root.string : "a local symbol");
 	      break;
 	    default:
+	      if (branch_reloc_p (r_type) && r_symndx == STN_UNDEF)
+		{
+		  howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, r_type, NEWABI_P (abfd));
+		  info->callbacks->einfo
+		    /* xgettext:c-format */
+		    (_("%X%H: relocation %s against an absolute value cannot be"
+		       " used when making a PIC/PIE object\n"),
+		     abfd, sec, rel->r_offset, howto->name);
+		}
 	      break;
 	    }
 	}
diff --git a/ld/testsuite/ld-mips-elf/mips-elf.exp b/ld/testsuite/ld-mips-elf/mips-elf.exp
index 50af78d1430..a8e1b91b3a1 100644
--- a/ld/testsuite/ld-mips-elf/mips-elf.exp
+++ b/ld/testsuite/ld-mips-elf/mips-elf.exp
@@ -1678,6 +1678,7 @@  run_dump_test_o32 "pic-reloc-6"
 run_dump_test_n64 "pic-reloc-7"
 run_dump_test_n64 "pic-reloc-7" [list [list name (microMIPS)] \
 				      [list as "-mmicromips"]]
+run_dump_test "pic-reject-abs-reloc"
 
 run_dump_test_o32 "reloc-pcrel-r6"
 
diff --git a/ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.d b/ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.d
new file mode 100644
index 00000000000..b18c2698f81
--- /dev/null
+++ b/ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.d
@@ -0,0 +1,5 @@ 
+#name: MIPS PIC rejects branch absolute
+#ld: -shared -T pic-reloc-absolute-lo.ld
+#target: [check_shared_lib_support]
+#error: \A[^\n]*: in function `foo':\n
+#error:   \(\.text\+0x0\): relocation R_MIPS_PC16 against an absolute value cannot be used when making a PIC/PIE object
diff --git a/ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.s b/ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.s
new file mode 100644
index 00000000000..a845fd50a77
--- /dev/null
+++ b/ld/testsuite/ld-mips-elf/pic-reject-abs-reloc.s
@@ -0,0 +1,2 @@ 
+foo:
+	b	8