Expand VirtualMachineConfig to RawConfig

As /apex/com.android.virtualization/bin/vm does, made Java API support
RawConfig as well.

Test: setRawConfigPath, and then create a vm
Bug: 330256602
Change-Id: I88676a2bf44a51effc7a7a9d6b267c097399759e
diff --git a/java/framework/src/android/system/virtualmachine/VirtualMachine.java b/java/framework/src/android/system/virtualmachine/VirtualMachine.java
index a5c8062..f9ca2f2 100644
--- a/java/framework/src/android/system/virtualmachine/VirtualMachine.java
+++ b/java/framework/src/android/system/virtualmachine/VirtualMachine.java
@@ -71,6 +71,7 @@
 import android.system.virtualizationservice.MemoryTrimLevel;
 import android.system.virtualizationservice.PartitionType;
 import android.system.virtualizationservice.VirtualMachineAppConfig;
+import android.system.virtualizationservice.VirtualMachineRawConfig;
 import android.system.virtualizationservice.VirtualMachineState;
 import android.util.JsonReader;
 import android.util.Log;
@@ -810,6 +811,58 @@
         }
     }
 
+    private android.system.virtualizationservice.VirtualMachineConfig
+            createVirtualMachineConfigForRawFrom(VirtualMachineConfig vmConfig)
+                    throws IllegalStateException {
+        VirtualMachineRawConfig rawConfig = vmConfig.toVsRawConfig();
+        return android.system.virtualizationservice.VirtualMachineConfig.rawConfig(rawConfig);
+    }
+
+    private android.system.virtualizationservice.VirtualMachineConfig
+            createVirtualMachineConfigForAppFrom(
+                    VirtualMachineConfig vmConfig, IVirtualizationService service)
+                    throws RemoteException, IOException, VirtualMachineException {
+        VirtualMachineAppConfig appConfig = vmConfig.toVsConfig(mContext.getPackageManager());
+        appConfig.instanceImage = ParcelFileDescriptor.open(mInstanceFilePath, MODE_READ_WRITE);
+        appConfig.name = mName;
+        if (mInstanceIdPath != null) {
+            appConfig.instanceId = Files.readAllBytes(mInstanceIdPath.toPath());
+        } else {
+            // FEATURE_LLPVM_CHANGES is disabled, instance_id is not used.
+            appConfig.instanceId = new byte[64];
+        }
+        if (mEncryptedStoreFilePath != null) {
+            appConfig.encryptedStorageImage =
+                    ParcelFileDescriptor.open(mEncryptedStoreFilePath, MODE_READ_WRITE);
+        }
+
+        if (!vmConfig.getExtraApks().isEmpty()) {
+            // Extra APKs were specified directly, rather than via config file.
+            // We've already populated the file names for the extra APKs and IDSigs
+            // (via setupExtraApks). But we also need to open the APK files and add
+            // fds for them to the payload config.
+            // This isn't needed when the extra APKs are specified in a config file -
+            // then
+            // Virtualization Manager opens them itself.
+            List<ParcelFileDescriptor> extraApkFiles = new ArrayList<>(mExtraApks.size());
+            for (ExtraApkSpec extraApk : mExtraApks) {
+                try {
+                    extraApkFiles.add(ParcelFileDescriptor.open(extraApk.apk, MODE_READ_ONLY));
+                } catch (FileNotFoundException e) {
+                    throw new VirtualMachineException("Failed to open extra APK", e);
+                }
+            }
+            appConfig.payload.getPayloadConfig().extraApks = extraApkFiles;
+        }
+
+        try {
+            createIdSigsAndUpdateConfig(service, appConfig);
+        } catch (FileNotFoundException e) {
+            throw new VirtualMachineException("Failed to generate APK signature", e);
+        }
+        return android.system.virtualizationservice.VirtualMachineConfig.appConfig(appConfig);
+    }
+
     /**
      * 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
@@ -850,50 +903,10 @@
                 }
 
                 VirtualMachineConfig vmConfig = getConfig();
-                VirtualMachineAppConfig appConfig =
-                        vmConfig.toVsConfig(mContext.getPackageManager());
-                appConfig.instanceImage =
-                        ParcelFileDescriptor.open(mInstanceFilePath, MODE_READ_WRITE);
-                appConfig.name = mName;
-                if (mInstanceIdPath != null) {
-                    appConfig.instanceId = Files.readAllBytes(mInstanceIdPath.toPath());
-                } else {
-                    // FEATURE_LLPVM_CHANGES is disabled, instance_id is not used.
-                    appConfig.instanceId = new byte[64];
-                }
-                if (mEncryptedStoreFilePath != null) {
-                    appConfig.encryptedStorageImage =
-                            ParcelFileDescriptor.open(mEncryptedStoreFilePath, MODE_READ_WRITE);
-                }
-
-                if (!vmConfig.getExtraApks().isEmpty()) {
-                    // Extra APKs were specified directly, rather than via config file.
-                    // We've already populated the file names for the extra APKs and IDSigs
-                    // (via setupExtraApks). But we also need to open the APK files and add
-                    // fds for them to the payload config.
-                    // This isn't needed when the extra APKs are specified in a config file - then
-                    // Virtualization Manager opens them itself.
-                    List<ParcelFileDescriptor> extraApkFiles = new ArrayList<>(mExtraApks.size());
-                    for (ExtraApkSpec extraApk : mExtraApks) {
-                        try {
-                            extraApkFiles.add(
-                                    ParcelFileDescriptor.open(extraApk.apk, MODE_READ_ONLY));
-                        } catch (FileNotFoundException e) {
-                            throw new VirtualMachineException("Failed to open extra APK", e);
-                        }
-                    }
-                    appConfig.payload.getPayloadConfig().extraApks = extraApkFiles;
-                }
-
-                try {
-                    createIdSigsAndUpdateConfig(service, appConfig);
-                } catch (FileNotFoundException e) {
-                    throw new VirtualMachineException("Failed to generate APK signature", e);
-                }
-
                 android.system.virtualizationservice.VirtualMachineConfig vmConfigParcel =
-                        android.system.virtualizationservice.VirtualMachineConfig.appConfig(
-                                appConfig);
+                        vmConfig.getRawConfigPath() != null
+                                ? createVirtualMachineConfigForRawFrom(vmConfig)
+                                : createVirtualMachineConfigForAppFrom(vmConfig, service);
 
                 mVirtualMachine =
                         service.createVm(
diff --git a/java/framework/src/android/system/virtualmachine/VirtualMachineConfig.java b/java/framework/src/android/system/virtualmachine/VirtualMachineConfig.java
index 054d73c..99c3d05 100644
--- a/java/framework/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/java/framework/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -18,6 +18,7 @@
 
 import static android.os.ParcelFileDescriptor.AutoCloseInputStream;
 import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
+import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
 
 import static java.util.Objects.requireNonNull;
 
@@ -37,12 +38,19 @@
 import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.sysprop.HypervisorProperties;
+import android.system.virtualizationservice.DiskImage;
+import android.system.virtualizationservice.Partition;
 import android.system.virtualizationservice.VirtualMachineAppConfig;
 import android.system.virtualizationservice.VirtualMachinePayloadConfig;
+import android.system.virtualizationservice.VirtualMachineRawConfig;
 import android.util.Log;
 
 import com.android.system.virtualmachine.flags.Flags;
 
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -52,6 +60,8 @@
 import java.io.OutputStream;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -78,6 +88,7 @@
     private static final String KEY_PACKAGENAME = "packageName";
     private static final String KEY_APKPATH = "apkPath";
     private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
+    private static final String KEY_RAWCONFIGPATH = "rawConfigPath";
     private static final String KEY_PAYLOADBINARYNAME = "payloadBinaryPath";
     private static final String KEY_DEBUGLEVEL = "debugLevel";
     private static final String KEY_PROTECTED_VM = "protectedVm";
@@ -173,6 +184,9 @@
     /** Name of the payload binary file within the APK that will be executed within the VM. */
     @Nullable private final String mPayloadBinaryName;
 
