Merge "Add a uid_gid test for zipfuse"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 321dbf4..c37fd19 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -46,9 +46,18 @@
"path": "packages/modules/Virtualization/virtualizationservice"
},
{
+ "path": "packages/modules/Virtualization/libs/apexutil"
+ },
+ {
"path": "packages/modules/Virtualization/libs/apkverify"
},
{
+ "path": "packages/modules/Virtualization/libs/avb"
+ },
+ {
+ "path": "packages/modules/Virtualization/libs/capabilities"
+ },
+ {
"path": "packages/modules/Virtualization/libs/devicemapper"
},
{
@@ -58,12 +67,18 @@
"path": "packages/modules/Virtualization/authfs"
},
{
+ "path": "packages/modules/Virtualization/microdroid_manager"
+ },
+ {
"path": "packages/modules/Virtualization/pvmfw"
},
{
"path": "packages/modules/Virtualization/rialto"
},
{
+ "path": "packages/modules/Virtualization/vm"
+ },
+ {
"path": "packages/modules/Virtualization/vmbase"
},
{
diff --git a/demo/java/com/android/microdroid/demo/MainActivity.java b/demo/java/com/android/microdroid/demo/MainActivity.java
index 54d7420..c3fa55f 100644
--- a/demo/java/com/android/microdroid/demo/MainActivity.java
+++ b/demo/java/com/android/microdroid/demo/MainActivity.java
@@ -19,7 +19,6 @@
import android.app.Application;
import android.os.Bundle;
import android.os.IBinder;
-import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.system.virtualmachine.VirtualMachine;
import android.system.virtualmachine.VirtualMachineCallback;
@@ -243,7 +242,7 @@
try {
VirtualMachineConfig.Builder builder =
new VirtualMachineConfig.Builder(getApplication());
- builder.setPayloadBinaryPath("MicrodroidTestNativeLib.so");
+ builder.setPayloadBinaryName("MicrodroidTestNativeLib.so");
builder.setProtectedVm(true);
if (debug) {
builder.setDebugLevel(VirtualMachineConfig.DEBUG_LEVEL_FULL);
diff --git a/javalib/Android.bp b/javalib/Android.bp
index 3f957d2..118b648 100644
--- a/javalib/Android.bp
+++ b/javalib/Android.bp
@@ -56,3 +56,12 @@
name: "android-virtualization-framework-sdk",
api_dirs: ["32"],
}
+
+java_api_contribution {
+ name: "framework-virtualization-public-stubs",
+ api_surface: "public",
+ api_file: "api/current.txt",
+ visibility: [
+ "//build/orchestrator/apis",
+ ],
+}
diff --git a/javalib/api/system-current.txt b/javalib/api/system-current.txt
index 30e437b..71bdf13 100644
--- a/javalib/api/system-current.txt
+++ b/javalib/api/system-current.txt
@@ -61,7 +61,7 @@
method @IntRange(from=0) public long getEncryptedStorageKib();
method @IntRange(from=0) public int getMemoryMib();
method @IntRange(from=1) public int getNumCpus();
- method @Nullable public String getPayloadBinaryPath();
+ method @Nullable public String getPayloadBinaryName();
method public boolean isCompatibleWith(@NonNull android.system.virtualmachine.VirtualMachineConfig);
method public boolean isEncryptedStorageEnabled();
method public boolean isProtectedVm();
@@ -77,7 +77,7 @@
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setEncryptedStorageKib(@IntRange(from=1) long);
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setMemoryMib(@IntRange(from=1) int);
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setNumCpus(@IntRange(from=1) int);
- method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryPath(@NonNull String);
+ method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryName(@NonNull String);
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setProtectedVm(boolean);
}
diff --git a/javalib/jni/android_system_virtualmachine_VirtualMachine.cpp b/javalib/jni/android_system_virtualmachine_VirtualMachine.cpp
index 3230af4..afdc944 100644
--- a/javalib/jni/android_system_virtualmachine_VirtualMachine.cpp
+++ b/javalib/jni/android_system_virtualmachine_VirtualMachine.cpp
@@ -27,7 +27,8 @@
#include "common.h"
-JNIEXPORT jobject JNICALL android_system_virtualmachine_VirtualMachine_connectToVsockServer(
+extern "C" JNIEXPORT jobject JNICALL
+Java_android_system_virtualmachine_VirtualMachine_nativeConnectToVsockServer(
JNIEnv* env, [[maybe_unused]] jclass clazz, jobject vmBinder, jint port) {
using aidl::android::system::virtualizationservice::IVirtualMachine;
using ndk::ScopedFileDescriptor;
@@ -59,32 +60,3 @@
auto client = ARpcSession_setupPreconnectedClient(session.get(), requestFunc, &args);
return AIBinder_toJavaBinder(env, client);
}
-
-JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/) {
- JNIEnv* env;
- if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
- ALOGE("%s: Failed to get the environment", __FUNCTION__);
- return JNI_ERR;
- }
-
- jclass c = env->FindClass("android/system/virtualmachine/VirtualMachine");
- if (c == nullptr) {
- ALOGE("%s: Failed to find class android.system.virtualmachine.VirtualMachine",
- __FUNCTION__);
- return JNI_ERR;
- }
-
- // Register your class' native methods.
- static const JNINativeMethod methods[] = {
- {"nativeConnectToVsockServer", "(Landroid/os/IBinder;I)Landroid/os/IBinder;",
- reinterpret_cast<void*>(
- android_system_virtualmachine_VirtualMachine_connectToVsockServer)},
- };
- int rc = env->RegisterNatives(c, methods, sizeof(methods) / sizeof(JNINativeMethod));
- if (rc != JNI_OK) {
- ALOGE("%s: Failed to register natives", __FUNCTION__);
- return rc;
- }
-
- return JNI_VERSION_1_6;
-}
diff --git a/javalib/jni/android_system_virtualmachine_VirtualizationService.cpp b/javalib/jni/android_system_virtualmachine_VirtualizationService.cpp
index b0e2cd2..bd80880 100644
--- a/javalib/jni/android_system_virtualmachine_VirtualizationService.cpp
+++ b/javalib/jni/android_system_virtualmachine_VirtualizationService.cpp
@@ -31,7 +31,8 @@
static constexpr const char VIRTMGR_PATH[] = "/apex/com.android.virt/bin/virtmgr";
static constexpr size_t VIRTMGR_THREADS = 16;
-JNIEXPORT jint JNICALL android_system_virtualmachine_VirtualizationService_spawn(
+extern "C" JNIEXPORT jint JNICALL
+Java_android_system_virtualmachine_VirtualizationService_nativeSpawn(
JNIEnv* env, [[maybe_unused]] jclass clazz) {
unique_fd serverFd, clientFd;
if (!Socketpair(SOCK_STREAM, &serverFd, &clientFd)) {
@@ -74,8 +75,10 @@
return clientFd.release();
}
-JNIEXPORT jobject JNICALL android_system_virtualmachine_VirtualizationService_connect(
- JNIEnv* env, [[maybe_unused]] jobject obj, int clientFd) {
+extern "C" JNIEXPORT jobject JNICALL
+Java_android_system_virtualmachine_VirtualizationService_nativeConnect(JNIEnv* env,
+ [[maybe_unused]] jobject obj,
+ int clientFd) {
RpcSessionHandle session;
ARpcSession_setFileDescriptorTransportMode(session.get(),
ARpcSession_FileDescriptorTransportMode::Unix);
@@ -86,8 +89,10 @@
return AIBinder_toJavaBinder(env, client);
}
-JNIEXPORT jboolean JNICALL android_system_virtualmachine_VirtualizationService_isOk(
- JNIEnv* env, [[maybe_unused]] jobject obj, int clientFd) {
+extern "C" JNIEXPORT jboolean JNICALL
+Java_android_system_virtualmachine_VirtualizationService_nativeIsOk(JNIEnv* env,
+ [[maybe_unused]] jobject obj,
+ int clientFd) {
/* Setting events=0 only returns POLLERR, POLLHUP or POLLNVAL. */
struct pollfd pfds[] = {{.fd = clientFd, .events = 0}};
if (poll(pfds, /*nfds*/ 1, /*timeout*/ 0) < 0) {
@@ -97,35 +102,3 @@
}
return pfds[0].revents == 0;
}
-
-JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/) {
- JNIEnv* env;
- if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
- ALOGE("%s: Failed to get the environment", __FUNCTION__);
- return JNI_ERR;
- }
-
- jclass c = env->FindClass("android/system/virtualmachine/VirtualizationService");
- if (c == nullptr) {
- ALOGE("%s: Failed to find class android.system.virtualmachine.VirtualizationService",
- __FUNCTION__);
- return JNI_ERR;
- }
-
- // Register your class' native methods.
- static const JNINativeMethod methods[] = {
- {"nativeSpawn", "()I",
- reinterpret_cast<void*>(android_system_virtualmachine_VirtualizationService_spawn)},
- {"nativeConnect", "(I)Landroid/os/IBinder;",
- reinterpret_cast<void*>(android_system_virtualmachine_VirtualizationService_connect)},
- {"nativeIsOk", "(I)Z",
- reinterpret_cast<void*>(android_system_virtualmachine_VirtualizationService_isOk)},
- };
- int rc = env->RegisterNatives(c, methods, sizeof(methods) / sizeof(JNINativeMethod));
- if (rc != JNI_OK) {
- ALOGE("%s: Failed to register natives", __FUNCTION__);
- return rc;
- }
-
- return JNI_VERSION_1_6;
-}
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachine.java b/javalib/src/android/system/virtualmachine/VirtualMachine.java
index 3295681..e319aa3 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -162,7 +162,7 @@
})
public @interface Status {}
- /** The virtual machine has just been created, or {@link #stop()} was called on it. */
+ /** The virtual machine has just been created, or {@link #stop} was called on it. */
public static final int STATUS_STOPPED = 0;
/** The virtual machine is running. */
@@ -278,6 +278,9 @@
}
}
+ /** Running instance of virtmgr that hosts VirtualizationService for this VM. */
+ @NonNull private final VirtualizationService mVirtualizationService;
+
@NonNull private final MemoryManagementCallbacks mMemoryManagementCallbacks;
@NonNull private final Context mContext;
@@ -333,9 +336,6 @@
@Nullable
private Executor mCallbackExecutor;
- /* Running instance of virtmgr that hosts VirtualizationService for this VM. */
- @NonNull private VirtualizationService mVirtualizationService;
-
private static class ExtraApkSpec {
public final File apk;
public final File idsig;
@@ -588,8 +588,7 @@
* Returns the currently selected config of this virtual machine. There can be multiple virtual
* machines sharing the same config. Even in that case, the virtual machines are completely
* isolated from each other; they have different secrets. It is also possible that a virtual
- * machine can change its config, which can be done by calling {@link
- * #setConfig(VirtualMachineConfig)}.
+ * machine can change its config, which can be done by calling {@link #setConfig}.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
@@ -748,8 +747,7 @@
/**
* Runs this virtual machine. The returning of this method however doesn't mean that the VM has
* actually started running or the OS has booted there. Such events can be notified by
- * registering a callback using {@link #setCallback(Executor, VirtualMachineCallback)} before
- * calling {@code run()}.
+ * registering a callback using {@link #setCallback} before calling {@code run()}.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
@@ -933,7 +931,15 @@
/**
* Stops this virtual machine. Stopping a virtual machine is like pulling the plug on a real
* computer; the machine halts immediately. Software running on the virtual machine is not
- * notified of the event. A stopped virtual machine can be re-started by calling {@link #run()}.
+ * notified of the event. Writes to {@linkplain
+ * VirtualMachineConfig.Builder#setEncryptedStorageKib encrypted storage} might not be
+ * persisted, and the instance might be left in an inconsistent state.
+ *
+ * <p>For a graceful shutdown, you could request the payload to call {@code exit()}, e.g. via a
+ * {@linkplain #connectToVsockServer binder request}, and wait for {@link
+ * VirtualMachineCallback#onPayloadFinished} to be called.
+ *
+ * <p>A stopped virtual machine can be re-started by calling {@link #run()}.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
@@ -1016,8 +1022,8 @@
* like the number of CPU and size of the RAM, depending on the situation (e.g. the size of the
* application to run on the virtual machine, etc.)
*
- * <p>The new config must be {@link VirtualMachineConfig#isCompatibleWith compatible with} the
- * existing config.
+ * <p>The new config must be {@linkplain VirtualMachineConfig#isCompatibleWith compatible with}
+ * the existing config.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
@@ -1053,8 +1059,8 @@
/**
* Connect to a VM's binder service via vsock and return the root IBinder object. Guest VMs are
* expected to set up vsock servers in their payload. After the host app receives the {@link
- * VirtualMachineCallback#onPayloadReady(VirtualMachine)}, it can use this method to establish a
- * connection to the guest VM.
+ * VirtualMachineCallback#onPayloadReady}, it can use this method to establish a connection to
+ * the guest VM.
*
* <p>NOTE: This method may block and should not be called on the main thread.
*
@@ -1082,6 +1088,8 @@
/**
* Opens a vsock connection to the VM on the given port.
*
+ * <p>The caller is responsible for closing the returned {@code ParcelFileDescriptor}.
+ *
* <p>NOTE: This method may block and should not be called on the main thread.
*
* @throws VirtualMachineException if connecting fails.
@@ -1218,17 +1226,15 @@
public String toString() {
VirtualMachineConfig config = getConfig();
String payloadConfigPath = config.getPayloadConfigPath();
- String payloadBinaryPath = config.getPayloadBinaryPath();
+ String payloadBinaryName = config.getPayloadBinaryName();
StringBuilder result = new StringBuilder();
result.append("VirtualMachine(")
.append("name:")
.append(getName())
.append(", ");
- if (payloadBinaryPath != null) {
- result.append("payload:")
- .append(payloadBinaryPath)
- .append(", ");
+ if (payloadBinaryName != null) {
+ result.append("payload:").append(payloadBinaryName).append(", ");
}
if (payloadConfigPath != null) {
result.append("config:")
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java b/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java
index 9aaecf0..d72ba14 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineCallback.java
@@ -141,8 +141,8 @@
void onPayloadStarted(@NonNull VirtualMachine vm);
/**
- * Called when the payload in the VM is ready to serve. See
- * {@link VirtualMachine#connectToVsockServer(int)}.
+ * Called when the payload in the VM is ready to serve. See {@link
+ * VirtualMachine#connectToVsockServer}.
*/
void onPayloadReady(@NonNull VirtualMachine vm);
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index 7555dec..0e9e86b 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -62,7 +62,7 @@
private static final String KEY_VERSION = "version";
private static final String KEY_APKPATH = "apkPath";
private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
- private static final String KEY_PAYLOADBINARYPATH = "payloadBinaryPath";
+ private static final String KEY_PAYLOADBINARYNAME = "payloadBinaryPath";
private static final String KEY_DEBUGLEVEL = "debugLevel";
private static final String KEY_PROTECTED_VM = "protectedVm";
private static final String KEY_MEMORY_MIB = "memoryMib";
@@ -118,10 +118,8 @@
*/
@Nullable private final String mPayloadConfigPath;
- /**
- * Path within the APK to the payload binary file that will be executed within the VM.
- */
- @Nullable private final String mPayloadBinaryPath;
+ /** Name of the payload binary file within the APK that will be executed within the VM. */
+ @Nullable private final String mPayloadBinaryName;
/** The size of storage in KiB. 0 indicates that encryptedStorage is not required */
private final long mEncryptedStorageKib;
@@ -129,7 +127,7 @@
private VirtualMachineConfig(
@NonNull String apkPath,
@Nullable String payloadConfigPath,
- @Nullable String payloadBinaryPath,
+ @Nullable String payloadBinaryName,
@DebugLevel int debugLevel,
boolean protectedVm,
int memoryMib,
@@ -138,7 +136,7 @@
// This is only called from Builder.build(); the builder handles parameter validation.
mApkPath = apkPath;
mPayloadConfigPath = payloadConfigPath;
- mPayloadBinaryPath = payloadBinaryPath;
+ mPayloadBinaryName = payloadBinaryName;
mDebugLevel = debugLevel;
mProtectedVm = protectedVm;
mMemoryMib = memoryMib;
@@ -192,7 +190,7 @@
String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
if (payloadConfigPath == null) {
- builder.setPayloadBinaryPath(b.getString(KEY_PAYLOADBINARYPATH));
+ builder.setPayloadBinaryName(b.getString(KEY_PAYLOADBINARYNAME));
} else {
builder.setPayloadConfigPath(payloadConfigPath);
}
@@ -231,7 +229,7 @@
b.putInt(KEY_VERSION, VERSION);
b.putString(KEY_APKPATH, mApkPath);
b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
- b.putString(KEY_PAYLOADBINARYPATH, mPayloadBinaryPath);
+ b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
b.putBoolean(KEY_PROTECTED_VM, mProtectedVm);
b.putInt(KEY_NUM_CPUS, mNumCpus);
@@ -269,15 +267,15 @@
}
/**
- * Returns the path within the {@code lib/<ABI>} directory of the APK to the payload binary file
+ * Returns the name of the payload binary file, in the {@code lib/<ABI>} directory of the APK,
* that will be executed within the VM.
*
* @hide
*/
@SystemApi
@Nullable
- public String getPayloadBinaryPath() {
- return mPayloadBinaryPath;
+ public String getPayloadBinaryName() {
+ return mPayloadBinaryName;
}
/**
@@ -362,7 +360,7 @@
&& this.mProtectedVm == other.mProtectedVm
&& this.mEncryptedStorageKib == other.mEncryptedStorageKib
&& Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
- && Objects.equals(this.mPayloadBinaryPath, other.mPayloadBinaryPath)
+ && Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
&& this.mApkPath.equals(other.mApkPath);
}
@@ -376,9 +374,9 @@
VirtualMachineAppConfig toVsConfig() throws FileNotFoundException {
VirtualMachineAppConfig vsConfig = new VirtualMachineAppConfig();
vsConfig.apk = ParcelFileDescriptor.open(new File(mApkPath), MODE_READ_ONLY);
- if (mPayloadBinaryPath != null) {
+ if (mPayloadBinaryName != null) {
VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
- payloadConfig.payloadPath = mPayloadBinaryPath;
+ payloadConfig.payloadBinaryName = mPayloadBinaryName;
vsConfig.payload =
VirtualMachineAppConfig.Payload.payloadConfig(payloadConfig);
} else {
@@ -411,7 +409,7 @@
@Nullable private final Context mContext;
@Nullable private String mApkPath;
@Nullable private String mPayloadConfigPath;
- @Nullable private String mPayloadBinaryPath;
+ @Nullable private String mPayloadBinaryName;
@DebugLevel private int mDebugLevel = DEBUG_LEVEL_NONE;
private boolean mProtectedVm;
private boolean mProtectedVmSet;
@@ -455,14 +453,14 @@
apkPath = mApkPath;
}
- if (mPayloadBinaryPath == null) {
+ if (mPayloadBinaryName == null) {
if (mPayloadConfigPath == null) {
- throw new IllegalStateException("setPayloadBinaryPath must be called");
+ throw new IllegalStateException("setPayloadBinaryName must be called");
}
} else {
if (mPayloadConfigPath != null) {
throw new IllegalStateException(
- "setPayloadBinaryPath and setPayloadConfigPath may not both be called");
+ "setPayloadBinaryName and setPayloadConfigPath may not both be called");
}
}
@@ -473,7 +471,7 @@
return new VirtualMachineConfig(
apkPath,
mPayloadConfigPath,
- mPayloadBinaryPath,
+ mPayloadBinaryName,
mDebugLevel,
mProtectedVm,
mMemoryMib,
@@ -515,16 +513,23 @@
}
/**
- * Sets the path within the {@code lib/<ABI>} directory of the APK to the payload binary
- * file that will be executed within the VM.
+ * Sets the name of the payload binary file that will be executed within the VM, e.g.
+ * "payload.so". The file must reside in the {@code lib/<ABI>} directory of the APK.
+ *
+ * <p>Note that VMs only support 64-bit code, even if the owning app is running as a 32-bit
+ * process.
*
* @hide
*/
@SystemApi
@NonNull
- public Builder setPayloadBinaryPath(@NonNull String payloadBinaryPath) {
- mPayloadBinaryPath =
- requireNonNull(payloadBinaryPath, "payloadBinaryPath must not be null");
+ public Builder setPayloadBinaryName(@NonNull String payloadBinaryName) {
+ if (payloadBinaryName.contains(File.separator)) {
+ throw new IllegalArgumentException(
+ "Invalid binary file name: " + payloadBinaryName);
+ }
+ mPayloadBinaryName =
+ requireNonNull(payloadBinaryName, "payloadBinaryName must not be null");
return this;
}
@@ -587,7 +592,7 @@
/**
* Sets the number of vCPUs in the VM. Defaults to 1. Cannot be more than the number of real
- * CPUs (as returned by {@link Runtime#availableProcessors()}).
+ * CPUs (as returned by {@link Runtime#availableProcessors}).
*
* @hide
*/
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineDescriptor.java b/javalib/src/android/system/virtualmachine/VirtualMachineDescriptor.java
index c9718aa..483779a 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineDescriptor.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineDescriptor.java
@@ -29,7 +29,7 @@
* A VM descriptor that captures the state of a Virtual Machine.
*
* <p>You can capture the current state of VM by creating an instance of this class with {@link
- * VirtualMachine#toDescriptor()}, optionally pass it to another App, and then build an identical VM
+ * VirtualMachine#toDescriptor}, optionally pass it to another App, and then build an identical VM
* with the descriptor received.
*
* @hide
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineManager.java b/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
index 6aa8133..7773cb5 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
@@ -38,9 +38,9 @@
import java.util.Map;
/**
- * Manages {@link VirtualMachine virtual machine} instances created by an app. Each instance is
- * created from a {@link VirtualMachineConfig configuration} that defines the shape of the VM (RAM,
- * CPUs), the code to execute within it, etc.
+ * Manages {@linkplain VirtualMachine virtual machine} instances created by an app. Each instance is
+ * created from a {@linkplain VirtualMachineConfig configuration} that defines the shape of the VM
+ * (RAM, CPUs), the code to execute within it, etc.
*
* <p>Each virtual machine instance is named; the configuration and related state of each is
* persisted in the app's private data directory and an instance can be retrieved given the name.
diff --git a/javalib/src/android/system/virtualmachine/VirtualizationService.java b/javalib/src/android/system/virtualmachine/VirtualizationService.java
index 06ef494..75e359f 100644
--- a/javalib/src/android/system/virtualmachine/VirtualizationService.java
+++ b/javalib/src/android/system/virtualmachine/VirtualizationService.java
@@ -23,7 +23,7 @@
import com.android.internal.annotations.GuardedBy;
-import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
/** A running instance of virtmgr that is hosting a VirtualizationService AIDL service. */
class VirtualizationService {
@@ -33,7 +33,7 @@
/* Soft reference caching the last created instance of this class. */
@GuardedBy("VirtualMachineManager.sCreateLock")
- private static SoftReference<VirtualizationService> sInstance;
+ private static WeakReference<VirtualizationService> sInstance;
/*
* Client FD for UDS connection to virtmgr's RpcBinder server. Closing it
@@ -86,7 +86,7 @@
VirtualizationService service = (sInstance == null) ? null : sInstance.get();
if (service == null || !service.isOk()) {
service = new VirtualizationService();
- sInstance = new SoftReference(service);
+ sInstance = new WeakReference(service);
}
return service;
}
diff --git a/libs/apexutil/TEST_MAPPING b/libs/apexutil/TEST_MAPPING
new file mode 100644
index 0000000..f66a400
--- /dev/null
+++ b/libs/apexutil/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "avf-presubmit" : [
+ {
+ "name" : "libapexutil_rust.test"
+ }
+ ]
+}
diff --git a/libs/avb/TEST_MAPPING b/libs/avb/TEST_MAPPING
new file mode 100644
index 0000000..2f4bccc
--- /dev/null
+++ b/libs/avb/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "avf-presubmit" : [
+ {
+ "name" : "libavb_bindgen_test"
+ }
+ ]
+}
diff --git a/libs/capabilities/TEST_MAPPING b/libs/capabilities/TEST_MAPPING
new file mode 100644
index 0000000..568a771
--- /dev/null
+++ b/libs/capabilities/TEST_MAPPING
@@ -0,0 +1,10 @@
+{
+ "avf-presubmit" : [
+ {
+ "name" : "libcap_rust.test"
+ },
+ {
+ "name" : "libcap_bindgen_test"
+ }
+ ]
+}
diff --git a/libs/fdtpci/src/lib.rs b/libs/fdtpci/src/lib.rs
index a63e05b..1ddda9f 100644
--- a/libs/fdtpci/src/lib.rs
+++ b/libs/fdtpci/src/lib.rs
@@ -23,7 +23,7 @@
};
use libfdt::{AddressRange, Fdt, FdtError, FdtNode};
use log::debug;
-use virtio_drivers::pci::bus::{Cam, PciRoot};
+use virtio_drivers::transport::pci::bus::{Cam, PciRoot};
/// PCI MMIO configuration region size.
const PCI_CFG_SIZE: usize = 0x100_0000;
diff --git a/microdroid/payload/metadata.proto b/microdroid/payload/metadata.proto
index 1d8dd8c..c74c23b 100644
--- a/microdroid/payload/metadata.proto
+++ b/microdroid/payload/metadata.proto
@@ -65,6 +65,6 @@
message PayloadConfig {
// Required.
- // Path to the payload binary file inside the APK.
- string payload_binary_path = 1;
+ // Name of the payload binary file inside the APK.
+ string payload_binary_name = 1;
}
diff --git a/microdroid_manager/TEST_MAPPING b/microdroid_manager/TEST_MAPPING
new file mode 100644
index 0000000..af0abe7
--- /dev/null
+++ b/microdroid_manager/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "avf-presubmit" : [
+ {
+ "name" : "microdroid_manager_test"
+ }
+ ]
+}
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 1ef41cb..f48611b 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -259,7 +259,7 @@
// ? -71001: PayloadConfig
// }
// PayloadConfig = {
- // 1: tstr // payload_binary_path
+ // 1: tstr // payload_binary_name
// }
let mut config_desc = vec![
@@ -278,7 +278,7 @@
encode_negative_number(-71001, &mut config_desc)?;
encode_header(5, 1, &mut config_desc)?; // map(1)
encode_number(1, &mut config_desc)?;
- encode_tstr(&payload_config.payload_binary_path, &mut config_desc)?;
+ encode_tstr(&payload_config.payload_binary_name, &mut config_desc)?;
}
}
@@ -761,7 +761,7 @@
PayloadMetadata::config(payload_config) => {
let task = Task {
type_: TaskType::MicrodroidLauncher,
- command: payload_config.payload_binary_path,
+ command: payload_config.payload_binary_name,
};
Ok(VmPayloadConfig {
os: OsConfig { name: "microdroid".to_owned() },
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index d5f7283..f01c6b8 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -144,6 +144,45 @@
AvbIOResult::AVB_IO_RESULT_OK
}
+unsafe extern "C" fn get_preloaded_partition(
+ ops: *mut AvbOps,
+ partition: *const c_char,
+ num_bytes: usize,
+ out_pointer: *mut *mut u8,
+ out_num_bytes_preloaded: *mut usize,
+) -> AvbIOResult {
+ to_avb_io_result(try_get_preloaded_partition(
+ ops,
+ partition,
+ num_bytes,
+ out_pointer,
+ out_num_bytes_preloaded,
+ ))
+}
+
+fn try_get_preloaded_partition(
+ ops: *mut AvbOps,
+ partition: *const c_char,
+ num_bytes: usize,
+ out_pointer: *mut *mut u8,
+ out_num_bytes_preloaded: *mut usize,
+) -> Result<(), AvbIOError> {
+ let ops = as_avbops_ref(ops)?;
+ let partition = ops.as_ref().get_partition(partition)?;
+ let out_pointer = to_nonnull(out_pointer)?;
+ // SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
+ unsafe {
+ *out_pointer.as_ptr() = partition.as_ptr() as _;
+ }
+ let out_num_bytes_preloaded = to_nonnull(out_num_bytes_preloaded)?;
+ // SAFETY: The raw pointer `out_num_bytes_preloaded` was created to point to a valid a `usize`
+ // and we checked it is nonnull.
+ unsafe {
+ *out_num_bytes_preloaded.as_ptr() = partition.len().min(num_bytes);
+ }
+ Ok(())
+}
+
extern "C" fn read_from_partition(
ops: *mut AvbOps,
partition: *const c_char,
@@ -355,7 +394,7 @@
ab_ops: ptr::null_mut(),
atx_ops: ptr::null_mut(),
read_from_partition: Some(read_from_partition),
- get_preloaded_partition: None,
+ get_preloaded_partition: Some(get_preloaded_partition),
write_to_partition: None,
validate_vbmeta_public_key: None,
read_rollback_index: Some(read_rollback_index),
@@ -393,10 +432,12 @@
mod tests {
use super::*;
use anyhow::Result;
- use std::fs;
+ use avb_bindgen::AvbFooter;
+ use std::{fs, mem::size_of};
const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
+ const RANDOM_FOOTER_POS: usize = 30;
/// This test uses the Microdroid payload compiled on the fly to check that
/// the latest payload can be verified successfully.
@@ -457,6 +498,19 @@
)
}
+ #[test]
+ fn tampered_kernel_footer_fails_verification() -> Result<()> {
+ let mut kernel = load_latest_signed_kernel()?;
+ let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
+ kernel[avb_footer_index] = !kernel[avb_footer_index];
+
+ assert_payload_verification_fails(
+ &kernel,
+ &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
+ AvbImageVerifyError::InvalidMetadata,
+ )
+ }
+
fn assert_payload_verification_fails(
kernel: &[u8],
trusted_public_key: &[u8],
diff --git a/pvmfw/src/pci.rs b/pvmfw/src/pci.rs
index e9ac45b..2b81772 100644
--- a/pvmfw/src/pci.rs
+++ b/pvmfw/src/pci.rs
@@ -17,7 +17,7 @@
use crate::{entry::RebootReason, memory::MemoryTracker};
use fdtpci::{PciError, PciInfo};
use log::{debug, error};
-use virtio_drivers::pci::{bus::PciRoot, virtio_device_type};
+use virtio_drivers::transport::pci::{bus::PciRoot, virtio_device_type};
/// Maps the CAM and BAR range in the page table and MMIO guard.
pub fn map_mmio(pci_info: &PciInfo, memory: &mut MemoryTracker) -> Result<(), RebootReason> {
diff --git a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
index 3c3faf2..9e4b228 100644
--- a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
+++ b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
@@ -65,6 +65,7 @@
private static final String APEX_ETC_FS = "/apex/com.android.virt/etc/fs/";
private static final double SIZE_MB = 1024.0 * 1024.0;
+ private static final double NANO_TO_MILLI = 1000000.0;
private static final String MICRODROID_IMG_PREFIX = "microdroid_";
private static final String MICRODROID_IMG_SUFFIX = ".img";
@@ -80,10 +81,11 @@
private Instrumentation mInstrumentation;
@Before
- public void setup() {
+ public void setup() throws IOException {
grantPermission(VirtualMachine.MANAGE_VIRTUAL_MACHINE_PERMISSION);
grantPermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
prepareTestSetup(mProtectedVm);
+ setMaxPerformanceTaskProfile();
mInstrumentation = getInstrumentation();
}
@@ -91,7 +93,7 @@
throws VirtualMachineException, InterruptedException, IOException {
VirtualMachineConfig normalConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_NONE)
.setMemoryMib(mem)
.build();
@@ -140,19 +142,12 @@
final int trialCount = 10;
- List<Double> vmStartingTimeMetrics = new ArrayList<>();
List<Double> bootTimeMetrics = new ArrayList<>();
- List<Double> bootloaderTimeMetrics = new ArrayList<>();
- List<Double> kernelBootTimeMetrics = new ArrayList<>();
- List<Double> userspaceBootTimeMetrics = new ArrayList<>();
-
for (int i = 0; i < trialCount; i++) {
-
- // To grab boot events from log, set debug mode to FULL
VirtualMachineConfig normalConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
- .setDebugLevel(DEBUG_LEVEL_FULL)
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
+ .setDebugLevel(DEBUG_LEVEL_NONE)
.setMemoryMib(256)
.build();
forceCreateNewVirtualMachine("test_vm_boot_time", normalConfig);
@@ -160,12 +155,74 @@
BootResult result = tryBootVm(TAG, "test_vm_boot_time");
assertThat(result.payloadStarted).isTrue();
- final double nanoToMilli = 1000000.0;
- vmStartingTimeMetrics.add(result.getVMStartingElapsedNanoTime() / nanoToMilli);
- bootTimeMetrics.add(result.endToEndNanoTime / nanoToMilli);
- bootloaderTimeMetrics.add(result.getBootloaderElapsedNanoTime() / nanoToMilli);
- kernelBootTimeMetrics.add(result.getKernelElapsedNanoTime() / nanoToMilli);
- userspaceBootTimeMetrics.add(result.getUserspaceElapsedNanoTime() / nanoToMilli);
+ bootTimeMetrics.add(result.endToEndNanoTime / NANO_TO_MILLI);
+ }
+
+ reportMetrics(bootTimeMetrics, "boot_time", "ms");
+ }
+
+ @Test
+ public void testMicrodroidMulticoreBootTime()
+ throws VirtualMachineException, InterruptedException, IOException {
+ assume().withMessage("Skip on CF; too slow").that(isCuttlefish()).isFalse();
+
+ final int trialCount = 10;
+ final int[] trialNumCpus = {2, 4, 8};
+
+ for (int numCpus : trialNumCpus) {
+ List<Double> bootTimeMetrics = new ArrayList<>();
+ for (int i = 0; i < trialCount; i++) {
+ VirtualMachineConfig normalConfig =
+ newVmConfigBuilder()
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
+ .setDebugLevel(DEBUG_LEVEL_NONE)
+ .setMemoryMib(256)
+ .setNumCpus(numCpus)
+ .build();
+ forceCreateNewVirtualMachine("test_vm_boot_time_multicore", normalConfig);
+
+ BootResult result = tryBootVm(TAG, "test_vm_boot_time_multicore");
+ assertThat(result.payloadStarted).isTrue();
+
+ bootTimeMetrics.add(result.endToEndNanoTime / NANO_TO_MILLI);
+ }
+
+ String metricName = "boot_time_" + numCpus + "cpus";
+ reportMetrics(bootTimeMetrics, metricName, "ms");
+ }
+ }
+
+ @Test
+ public void testMicrodroidDebugBootTime()
+ throws VirtualMachineException, InterruptedException, IOException {
+ assume().withMessage("Skip on CF; too slow").that(isCuttlefish()).isFalse();
+
+ final int trialCount = 10;
+
+ List<Double> vmStartingTimeMetrics = new ArrayList<>();
+ List<Double> bootTimeMetrics = new ArrayList<>();
+ List<Double> bootloaderTimeMetrics = new ArrayList<>();
+ List<Double> kernelBootTimeMetrics = new ArrayList<>();
+ List<Double> userspaceBootTimeMetrics = new ArrayList<>();
+
+ for (int i = 0; i < trialCount; i++) {
+ // To grab boot events from log, set debug mode to FULL
+ VirtualMachineConfig normalConfig =
+ newVmConfigBuilder()
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
+ .setDebugLevel(DEBUG_LEVEL_FULL)
+ .setMemoryMib(256)
+ .build();
+ forceCreateNewVirtualMachine("test_vm_boot_time_debug", normalConfig);
+
+ BootResult result = tryBootVm(TAG, "test_vm_boot_time_debug");
+ assertThat(result.payloadStarted).isTrue();
+
+ vmStartingTimeMetrics.add(result.getVMStartingElapsedNanoTime() / NANO_TO_MILLI);
+ bootTimeMetrics.add(result.endToEndNanoTime / NANO_TO_MILLI);
+ bootloaderTimeMetrics.add(result.getBootloaderElapsedNanoTime() / NANO_TO_MILLI);
+ kernelBootTimeMetrics.add(result.getKernelElapsedNanoTime() / NANO_TO_MILLI);
+ userspaceBootTimeMetrics.add(result.getUserspaceElapsedNanoTime() / NANO_TO_MILLI);
}
reportMetrics(vmStartingTimeMetrics, "vm_starting_time", "ms");
diff --git a/tests/benchmark/src/native/io_vsock.cpp b/tests/benchmark/src/native/io_vsock.cpp
index 8edc7c8..b1a4c96 100644
--- a/tests/benchmark/src/native/io_vsock.cpp
+++ b/tests/benchmark/src/native/io_vsock.cpp
@@ -59,15 +59,25 @@
}
LOG(INFO) << "VM:Connection from CID " << client_sa.svm_cid << " on port "
<< client_sa.svm_port;
- std::string data;
- if (!ReadFdToString(client_fd, &data)) {
- return Error() << "Cannot get data from the host.";
+
+ ssize_t total = 0;
+ char buf[4096];
+ for (;;) {
+ ssize_t n = TEMP_FAILURE_RETRY(read(client_fd.get(), buf, sizeof(buf)));
+ if (n < 0) {
+ return Error() << "Cannot get data from the host.";
+ }
+ if (n == 0) {
+ break;
+ }
+ total += n;
}
- if (data.length() != num_bytes_to_receive) {
- return Error() << "Received data length(" << data.length() << ") is not equal to "
+
+ if (total != num_bytes_to_receive) {
+ return Error() << "Received data length(" << total << ") is not equal to "
<< num_bytes_to_receive;
}
LOG(INFO) << "VM:Finished reading data.";
return {};
}
-} // namespace io_vsock
\ No newline at end of file
+} // namespace io_vsock
diff --git a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
index 536f663..d762310 100644
--- a/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
+++ b/tests/helper/src/java/com/android/microdroid/test/device/MicrodroidDeviceTestBase.java
@@ -24,6 +24,7 @@
import android.content.Context;
import android.os.ParcelFileDescriptor;
import android.os.SystemProperties;
+import android.system.Os;
import android.system.virtualmachine.VirtualMachine;
import android.system.virtualmachine.VirtualMachineCallback;
import android.system.virtualmachine.VirtualMachineConfig;
@@ -50,6 +51,8 @@
import java.util.concurrent.TimeUnit;
public abstract class MicrodroidDeviceTestBase {
+ private final String MAX_PERFORMANCE_TASK_PROFILE = "CPUSET_SP_TOP_APP";
+
public static boolean isCuttlefish() {
return DeviceProperties.create(SystemProperties::get).isCuttlefish();
}
@@ -73,6 +76,17 @@
permission);
}
+ protected final void setMaxPerformanceTaskProfile() throws IOException {
+ Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+ UiAutomation uiAutomation = instrumentation.getUiAutomation();
+ String cmd = "settaskprofile " + Os.gettid() + " " + MAX_PERFORMANCE_TASK_PROFILE;
+ String out = runInShell("MicrodroidDeviceTestBase", uiAutomation, cmd).trim();
+ String expect = "Profile " + MAX_PERFORMANCE_TASK_PROFILE + " is applied successfully!";
+ if (!expect.equals(out)) {
+ throw new IOException("Could not apply max performance task profile: " + out);
+ }
+ }
+
private Context mCtx;
private boolean mProtectedVm;
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 464e091..617c300 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -792,6 +792,39 @@
+ " permission");
}
+ @Test
+ public void testPathToBinaryIsRejected() throws Exception {
+ CommandRunner android = new CommandRunner(getDevice());
+
+ // Create the idsig file for the APK
+ final String apkPath = getPathForPackage(PACKAGE_NAME);
+ final String idSigPath = TEST_ROOT + "idsig";
+ android.run(VIRT_APEX + "bin/vm", "create-idsig", apkPath, idSigPath);
+
+ // Create the instance image for the VM
+ final String instanceImgPath = TEST_ROOT + "instance.img";
+ android.run(
+ VIRT_APEX + "bin/vm",
+ "create-partition",
+ "--type instance",
+ instanceImgPath,
+ Integer.toString(10 * 1024 * 1024));
+
+ final String ret =
+ android.runForResult(
+ VIRT_APEX + "bin/vm",
+ "run-app",
+ "--payload-binary-name",
+ "./MicrodroidTestNativeLib.so",
+ apkPath,
+ idSigPath,
+ instanceImgPath)
+ .getStderr()
+ .trim();
+
+ assertThat(ret).contains("Payload binary name must not specify a path");
+ }
+
@Before
public void setUp() throws Exception {
testIfDeviceIsCapable(getDevice());
diff --git a/tests/testapk/assets/file.txt b/tests/testapk/assets/file.txt
new file mode 100644
index 0000000..4de897c
--- /dev/null
+++ b/tests/testapk/assets/file.txt
@@ -0,0 +1 @@
+Hello, I am a file!
\ No newline at end of file
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 897879b..c1c4b53 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -20,6 +20,8 @@
import static android.system.virtualmachine.VirtualMachine.STATUS_STOPPED;
import static android.system.virtualmachine.VirtualMachineConfig.DEBUG_LEVEL_FULL;
import static android.system.virtualmachine.VirtualMachineConfig.DEBUG_LEVEL_NONE;
+import static android.system.virtualmachine.VirtualMachineManager.CAPABILITY_NON_PROTECTED_VM;
+import static android.system.virtualmachine.VirtualMachineManager.CAPABILITY_PROTECTED_VM;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
@@ -48,6 +50,8 @@
import com.android.microdroid.test.device.MicrodroidDeviceTestBase;
import com.android.microdroid.testservice.ITestService;
+import com.google.common.truth.BooleanSubject;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
@@ -122,7 +126,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -146,7 +150,7 @@
// But we do need non-debug VMs to work, so run one.
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_NONE)
.build();
@@ -170,7 +174,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.build();
@@ -189,7 +193,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -220,7 +224,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -269,7 +273,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -314,21 +318,23 @@
@Test
@CddTest(requirements = {"9.17/C-1-1"})
- public void vmConfigUnitTests() {
-
+ public void vmConfigGetAndSetTests() {
+ // Minimal has as little as specified as possible; everything that can be is defaulted.
VirtualMachineConfig.Builder minimalBuilder = newVmConfigBuilder();
- VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryPath("binary/path").build();
+ VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryName("binary.so").build();
assertThat(minimal.getApkPath()).isEqualTo(getContext().getPackageCodePath());
assertThat(minimal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_NONE);
assertThat(minimal.getMemoryMib()).isEqualTo(0);
assertThat(minimal.getNumCpus()).isEqualTo(1);
- assertThat(minimal.getPayloadBinaryPath()).isEqualTo("binary/path");
+ assertThat(minimal.getPayloadBinaryName()).isEqualTo("binary.so");
assertThat(minimal.getPayloadConfigPath()).isNull();
assertThat(minimal.isProtectedVm()).isEqualTo(isProtectedVm());
assertThat(minimal.isEncryptedStorageEnabled()).isFalse();
assertThat(minimal.getEncryptedStorageKib()).isEqualTo(0);
+ // Maximal has everything that can be set to some non-default value. (And has different
+ // values than minimal for the required fields.)
int maxCpus = Runtime.getRuntime().availableProcessors();
VirtualMachineConfig.Builder maximalBuilder =
newVmConfigBuilder()
@@ -344,7 +350,7 @@
assertThat(maximal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_FULL);
assertThat(maximal.getMemoryMib()).isEqualTo(42);
assertThat(maximal.getNumCpus()).isEqualTo(maxCpus);
- assertThat(maximal.getPayloadBinaryPath()).isNull();
+ assertThat(maximal.getPayloadBinaryName()).isNull();
assertThat(maximal.getPayloadConfigPath()).isEqualTo("config/path");
assertThat(maximal.isProtectedVm()).isEqualTo(isProtectedVm());
assertThat(maximal.isEncryptedStorageEnabled()).isTrue();
@@ -353,30 +359,25 @@
assertThat(minimal.isCompatibleWith(maximal)).isFalse();
assertThat(minimal.isCompatibleWith(minimal)).isTrue();
assertThat(maximal.isCompatibleWith(maximal)).isTrue();
-
- VirtualMachineConfig compatible = maximalBuilder.setNumCpus(1).setMemoryMib(99).build();
- assertThat(compatible.isCompatibleWith(maximal)).isTrue();
-
- // Assert that different encrypted storage size would imply the configs are incompatible
- VirtualMachineConfig incompatible = minimalBuilder.setEncryptedStorageKib(1048).build();
- assertThat(incompatible.isCompatibleWith(minimal)).isFalse();
}
@Test
@CddTest(requirements = {"9.17/C-1-1"})
- public void vmConfigBuilderUnitTests() {
+ public void vmConfigBuilderValidationTests() {
VirtualMachineConfig.Builder builder = newVmConfigBuilder();
// All your null are belong to me.
assertThrows(NullPointerException.class, () -> new VirtualMachineConfig.Builder(null));
assertThrows(NullPointerException.class, () -> builder.setApkPath(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
- assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryPath(null));
+ assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryName(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
// Individual property checks.
assertThrows(
IllegalArgumentException.class, () -> builder.setApkPath("relative/path/to.apk"));
+ assertThrows(
+ IllegalArgumentException.class, () -> builder.setPayloadBinaryName("dir/file.so"));
assertThrows(IllegalArgumentException.class, () -> builder.setDebugLevel(-1));
assertThrows(IllegalArgumentException.class, () -> builder.setMemoryMib(0));
assertThrows(IllegalArgumentException.class, () -> builder.setNumCpus(0));
@@ -385,31 +386,69 @@
// Consistency checks enforced at build time.
Exception e;
e = assertThrows(IllegalStateException.class, () -> builder.build());
- assertThat(e).hasMessageThat().contains("setPayloadBinaryPath must be called");
+ assertThat(e).hasMessageThat().contains("setPayloadBinaryName must be called");
VirtualMachineConfig.Builder protectedNotSet =
- new VirtualMachineConfig.Builder(getContext()).setPayloadBinaryPath("binary/path");
+ new VirtualMachineConfig.Builder(getContext()).setPayloadBinaryName("binary.so");
e = assertThrows(IllegalStateException.class, () -> protectedNotSet.build());
assertThat(e).hasMessageThat().contains("setProtectedVm must be called");
}
@Test
@CddTest(requirements = {"9.17/C-1-1"})
+ public void compatibleConfigTests() throws Exception {
+ int maxCpus = Runtime.getRuntime().availableProcessors();
+
+ VirtualMachineConfig.Builder builder =
+ newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
+ VirtualMachineConfig baseline = builder.build();
+
+ // A config must be compatible with itself
+ assertConfigCompatible(baseline, builder).isTrue();
+
+ // Changes that must always be compatible
+ assertConfigCompatible(baseline, builder.setMemoryMib(99)).isTrue();
+ if (maxCpus > 1) {
+ assertConfigCompatible(baseline, builder.setNumCpus(2)).isTrue();
+ }
+
+ // Changes that must be incompatible, since they must change the VM identity.
+ assertConfigCompatible(baseline, builder.setDebugLevel(DEBUG_LEVEL_FULL)).isFalse();
+ assertConfigCompatible(baseline, builder.setPayloadBinaryName("different")).isFalse();
+ int capabilities = getVirtualMachineManager().getCapabilities();
+ if ((capabilities & CAPABILITY_PROTECTED_VM) != 0
+ && (capabilities & CAPABILITY_NON_PROTECTED_VM) != 0) {
+ assertConfigCompatible(baseline, builder.setProtectedVm(!isProtectedVm())).isFalse();
+ }
+
+ // Changes that are currently incompatible for ease of implementation, but this might change
+ // in the future.
+ assertConfigCompatible(baseline, builder.setApkPath("/different")).isFalse();
+ assertConfigCompatible(baseline, builder.setEncryptedStorageKib(100)).isFalse();
+ }
+
+ private BooleanSubject assertConfigCompatible(
+ VirtualMachineConfig baseline, VirtualMachineConfig.Builder builder) {
+ return assertThat(builder.build().isCompatibleWith(baseline));
+ }
+
+ @Test
+ @CddTest(requirements = {"9.17/C-1-1"})
public void vmUnitTests() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path");
+ newVmConfigBuilder().setPayloadBinaryName("binary.so");
VirtualMachineConfig config = builder.build();
VirtualMachine vm = forceCreateNewVirtualMachine("vm_name", config);
assertThat(vm.getName()).isEqualTo("vm_name");
- assertThat(vm.getConfig().getPayloadBinaryPath()).isEqualTo("binary/path");
+ assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
assertThat(vm.getConfig().getMemoryMib()).isEqualTo(0);
VirtualMachineConfig compatibleConfig = builder.setMemoryMib(42).build();
vm.setConfig(compatibleConfig);
assertThat(vm.getName()).isEqualTo("vm_name");
- assertThat(vm.getConfig().getPayloadBinaryPath()).isEqualTo("binary/path");
+ assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
assertThat(vm.getConfig().getMemoryMib()).isEqualTo(42);
assertThat(getVirtualMachineManager().get("vm_name")).isSameInstanceAs(vm);
@@ -422,7 +461,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -470,7 +509,7 @@
final int userId = ctx.getUserId();
final VirtualMachineManager vmm = ctx.getSystemService(VirtualMachineManager.class);
VirtualMachineConfig config =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path").build();
+ newVmConfigBuilder().setPayloadBinaryName("binary.so").build();
try {
VirtualMachine vm = vmm.create("vm-name", config);
// TODO(b/261430346): what about non-primary user?
@@ -489,7 +528,7 @@
final int userId = ctx.getUserId();
final VirtualMachineManager vmm = ctx.getSystemService(VirtualMachineManager.class);
VirtualMachineConfig config =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path").build();
+ newVmConfigBuilder().setPayloadBinaryName("binary.so").build();
try {
VirtualMachine vm = vmm.create("vm-name", config);
// TODO(b/261430346): what about non-primary user?
@@ -541,7 +580,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.build();
@@ -568,7 +607,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setApkPath(getContext().getPackageCodePath())
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
@@ -614,7 +653,7 @@
for (int memMib : new int[]{ 10, 20, 40 }) {
VirtualMachineConfig lowMemConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(memMib)
.setDebugLevel(DEBUG_LEVEL_NONE)
.build();
@@ -658,7 +697,7 @@
VirtualMachineConfig.Builder builder =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(fromLevel);
VirtualMachineConfig normalConfig = builder.build();
forceCreateNewVirtualMachine("test_vm", normalConfig);
@@ -828,7 +867,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
forceCreateNewVirtualMachine("test_vm", config);
@@ -875,7 +914,7 @@
private RandomAccessFile prepareInstanceImage(String vmName) throws Exception {
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -948,9 +987,9 @@
}
@Test
- public void bootFailsWhenBinaryPathIsInvalid() throws Exception {
+ public void bootFailsWhenBinaryNameIsInvalid() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("DoesNotExist.so");
+ newVmConfigBuilder().setPayloadBinaryName("DoesNotExist.so");
VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
forceCreateNewVirtualMachine("test_vm_invalid_binary_path", normalConfig);
@@ -987,7 +1026,7 @@
@Test
public void bootFailsWhenBinaryIsMissingEntryFunction() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("MicrodroidEmptyNativeLib.so");
+ newVmConfigBuilder().setPayloadBinaryName("MicrodroidEmptyNativeLib.so");
VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_missing_entry", normalConfig);
@@ -997,7 +1036,7 @@
@Test
public void bootFailsWhenBinaryTriesToLinkAgainstPrivateLibs() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("MicrodroidPrivateLinkingNativeLib.so");
+ newVmConfigBuilder().setPayloadBinaryName("MicrodroidPrivateLinkingNativeLib.so");
VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_private_linking", normalConfig);
@@ -1007,9 +1046,7 @@
@Test
public void sameInstancesShareTheSameVmObject() throws Exception {
VirtualMachineConfig config =
- newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
- .build();
+ newVmConfigBuilder().setPayloadBinaryName("MicrodroidTestNativeLib.so").build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
VirtualMachine vm2 = getVirtualMachineManager().get("test_vm");
@@ -1071,7 +1108,7 @@
// Arrange
VirtualMachineConfig.Builder builder =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL);
if (encryptedStoreEnabled) builder = builder.setEncryptedStorageKib(4096);
VirtualMachineConfig config = builder.build();
@@ -1113,7 +1150,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setEncryptedStorageKib(4096)
.setDebugLevel(DEBUG_LEVEL_FULL)
@@ -1131,7 +1168,7 @@
final VirtualMachineConfig vmConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -1150,7 +1187,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setEncryptedStorageKib(4096)
.setDebugLevel(DEBUG_LEVEL_FULL)
@@ -1166,6 +1203,30 @@
assertThat(testResults.mFileContent).isEqualTo(EXAMPLE_STRING);
}
+ @Test
+ @CddTest(requirements = {"9.17/C-1-1", "9.17/C-2-1"})
+ public void canReadFileFromAssets_debugFull() throws Exception {
+ assumeSupportedKernel();
+
+ VirtualMachineConfig config =
+ newVmConfigBuilder()
+ .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setMemoryMib(minMemoryRequired())
+ .setDebugLevel(DEBUG_LEVEL_FULL)
+ .build();
+ VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_read_from_assets", config);
+
+ TestResults testResults =
+ runVmTestService(
+ vm,
+ (testService, ts) -> {
+ ts.mFileContent = testService.readFromFile("/mnt/apk/assets/file.txt");
+ });
+
+ assertThat(testResults.mException).isNull();
+ assertThat(testResults.mFileContent).isEqualTo("Hello, I am a file!");
+ }
+
private void assertFileContentsAreEqualInTwoVms(String fileName, String vmName1, String vmName2)
throws IOException {
File file1 = getVmFile(vmName1, fileName);
@@ -1284,4 +1345,47 @@
assertThat(payloadReady.getNow(false)).isTrue();
return testResults;
}
+
+ private TestResults runVmTestService(VirtualMachine vm, RunTestsAgainstTestService testsToRun)
+ throws Exception {
+ CompletableFuture<Boolean> payloadStarted = new CompletableFuture<>();
+ CompletableFuture<Boolean> payloadReady = new CompletableFuture<>();
+ TestResults testResults = new TestResults();
+ VmEventListener listener =
+ new VmEventListener() {
+ private void testVMService(VirtualMachine vm) {
+ try {
+ ITestService testService =
+ ITestService.Stub.asInterface(
+ vm.connectToVsockServer(ITestService.SERVICE_PORT));
+ testsToRun.runTests(testService, testResults);
+ } catch (Exception e) {
+ testResults.mException = e;
+ }
+ }
+
+ @Override
+ public void onPayloadReady(VirtualMachine vm) {
+ Log.i(TAG, "onPayloadReady");
+ payloadReady.complete(true);
+ testVMService(vm);
+ forceStop(vm);
+ }
+
+ @Override
+ public void onPayloadStarted(VirtualMachine vm) {
+ Log.i(TAG, "onPayloadStarted");
+ payloadStarted.complete(true);
+ }
+ };
+ listener.runToFinish(TAG, vm);
+ assertThat(payloadStarted.getNow(false)).isTrue();
+ assertThat(payloadReady.getNow(false)).isTrue();
+ return testResults;
+ }
+
+ @FunctionalInterface
+ interface RunTestsAgainstTestService {
+ void runTests(ITestService testService, TestResults testResults) throws Exception;
+ }
}
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
index ed3c512..55c2f5d 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
@@ -18,8 +18,9 @@
parcelable VirtualMachinePayloadConfig {
/**
- * Path to the payload executable code in an APK. The code is in the form of a .so with a
- * defined entry point; inside the VM this file is loaded and the entry function invoked.
+ * Name of the payload executable file in the lib/<ABI> folder of an APK. The payload is in the
+ * form of a .so with a defined entry point; inside the VM this file is loaded and the entry
+ * function invoked.
*/
- @utf8InCpp String payloadPath;
+ @utf8InCpp String payloadBinaryName;
}
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 733d9c5..0859a76 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -841,7 +841,7 @@
load_vm_payload_config_from_file(&apk_file, config_path.as_str())
.with_context(|| format!("Couldn't read config from {}", config_path))?
}
- Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
+ Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
};
// For now, the only supported OS is Microdroid
@@ -887,13 +887,20 @@
Ok(serde_json::from_reader(config_file)?)
}
-fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
+fn create_vm_payload_config(
+ payload_config: &VirtualMachinePayloadConfig,
+) -> Result<VmPayloadConfig> {
// There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
// parameters we've been given. Microdroid will do something equivalent inside the VM using the
// payload config that we send it via the metadata file.
- let task =
- Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
- VmPayloadConfig {
+
+ let payload_binary_name = &payload_config.payloadBinaryName;
+ if payload_binary_name.contains('/') {
+ bail!("Payload binary name must not specify a path: {payload_binary_name}");
+ }
+
+ let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
+ Ok(VmPayloadConfig {
os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
task: Some(task),
apexes: vec![],
@@ -901,7 +908,7 @@
prefer_staged: false,
export_tombstones: false,
enable_authfs: false,
- }
+ })
}
/// Generates a unique filename to use for a composite disk image.
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index eb3e9eb..02e8f8e 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -194,7 +194,7 @@
) -> Result<ParcelFileDescriptor> {
let payload_metadata = match &app_config.payload {
Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
- payload_binary_path: payload_config.payloadPath.clone(),
+ payload_binary_name: payload_config.payloadBinaryName.clone(),
..Default::default()
}),
Payload::ConfigPath(config_path) => {
diff --git a/virtualizationservice/src/virtmgr.rs b/virtualizationservice/src/virtmgr.rs
index 90b4789..5616097 100644
--- a/virtualizationservice/src/virtmgr.rs
+++ b/virtualizationservice/src/virtmgr.rs
@@ -30,6 +30,7 @@
use rpcbinder::{FileDescriptorTransportMode, RpcServer};
use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
use clap::Parser;
+use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
use nix::unistd::{Pid, Uid};
use std::os::unix::raw::{pid_t, uid_t};
@@ -66,8 +67,12 @@
fn take_fd_ownership(raw_fd: RawFd, owned_fds: &mut Vec<RawFd>) -> Result<OwnedFd, anyhow::Error> {
// Basic check that the integer value does correspond to a file descriptor.
- nix::fcntl::fcntl(raw_fd, nix::fcntl::F_GETFD)
- .with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
+ fcntl(raw_fd, F_GETFD).with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
+
+ // The file descriptor had CLOEXEC disabled to be inherited from the parent.
+ // Re-enable it to make sure it is not accidentally inherited further.
+ fcntl(raw_fd, F_SETFD(FdFlag::FD_CLOEXEC))
+ .with_context(|| format!("Could not set CLOEXEC on file descriptor {raw_fd}"))?;
// Creating OwnedFd for stdio FDs is not safe.
if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {
diff --git a/vm/TEST_MAPPING b/vm/TEST_MAPPING
new file mode 100644
index 0000000..a8d1fa6
--- /dev/null
+++ b/vm/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "avf-presubmit" : [
+ {
+ "name" : "vm.test"
+ }
+ ]
+}
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 002e505..9fa805e 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -51,9 +51,10 @@
#[clap(long)]
config_path: Option<String>,
- /// Path to VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
+ /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
#[clap(long)]
- payload_path: Option<String>,
+ #[clap(alias = "payload_path")]
+ payload_binary_name: Option<String>,
/// Name of VM
#[clap(long)]
@@ -258,7 +259,7 @@
storage,
storage_size,
config_path,
- payload_path,
+ payload_binary_name,
daemonize,
console,
log,
@@ -277,7 +278,7 @@
storage.as_deref(),
storage_size,
config_path,
- payload_path,
+ payload_binary_name,
daemonize,
console.as_deref(),
log.as_deref(),
diff --git a/vm/src/run.rs b/vm/src/run.rs
index 6096913..b99328a 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -48,7 +48,7 @@
storage: Option<&Path>,
storage_size: Option<u64>,
config_path: Option<String>,
- payload_path: Option<String>,
+ payload_binary_name: Option<String>,
daemonize: bool,
console_path: Option<&Path>,
log_path: Option<&Path>,
@@ -117,14 +117,16 @@
let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
let payload = if let Some(config_path) = config_path {
- if payload_path.is_some() {
- bail!("Only one of --config-path or --payload-path can be defined")
+ if payload_binary_name.is_some() {
+ bail!("Only one of --config-path or --payload-binary-name can be defined")
}
Payload::ConfigPath(config_path)
- } else if let Some(payload_path) = payload_path {
- Payload::PayloadConfig(VirtualMachinePayloadConfig { payloadPath: payload_path })
+ } else if let Some(payload_binary_name) = payload_binary_name {
+ Payload::PayloadConfig(VirtualMachinePayloadConfig {
+ payloadBinaryName: payload_binary_name,
+ })
} else {
- bail!("Either --config-path or --payload-path must be defined")
+ bail!("Either --config-path or --payload-binary-name must be defined")
};
let payload_config_str = format!("{:?}!{:?}", apk, payload);
@@ -197,7 +199,7 @@
let instance_img = work_dir.join("instance.img");
println!("instance.img path: {}", instance_img.display());
- let payload_path = "MicrodroidEmptyPayloadJniLib.so";
+ let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
let extra_sig = [];
command_run_app(
name,
@@ -208,7 +210,7 @@
storage,
storage_size,
/* config_path= */ None,
- Some(payload_path.to_owned()),
+ Some(payload_binary_name.to_owned()),
daemonize,
console_path,
log_path,
diff --git a/vmbase/example/src/pci.rs b/vmbase/example/src/pci.rs
index a204b90..438ff9e 100644
--- a/vmbase/example/src/pci.rs
+++ b/vmbase/example/src/pci.rs
@@ -16,12 +16,16 @@
use aarch64_paging::paging::MemoryRegion;
use alloc::alloc::{alloc, dealloc, Layout};
-use core::mem::size_of;
+use core::{mem::size_of, ptr::NonNull};
use fdtpci::PciInfo;
use log::{debug, info};
use virtio_drivers::{
- pci::{bus::PciRoot, virtio_device_type, PciTransport},
- DeviceType, Hal, PhysAddr, Transport, VirtAddr, VirtIOBlk, PAGE_SIZE,
+ device::blk::VirtIOBlk,
+ transport::{
+ pci::{bus::PciRoot, virtio_device_type, PciTransport},
+ DeviceType, Transport,
+ },
+ BufferDirection, Hal, PhysAddr, VirtAddr, PAGE_SIZE,
};
/// The standard sector size of a VirtIO block device, in bytes.
@@ -88,7 +92,7 @@
let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
// Safe because the layout has a non-zero size.
let vaddr = unsafe { alloc(layout) } as VirtAddr;
- Self::virt_to_phys(vaddr)
+ virt_to_phys(vaddr)
}
fn dma_dealloc(paddr: PhysAddr, pages: usize) -> i32 {
@@ -107,7 +111,18 @@
paddr
}
- fn virt_to_phys(vaddr: VirtAddr) -> PhysAddr {
- vaddr
+ fn share(buffer: NonNull<[u8]>, _direction: BufferDirection) -> PhysAddr {
+ let vaddr = buffer.as_ptr() as *mut u8 as usize;
+ // Nothing to do, as the host already has access to all memory.
+ virt_to_phys(vaddr)
}
+
+ fn unshare(_paddr: PhysAddr, _buffer: NonNull<[u8]>, _direction: BufferDirection) {
+ // Nothing to do, as the host already has access to all memory and we didn't copy the buffer
+ // anywhere else.
+ }
+}
+
+fn virt_to_phys(vaddr: VirtAddr) -> PhysAddr {
+ vaddr
}