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 "berberis/guest_os_primitives/guest_thread.h"
18
19 #include <pthread.h>
20 #include <semaphore.h>
21
22 #include "berberis/guest_state/guest_addr.h"
23
24 #include "guest_thread_pthread_create.h"
25 #include "scoped_signal_blocker.h"
26
27 namespace berberis {
28
CreateNewGuestThread(pthread_t * thread_id,const pthread_attr_t * attr,void * guest_stack,size_t guest_stack_size,size_t guest_guard_size,GuestAddr func,GuestAddr arg)29 int CreateNewGuestThread(pthread_t* thread_id,
30 const pthread_attr_t* attr,
31 void* guest_stack,
32 size_t guest_stack_size,
33 size_t guest_guard_size,
34 GuestAddr func,
35 GuestAddr arg) {
36 GuestThreadCreateInfo info;
37 info.thread = GuestThread::CreatePthread(guest_stack, guest_stack_size, guest_guard_size);
38 if (info.thread == nullptr) {
39 return EAGAIN;
40 }
41 info.func = func;
42 info.arg = arg;
43 sem_init(&info.sem, 0, 0);
44
45 int res;
46 {
47 ScopedSignalBlocker signal_blocker;
48 info.mask = *signal_blocker.old_mask();
49 res = pthread_create(thread_id, attr, RunGuestThread, &info);
50 if (res == 0) {
51 CHECK_EQ(0, sem_wait(&info.sem)); // Wait with blocked signals to avoid EINTR.
52 }
53 }
54
55 if (res != 0) {
56 GuestThread::Destroy(info.thread);
57 }
58
59 sem_destroy(&info.sem);
60 return res;
61 }
62
63 } // namespace berberis
64