+    /** Path within the raw config file to launch the VM. */
+    @Nullable private final String mRawConfigPath;
+
     /** The size of storage in bytes. 0 indicates that encryptedStorage is not required */
     private final long mEncryptedStorageBytes;
 
@@ -210,6 +224,7 @@
             List<String> extraApks,
             @Nullable String payloadConfigPath,
             @Nullable String payloadBinaryName,
+            @Nullable String rawConfigPath,
             @DebugLevel int debugLevel,
             boolean protectedVm,
             long memoryBytes,
@@ -229,6 +244,7 @@
                                 Arrays.asList(extraApks.toArray(new String[0])));
         mPayloadConfigPath = payloadConfigPath;
         mPayloadBinaryName = payloadBinaryName;
+        mRawConfigPath = rawConfigPath;
         mDebugLevel = debugLevel;
         mProtectedVm = protectedVm;
         mMemoryBytes = memoryBytes;
@@ -290,10 +306,14 @@
         }
 
         String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
-        if (payloadConfigPath == null) {
-            builder.setPayloadBinaryName(b.getString(KEY_PAYLOADBINARYNAME));
-        } else {
+        String payloadBinaryName = b.getString(KEY_PAYLOADBINARYNAME);
+        String rawConfigPath = b.getString(KEY_RAWCONFIGPATH);
+        if (rawConfigPath != null) {
+            builder.setRawConfigPath(rawConfigPath);
+        } else if (payloadConfigPath != null) {
             builder.setPayloadConfigPath(payloadConfigPath);
+        } else {
+            builder.setPayloadBinaryName(payloadBinaryName);
         }
 
         @DebugLevel int debugLevel = b.getInt(KEY_DEBUGLEVEL);
@@ -352,6 +372,7 @@
         }
         b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
         b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
