Merge "Moving network config to VirtualMachineCustomImageConfig" into main
diff --git a/Android.bp b/Android.bp
index b2af69e..3b6b8b5 100644
--- a/Android.bp
+++ b/Android.bp
@@ -77,7 +77,6 @@
     config_namespace: "ANDROID",
     bool_variables: [
         "release_avf_enable_dice_changes",
-        "release_avf_enable_network",
         "release_avf_enable_vendor_modules",
         "release_avf_enable_virt_cpufreq",
     ],
@@ -92,9 +91,6 @@
         release_avf_enable_dice_changes: {
             cflags: ["-DAVF_OPEN_DICE_CHANGES=1"],
         },
-        release_avf_enable_network: {
-            cflags: ["-DAVF_ENABLE_NETWORK=1"],
-        },
         release_avf_enable_vendor_modules: {
             cflags: ["-DAVF_ENABLE_VENDOR_MODULES=1"],
         },
diff --git a/apex/Android.bp b/apex/Android.bp
index 8a53a3d..17b1f9e 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -89,7 +89,6 @@
     ],
     jni_libs: [
         "libvirtualizationservice_jni",
-        "libvirtualizationsystemservice_jni",
         "libvirtualmachine_jni",
     ],
     // TODO(b/295593640) Unfortunately these are added to the apex even though they are unused.
diff --git a/docs/custom_vm.md b/docs/custom_vm.md
index 4b027f1..077d388 100644
--- a/docs/custom_vm.md
+++ b/docs/custom_vm.md
@@ -210,7 +210,7 @@
 
 ```
 $ adb root
-$ adb shell pm enable com.android.virtualization.vmlauncher/.MainActivity
+$ adb shell pm enable com.android.virtualization.vmlauncher/.MainActivityAlias
 $ adb unroot
 ```
 
@@ -218,7 +218,7 @@
 permission to the app.
 ```
 $ adb root
-$ adb shell pm enable com.google.android.virtualization.vmlauncher/com.android.virtualization.vmlauncher.MainActivity
+$ adb shell pm enable com.google.android.virtualization.vmlauncher/com.android.virtualization.vmlauncher.MainActivityAlias
 $ adb shell pm grant com.google.android.virtualization.vmlauncher android.permission.USE_CUSTOM_VIRTUAL_MACHINE
 $ adb unroot
 ```
