From patchwork Wed Sep 9 17:05:08 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Adhemerval Zanella X-Patchwork-Id: 143249 X-Patchwork-Delegate: fweimer@redhat.com Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from vm01.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id BAEB34BB3B98 for ; Wed, 9 Sep 2026 17:06:12 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org BAEB34BB3B98 Authentication-Results: sourceware.org; dkim=pass (2048-bit key, unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=VVn+aYfQ X-Original-To: libc-alpha@sourceware.org Delivered-To: libc-alpha@sourceware.org Received: from mail-pj2-x10.google.com (mail-pj2-x10.google.com [IPv6:2607:f8b0:4864:39::10]) by sourceware.org (Postfix) with ESMTPS id 394604BA902F for ; Wed, 9 Sep 2026 17:05:34 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 394604BA902F Authentication-Results: sourceware.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=linaro.org ARC-Filter: OpenARC Filter v1.0.0 sourceware.org 394604BA902F Authentication-Results: sourceware.org; arc=none smtp.remote-ip=2607:f8b0:4864:39::10 ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1788973534; cv=none; b=m8NoWeNP7hneJcyuWyzYaLgr1GQBuJMFWKjnY1mQans2/Fyfae3JJmcqnEn0w1fgEI6P99+KSGpM9dET2VTCScWBXs91dzDlipjmS/JQDvjmdkZ5spDYymNl5F8ntJJgQJx9QaYschrnx52XGLdNmuSFWaGOoUMvvbaDLNmB4Y0= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1788973534; c=relaxed/simple; bh=Wh9oi9d8WFR+89Iu3eGWxvykvdWVM4A2p49wnUMJeBw=; h=DKIM-Signature:From:To:Subject:Date:Message-ID:MIME-Version; b=LQexiYsGCIt0dr9XWsq4Q0JE3NNnSiP1rLcfKLUDrRPIlC3M8PuylPYn3ghTZmGIqMbAXB0hFBjvAaDuQvxnicNGG9v9nrjrauZGjEYtpKkMbwpupbTrvM3BbSM5c5mbYUWzzz6c6WhPavb0YhEIiJ+AmhLLmm691/PaoaAXO88= ARC-Authentication-Results: i=1; sourceware.org; dkim=pass (2048-bit key, unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=VVn+aYfQ DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 394604BA902F Received: by mail-pj2-x10.google.com with SMTP id d9443c01a7336-2d8fb334e72so13129115ad.1 for ; Wed, 09 Sep 2026 10:05:34 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1788973533; x=1789578333; darn=sourceware.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to:content-type; bh=L4x3oqjNNmnSLaO+AdERARvNx/zf0jh29mS3vfOFkq4=; b=VVn+aYfQrS1nQPyLuelVoN/Y8WpIxVpAtlqzxQVFkEe+hC8H7E4N4F6JYmZUkPWZFq V7GLI3DqtMNxB7eVFBlpxBvcnHrPrHMzrdsTyHgjB9NT+tOl94mOZYL2aDftcleKA4va S3yWPak4gqAV1Z/I9uFsBmL412sxZ6/Ey4empeRh+aQT/Y8SHGvjcvOJumMOMnHum8Be 03ta4ExoAQCDyXCefIld9RB8QqIB4x7FPke7kmcagUj81jOLCbkA/RDNdzqIbkTpChQJ kZRR7UhNeZiLCGlxxwux4EJYJ3k522S8oDqFxetztHCqRJXT2YK+iMzjUF6DK2z/f0vs HOVw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1788973533; x=1789578333; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=L4x3oqjNNmnSLaO+AdERARvNx/zf0jh29mS3vfOFkq4=; b=UI9beQAZnriNYYGL5SS5zRoS+mcN53fuRJA1ln0DjNNev6fQLV96wPLSprtP6bb4og rsneQaGcmhmUbL/9CDS3uBEGD5NU9q74wnDdPRUGdRu75HtTwxyA2l6lWI+E8W0mOwnp xCizr75KFgmOIONSuDeXHut8VMa+MeGWTQL0ZF8BxVof1PoeWari3KqRfvnpTqgAVJiL 0In1i+meWKlMwLw19Kdu/wg6AUROva/eSkhRqA0jDt/l1l8BRz+IhEoi+TlCg0eec4KR 6VyT8MQFrLgJbsZIShFHvhWGQsBjAo1gPrwhPN+y7AS93Ysnnf3b4DN7oR3TRMIIf8bD COBg== X-Gm-Message-State: AFuF++l4xWAEHL/lyPRmCLwR/ub6fwwSAfwrkWPG+aJlIbX1aTjy3pCj 0VFegS/Tj31aYs8fAiLZCPWV8drUZ0NWycRz+oP4wo18X1RuiO+uqGt5el1u/hiShVNWMoaTqB1 S59JZ X-Gm-Gg: AYBFou1odC5jqSEZhgXmskxOyTF7CrRkK+QdPzePHYG5WA3xg8GTreALx/A+C7j+sr/ WTwnQuLVKJd49ZvPuIcigMC/GHxwV6cfmCkfKwdumWw/lSYlFBM3cUzjAOhaIWotYL9itrPHLPp cy52OVgJWILqi/opbsDFexm+MnOGiJNeprITy6Rd9U9AlVoOJJZMB41h2+2UjcXLO65GQI+nmtA YroDGhm2sq0kRhjDGa1GmmhdmD5MsZj8FmpassbiEUYo8uHpfxr4rsK7u+8DqMcpIy1nks7usfj tALZTcRbILMG4wljJXcKnvLNxXdHz8JUqNcDXSwf64Dt+qYiPfMwB5w8ukuuWVh9W4pgs4r0+4K socsON3gi8ACaH6ueUZktI3QLuf+jZWGN58M9tTvI2fv/SysZ36KzkNt2mYAzEO8cRe0HeEkqOo MliGIGXwvGtrGDUokOPeohy4hA/ZOEOTORCWXOrGbwq9CWTJNayZWGdvUojNzNxehcNZWIwDmFf BRrgfBFV6uy2thgHbjrmJysUKdmQgV5widxQXmi4g== X-Received: by 2002:a17:903:2285:b0:2d9:520c:38e7 with SMTP id d9443c01a7336-2db8d817b24mr71750155ad.1.1788973532638; Wed, 09 Sep 2026 10:05:32 -0700 (PDT) Received: from mandiga ([2804:1b3:a7c3:566e:4c11:49d2:3746:f07b]) by smtp.gmail.com with ESMTPSA id 5a478bee46e88-3339885ca07sm51481268eec.1.2026.09.09.10.05.30 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 09 Sep 2026 10:05:32 -0700 (PDT) From: Adhemerval Zanella To: libc-alpha@sourceware.org Cc: Florian Weimer , Justin Rivera Subject: [PATCH v3] elf: Support multiple PT_GNU_RELRO segments Date: Wed, 9 Sep 2026 14:05:08 -0300 Message-ID: <20260909170525.475741-1-adhemerval.zanella@linaro.org> X-Mailer: git-send-email 2.53.0 MIME-Version: 1.0 X-Spam-Status: No, score=-12.6 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_NONE, TXREP shortcircuit=no autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on sourceware.org X-BeenThere: libc-alpha@sourceware.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Libc-alpha mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libc-alpha-bounces~patchwork=sourceware.org@sourceware.org When binaries become extremely large, PC-relative references to a single GOT can exceed the range of the relocations used to address it (for instance +/- 2GB on x86-64). To resolve this, we'd like to generate multiple GOTs, which would require multiple PT_GNU_RELRO segments. Remove the cached l_relro_addr and l_relro_size fields and iterate over the program headers instead, so that every PT_GNU_RELRO segment is protected. The same applies to _dl_readonly_area, where the queried range may span multiple adjacent segments. Since mprotect operates on whole pages while the linker only aligns the segment end, _dl_protect_relro rounds the mapped end range down, and the start down only for a segment that starts a PT_LOAD segment (where the leading page slack is unused, since(BFD ld does not page-align the start). If no complete page is left the segment is not protected, and a note is issued with LD_DEBUG=reloc. The new tests tst-relro-multi and tst-relro-multi-static use marker ELF notes with the GLIBC-TST-RELRO owner name, placed by a linker script and converted to PT_GNU_RELRO by scripts/tst-elf-edit.py --note-to-relro. Co-authored-by: Justin Rivera --- elf/Makefile | 32 ++++++++++++++++++++ elf/dl-load.c | 5 ---- elf/dl-readonly-area.c | 34 +++++++++++++-------- elf/dl-reloc.c | 51 +++++++++++++++++++++---------- elf/dl-support.c | 5 ---- elf/rtld.c | 15 ---------- elf/tst-relro-multi-notes.S | 58 ++++++++++++++++++++++++++++++++++++ elf/tst-relro-multi-static.c | 19 ++++++++++++ elf/tst-relro-multi.c | 43 ++++++++++++++++++++++++++ elf/tst-relro-multi.lds | 24 +++++++++++++++ elf/tst-relro-symbols.py | 45 +++++++++++++++------------- include/link.h | 4 --- scripts/tst-elf-edit.py | 46 ++++++++++++++++++++++++++++ sysdeps/generic/ldsodefs.h | 1 + 14 files changed, 305 insertions(+), 77 deletions(-) create mode 100644 elf/tst-relro-multi-notes.S create mode 100644 elf/tst-relro-multi-static.c create mode 100644 elf/tst-relro-multi.c create mode 100644 elf/tst-relro-multi.lds diff --git a/elf/Makefile b/elf/Makefile index 4d1032bb2a..522b04327a 100644 --- a/elf/Makefile +++ b/elf/Makefile @@ -1559,6 +1559,38 @@ tests-special += $(objpfx)tst-tls-debug-recursive.out tests-special += $(objpfx)tst-dl-debug-exclude.out endif +test-srcs += tst-relro-multi +tests-static += tst-relro-multi-static +extra-test-objs += tst-relro-multi-notes.o +LDFLAGS-tst-relro-multi = -Wl,-z,now -Wl,-T,$(..)elf/tst-relro-multi.lds +LDFLAGS-tst-relro-multi-static = -Wl,-T,$(..)elf/tst-relro-multi.lds +$(objpfx)tst-relro-multi: +nolink-deps += tst-relro-multi.lds +$(objpfx)tst-relro-multi: $(objpfx)tst-relro-multi-notes.o tst-relro-multi.lds +$(objpfx)tst-relro-multi-static: +nolink-deps += tst-relro-multi.lds +$(objpfx)tst-relro-multi-static: $(objpfx)tst-relro-multi-notes.o \ + tst-relro-multi.lds + +$(objpfx)tst-relro-multi-patched $(objpfx)tst-relro-multi-static-patched: \ + %-patched: % $(..)scripts/tst-elf-edit.py + cp $< $@.tmp + $(PYTHON) $(..)scripts/tst-elf-edit.py --note-to-relro 2 $@.tmp + mv $@.tmp $@ + +$(objpfx)tst-relro-multi-patched.out: $(objpfx)tst-relro-multi-patched \ + $(objpfx)ld.so + $(run-program-prefix) $< > $@ 2>&1; \ + $(evaluate-test) + +$(objpfx)tst-relro-multi-static-patched.out: \ + $(objpfx)tst-relro-multi-static-patched + $(test-wrapper) $< > $@ 2>&1; \ + $(evaluate-test) + +ifeq ($(run-built-tests),yes) +tests-special += $(objpfx)tst-relro-multi-patched.out +tests-special += $(objpfx)tst-relro-multi-static-patched.out +endif + # The test requires shared _and_ PIE because the executable # unit test driver must be able to link with the shared object # that is going to eventually go into an installed DSO. diff --git a/elf/dl-load.c b/elf/dl-load.c index 1621cb1bde..a25e455ce7 100644 --- a/elf/dl-load.c +++ b/elf/dl-load.c @@ -1060,11 +1060,6 @@ _dl_map_object_scan_phdrs (struct dl_pt_load_iterator *it, case PT_GNU_STACK: *stack_flagsp = pf_to_prot (ph->p_flags); break; - - case PT_GNU_RELRO: - l->l_relro_addr = ph->p_vaddr; - l->l_relro_size = ph->p_memsz; - break; } } diff --git a/elf/dl-readonly-area.c b/elf/dl-readonly-area.c index 833f455904..b1cfa003e0 100644 --- a/elf/dl-readonly-area.c +++ b/elf/dl-readonly-area.c @@ -17,23 +17,31 @@ . */ #include +#include -static bool +static enum dl_readonly_area_error_type check_relro (const struct link_map *l, uintptr_t start, uintptr_t end) { - if (l->l_relro_addr != 0) - { - uintptr_t relro_start = ALIGN_DOWN (l->l_addr + l->l_relro_addr, - GLRO(dl_pagesize)); - uintptr_t relro_end = ALIGN_DOWN (l->l_addr + l->l_relro_addr - + l->l_relro_size, - GLRO(dl_pagesize)); - /* RELRO is caved out from a RW segment, so the next range is either - RW or nonexistent. */ - return relro_start <= start && end <= relro_end - ? dl_readonly_area_rdonly : dl_readonly_area_writable; + /* The range may span multiple PT_GNU_RELRO segments whose ranges are + adjacent, so accumulate the covered bytes. There is no need to handle + the rounding done by _dl_protect_relro, the toolchain is expected to + place the objects within the segments. */ + size_t size = end - start; + for (const ElfW(Phdr) *ph = l->l_phdr; ph < &l->l_phdr[l->l_phnum]; ++ph) + if (ph->p_type == PT_GNU_RELRO) + { + uintptr_t relro_start = l->l_addr + ph->p_vaddr; + uintptr_t relro_end = relro_start + ph->p_memsz; + uintptr_t from = MAX (relro_start, start); + uintptr_t to = MIN (relro_end, end); + if (from < to) + size -= to - from; + if (size == 0) + return dl_readonly_area_rdonly; + } - } + /* RELRO is caved out from a RW segment, so any range outside of + a RELRO segment is either RW or nonexistent. */ return dl_readonly_area_writable; } diff --git a/elf/dl-reloc.c b/elf/dl-reloc.c index 8077f90167..c95bae07fe 100644 --- a/elf/dl-reloc.c +++ b/elf/dl-reloc.c @@ -409,23 +409,44 @@ _dl_relocate_object (struct link_map *l, struct r_scope_elem *scope[], void _dl_protect_relro (struct link_map *l) { - if (l->l_relro_size == 0) - return; + for (const ElfW(Phdr) *ph = l->l_phdr; ph < &l->l_phdr[l->l_phnum]; ++ph) + if (ph->p_type == PT_GNU_RELRO) + { + bool at_load_start = false; + for (const ElfW(Phdr) *lph = l->l_phdr; + lph < &l->l_phdr[l->l_phnum]; ++lph) + if (lph->p_type == PT_LOAD && lph->p_vaddr == ph->p_vaddr) + { + at_load_start = true; + break; + } - ElfW(Addr) start = ALIGN_DOWN((l->l_addr - + l->l_relro_addr), - GLRO(dl_pagesize)); - ElfW(Addr) end = ALIGN_DOWN((l->l_addr - + l->l_relro_addr - + l->l_relro_size), - GLRO(dl_pagesize)); - if (start != end - && __mprotect ((void *) start, end - start, PROT_READ) < 0) - { - static const char errstring[] = N_("\ + ElfW(Addr) vaddr = l->l_addr + ph->p_vaddr; + ElfW(Addr) start = at_load_start + ? ALIGN_DOWN (vaddr, GLRO(dl_pagesize)) + : ALIGN_UP (vaddr, GLRO(dl_pagesize)); + ElfW(Addr) end = ALIGN_DOWN (vaddr + ph->p_memsz, GLRO(dl_pagesize)); + + /* A segment that does not cover a complete page is not protected at + all. This is a loss of hardening (and arguably a malformed + object). */ + if (start >= end) + { + if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_RELOC)) + _dl_debug_printf ("\nnot protecting RELRO segment at 0x%lx of " + "%s: no complete page in range\n", + (unsigned long int) vaddr, + DSO_FILENAME (l->l_name)); + continue; + } + + if (__mprotect ((void *) start, end - start, PROT_READ) < 0) + { + static const char errstring[] = N_("\ cannot apply additional memory protection after relocation"); - _dl_signal_error (errno, l->l_name, NULL, errstring); - } + _dl_signal_error (errno, l->l_name, NULL, errstring); + } + } } void diff --git a/elf/dl-support.c b/elf/dl-support.c index b57fd74670..041b89da79 100644 --- a/elf/dl-support.c +++ b/elf/dl-support.c @@ -327,11 +327,6 @@ _dl_non_dynamic_init (void) case PT_GNU_STACK: _dl_stack_prot_flags = pf_to_prot (ph->p_flags); break; - - case PT_GNU_RELRO: - _dl_main_map.l_relro_addr = ph->p_vaddr; - _dl_main_map.l_relro_size = ph->p_memsz; - break; } _dl_handle_execstack_tunable (); diff --git a/elf/rtld.c b/elf/rtld.c index 324393d606..683e0814c6 100644 --- a/elf/rtld.c +++ b/elf/rtld.c @@ -1198,11 +1198,6 @@ rtld_setup_main_map (struct link_map *main_map) case PT_GNU_STACK: GL(dl_stack_prot_flags) = pf_to_prot (ph->p_flags); break; - - case PT_GNU_RELRO: - main_map->l_relro_addr = ph->p_vaddr; - main_map->l_relro_size = ph->p_memsz; - break; } _dl_executable_postprocess (main_map, phdr, phnum); @@ -1270,16 +1265,6 @@ rtld_setup_phdr (void) & ~(GLRO(dl_pagesize) - 1)); } } - - /* PT_GNU_RELRO is usually the last phdr. */ - size_t cnt = rtld_ehdr->e_phnum; - while (cnt-- > 0) - if (rtld_phdr[cnt].p_type == PT_GNU_RELRO) - { - _dl_rtld_map.l_relro_addr = rtld_phdr[cnt].p_vaddr; - _dl_rtld_map.l_relro_size = rtld_phdr[cnt].p_memsz; - break; - } } /* Adjusts the contents of the stack and related globals for the user diff --git a/elf/tst-relro-multi-notes.S b/elf/tst-relro-multi-notes.S new file mode 100644 index 0000000000..94cd05f28c --- /dev/null +++ b/elf/tst-relro-multi-notes.S @@ -0,0 +1,58 @@ +/* Data definitions for the multiple PT_GNU_RELRO test. + Copyright (C) 2026 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +/* Assembly is used because compilers emit SHT_PROGBITS for + __attribute__ ((section)) definitions and gas might warn when its + name-based heuristic retypes .note.* sections; and note sections + must not have the SHF_WRITE flag for the same reason. */ + + .section .note.a, "a", %note + .balign 4 + .long 2f-1f /* n_namesz */ + .long 4f-3f /* n_descsz */ + .long 1 /* n_type */ +1: .asciz "GLIBC-TST-RELRO" +2: .balign 4 +3: .globl relro_a + .type relro_a, %object +relro_a: + .dc.a 0xAAAA + .size relro_a, .-relro_a +4: + + .section .gap, "aw", %progbits + .balign 8 + .globl gap_d + .type gap_d, %object +gap_d: + .dc.a 0xDDDD + .size gap_d, .-gap_d + + .section .note.b, "a", %note + .balign 4 + .long 2f-1f /* n_namesz */ + .long 4f-3f /* n_descsz */ + .long 1 /* n_type */ +1: .asciz "GLIBC-TST-RELRO" +2: .balign 4 +3: .globl relro_b + .type relro_b, %object +relro_b: + .dc.a 0xBBBB + .size relro_b, .-relro_b +4: diff --git a/elf/tst-relro-multi-static.c b/elf/tst-relro-multi-static.c new file mode 100644 index 0000000000..8f795c84bb --- /dev/null +++ b/elf/tst-relro-multi-static.c @@ -0,0 +1,19 @@ +/* Multiple PT_GNU_RELRO test, static version. + Copyright (C) 2026 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include "tst-relro-multi.c" diff --git a/elf/tst-relro-multi.c b/elf/tst-relro-multi.c new file mode 100644 index 0000000000..be8feb3252 --- /dev/null +++ b/elf/tst-relro-multi.c @@ -0,0 +1,43 @@ +/* Multiple PT_GNU_RELRO test. + Copyright (C) 2026 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include + +/* The tst-elf-edit.py --note-to-relro convert relro_a and relro_b + to page-padded PT_GNU_RELRO seguments. */ +extern unsigned long int relro_a; +extern unsigned long int gap_d; +extern unsigned long int relro_b; + +static int +do_test (void) +{ + /* Both RELRO regions must be readable but not writable. */ + TEST_COMPARE (check_mem_access (&relro_a, false), true); + TEST_COMPARE (check_mem_access (&relro_a, true), false); + TEST_COMPARE (check_mem_access (&relro_b, false), true); + TEST_COMPARE (check_mem_access (&relro_b, true), false); + + /* The gap between the two RELRO regions must remain writable. */ + TEST_COMPARE (check_mem_access (&gap_d, true), true); + + return 0; +} + +#include diff --git a/elf/tst-relro-multi.lds b/elf/tst-relro-multi.lds new file mode 100644 index 0000000000..eeb6af15d3 --- /dev/null +++ b/elf/tst-relro-multi.lds @@ -0,0 +1,24 @@ +/* Multiple PT_GNU_RELRO test. + Copyright (C) 2026 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ +SECTIONS { + . = ALIGN(CONSTANT(MAXPAGESIZE)); + .note.a : { *(.note.a) . = ALIGN(CONSTANT(MAXPAGESIZE)); } + .gap : { *(.gap) . = ALIGN(CONSTANT(MAXPAGESIZE)); } + .note.b : { *(.note.b) . = ALIGN(CONSTANT(MAXPAGESIZE)); } +} +INSERT AFTER .data; diff --git a/elf/tst-relro-symbols.py b/elf/tst-relro-symbols.py index ffbe9958fe..7bd838be32 100644 --- a/elf/tst-relro-symbols.py +++ b/elf/tst-relro-symbols.py @@ -32,25 +32,30 @@ sys.path.append(os.path.join( import glibcelf -def find_relro(path: str, img: glibcelf.Image) -> (int, int): - """Discover the address range of the PT_GNU_RELRO segment.""" - for phdr in img.phdrs(): - if phdr.p_type == glibcelf.Pt.PT_GNU_RELRO: - # The computation is not entirely accurate because - # _dl_protect_relro in elf/dl-reloc.c rounds both the - # start end and downwards using the run-time page size. - return phdr.p_vaddr, phdr.p_vaddr + phdr.p_memsz - sys.stdout.write('{}: error: no PT_GNU_RELRO segment\n'.format(path)) - sys.exit(1) +def find_relro(path: str, img: glibcelf.Image) -> list: + """Discover the address ranges of the PT_GNU_RELRO segments.""" + # The computation is not entirely accurate because + # _dl_protect_relro in elf/dl-reloc.c rounds the range inwards + # using the run-time page size. + regions = [(phdr.p_vaddr, phdr.p_vaddr + phdr.p_memsz) + for phdr in img.phdrs() + if phdr.p_type == glibcelf.Pt.PT_GNU_RELRO] + if not regions: + sys.stdout.write('{}: error: no PT_GNU_RELRO segment\n'.format(path)) + sys.exit(1) + return regions -def check_in_relro(kind, relro_begin, relro_end, name, start, size, error): - """Check if a section or symbol falls within in the RELRO segment.""" +def check_in_relro(kind, relro_regions, name, start, size, error): + """Check if a section or symbol falls within in any RELRO segment.""" end = start + size - 1 - if not (relro_begin <= start < end < relro_end): - error( - '{} {!r} of size {} at 0x{:x} is not in RELRO range [0x{:x}, 0x{:x})'.format( - kind, name.decode('UTF-8'), start, size, - relro_begin, relro_end)) + for relro_begin, relro_end in relro_regions: + if relro_begin <= start <= end < relro_end: + return + error( + '{} {!r} of size {} at 0x{:x} is not in any RELRO range: {}'.format( + kind, name.decode('UTF-8'), size, start, + ', '.join('[0x{:x}, 0x{:x})'.format(*region) + for region in relro_regions))) def get_parser(): """Return an argument parser for this script.""" @@ -78,7 +83,7 @@ def main(argv): symbols_found = set() # Discover the extent of the RELRO segment. - relro_begin, relro_end = find_relro(opts.object, img) + relro_regions = find_relro(opts.object, img) symbol_table_found = False errors = False @@ -109,13 +114,13 @@ def main(argv): sym.st_name.decode('UTF-8'))) continue - check_in_relro('symbol', relro_begin, relro_end, + check_in_relro('symbol', relro_regions, sym.st_name, sym.st_value, sym.st_size, error) continue # SHT_SYMTAB if shdr.sh_name == b'.data.rel.ro' \ or shdr.sh_name.startswith(b'.data.rel.ro.'): - check_in_relro('section', relro_begin, relro_end, + check_in_relro('section', relro_regions, shdr.sh_name, shdr.sh_addr, shdr.sh_size, error) continue diff --git a/include/link.h b/include/link.h index e299ca35fd..14c049301b 100644 --- a/include/link.h +++ b/include/link.h @@ -337,10 +337,6 @@ struct link_map lock. See also: CONCURRENCY NOTES in cxa_thread_atexit_impl.c. */ size_t l_tls_dtor_count; - /* Information used to change permission after the relocations are - done. */ - ElfW(Addr) l_relro_addr; - size_t l_relro_size; unsigned long long int l_serial; }; diff --git a/scripts/tst-elf-edit.py b/scripts/tst-elf-edit.py index 07fa7e90f5..1d036e925c 100644 --- a/scripts/tst-elf-edit.py +++ b/scripts/tst-elf-edit.py @@ -47,7 +47,12 @@ ET_EXEC=2 ET_DYN=3 PT_LOAD=1 +PT_NOTE=4 PT_TLS=7 +PT_GNU_RELRO=0x6474e552 + +# PT_NOTE constant mark used by --note-to-relro. +NN_GLIBC_TST_RELRO=b'GLIBC-TST-RELRO\x00' def elf_types_fmts(e_ident): endian = '<' if e_ident[EI_DATA] == ELFDATA2LSB else '>' @@ -156,6 +161,40 @@ def elf_edit_maximize_tls_size(phdr, elfclass): else: phdr.p_memsz = 1 << 63 +def elf_note_name(f, e_ident, phdr): + """Return the owner name of the first note in a PT_NOTE segment.""" + endian, _, _ = elf_types_fmts(e_ident) + fmt = '{}III'.format(endian) + nhdr_len = struct.calcsize(fmt) + if phdr.p_filesz < nhdr_len: + return None + f.seek(phdr.p_offset) + namesz, descsz, n_type = struct.unpack(fmt, f.read(nhdr_len)) + if namesz == 0 or namesz > phdr.p_filesz - nhdr_len: + return None + return f.read(namesz) + +def elf_edit_note_to_relro(f, e_ident, ehdr, expected): + converted = 0 + for i in range(0, ehdr.e_phnum): + phdr = Elf_Phdr(e_ident) + f.seek(ehdr.e_phoff + i * phdr.len) + phdr.read(f) + if phdr.p_type != PT_NOTE: + continue + if elf_note_name(f, e_ident, phdr) != NN_GLIBC_TST_RELRO: + continue + phdr.p_type = PT_GNU_RELRO + # Match the alignment the linker uses for PT_GNU_RELRO. + phdr.p_align = 1 + f.seek(ehdr.e_phoff + i * phdr.len) + phdr.write(f) + converted += 1 + + if converted != expected: + error('{}: converted {} PT_NOTE segment(s), expected {}'.format( + f.name, converted, expected)) + def elf_edit(f, opts): ei_nident_fmt = 'c' * EI_NIDENT ei_nident_len = struct.calcsize(ei_nident_fmt) @@ -184,6 +223,10 @@ def elf_edit(f, opts): if ehdr.e_type not in (ET_EXEC, ET_DYN): error('{}: not an executable or shared library'.format(f.name)) + if opts.note_to_relro is not None: + elf_edit_note_to_relro(f, e_ident, ehdr, opts.note_to_relro) + return + phdr = Elf_Phdr(e_ident) maximize_tls_size_done = False for i in range(0, ehdr.e_phnum): @@ -210,6 +253,9 @@ def get_parser(): help='How to set the LOAD alignment') parser.add_argument('--maximize-tls-size', action='store_true', help='Set maximum PT_TLS size') + parser.add_argument('--note-to-relro', type=int, metavar='COUNT', + help='Convert COUNT PT_NOTE segments whose first ' + 'note has the GLIBC-TST-RELRO name to PT_GNU_RELRO') parser.add_argument('output', help='ELF file to edit') return parser diff --git a/sysdeps/generic/ldsodefs.h b/sysdeps/generic/ldsodefs.h index 305ca6e0df..70e4fa9b82 100644 --- a/sysdeps/generic/ldsodefs.h +++ b/sysdeps/generic/ldsodefs.h @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include