1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <sched.h>
18 #include <semaphore.h>
19
20 #include "berberis/base/checks.h"
21 #include "berberis/base/host_signal.h" // RTSigprocmaskSyscallOrDie
22 #include "berberis/guest_abi/guest_call.h"
23
24 #include "guest_thread_manager_impl.h" // InsertCurrentThread
25 #include "guest_thread_pthread_create.h"
26
27 namespace berberis {
28
RunGuestThread(void * arg)29 void* RunGuestThread(void* arg) {
30 GuestThreadCreateInfo* info = static_cast<GuestThreadCreateInfo*>(arg);
31
32 // The thread is created by pthread_create, use pthread_key dtor for destruction.
33 // Might handle destruction in pthread_join/pthread_exit instead, but seems more complex.
34 InsertCurrentThread(info->thread, true);
35 info->thread->InitStaticTls();
36
37 // Caller will destroy info after we notify it, so save thread function locally.
38 GuestAddr guest_func = info->func;
39 GuestAddr guest_arg = info->arg;
40
41 RTSigprocmaskSyscallOrDie(SIG_SETMASK, &info->mask, nullptr);
42
43 // Notify the caller that thread is ready.
44 CHECK_EQ(0, sem_post(&info->sem));
45 // TODO(b/77574158): Ensure caller has a chance to handle the notification.
46 sched_yield();
47
48 GuestCall call;
49 call.AddArgGuestAddr(guest_arg);
50 return ToHostAddr<void>(call.RunResGuestAddr(guest_func));
51 }
52
53 } // namespace berberis