Merge "load rialto in kernel mode" into main
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..a246e08
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,3 @@
+package {
+ default_team: "trendy_team_android_kvm",
+}
diff --git a/TEST_MAPPING b/TEST_MAPPING
index fc88a59..2112125 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -144,7 +144,7 @@
"path": "packages/modules/Virtualization/android/vm"
},
{
- "path": "packages/modules/Virtualization/libs/libvmbase"
+ "path": "packages/modules/Virtualization/tests/vmbase_example"
},
{
"path": "packages/modules/Virtualization/guest/zipfuse"
diff --git a/android/TerminalApp/Android.bp b/android/TerminalApp/Android.bp
new file mode 100644
index 0000000..f5f39e3
--- /dev/null
+++ b/android/TerminalApp/Android.bp
@@ -0,0 +1,17 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_app {
+ name: "VmTerminalApp",
+ srcs: ["java/**/*.java"],
+ resource_dirs: ["res"],
+ static_libs: [
+ "vm_launcher_lib",
+ ],
+ sdk_version: "system_current",
+ product_specific: true,
+ optimize: {
+ shrink_resources: true,
+ },
+}
diff --git a/android/TerminalApp/AndroidManifest.xml b/android/TerminalApp/AndroidManifest.xml
new file mode 100644
index 0000000..07e6147
--- /dev/null
+++ b/android/TerminalApp/AndroidManifest.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.virtualization.terminal" >
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="com.android.virtualization.vmlauncher.permission.USE_VM_LAUNCHER"/>
+
+ <application
+ android:label="VmTerminalApp"
+ android:usesCleartextTraffic="true">
+ <activity android:name=".MainActivity"
+ android:screenOrientation="landscape"
+ android:configChanges="orientation|screenSize|keyboard|keyboardHidden|navigation|uiMode"
+ 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/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java
new file mode 100644
index 0000000..e6e56d9
--- /dev/null
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java
@@ -0,0 +1,82 @@
+/*
+ * 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.terminal;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+import android.webkit.WebChromeClient;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+import android.widget.TextView;
+
+import com.android.virtualization.vmlauncher.VmLauncherServices;
+
+public class MainActivity extends Activity implements VmLauncherServices.VmLauncherServiceCallback {
+ private static final String TAG = "VmTerminalApp";
+ private String mVmIpAddr;
+ private WebView mWebView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ VmLauncherServices.startVmLauncherService(this, this);
+
+ setContentView(R.layout.activity_headless);
+ mWebView = (WebView) findViewById(R.id.webview);
+ mWebView.getSettings().setDatabaseEnabled(true);
+ mWebView.getSettings().setDomStorageEnabled(true);
+ mWebView.getSettings().setJavaScriptEnabled(true);
+ mWebView.setWebChromeClient(new WebChromeClient());
+ mWebView.setWebViewClient(
+ new WebViewClient() {
+ @Override
+ public boolean shouldOverrideUrlLoading(WebView view, String url) {
+ view.loadUrl(url);
+ return true;
+ }
+ });
+ }
+
+ private void gotoURL(String url) {
+ runOnUiThread(() -> mWebView.loadUrl(url));
+ }
+
+ public void onVmStart() {
+ Log.i(TAG, "onVmStart()");
+ }
+
+ public void onVmStop() {
+ Log.i(TAG, "onVmStop()");
+ finish();
+ }
+
+ public void onVmError() {
+ Log.i(TAG, "onVmError()");
+ finish();
+ }
+
+ public void onIpAddrAvailable(String ipAddr) {
+ mVmIpAddr = ipAddr;
+ ((TextView) findViewById(R.id.ip_addr_textview)).setText(mVmIpAddr);
+
+ // TODO(b/359523803): Use AVF API to be notified when shell is ready instead of using dealy
+ new Handler(Looper.getMainLooper())
+ .postDelayed(() -> gotoURL("http://" + mVmIpAddr + ":7681"), 2000);
+ }
+}
diff --git a/android/TerminalApp/res/layout/activity_headless.xml b/android/TerminalApp/res/layout/activity_headless.xml
new file mode 100644
index 0000000..2a640f3
--- /dev/null
+++ b/android/TerminalApp/res/layout/activity_headless.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout 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"
+ android:orientation="vertical"
+ tools:context=".MainActivity">
+ <TextView
+ android:id="@+id/ip_addr_textview"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content" />
+ <WebView
+ android:id="@+id/webview"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layout_marginBottom="5dp" />
+
+</LinearLayout>
diff --git a/android/VmLauncherApp/AndroidManifest.xml b/android/VmLauncherApp/AndroidManifest.xml
index 67b7a45..583fce7 100644
--- a/android/VmLauncherApp/AndroidManifest.xml
+++ b/android/VmLauncherApp/AndroidManifest.xml
@@ -6,6 +6,8 @@
<uses-permission android:name="android.permission.USE_CUSTOM_VIRTUAL_MACHINE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
<uses-feature android:name="android.software.virtualization_framework" android:required="true" />
<permission android:name="com.android.virtualization.vmlauncher.permission.USE_VM_LAUNCHER"
@@ -26,6 +28,21 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
+ <service
+ android:name=".VmLauncherService"
+ android:enabled="true"
+ android:exported="true"
+ android:permission="com.android.virtualization.vmlauncher.permission.USE_VM_LAUNCHER"
+ android:foregroundServiceType="specialUse">
+ <property
+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
+ android:value="Run VM instances" />
+ <intent-filter>
+ <action android:name="android.virtualization.START_VM_LAUNCHER_SERVICE" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </service>
+
</application>
</manifest>
diff --git a/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/Runner.java b/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/Runner.java
index f50ec86..a5f58fe 100644
--- a/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/Runner.java
+++ b/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/Runner.java
@@ -42,7 +42,10 @@
/** Create a virtual machine of the given config, under the given context. */
static Runner create(Context context, VirtualMachineConfig config)
throws VirtualMachineException {
- VirtualMachineManager vmm = context.getSystemService(VirtualMachineManager.class);
+ // context may already be the app context, but calling this again is not harmful.
+ // See b/359439878 on why vmm should be obtained from the app context.
+ Context appContext = context.getApplicationContext();
+ VirtualMachineManager vmm = appContext.getSystemService(VirtualMachineManager.class);
VirtualMachineCustomImageConfig customConfig = config.getCustomImageConfig();
if (customConfig == null) {
throw new RuntimeException("CustomImageConfig is missing");
diff --git a/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/VmLauncherService.java b/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/VmLauncherService.java
new file mode 100644
index 0000000..ec98f4c
--- /dev/null
+++ b/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/VmLauncherService.java
@@ -0,0 +1,149 @@
+/*
+ * 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.vmlauncher;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.Service;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.ParcelFileDescriptor;
+import android.os.ResultReceiver;
+import android.system.virtualmachine.VirtualMachine;
+import android.system.virtualmachine.VirtualMachineConfig;
+import android.system.virtualmachine.VirtualMachineException;
+import android.util.Log;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.file.Path;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class VmLauncherService extends Service {
+ private static final String TAG = "VmLauncherService";
+ // TODO: this path should be from outside of this service
+ private static final String VM_CONFIG_PATH = "/data/local/tmp/vm_config.json";
+
+ private static final int RESULT_START = 0;
+ private static final int RESULT_STOP = 1;
+ private static final int RESULT_ERROR = 2;
+ private static final int RESULT_IPADDR = 3;
+ private static final String KEY_VM_IP_ADDR = "ip_addr";
+
+ private ExecutorService mExecutorService;
+ private VirtualMachine mVirtualMachine;
+ private ResultReceiver mResultReceiver;
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ private void startForeground() {
+ NotificationManager notificationManager = getSystemService(NotificationManager.class);
+ NotificationChannel notificationChannel =
+ new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_LOW);
+ notificationManager.createNotificationChannel(notificationChannel);
+ startForeground(
+ this.hashCode(),
+ new Notification.Builder(this, TAG)
+ .setChannelId(TAG)
+ .setSmallIcon(android.R.drawable.ic_dialog_info)
+ .setContentText("A VM " + mVirtualMachine.getName() + " is running")
+ .build());
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ mExecutorService = Executors.newCachedThreadPool();
+
+ ConfigJson json = ConfigJson.from(VM_CONFIG_PATH);
+ VirtualMachineConfig config = json.toConfig(this);
+
+ Runner runner;
+ try {
+ runner = Runner.create(this, config);
+ } catch (VirtualMachineException e) {
+ throw new RuntimeException(e);
+ }
+ mVirtualMachine = runner.getVm();
+ mResultReceiver =
+ intent.getParcelableExtra(Intent.EXTRA_RESULT_RECEIVER, ResultReceiver.class);
+
+ runner.getExitStatus()
+ .thenAcceptAsync(
+ success -> {
+ if (mResultReceiver != null) {
+ mResultReceiver.send(success ? RESULT_STOP : RESULT_ERROR, null);
+ }
+ if (!success) {
+ stopSelf();
+ }
+ });
+ Path logPath = getFileStreamPath(mVirtualMachine.getName() + ".log").toPath();
+ Logger.setup(mVirtualMachine, logPath, mExecutorService);
+
+ startForeground();
+
+ mResultReceiver.send(RESULT_START, null);
+ if (config.getCustomImageConfig().useNetwork()) {
+ Handler handler = new Handler(Looper.getMainLooper());
+ gatherIpAddrFromVm(handler);
+ }
+ return START_NOT_STICKY;
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ mExecutorService.shutdownNow();
+ }
+
+ // TODO(b/359523803): Use AVF API to get ip addr when it exists
+ private void gatherIpAddrFromVm(Handler handler) {
+ handler.postDelayed(
+ () -> {
+ int INTERNAL_VSOCK_SERVER_PORT = 1024;
+ try (ParcelFileDescriptor pfd =
+ mVirtualMachine.connectVsock(INTERNAL_VSOCK_SERVER_PORT)) {
+ try (BufferedReader input =
+ new BufferedReader(
+ new InputStreamReader(
+ new FileInputStream(pfd.getFileDescriptor())))) {
+ String vmIpAddr = input.readLine().strip();
+ Bundle b = new Bundle();
+ b.putString(KEY_VM_IP_ADDR, vmIpAddr);
+ mResultReceiver.send(RESULT_IPADDR, b);
+ return;
+ } catch (IOException e) {
+ Log.e(TAG, e.toString());
+ }
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ }
+ gatherIpAddrFromVm(handler);
+ },
+ 1000);
+ }
+}
diff --git a/guest/vmbase_example/Android.bp b/guest/vmbase_example/Android.bp
new file mode 100644
index 0000000..ff7bd83
--- /dev/null
+++ b/guest/vmbase_example/Android.bp
@@ -0,0 +1,114 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_ffi_static {
+ name: "libvmbase_example",
+ defaults: ["vmbase_ffi_defaults"],
+ crate_name: "vmbase_example",
+ srcs: ["src/main.rs"],
+ rustlibs: [
+ "libaarch64_paging",
+ "libcstr",
+ "libdiced_open_dice_nostd",
+ "libfdtpci",
+ "liblibfdt",
+ "liblog_rust_nostd",
+ "libvirtio_drivers",
+ "libvmbase",
+ ],
+}
+
+genrule {
+ name: "vmbase_image.ld.S.mm",
+ // Soong won't let us use cc_object to preprocess *.ld.S files because it
+ // can't resist feeding any and all *.S files to the assembler, which fails
+ // because linker scripts typically aren't valid assembly. Also, cc_object
+ // rejects inputs that don't end in one of .{s,S,c,cpp,cc,cxx,mm}. So keep
+ // the proper extension (.ld.S) for the file in VCS and use this convoluted
+ // extra step to please Soong by pretending that our linker script is in
+ // fact some Object C++ code, which fortunately it doesn't try to compile.
+ srcs: ["image.ld.S"],
+ out: ["image.ld.S.mm"],
+ cmd: "cp $(in) $(out)",
+ visibility: ["//visibility:private"],
+}
+
+cc_defaults {
+ name: "vmbase_example_ld_defaults",
+ defaults: ["vmbase_cc_defaults"],
+ cflags: [
+ "-E",
+ "-P",
+ "-xassembler-with-cpp", // allow C preprocessor directives
+ ],
+ srcs: [":vmbase_image.ld.S.mm"],
+ visibility: ["//visibility:private"],
+}
+
+cc_object {
+ name: "vmbase_example_bios.ld",
+ defaults: ["vmbase_example_ld_defaults"],
+ cflags: ["-DVMBASE_EXAMPLE_IS_BIOS"],
+}
+
+cc_object {
+ name: "vmbase_example_kernel.ld",
+ defaults: ["vmbase_example_ld_defaults"],
+ cflags: ["-DVMBASE_EXAMPLE_IS_KERNEL"],
+}
+
+cc_defaults {
+ name: "vmbase_example_elf_defaults",
+ defaults: ["vmbase_elf_defaults"],
+ srcs: [
+ "idmap.S",
+ ],
+ static_libs: [
+ "libvmbase_example",
+ ],
+}
+
+cc_binary {
+ name: "vmbase_example_bios",
+ defaults: ["vmbase_example_elf_defaults"],
+ asflags: ["-DVMBASE_EXAMPLE_IS_BIOS"],
+ linker_scripts: [
+ ":vmbase_example_bios.ld",
+ ":vmbase_sections",
+ ],
+}
+
+cc_binary {
+ name: "vmbase_example_kernel",
+ defaults: ["vmbase_example_elf_defaults"],
+ asflags: ["-DVMBASE_EXAMPLE_IS_KERNEL"],
+ linker_scripts: [
+ ":vmbase_example_kernel.ld",
+ ":vmbase_sections",
+ ],
+}
+
+raw_binary {
+ name: "vmbase_example_bios_bin",
+ stem: "vmbase_example_bios.bin",
+ src: ":vmbase_example_bios",
+ enabled: false,
+ target: {
+ android_arm64: {
+ enabled: true,
+ },
+ },
+}
+
+raw_binary {
+ name: "vmbase_example_kernel_bin",
+ stem: "vmbase_example_kernel.bin",
+ src: ":vmbase_example_kernel",
+ enabled: false,
+ target: {
+ android_arm64: {
+ enabled: true,
+ },
+ },
+}
diff --git a/libs/libvmbase/example/idmap.S b/guest/vmbase_example/idmap.S
similarity index 82%
rename from libs/libvmbase/example/idmap.S
rename to guest/vmbase_example/idmap.S
index 71a6ade..881850c 100644
--- a/libs/libvmbase/example/idmap.S
+++ b/guest/vmbase_example/idmap.S
@@ -43,8 +43,16 @@
.quad .L_TT_TYPE_TABLE + 0f // up to 1 GiB of DRAM
.fill 509, 8, 0x0 // 509 GiB of remaining VA space
- /* level 2 */
-0: .quad .L_BLOCK_MEM | 0x80000000 // DT provided by VMM
+0: /* level 2 */
+#if defined(VMBASE_EXAMPLE_IS_BIOS)
+ .quad 0 // 2 MiB not mapped (DT)
.quad .L_BLOCK_MEM_XIP | 0x80200000 // 2 MiB of DRAM containing image
.quad .L_BLOCK_MEM | 0x80400000 // 2 MiB of writable DRAM
.fill 509, 8, 0x0
+#elif defined(VMBASE_EXAMPLE_IS_KERNEL)
+ .quad .L_BLOCK_MEM_XIP | 0x80000000 // 2 MiB of DRAM containing image
+ .quad .L_BLOCK_MEM | 0x80200000 // 2 MiB of writable DRAM
+ .fill 510, 8, 0x0
+#else
+#error "Unexpected vmbase_example mode: failed to generate idmap"
+#endif
diff --git a/libs/libvmbase/example/image.ld b/guest/vmbase_example/image.ld.S
similarity index 73%
rename from libs/libvmbase/example/image.ld
rename to guest/vmbase_example/image.ld.S
index 95ffdf8..a5cd965 100644
--- a/libs/libvmbase/example/image.ld
+++ b/guest/vmbase_example/image.ld.S
@@ -16,6 +16,13 @@
MEMORY
{
+#if defined(VMBASE_EXAMPLE_IS_BIOS)
image : ORIGIN = 0x80200000, LENGTH = 2M
writable_data : ORIGIN = 0x80400000, LENGTH = 2M
+#elif defined(VMBASE_EXAMPLE_IS_KERNEL)
+ image : ORIGIN = 0x80000000, LENGTH = 2M
+ writable_data : ORIGIN = 0x80200000, LENGTH = 2M
+#else
+#error "Unexpected vmbase_example mode: failed to generate image layout"
+#endif
}
diff --git a/libs/libvmbase/example/src/exceptions.rs b/guest/vmbase_example/src/exceptions.rs
similarity index 100%
rename from libs/libvmbase/example/src/exceptions.rs
rename to guest/vmbase_example/src/exceptions.rs
diff --git a/libs/libvmbase/example/src/layout.rs b/guest/vmbase_example/src/layout.rs
similarity index 100%
rename from libs/libvmbase/example/src/layout.rs
rename to guest/vmbase_example/src/layout.rs
diff --git a/libs/libvmbase/example/src/main.rs b/guest/vmbase_example/src/main.rs
similarity index 91%
rename from libs/libvmbase/example/src/main.rs
rename to guest/vmbase_example/src/main.rs
index 4d535cc..7a3f427 100644
--- a/libs/libvmbase/example/src/main.rs
+++ b/guest/vmbase_example/src/main.rs
@@ -25,10 +25,10 @@
use crate::layout::{boot_stack_range, print_addresses, DEVICE_REGION};
use crate::pci::{check_pci, get_bar_region};
-use aarch64_paging::paging::MemoryRegion;
use aarch64_paging::paging::VirtualAddress;
use aarch64_paging::MapError;
use alloc::{vec, vec::Vec};
+use core::mem;
use core::ptr::addr_of_mut;
use cstr::cstr;
use fdtpci::PciInfo;
@@ -36,12 +36,10 @@
use log::{debug, error, info, trace, warn, LevelFilter};
use vmbase::{
bionic, configure_heap, generate_image_header,
- layout::{
- crosvm::{FDT_MAX_SIZE, MEM_START},
- rodata_range, scratch_range, text_range,
- },
+ layout::{crosvm::FDT_MAX_SIZE, rodata_range, scratch_range, text_range},
linker, logger, main,
memory::{PageTable, SIZE_64KB},
+ util::RangeExt as _,
};
static INITIALISED_DATA: [u32; 4] = [1, 2, 3, 4];
@@ -52,16 +50,12 @@
main!(main);
configure_heap!(SIZE_64KB);
-fn init_page_table(dtb: &MemoryRegion, pci_bar_range: &MemoryRegion) -> Result<(), MapError> {
- let mut page_table = PageTable::default();
-
+fn init_page_table(page_table: &mut PageTable) -> Result<(), MapError> {
page_table.map_device(&DEVICE_REGION)?;
page_table.map_code(&text_range().into())?;
page_table.map_rodata(&rodata_range().into())?;
page_table.map_data(&scratch_range().into())?;
page_table.map_data(&boot_stack_range().into())?;
- page_table.map_rodata(dtb)?;
- page_table.map_device(pci_bar_range)?;
info!("Activating IdMap...");
// SAFETY: page_table duplicates the static mappings for everything that the Rust code is
@@ -84,13 +78,15 @@
check_data();
check_stack_guard();
+ let mut page_table = PageTable::default();
+ init_page_table(&mut page_table).unwrap();
+
info!("Checking FDT...");
let fdt_addr = usize::try_from(arg0).unwrap();
- // We are about to access the region so check that it matches our page tables in idmap.S.
- assert_eq!(fdt_addr, MEM_START);
// SAFETY: The DTB range is valid, writable memory, and we don't construct any aliases to it.
let fdt = unsafe { core::slice::from_raw_parts_mut(fdt_addr as *mut u8, FDT_MAX_SIZE) };
let fdt_region = (VirtualAddress(fdt_addr)..VirtualAddress(fdt_addr + fdt.len())).into();
+ page_table.map_data(&fdt_region).unwrap();
let fdt = Fdt::from_mut_slice(fdt).unwrap();
info!("FDT passed verification.");
check_fdt(fdt);
@@ -102,7 +98,13 @@
check_alloc();
- init_page_table(&fdt_region, &get_bar_region(&pci_info)).unwrap();
+ let bar_region = get_bar_region(&pci_info);
+ if bar_region.is_within(&DEVICE_REGION) {
+ // Avoid a MapError::BreakBeforeMakeViolation.
+ info!("BAR region is within already mapped device region: skipping page table ops.");
+ } else {
+ page_table.map_device(&bar_region).unwrap();
+ }
check_data();
check_dice();
@@ -112,6 +114,10 @@
check_pci(&mut pci_root);
emit_suppressed_log();
+
+ info!("De-activating IdMap...");
+ mem::drop(page_table); // Release PageTable and switch back to idmap.S
+ info!("De-activated.");
}
fn check_stack_guard() {
diff --git a/libs/libvmbase/example/src/pci.rs b/guest/vmbase_example/src/pci.rs
similarity index 100%
rename from libs/libvmbase/example/src/pci.rs
rename to guest/vmbase_example/src/pci.rs
diff --git a/libs/libvmbase/example/Android.bp b/libs/libvmbase/example/Android.bp
deleted file mode 100644
index fe9de44..0000000
--- a/libs/libvmbase/example/Android.bp
+++ /dev/null
@@ -1,74 +0,0 @@
-package {
- default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-rust_ffi_static {
- name: "libvmbase_example",
- defaults: ["vmbase_ffi_defaults"],
- crate_name: "vmbase_example",
- srcs: ["src/main.rs"],
- rustlibs: [
- "libaarch64_paging",
- "libcstr",
- "libdiced_open_dice_nostd",
- "libfdtpci",
- "liblibfdt",
- "liblog_rust_nostd",
- "libvirtio_drivers",
- "libvmbase",
- ],
-}
-
-cc_binary {
- name: "vmbase_example",
- defaults: ["vmbase_elf_defaults"],
- srcs: [
- "idmap.S",
- ],
- static_libs: [
- "libvmbase_example",
- ],
- linker_scripts: [
- "image.ld",
- ":vmbase_sections",
- ],
-}
-
-raw_binary {
- name: "vmbase_example_bin",
- stem: "vmbase_example.bin",
- src: ":vmbase_example",
- enabled: false,
- target: {
- android_arm64: {
- enabled: true,
- },
- },
-}
-
-rust_test {
- name: "vmbase_example.integration_test",
- crate_name: "vmbase_example_test",
- srcs: ["tests/test.rs"],
- prefer_rlib: true,
- edition: "2021",
- rustlibs: [
- "android.system.virtualizationservice-rust",
- "libandroid_logger",
- "libanyhow",
- "liblibc",
- "liblog_rust",
- "libnix",
- "libvmclient",
- ],
- data: [
- ":vmbase_example_bin",
- ],
- test_suites: ["general-tests"],
- enabled: false,
- target: {
- android_arm64: {
- enabled: true,
- },
- },
-}
diff --git a/libs/libvmbase/src/util.rs b/libs/libvmbase/src/util.rs
index 8c230a1..e52ac8e 100644
--- a/libs/libvmbase/src/util.rs
+++ b/libs/libvmbase/src/util.rs
@@ -14,6 +14,7 @@
//! Utility functions.
+use aarch64_paging::paging::MemoryRegion;
use core::ops::Range;
/// Flatten [[T; N]] into &[T]
@@ -91,3 +92,13 @@
self.start < other.end && other.start < self.end
}
}
+
+impl RangeExt for MemoryRegion {
+ fn is_within(&self, other: &Self) -> bool {
+ self.start() >= other.start() && self.end() <= other.end()
+ }
+
+ fn overlaps(&self, other: &Self) -> bool {
+ self.start() < other.end() && other.start() < self.end()
+ }
+}
diff --git a/libs/vm_launcher_lib/Android.bp b/libs/vm_launcher_lib/Android.bp
new file mode 100644
index 0000000..8591c8d
--- /dev/null
+++ b/libs/vm_launcher_lib/Android.bp
@@ -0,0 +1,13 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_library {
+ name: "vm_launcher_lib",
+ srcs: ["java/**/*.java"],
+ apex_available: [
+ "//apex_available:platform",
+ "com.android.virt",
+ ],
+ sdk_version: "system_current",
+}
diff --git a/libs/vm_launcher_lib/java/com/android/virtualization/vmlauncher/VmLauncherServices.java b/libs/vm_launcher_lib/java/com/android/virtualization/vmlauncher/VmLauncherServices.java
new file mode 100644
index 0000000..c5bc5fb
--- /dev/null
+++ b/libs/vm_launcher_lib/java/com/android/virtualization/vmlauncher/VmLauncherServices.java
@@ -0,0 +1,112 @@
+/*
+ * 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.vmlauncher;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Parcel;
+import android.os.ResultReceiver;
+import android.util.Log;
+
+import java.util.List;
+
+public class VmLauncherServices {
+ private static final String TAG = "VmLauncherServices";
+
+ private static final String ACTION_START_VM_LAUNCHER_SERVICE =
+ "android.virtualization.START_VM_LAUNCHER_SERVICE";
+
+ private static final int RESULT_START = 0;
+ private static final int RESULT_STOP = 1;
+ private static final int RESULT_ERROR = 2;
+ private static final int RESULT_IPADDR = 3;
+ private static final String KEY_VM_IP_ADDR = "ip_addr";
+
+ private static Intent buildVmLauncherServiceIntent(Context context) {
+ Intent i = new Intent();
+ i.setAction(ACTION_START_VM_LAUNCHER_SERVICE);
+
+ Intent intent = new Intent(ACTION_START_VM_LAUNCHER_SERVICE);
+ PackageManager pm = context.getPackageManager();
+ List<ResolveInfo> resolveInfos =
+ pm.queryIntentServices(intent, PackageManager.MATCH_DEFAULT_ONLY);
+ if (resolveInfos == null || resolveInfos.size() != 1) {
+ Log.e(TAG, "cannot find a service to handle ACTION_START_VM_LAUNCHER_SERVICE");
+ return null;
+ }
+ String packageName = resolveInfos.get(0).serviceInfo.packageName;
+
+ i.setPackage(packageName);
+ return i;
+ }
+
+ public static void startVmLauncherService(Context context, VmLauncherServiceCallback callback) {
+ Intent i = buildVmLauncherServiceIntent(context);
+ if (i == null) {
+ return;
+ }
+ ResultReceiver resultReceiver =
+ new ResultReceiver(new Handler(Looper.myLooper())) {
+ @Override
+ protected void onReceiveResult(int resultCode, Bundle resultData) {
+ if (callback == null) {
+ return;
+ }
+ switch (resultCode) {
+ case RESULT_START:
+ callback.onVmStart();
+ return;
+ case RESULT_STOP:
+ callback.onVmStop();
+ return;
+ case RESULT_ERROR:
+ callback.onVmError();
+ return;
+ case RESULT_IPADDR:
+ callback.onIpAddrAvailable(resultData.getString(KEY_VM_IP_ADDR));
+ return;
+ }
+ }
+ };
+ i.putExtra(Intent.EXTRA_RESULT_RECEIVER, getResultReceiverForIntent(resultReceiver));
+ context.startForegroundService(i);
+ }
+
+ public interface VmLauncherServiceCallback {
+ void onVmStart();
+
+ void onVmStop();
+
+ void onVmError();
+
+ void onIpAddrAvailable(String ipAddr);
+ }
+
+ private static ResultReceiver getResultReceiverForIntent(ResultReceiver r) {
+ Parcel parcel = Parcel.obtain();
+ r.writeToParcel(parcel, 0);
+ parcel.setDataPosition(0);
+ r = ResultReceiver.CREATOR.createFromParcel(parcel);
+ parcel.recycle();
+ return r;
+ }
+}
diff --git a/tests/vmbase_example/Android.bp b/tests/vmbase_example/Android.bp
new file mode 100644
index 0000000..4c1aa30
--- /dev/null
+++ b/tests/vmbase_example/Android.bp
@@ -0,0 +1,31 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_test {
+ name: "vmbase_example.integration_test",
+ crate_name: "vmbase_example_test",
+ srcs: ["src/main.rs"],
+ prefer_rlib: true,
+ edition: "2021",
+ rustlibs: [
+ "android.system.virtualizationservice-rust",
+ "libandroid_logger",
+ "libanyhow",
+ "liblibc",
+ "liblog_rust",
+ "libnix",
+ "libvmclient",
+ ],
+ data: [
+ ":vmbase_example_bios_bin",
+ ":vmbase_example_kernel_bin",
+ ],
+ test_suites: ["general-tests"],
+ enabled: false,
+ target: {
+ android_arm64: {
+ enabled: true,
+ },
+ },
+}
diff --git a/libs/libvmbase/example/tests/test.rs b/tests/vmbase_example/src/main.rs
similarity index 86%
rename from libs/libvmbase/example/tests/test.rs
rename to tests/vmbase_example/src/main.rs
index 8f9fafc..e0563b7 100644
--- a/libs/libvmbase/example/tests/test.rs
+++ b/tests/vmbase_example/src/main.rs
@@ -31,13 +31,27 @@
};
use vmclient::{DeathReason, VmInstance};
-const VMBASE_EXAMPLE_PATH: &str = "vmbase_example.bin";
+const VMBASE_EXAMPLE_KERNEL_PATH: &str = "vmbase_example_kernel.bin";
+const VMBASE_EXAMPLE_BIOS_PATH: &str = "vmbase_example_bios.bin";
const TEST_DISK_IMAGE_PATH: &str = "test_disk.img";
const EMPTY_DISK_IMAGE_PATH: &str = "empty_disk.img";
-/// Runs the vmbase_example VM as an unprotected VM via VirtualizationService.
+/// Runs the vmbase_example VM as an unprotected VM kernel via VirtualizationService.
#[test]
-fn test_run_example_vm() -> Result<(), Error> {
+fn test_run_example_kernel_vm() -> Result<(), Error> {
+ run_test(Some(open_payload(VMBASE_EXAMPLE_KERNEL_PATH)?), None)
+}
+
+/// Runs the vmbase_example VM as an unprotected VM BIOS via VirtualizationService.
+#[test]
+fn test_run_example_bios_vm() -> Result<(), Error> {
+ run_test(None, Some(open_payload(VMBASE_EXAMPLE_BIOS_PATH)?))
+}
+
+fn run_test(
+ kernel: Option<ParcelFileDescriptor>,
+ bootloader: Option<ParcelFileDescriptor>,
+) -> Result<(), Error> {
android_logger::init_once(
android_logger::Config::default()
.with_tag("vmbase")
@@ -56,12 +70,6 @@
vmclient::VirtualizationService::new().context("Failed to spawn VirtualizationService")?;
let service = virtmgr.connect().context("Failed to connect to VirtualizationService")?;
- // Start example VM.
- let bootloader = ParcelFileDescriptor::new(
- File::open(VMBASE_EXAMPLE_PATH)
- .with_context(|| format!("Failed to open VM image {}", VMBASE_EXAMPLE_PATH))?,
- );
-
// Make file for test disk image.
let mut test_image = File::options()
.create(true)
@@ -91,10 +99,10 @@
let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
name: String::from("VmBaseTest"),
- kernel: None,
+ kernel,
initrd: None,
params: None,
- bootloader: Some(bootloader),
+ bootloader,
disks: vec![disk_image, empty_disk_image],
protectedVm: false,
memoryMib: 300,
@@ -142,6 +150,11 @@
Ok((reader_fd.into(), writer_fd.into()))
}
+fn open_payload(path: &str) -> Result<ParcelFileDescriptor, Error> {
+ let file = File::open(path).with_context(|| format!("Failed to open VM image {path}"))?;
+ Ok(ParcelFileDescriptor::new(file))
+}
+
struct VmLogProcessor {
reader: Option<File>,
expected: VecDeque<String>,