1 /*
2  * Copyright 2022 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 #define LOG_TAG "VirtualizationService"
18 
19 #include <android-base/unique_fd.h>
20 #include <android/avf_cc_flags.h>
21 #include <android/binder_ibinder_jni.h>
22 #include <jni.h>
23 #include <log/log.h>
24 #include <poll.h>
25 
26 #include <string>
27 
28 #include "common.h"
29 
30 using namespace android::base;
31 
32 static constexpr const char VIRTMGR_PATH[] = "/apex/com.android.virt/bin/virtmgr";
33 static constexpr size_t VIRTMGR_THREADS = 2;
34 
35 extern "C" JNIEXPORT jint JNICALL
Java_android_system_virtualmachine_VirtualizationService_nativeSpawn(JNIEnv * env,jclass clazz)36 Java_android_system_virtualmachine_VirtualizationService_nativeSpawn(
37         JNIEnv* env, [[maybe_unused]] jclass clazz) {
38     unique_fd serverFd, clientFd;
39     if (!Socketpair(SOCK_STREAM, &serverFd, &clientFd)) {
40         env->ThrowNew(env->FindClass("android/system/virtualmachine/VirtualMachineException"),
41                       ("Failed to create socketpair: " + std::string(strerror(errno))).c_str());
42         return -1;
43     }
44 
45     unique_fd waitFd, readyFd;
46     if (!Pipe(&waitFd, &readyFd, 0)) {
47         env->ThrowNew(env->FindClass("android/system/virtualmachine/VirtualMachineException"),
48                       ("Failed to create pipe: " + std::string(strerror(errno))).c_str());
49         return -1;
50     }
51 
52     if (fork() == 0) {
53         // Close client's FDs.
54         clientFd.reset();
55         waitFd.reset();
56 
57         auto strServerFd = std::to_string(serverFd.get());
58         auto strReadyFd = std::to_string(readyFd.get());
59 
60         execl(VIRTMGR_PATH, VIRTMGR_PATH, "--rpc-server-fd", strServerFd.c_str(), "--ready-fd",
61               strReadyFd.c_str(), NULL);
62     }
63 
64     // Close virtmgr's FDs.
65     serverFd.reset();
66     readyFd.reset();
67 
68     // Wait for the server to signal its readiness by closing its end of the pipe.
69     char buf;
70     int ret = read(waitFd.get(), &buf, sizeof(buf));
71     if (ret < 0) {
72         env->ThrowNew(env->FindClass("android/system/virtualmachine/VirtualMachineException"),
73                       "Failed to wait for VirtualizationService to be ready");
74         return -1;
75     } else if (ret < 1) {
76         env->ThrowNew(env->FindClass("java/lang/SecurityException"),
77                       "Virtmgr didn't send any data through pipe. Please consider checking if "
78                       "android.permission.MANAGE_VIRTUAL_MACHINE permission is granted");
79         return -1;
80     }
81 
82     return clientFd.release();
83 }
84 
85 extern "C" JNIEXPORT jobject JNICALL
Java_android_system_virtualmachine_VirtualizationService_nativeConnect(JNIEnv * env,jobject obj,int clientFd)86 Java_android_system_virtualmachine_VirtualizationService_nativeConnect(JNIEnv* env,
87                                                                        [[maybe_unused]] jobject obj,
88                                                                        int clientFd) {
89     RpcSessionHandle session;
90     ARpcSession_setFileDescriptorTransportMode(session.get(),
91                                                ARpcSession_FileDescriptorTransportMode::Unix);
92     ARpcSession_setMaxIncomingThreads(session.get(), VIRTMGR_THREADS);
93     // SAFETY - ARpcSession_setupUnixDomainBootstrapClient does not take ownership of clientFd.
94     auto client = ARpcSession_setupUnixDomainBootstrapClient(session.get(), clientFd);
95     return AIBinder_toJavaBinder(env, client);
96 }
97 
98 extern "C" JNIEXPORT jboolean JNICALL
Java_android_system_virtualmachine_VirtualizationService_nativeIsOk(JNIEnv * env,jobject obj,int clientFd)99 Java_android_system_virtualmachine_VirtualizationService_nativeIsOk(JNIEnv* env,
100                                                                     [[maybe_unused]] jobject obj,
101                                                                     int clientFd) {
102     /* Setting events=0 only returns POLLERR, POLLHUP or POLLNVAL. */
103     struct pollfd pfds[] = {{.fd = clientFd, .events = 0}};
104     if (poll(pfds, /*nfds*/ 1, /*timeout*/ 0) < 0) {
105         env->ThrowNew(env->FindClass("android/system/virtualmachine/VirtualMachineException"),
106                       ("Failed to poll client FD: " + std::string(strerror(errno))).c_str());
107         return false;
108     }
109     return pfds[0].revents == 0;
110 }
111 
112 extern "C" JNIEXPORT jboolean JNICALL
Java_android_system_virtualmachine_VirtualizationService_nativeIsVendorModulesFlagEnabled(JNIEnv * env,jobject obj)113 Java_android_system_virtualmachine_VirtualizationService_nativeIsVendorModulesFlagEnabled(
114         [[maybe_unused]] JNIEnv* env, [[maybe_unused]] jobject obj) {
115     return android::virtualization::IsVendorModulesFlagEnabled();
116 }
117