+        b.putString(KEY_RAWCONFIGPATH, mRawConfigPath);
         b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
         b.putBoolean(KEY_PROTECTED_VM, mProtectedVm);
         b.putInt(KEY_CPU_TOPOLOGY, mCpuTopology);
@@ -412,6 +433,16 @@
     }
 
     /**
+     * Returns the path within the raw config file to launch the VM.
+     *
+     * @hide
+     */
+    @Nullable
+    public String getRawConfigPath() {
+        return mRawConfigPath;
+    }
+
+    /**
      * Returns the name of the payload binary file, in the {@code lib/<ABI>} directory of the APK,
      * that will be executed within the VM.
      *
@@ -554,6 +585,99 @@
                 && Objects.equals(this.mExtraApks, other.mExtraApks);
     }
 
+    // Needs to sync with packages/modules/Virtualization/libs/vmconfig/src/lib.rs
+    VirtualMachineRawConfig toVsRawConfig() throws IllegalStateException {
+        VirtualMachineRawConfig config = new VirtualMachineRawConfig();
+
+        try {
+            String rawJson = new String(Files.readAllBytes(Path.of(mRawConfigPath)));
+            JSONObject json = new JSONObject(rawJson);
+            config.name = json.optString("name", "");
+            config.instanceId = new byte[64];
+            if (json.has("kernel")) {
+                config.kernel =
+                        ParcelFileDescriptor.open(
+                                new File(json.getString("kernel")), MODE_READ_ONLY);
+            }
+            if (json.has("initrd")) {
+                config.initrd =
+                        ParcelFileDescriptor.open(
+                                new File(json.getString("initrd")), MODE_READ_ONLY);
+            }
+            if (json.has("params")) {
+                config.params = json.getString("params");
+            }
+            if (json.has("bootloader")) {
+                config.bootloader =
+                        ParcelFileDescriptor.open(
+                                new File(json.getString("bootloader")), MODE_READ_ONLY);
+            }
+            if (json.has("disks")) {
+                JSONArray diskArr = json.getJSONArray("disks");
+                config.disks = new DiskImage[diskArr.length()];
+                for (int i = 0; i < diskArr.length(); i++) {
+                    config.disks[i] = new DiskImage();
+                    JSONObject item = diskArr.getJSONObject(i);
+                    config.disks[i].writable = item.optBoolean("writable", false);
+                    if (item.has("image")) {
+                        config.disks[i].image =
+                                ParcelFileDescriptor.open(
+                                        new File(item.getString("image")),
+                                        config.disks[i].writable
+                                                ? MODE_READ_WRITE
+                                                : MODE_READ_ONLY);
+                    }
+                    if (item.has("partition")) {
+                        JSONArray partitionArr = json.getJSONArray("partition");
+                        config.disks[i].partitions = new Partition[partitionArr.length()];
+                        for (int j = 0; j < partitionArr.length(); j++) {
+                            config.disks[i].partitions[j] = new Partition();
+                            JSONObject partitionItem = partitionArr.getJSONObject(j);
+                            config.disks[i].partitions[j].writable =
+                                    partitionItem.optBoolean("writable", false);
+                            config.disks[i].partitions[j].label = partitionItem.getString("label");
+                            config.disks[i].partitions[j].image =
+                                    ParcelFileDescriptor.open(
+                                            new File(partitionItem.getString("image")),
+                                            config.disks[i].partitions[j].writable
+                                                    ? MODE_READ_WRITE
+                                                    : MODE_READ_ONLY);
+                        }
+                    } else {
+                        config.disks[i].partitions = new Partition[0];
+                    }
+                }
+            } else {
+                config.disks = new DiskImage[0];
+            }
+            // The value which is set by setProtectedVm is used.
+            if (json.has("protected")) {
+                Log.d(TAG, "'protected' field is ignored, the value from setProtectedVm is used");
+            }
+            config.protectedVm = this.mProtectedVm;
+            config.memoryMib = json.optInt("memory_mib", 0);
+            if (json.optString("cpu_topology", "one_cpu").equals("match_host")) {
+                config.cpuTopology = CPU_TOPOLOGY_MATCH_HOST;
+            } else {
+                config.cpuTopology = CPU_TOPOLOGY_ONE_CPU;
+            }
+            config.platformVersion = json.getString("platform_version");
+            if (json.has("devices")) {
+                JSONArray arr = json.getJSONArray("devices");
+                config.devices = new String[arr.length()];
+                for (int i = 0; i < arr.length(); i++) {
+                    config.devices[i] = arr.getString(i);
+                }
+            } else {
+                config.devices = new String[0];
+            }
+
+        } catch (JSONException | IOException e) {
+            throw new IllegalStateException("malformed input", e);
+        }
+        return config;
+    }
+
     /**
      * Converts this config object into the parcelable type used when creating a VM via the
      * virtualization service. Notice that the files are not passed as paths, but as file
@@ -680,6 +804,7 @@
         @Nullable private String mApkPath;
         private final List<String> mExtraApks = new ArrayList<>();
         @Nullable private String mPayloadConfigPath;
+        @Nullable private String mRawConfigPath;
         @Nullable private String mPayloadBinaryName;
         @DebugLevel private int mDebugLevel = DEBUG_LEVEL_NONE;
         private boolean mProtectedVm;
@@ -729,8 +854,13 @@
                 // This should never happen, unless we're deserializing a bad config
                 throw new IllegalStateException("apkPath or packageName must be specified");
             }
-
-            if (mPayloadBinaryName == null) {
+            if (mRawConfigPath != null) {
+                if (mPayloadBinaryName != null || mPayloadConfigPath != null) {
+                    throw new IllegalStateException(
+                            "setRawConfigPath and (setPayloadBinaryName or setPayloadConfigPath)"
+                                    + " may not both be called");
+                }
+            } else if (mPayloadBinaryName == null) {
                 if (mPayloadConfigPath == null) {
                     throw new IllegalStateException("setPayloadBinaryName must be called");
                 }
@@ -763,6 +893,7 @@
                     mExtraApks,
                     mPayloadConfigPath,
                     mPayloadBinaryName,
+                    mRawConfigPath,
                     mDebugLevel,
                     mProtectedVm,
                     mMemoryBytes,
@@ -824,6 +955,29 @@
         }
 
         /**
+         * Sets the path within the raw config file to launch the VM. The file is a JSON file; see
+         * packages/modules/Virtualization/libs/vmconfig/src/lib.rs for the format.
+         *
+         * @hide
+         */
+        @RequiresPermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION)
+        @NonNull
+        public Builder setRawConfigPath(@NonNull String rawConfigPath) {
+            // TODO: This method will be removed when the builder support more structured methods
+            // for that like below.
+            //    builder
+            //      .setLinuxKernelConfig(new LinuxKernelConfig()
+            //        .setKernelPath(...)
+            //        .setInitRamdiskPath(...)
+            //        .setKernelCommandLine(...))
+            //      .setDiskConfig(new DiskConfig()
+            //        .addDisk(...)
+            //        .addDisk(...))
+            mRawConfigPath = requireNonNull(rawConfigPath, "rawConfigPath must not be null");
+            return this;
+        }
+
+        /**
          * 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.
          *