1 // SPDX-License-Identifier: LGPL-2.1
5 * Copyright (C) 2016 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; only
10 * version 2.1 of the License.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
32 #include "../kselftest.h"
35 static const ptrdiff_t *libc_rseq_offset_p;
36 static const unsigned int *libc_rseq_size_p;
37 static const unsigned int *libc_rseq_flags_p;
39 /* Offset from the thread pointer to the rseq area. */
40 ptrdiff_t rseq_offset;
42 /* Size of the registered rseq area. 0 if the registration was
44 unsigned int rseq_size = -1U;
46 /* Flags used during rseq registration. */
47 unsigned int rseq_flags;
49 static int rseq_ownership;
52 __thread struct rseq_abi __rseq_abi __attribute__((tls_model("initial-exec"))) = {
53 .cpu_id = RSEQ_ABI_CPU_ID_UNINITIALIZED,
56 static int sys_rseq(struct rseq_abi *rseq_abi, uint32_t rseq_len,
57 int flags, uint32_t sig)
59 return syscall(__NR_rseq, rseq_abi, rseq_len, flags, sig);
62 int rseq_available(void)
66 rc = sys_rseq(NULL, 0, 0, 0);
79 int rseq_register_current_thread(void)
83 if (!rseq_ownership) {
84 /* Treat libc's ownership as a successful registration. */
87 rc = sys_rseq(&__rseq_abi, sizeof(struct rseq_abi), 0, RSEQ_SIG);
90 assert(rseq_current_cpu_raw() >= 0);
94 int rseq_unregister_current_thread(void)
98 if (!rseq_ownership) {
99 /* Treat libc's ownership as a successful unregistration. */
102 rc = sys_rseq(&__rseq_abi, sizeof(struct rseq_abi), RSEQ_ABI_FLAG_UNREGISTER, RSEQ_SIG);
108 static __attribute__((constructor))
111 libc_rseq_offset_p = dlsym(RTLD_NEXT, "__rseq_offset");
112 libc_rseq_size_p = dlsym(RTLD_NEXT, "__rseq_size");
113 libc_rseq_flags_p = dlsym(RTLD_NEXT, "__rseq_flags");
114 if (libc_rseq_size_p && libc_rseq_offset_p && libc_rseq_flags_p &&
115 *libc_rseq_size_p != 0) {
116 /* rseq registration owned by glibc */
117 rseq_offset = *libc_rseq_offset_p;
118 rseq_size = *libc_rseq_size_p;
119 rseq_flags = *libc_rseq_flags_p;
122 if (!rseq_available())
125 rseq_offset = (void *)&__rseq_abi - rseq_thread_pointer();
126 rseq_size = sizeof(struct rseq_abi);
130 static __attribute__((destructor))
140 int32_t rseq_fallback_current_cpu(void)
144 cpu = sched_getcpu();
146 perror("sched_getcpu()");