diff --git a/ferrochrome_app/Android.bp b/ferrochrome_app/Android.bp
new file mode 100644
index 0000000..182d289
--- /dev/null
+++ b/ferrochrome_app/Android.bp
@@ -0,0 +1,23 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_app {
+    name: "FerrochromeApp",
+    srcs: ["java/**/*.java"],
+    resource_dirs: ["res"],
+    platform_apis: true,
+    // TODO(b/348113995): move this app to product partition
+    system_ext_specific: true,
+    privileged: true,
+    init_rc: ["custom_vm_setup.rc"],
+    required: ["custom_vm_setup"],
+    certificate: "platform",
+}
+
+sh_binary {
+    name: "custom_vm_setup",
+    src: "custom_vm_setup.sh",
+    system_ext_specific: true,
+    host_supported: false,
+}
diff --git a/ferrochrome_app/AndroidManifest.xml b/ferrochrome_app/AndroidManifest.xml
new file mode 100644
index 0000000..d783bbc
--- /dev/null
+++ b/ferrochrome_app/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.virtualization.ferrochrome"
+    android:sharedUserId="android.uid.system" >
+
+    <uses-permission android:name="android.permission.INTERNET" />
+    <application
+        android:label="Ferrochrome">
+        <activity android:name=".FerrochromeActivity"
+                  android:configChanges="orientation|screenSize|keyboard|keyboardHidden|navigation|uiMode"
+                  android:theme="@style/MyTheme"
+                  android:screenOrientation="landscape"
+                  android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/ferrochrome_app/custom_vm_setup.rc b/ferrochrome_app/custom_vm_setup.rc
new file mode 100644
index 0000000..f4244b7
--- /dev/null
+++ b/ferrochrome_app/custom_vm_setup.rc
@@ -0,0 +1,23 @@
+# Copyright (C) 2024 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+service custom_vm_setup /system_ext/bin/custom_vm_setup
+    user shell
+    group shell
+    disabled
+    oneshot
+    seclabel u:r:shell:s0
+
+on property:debug.custom_vm_setup.start=true
+    start custom_vm_setup
\ No newline at end of file
diff --git a/ferrochrome_app/custom_vm_setup.sh b/ferrochrome_app/custom_vm_setup.sh
new file mode 100644
index 0000000..92a23a3
--- /dev/null
+++ b/ferrochrome_app/custom_vm_setup.sh
@@ -0,0 +1,13 @@
+#!/system/bin/sh
+
+function copy_files() {
+  cp -u /sdcard/vm_config.json /data/local/tmp
+  cp -u /sdcard/chromiumos_test_image.bin /data/local/tmp
+  chmod 666 /data/local/tmp/vm_config.json
+  chmod 666 /data/local/tmp/chromiumos_test_image.bin
+}
+setprop debug.custom_vm_setup.done false
+copy_files
+pm grant com.google.android.virtualization.vmlauncher android.permission.USE_CUSTOM_VIRTUAL_MACHINE
+setprop debug.custom_vm_setup.start false
+setprop debug.custom_vm_setup.done true
\ No newline at end of file
diff --git a/ferrochrome_app/java/com/android/virtualization/ferrochrome/FerrochromeActivity.java b/ferrochrome_app/java/com/android/virtualization/ferrochrome/FerrochromeActivity.java
new file mode 100644
index 0000000..71a9ff8
--- /dev/null
+++ b/ferrochrome_app/java/com/android/virtualization/ferrochrome/FerrochromeActivity.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.virtualization.ferrochrome;
+
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.SystemProperties;
+import android.util.Log;
+import android.view.WindowManager;
+import android.widget.TextView;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+public class FerrochromeActivity extends Activity {
+    ExecutorService executorService = Executors.newSingleThreadExecutor();
+    private static final String TAG = "FerrochromeActivity";
+    private static final String FERROCHROME_VERSION = "R127-15916.0.0";
+    private static final String EXTERNAL_STORAGE_DIR =
+            Environment.getExternalStorageDirectory().getPath() + File.separator;
+    private static final Path IMAGE_PATH =
+            Path.of(EXTERNAL_STORAGE_DIR + "chromiumos_test_image.bin");
+    private static final Path IMAGE_VERSION_INFO =
+            Path.of(EXTERNAL_STORAGE_DIR + "ferrochrome_image_version");
+    private static final Path VM_CONFIG_PATH = Path.of(EXTERNAL_STORAGE_DIR + "vm_config.json");
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_ferrochrome);
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+
+        // Clean up the existing vm launcher process if there is
+        ActivityManager am = getSystemService(ActivityManager.class);
+        am.killBackgroundProcesses(getVmLauncherAppPackageName());
+
+        executorService.execute(
+                () -> {
+                    if (Files.notExists(IMAGE_PATH)
+                            || !FERROCHROME_VERSION.equals(getVersionInfo())) {
+                        updateStatus("image doesn't exist");
+                        updateStatus("download image");
+                        if (download(FERROCHROME_VERSION)) {
+                            updateStatus("download done");
+                        } else {
+                            updateStatus("download failed, check internet connection and retry");
+                            return;
+                        }
+                    } else {
+                        updateStatus("there are already downloaded images");
+                    }
+                    updateStatus("write down vm config");
+                    copyVmConfigJson();
+                    updateStatus("custom_vm_setup: copy files to /data/local/tmp");
+                    SystemProperties.set("debug.custom_vm_setup.start", "true");
+                    while (!SystemProperties.getBoolean("debug.custom_vm_setup.done", false)) {
+                        // Wait for custom_vm_setup
+                        try {
+                            Thread.sleep(1000);
+                        } catch (Exception e) {
+                            Log.d(TAG, e.toString());
+                        }
+                        updateStatus("wait for custom_vm_setup");
+                    }
+                    updateStatus("enable vmlauncher");
+                    updateStatus("ready for ferrochrome");
+                    runOnUiThread(
+                            () ->
+                                    startActivity(
+                                            new Intent()
+                                                    .setClassName(
+                                                            getVmLauncherAppPackageName(),
+                                                            "com.android.virtualization.vmlauncher.MainActivity")));
+                });
+    }
+
+    private String getVmLauncherAppPackageName() {
+        PackageManager pm = getPackageManager();
+        for (String packageName :
+                new String[] {
+                    "com.android.virtualization.vmlauncher",
+                    "com.google.android.virtualization.vmlauncher"
+                }) {
+            try {
+                pm.getPackageInfo(packageName, 0);
+                return packageName;
+            } catch (PackageManager.NameNotFoundException e) {
+                continue;
+            }
+        }
+        return null;
+    }
+
+    private void updateStatus(String line) {
+        Log.d(TAG, line);
+        runOnUiThread(
+                () -> {
+                    TextView statusView = findViewById(R.id.status_txt_view);
+                    statusView.append(line + "\n");
+                });
+    }
+
+    private void copyVmConfigJson() {
+        if (Files.exists(VM_CONFIG_PATH)) {
+            return;
+        }
+        try (InputStream is = getResources().openRawResource(R.raw.vm_config)) {
+            Files.copy(is, VM_CONFIG_PATH, StandardCopyOption.REPLACE_EXISTING);
+        } catch (IOException e) {
+            updateStatus(e.toString());
+        }
+    }
+
+    private String getVersionInfo() {
+        try {
+            return new String(Files.readAllBytes(IMAGE_VERSION_INFO), StandardCharsets.UTF_8);
+        } catch (IOException e) {
+            return null;
+        }
+    }
+
+    private boolean updateVersionInfo(String version) {
+        try {
+            Files.write(IMAGE_VERSION_INFO, version.getBytes(StandardCharsets.UTF_8));
+        } catch (IOException e) {
+            Log.d(TAG, e.toString());
+        }
+        return true;
+    }
+
+    private boolean download(String version) {
+        String urlString =
+                "https://storage.googleapis.com/chromiumos-image-archive/ferrochrome-public/"
+                        + version
+                        + "/image.zip";
+        try (InputStream is = (new URL(urlString)).openStream();
+                ZipInputStream zis = new ZipInputStream(is)) {
+            ZipEntry entry;
+            while ((entry = zis.getNextEntry()) != null) {
+                if (!entry.getName().contains("chromiumos_test_image.bin")) {
+                    continue;
+                }
+                updateStatus("copy " + entry.getName() + " start");
+                Files.copy(zis, IMAGE_PATH, StandardCopyOption.REPLACE_EXISTING);
+                updateStatus("copy " + entry.getName() + " done");
+                updateVersionInfo(version);
+                break;
+            }
+        } catch (Exception e) {
+            updateStatus(e.toString());
+            return false;
+        }
+        return true;
+    }
+}
diff --git a/ferrochrome_app/res/layout/activity_ferrochrome.xml b/ferrochrome_app/res/layout/activity_ferrochrome.xml
new file mode 100644
index 0000000..7d5e8aa
--- /dev/null
+++ b/ferrochrome_app/res/layout/activity_ferrochrome.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context=".FerrochromeActivity">
+  <TextView
+      android:layout_width="match_parent"
+      android:layout_height="match_parent"
+      android:id="@+id/status_txt_view"/>
+
+</RelativeLayout>
\ No newline at end of file
diff --git a/ferrochrome_app/res/raw/vm_config.json b/ferrochrome_app/res/raw/vm_config.json
new file mode 100644
index 0000000..d79400c
--- /dev/null
+++ b/ferrochrome_app/res/raw/vm_config.json
@@ -0,0 +1,20 @@
+{
+    "name": "cros",
+    "disks": [
+        {
+            "image": "/data/local/tmp/chromiumos_test_image.bin",
+            "partitions": [],
+            "writable": true
+        }
+    ],
+    "params": "root=/dev/vda3 rootwait noinitrd ro enforcing=0 cros_debug cros_secure",
+    "protected": false,
+    "cpu_topology": "match_host",
+    "platform_version": "~1.0",
+    "memory_mib": 8096,
+    "gpu": {
+        "backend": "virglrenderer",
+        "context_types": ["virgl2"]
+    },
+    "console_input_device": "ttyS0"
+}
\ No newline at end of file
diff --git a/ferrochrome_app/res/values/themes.xml b/ferrochrome_app/res/values/themes.xml
new file mode 100644
index 0000000..c9a9ed2
--- /dev/null
+++ b/ferrochrome_app/res/values/themes.xml
@@ -0,0 +1,4 @@
+<resources xmlns:tools="http://schemas.android.com/tools">
+    <style name="MyTheme" parent="@android:style/Theme.DeviceDefault.NoActionBar">
+    </style>
+</resources>
diff --git a/flags/cpp/include/android/avf_cc_flags.h b/flags/cpp/include/android/avf_cc_flags.h
index 70be925..c922266 100644
--- a/flags/cpp/include/android/avf_cc_flags.h
+++ b/flags/cpp/include/android/avf_cc_flags.h
@@ -27,14 +27,6 @@
 #endif
 }
 
