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 "app_process.h"
18 
19 #include <pthread.h>
20 
21 #include <condition_variable>
22 #include <mutex>
23 
24 namespace berberis {
25 
26 namespace {
27 
28 std::mutex g_guest_loader_mtx;
29 std::condition_variable g_guest_loader_cv;
30 bool g_guest_loader_initialized = false;
31 
32 }  // namespace
33 
AppProcessPostInit()34 void AppProcessPostInit() {
35   {
36     std::lock_guard<std::mutex> guard(g_guest_loader_mtx);
37     g_guest_loader_initialized = true;
38   }
39   g_guest_loader_cv.notify_all();
40 
41   // Expect this call to occur on the main guest thread, after app
42   // initialization is done. Force exit since keeping the thread in the
43   // background might confuse an app that expects to be single-threaded.
44   // Specifically, this scenario happens when guest code is executed in
45   // app-zygote before forking children (b/146904103).
46   //
47   // Other threads may use main thread's stack to access argc/argv/auxvals.
48   // We ensure that stack is retained after pthread_exit() by disallowing
49   // stack unmap in main guest thread when starting an executable.
50   //
51   // Note that we cannot just let the thread exit from main(), which would
52   // exit the whole process, not just this thread.
53   pthread_exit(nullptr);
54 }
55 
WaitForAppProcess()56 void WaitForAppProcess() {
57   std::unique_lock<std::mutex> lock(g_guest_loader_mtx);
58   g_guest_loader_cv.wait(lock, [] { return g_guest_loader_initialized; });
59 }
60 
61 }  // namespace berberis