1 /* Support for relocating static PIE.
2 Copyright (C) 2017-2025 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
20 /* Mark symbols hidden in static PIE for early self relocation to work. */
21 # pragma GCC visibility push(hidden)
26 #include <dl-machine.h>
29 #define RESOLVE_MAP(map, scope, sym, version, flags) map
30 #include "dynamic-link.h"
31 #include "get-dynamic-info.h"
33 /* Relocate static executable with PIE. */
36 _dl_relocate_static_pie (void)
38 struct link_map
*main_map
= _dl_get_dl_main_map ();
40 /* NB: elf_machine_load_address () returns the run-time load address
41 of static PIE. The l_addr field contains the difference between the
42 link-time load address in the ELF file and the run-time load address
43 in memory. We must subtract the link-time load address of static PIE,
44 which can be non-zero, when computing the l_addr field. Since static
45 PIE usually doesn't have PT_PHDR segment, use p_vaddr of the PT_LOAD
46 segment with offset == 0 as the load address of static PIE. */
47 ElfW(Addr
) file_p_vaddr
= 0;
48 const ElfW(Phdr
) *ph
, *phdr
= GL(dl_phdr
);
49 size_t phnum
= GL(dl_phnum
);
50 for (ph
= phdr
; ph
< &phdr
[phnum
]; ++ph
)
54 if (ph
->p_offset
== 0)
55 file_p_vaddr
= ph
->p_vaddr
;
58 main_map
->l_ld_readonly
= (ph
->p_flags
& PF_W
) == 0;
64 /* Figure out the run-time load address of static PIE. */
65 ElfW(Addr
) l_addr
= elf_machine_load_address ();
66 main_map
->l_addr
= l_addr
- file_p_vaddr
;
68 /* Read our own dynamic section and fill in the info array. */
69 main_map
->l_ld
= ((void *) l_addr
+ elf_machine_dynamic ());
71 elf_get_dynamic_info (main_map
, false, true);
73 # ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
74 ELF_MACHINE_BEFORE_RTLD_RELOC (main_map
, main_map
->l_info
);
77 /* Relocate ourselves so we can do normal function calls and
78 data access using the global offset table. */
79 ELF_DYNAMIC_RELOCATE (main_map
, NULL
, 0, 0, 0);
80 main_map
->l_relocated
= 1;
82 /* Initialize _r_debug_extended. */
83 struct r_debug
*r
= _dl_debug_initialize (0, LM_ID_BASE
);
84 r
->r_state
= RT_CONSISTENT
;
86 /* Set up debugging before the debugger is notified for the first
88 elf_setup_debug_entry (main_map
, r
);