-inline bool IsNetworkFlagEnabled() {
-#ifdef AVF_ENABLE_NETWORK
-    return AVF_ENABLE_NETWORK;
-#else
-    return false;
-#endif
-}
-
 inline bool IsVendorModulesFlagEnabled() {
 #ifdef AVF_ENABLE_VENDOR_MODULES
     return AVF_ENABLE_VENDOR_MODULES;
diff --git a/java/jni/Android.bp b/java/jni/Android.bp
index d9b1880..4a569d4 100644
--- a/java/jni/Android.bp
+++ b/java/jni/Android.bp
@@ -20,20 +20,6 @@
 }
 
 cc_library_shared {
-    name: "libvirtualizationsystemservice_jni",
-    defaults: ["avf_build_flags_cc"],
-    srcs: [
-        "com_android_system_virtualmachine_VirtualizationSystemService.cpp",
-    ],
-    apex_available: ["com.android.virt"],
-    shared_libs: [
-        "liblog",
-        "libnativehelper",
-    ],
-    static_libs: ["libavf_cc_flags"],
-}
-
-cc_library_shared {
     name: "libvirtualmachine_jni",
     defaults: ["avf_build_flags_cc"],
     srcs: [
diff --git a/java/jni/com_android_system_virtualmachine_VirtualizationSystemService.cpp b/java/jni/com_android_system_virtualmachine_VirtualizationSystemService.cpp
deleted file mode 100644
index a15e7a7..0000000
--- a/java/jni/com_android_system_virtualmachine_VirtualizationSystemService.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "VirtualizationSystemService"
-
-#include <android/avf_cc_flags.h>
-#include <jni.h>
-#include <log/log.h>
-
-extern "C" JNIEXPORT jboolean JNICALL
-Java_com_android_system_virtualmachine_VirtualizationSystemService_nativeIsNetworkFlagEnabled(
-        [[maybe_unused]] JNIEnv* env, [[maybe_unused]] jobject obj) {
-    return android::virtualization::IsNetworkFlagEnabled();
-}
diff --git a/java/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java b/java/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
index f1d89d9..241eef4 100644
--- a/java/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
+++ b/java/service/src/com/android/system/virtualmachine/VirtualizationSystemService.java
@@ -35,6 +35,9 @@
 import com.android.internal.os.BackgroundThread;
 import com.android.server.SystemService;
 
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
 /**
  * This class exists to notify virtualization service of relevant things happening in the Android
  * framework.
@@ -43,24 +46,15 @@
  * storing secrets for apps or users that no longer exist.
  */
 public class VirtualizationSystemService extends SystemService {
-    static {
-        System.loadLibrary("virtualizationsystemservice_jni");
-    }
-
     private static final String TAG = VirtualizationSystemService.class.getName();
     private static final String MAINTENANCE_SERVICE_NAME =
             "android.system.virtualizationmaintenance";
     private Handler mHandler;
     private final TetheringService mTetheringService;
 
-    /*
-     * Retrieve boolean value whether RELEASE_AVF_ENABLE_NETWORK build flag is enabled or not.
-     */
-    static native boolean nativeIsNetworkFlagEnabled();
-
     public VirtualizationSystemService(Context context) {
         super(context);
-        if (nativeIsNetworkFlagEnabled()) {
+        if (Files.exists(Paths.get("/apex/com.android.virt/bin/vmnic"))) {
             mTetheringService = new TetheringService();
         } else {
             mTetheringService = null;
diff --git a/vmlauncher_app/AndroidManifest.xml b/vmlauncher_app/AndroidManifest.xml
index f4f13af..ecfef86 100644
--- a/vmlauncher_app/AndroidManifest.xml
+++ b/vmlauncher_app/AndroidManifest.xml
@@ -9,16 +9,20 @@
     <application
         android:label="VmLauncherApp">
         <activity android:name=".MainActivity"
-                  android:enabled="false"
                   android:screenOrientation="landscape"
                   android:configChanges="orientation|screenSize|keyboard|keyboardHidden|navigation|uiMode"
                   android:theme="@style/MyTheme"
                   android:exported="true">
+        </activity>
+        <activity-alias android:name=".MainActivityAlias"
+                android:targetActivity=".MainActivity"
+                android:exported="true"
+                android:enabled="false">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
-        </activity>
+        </activity-alias>
     </application>
 
 </manifest>