1/* Support for relocating static PIE.
2 Copyright (C) 2017-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
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.
9
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.
14
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/>. */
18
19#if ENABLE_STATIC_PIE
20/* Mark symbols hidden in static PIE for early self relocation to work. */
21# pragma GCC visibility push(hidden)
22#include <unistd.h>
23#include <ldsodefs.h>
24#include "dynamic-link.h"
25
26/* Relocate static executable with PIE. */
27
28void
29_dl_relocate_static_pie (void)
30{
31 struct link_map *main_map = _dl_get_dl_main_map ();
32
33# define STATIC_PIE_BOOTSTRAP
34# define BOOTSTRAP_MAP (main_map)
35# define RESOLVE_MAP(sym, version, flags) BOOTSTRAP_MAP
36# include "dynamic-link.h"
37
38 /* Figure out the run-time load address of static PIE. */
39 main_map->l_addr = elf_machine_load_address ();
40
41 /* Read our own dynamic section and fill in the info array. */
42 main_map->l_ld = ((void *) main_map->l_addr + elf_machine_dynamic ());
43 elf_get_dynamic_info (main_map, NULL);
44
45# ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
46 ELF_MACHINE_BEFORE_RTLD_RELOC (main_map->l_info);
47# endif
48
49 /* Relocate ourselves so we can do normal function calls and
50 data access using the global offset table. */
51 ELF_DYNAMIC_RELOCATE (main_map, 0, 0, 0);
52 main_map->l_relocated = 1;
53
54 /* Initialize _r_debug. */
55 struct r_debug *r = _dl_debug_initialize (0, LM_ID_BASE);
56 r->r_state = RT_CONSISTENT;
57
58 /* Set up debugging before the debugger is notified for the first
59 time. */
60# ifdef ELF_MACHINE_DEBUG_SETUP
61 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
62 ELF_MACHINE_DEBUG_SETUP (main_map, r);
63# else
64 if (main_map->l_info[DT_DEBUG] != NULL)
65 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
66 with the run-time address of the r_debug structure */
67 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
68# endif
69}
70#endif
71