1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/* Copyright (c) [2023] [Syswonder Community]
 *   [Rukos] is licensed under Mulan PSL v2.
 *   You can use this software according to the terms and conditions of the Mulan PSL v2.
 *   You may obtain a copy of Mulan PSL v2 at:
 *               http://license.coscl.org.cn/MulanPSL2
 *   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *   See the Mulan PSL v2 for more details.
 */

use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
use core::cell::UnsafeCell;
use core::ffi::{c_int, c_void};

use axerrno::{LinuxError, LinuxResult};
use axtask::AxTaskRef;
use spin::RwLock;

use crate::ctypes;

pub mod condvar;
pub mod futex;
pub mod mutex;

#[cfg(feature = "musl")]
pub mod dummy;
#[cfg(not(feature = "musl"))]
pub mod tsd;
#[cfg(feature = "musl")]
pub use dummy::{
    sys_pthread_getspecific, sys_pthread_key_create, sys_pthread_key_delete,
    sys_pthread_setspecific,
};
#[cfg(not(feature = "musl"))]
pub use tsd::{
    sys_pthread_getspecific, sys_pthread_key_create, sys_pthread_key_delete,
    sys_pthread_setspecific,
};

lazy_static::lazy_static! {
    static ref TID_TO_PTHREAD: RwLock<BTreeMap<u64, ForceSendSync<ctypes::pthread_t>>> = {
        let mut map = BTreeMap::new();
        let main_task = axtask::current();
        let main_tid = main_task.id().as_u64();
        let main_thread = Pthread {
            inner: main_task.as_task_ref().clone(),
            retval: Arc::new(Packet {
                result: UnsafeCell::new(core::ptr::null_mut()),
            }),
        };
        let ptr = Box::into_raw(Box::new(main_thread)) as *mut c_void;
        map.insert(main_tid, ForceSendSync(ptr));
        RwLock::new(map)
    };
}

struct Packet<T> {
    result: UnsafeCell<T>,
}

unsafe impl<T> Send for Packet<T> {}
unsafe impl<T> Sync for Packet<T> {}

pub struct Pthread {
    inner: AxTaskRef,
    retval: Arc<Packet<*mut c_void>>,
}

impl Pthread {
    fn create(
        _attr: *const ctypes::pthread_attr_t,
        start_routine: extern "C" fn(arg: *mut c_void) -> *mut c_void,
        arg: *mut c_void,
    ) -> LinuxResult<ctypes::pthread_t> {
        let arg_wrapper = ForceSendSync(arg);

        let my_packet: Arc<Packet<*mut c_void>> = Arc::new(Packet {
            result: UnsafeCell::new(core::ptr::null_mut()),
        });
        let their_packet = my_packet.clone();

        let main = move || {
            let arg = arg_wrapper;
            let ret = start_routine(arg.0);
            unsafe { *their_packet.result.get() = ret };
            drop(their_packet);
        };

        let task_inner = axtask::spawn(main);
        let tid = task_inner.id().as_u64();
        let thread = Pthread {
            inner: task_inner,
            retval: my_packet,
        };
        let ptr = Box::into_raw(Box::new(thread)) as *mut c_void;
        TID_TO_PTHREAD.write().insert(tid, ForceSendSync(ptr));
        Ok(ptr)
    }

    /// Posix create, used by musl libc
    #[cfg(feature = "musl")]
    fn pcreate(
        _attr: *const ctypes::pthread_attr_t,
        start_routine: extern "C" fn(arg: *mut c_void) -> *mut c_void,
        arg: *mut c_void,
        tls: *mut c_void,
        set_tid: core::sync::atomic::AtomicU64,
        tl: core::sync::atomic::AtomicU64,
    ) -> LinuxResult<(u64, AxTaskRef)> {
        let arg_wrapper = ForceSendSync(arg);

        let my_packet: Arc<Packet<*mut c_void>> = Arc::new(Packet {
            result: UnsafeCell::new(core::ptr::null_mut()),
        });

        let main = move || {
            let arg = arg_wrapper;
            start_routine(arg.0);
        };

        let task_inner = axtask::pspawn(main, tls as usize, set_tid, tl);

        let tid = task_inner.id().as_u64();
        let thread = Pthread {
            inner: task_inner.clone(),
            retval: my_packet,
        };
        let ptr = Box::into_raw(Box::new(thread)) as *mut c_void;
        TID_TO_PTHREAD.write().insert(tid, ForceSendSync(ptr));
        Ok((tid, task_inner))
    }

    fn current_ptr() -> *mut Pthread {
        let tid = axtask::current().id().as_u64();
        match TID_TO_PTHREAD.read().get(&tid) {
            None => core::ptr::null_mut(),
            Some(ptr) => ptr.0 as *mut Pthread,
        }
    }

