1 // SPDX-License-Identifier: LGPL-2.1-only
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 <rseq/rseq.h>
34 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
36 static const int *libc_rseq_offset_p
;
37 static const unsigned int *libc_rseq_size_p
;
38 static const unsigned int *libc_rseq_flags_p
;
40 /* Offset from the thread pointer to the rseq area. */
43 /* Size of the registered rseq area. 0 if the registration was
45 unsigned int rseq_size
= -1U;
47 /* Flags used during rseq registration. */
48 unsigned int rseq_flags
;
50 static int rseq_ownership
;
53 __thread
struct rseq __rseq_abi
__attribute__((tls_model("initial-exec"))) = {
54 .cpu_id
= RSEQ_CPU_ID_UNINITIALIZED
,
57 static int sys_rseq(struct rseq
*rseq_abi
, uint32_t rseq_len
,
58 int flags
, uint32_t sig
)
60 return syscall(__NR_rseq
, rseq_abi
, rseq_len
, flags
, sig
);
63 int rseq_available(void)
67 rc
= sys_rseq(NULL
, 0, 0, 0);
80 int rseq_register_current_thread(void)
84 if (!rseq_ownership
) {
85 /* Treat libc's ownership as a successful registration. */
88 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
), 0, RSEQ_SIG
);
91 assert(rseq_current_cpu_raw() >= 0);
95 int rseq_unregister_current_thread(void)
99 if (!rseq_ownership
) {
100 /* Treat libc's ownership as a successful unregistration. */
103 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
), RSEQ_FLAG_UNREGISTER
, RSEQ_SIG
);
109 static __attribute__((constructor
))
112 libc_rseq_offset_p
= dlsym(RTLD_NEXT
, "__rseq_offset");
113 libc_rseq_size_p
= dlsym(RTLD_NEXT
, "__rseq_size");
114 libc_rseq_flags_p
= dlsym(RTLD_NEXT
, "__rseq_flags");
115 if (libc_rseq_size_p
&& libc_rseq_offset_p
&& libc_rseq_flags_p
) {
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
);
130 static __attribute__((destructor
))
140 int32_t rseq_fallback_current_cpu(void)
144 cpu
= sched_getcpu();
146 perror("sched_getcpu()");