riscv: Fix alignment-ignorant memcpy implementation
[glibc.git] / sysdeps / unix / sysv / linux / dl-early_allocate.c
blob4d98076ab398cb5439976d98f6dd01ab9287cfd3
1 /* Early memory allocation for the dynamic loader. Generic version.
2 Copyright (C) 2022-2024 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/>. */
19 /* Mark symbols hidden in static PIE for early self relocation to work. */
20 #if BUILD_PIE_DEFAULT
21 # pragma GCC visibility push(hidden)
22 #endif
23 #include <startup.h>
25 #include <ldsodefs.h>
26 #include <stddef.h>
27 #include <string.h>
28 #include <sysdep.h>
29 #include <unistd.h>
31 #include <brk_call.h>
32 #include <mmap_call.h>
34 /* Defined in brk.c. */
35 extern void *__curbrk;
37 void *
38 _dl_early_allocate (size_t size)
40 void *result;
42 if (__curbrk != NULL)
43 /* If the break has been initialized, brk must have run before,
44 so just call it once more. */
46 result = __sbrk (size);
47 if (result == (void *) -1)
48 result = NULL;
50 else
52 /* If brk has not been invoked, there is no need to update
53 __curbrk. The first call to brk will take care of that. */
54 void *previous = __brk_call (0);
55 result = __brk_call (previous + size);
56 if (result == previous)
57 result = NULL;
58 else
59 result = previous;
62 /* If brk fails, fall back to mmap. This can happen due to
63 unfortunate ASLR layout decisions and kernel bugs, particularly
64 for static PIE. */
65 if (result == NULL)
67 long int ret;
68 int prot = PROT_READ | PROT_WRITE;
69 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
70 #ifdef __NR_mmap2
71 ret = MMAP_CALL_INTERNAL (mmap2, 0, size, prot, flags, -1, 0);
72 #else
73 ret = MMAP_CALL_INTERNAL (mmap, 0, size, prot, flags, -1, 0);
74 #endif
75 if (INTERNAL_SYSCALL_ERROR_P (ret))
76 result = NULL;
77 else
78 result = (void *) ret;
81 return result;