    fn current() -> Option<&'static Pthread> {
        unsafe { core::ptr::NonNull::new(Self::current_ptr()).map(|ptr| ptr.as_ref()) }
    }

    #[cfg(feature = "musl")]
    fn exit_musl(_retcode: usize) -> ! {
        let tid = Self::current()
            .expect("fail to get current thread")
            .inner
            .id()
            .as_u64();
        let thread = { TID_TO_PTHREAD.read().get(&tid).unwrap().0 };
        let thread = unsafe { Box::from_raw(thread as *mut Pthread) };
        TID_TO_PTHREAD.write().remove(&tid);
        debug!("Exit_musl, tid: {}", tid);
        drop(thread);
        axtask::exit(0)
    }

    #[cfg(not(feature = "musl"))]
    fn exit_current(retval: *mut c_void) -> ! {
        let thread = Self::current().expect("fail to get current thread");
        unsafe { *thread.retval.result.get() = retval };
        axtask::exit(0);
    }

    fn join(ptr: ctypes::pthread_t) -> LinuxResult<*mut c_void> {
        if core::ptr::eq(ptr, Self::current_ptr() as _) {
            return Err(LinuxError::EDEADLK);
        }

        let thread = unsafe { Box::from_raw(ptr as *mut Pthread) };
        thread.inner.join();
        let tid = thread.inner.id().as_u64();
        let retval = unsafe { *thread.retval.result.get() };
        TID_TO_PTHREAD.write().remove(&tid);
        drop(thread);
        Ok(retval)
    }
}

/// Returns the `pthread` struct of current thread.
pub fn sys_pthread_self() -> ctypes::pthread_t {
    Pthread::current().expect("fail to get current thread") as *const Pthread as _
}

/// Create a new thread with the given entry point and argument.
///
/// If successful, it stores the pointer to the newly created `struct __pthread`
/// in `res` and returns 0.
pub unsafe fn sys_pthread_create(
    res: *mut ctypes::pthread_t,
    attr: *const ctypes::pthread_attr_t,
    start_routine: extern "C" fn(arg: *mut c_void) -> *mut c_void,
    arg: *mut c_void,
) -> c_int {
    debug!(
        "sys_pthread_create <= {:#x}, {:#x}",
        start_routine as usize, arg as usize
    );
    syscall_body!(sys_pthread_create, {
        let ptr = Pthread::create(attr, start_routine, arg)?;
        unsafe { core::ptr::write(res, ptr) };
        Ok(0)
    })
}

/// Exits the current thread. The value `retval` will be returned to the joiner.
pub fn sys_pthread_exit(retval: *mut c_void) -> ! {
    debug!("sys_pthread_exit <= {:#x}", retval as usize);
    #[cfg(feature = "musl")]
    {
        let id = axtask::current().as_task_ref().id().as_u64();
        if id != 2u64 {
            axtask::current().as_task_ref().free_thread_list_lock();
        }
        // retval is exit code for musl
        Pthread::exit_musl(retval as usize);
    }
    #[cfg(not(feature = "musl"))]
    Pthread::exit_current(retval);
}

/// Waits for the given thread to exit, and stores the return value in `retval`.
pub unsafe fn sys_pthread_join(thread: ctypes::pthread_t, retval: *mut *mut c_void) -> c_int {
    debug!("sys_pthread_join <= {:#x}", retval as usize);
    syscall_body!(sys_pthread_join, {
        let ret = Pthread::join(thread)?;
        if !retval.is_null() {
            unsafe { core::ptr::write(retval, ret) };
        }
        Ok(0)
    })
}

#[derive(Clone, Copy)]
struct ForceSendSync<T>(T);

unsafe impl<T> Send for ForceSendSync<T> {}
unsafe impl<T> Sync for ForceSendSync<T> {}

/// Create new thread by `sys_clone`, return new thread ID
#[cfg(feature = "musl")]
pub unsafe fn sys_clone(
    flags: c_int,
    stack: *mut c_void,
    ptid: *mut ctypes::pid_t,
    tls: *mut c_void,
    ctid: *mut ctypes::pid_t,
) -> c_int {
    debug!(
        "sys_clone <= flags: {:x}, stack: {:p}, ctid: {:x}",
        flags, stack, ctid as usize
    );

    syscall_body!(sys_clone, {
        if (flags as u32 & ctypes::CLONE_THREAD) == 0 {
            debug!("ONLY support thread");
            return Err(LinuxError::EINVAL);
        }

        let func = unsafe {
            core::mem::transmute::<*const (), extern "C" fn(arg: *mut c_void) -> *mut c_void>(
                (*(stack as *mut usize)) as *const (),
            )
        };
        let args = unsafe { *((stack as usize + 8) as *mut usize) } as *mut c_void;

        let set_tid = if (flags as u32 & ctypes::CLONE_CHILD_SETTID) != 0 {
            core::sync::atomic::AtomicU64::new(ctid as _)
        } else {
            core::sync::atomic::AtomicU64::new(0)
        };

        let (tid, task_inner) = Pthread::pcreate(
            core::ptr::null(),
            func,
            args,
            tls,
            set_tid,
            core::sync::atomic::AtomicU64::from(ctid as u64),
        )?;

        // write tid to ptid
        if (flags as u32 & ctypes::CLONE_PARENT_SETTID) != 0 {
            unsafe { *ptid = tid as c_int };
        }

        axtask::put_task(task_inner);

        Ok(tid)
    })
}

/// Set child tid address
#[cfg(feature = "musl")]
pub fn sys_set_tid_address(tid: usize) -> c_int {
    syscall_body!(sys_set_tid_address, {
        debug!("set_tid_address <= addr: {:#x}", tid);
        let id = axtask::current().id().as_u64() as c_int;
        axtask::current().as_task_ref().set_child_tid(tid);
        Ok(id)
    })
}