Merge "Use select() in build/microdroid/Android.bp" into main
diff --git a/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/MainActivity.java b/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/MainActivity.java
index 9004c07..d837c04 100644
--- a/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/MainActivity.java
+++ b/android/VmLauncherApp/java/com/android/virtualization/vmlauncher/MainActivity.java
@@ -46,6 +46,7 @@
 import android.util.Log;
 import android.view.InputDevice;
 import android.view.KeyEvent;
+import android.view.SurfaceControl;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
@@ -497,7 +498,11 @@
                                     if (mCursorHandler != null) {
                                         mCursorHandler.interrupt();
                                     }
-                                    mCursorHandler = new CursorHandler(cursorSurfaceView, pfds[0]);
+                                    mCursorHandler =
+                                            new CursorHandler(
+                                                    surfaceView.getSurfaceControl(),
+                                                    cursorSurfaceView.getSurfaceControl(),
+                                                    pfds[0]);
                                     mCursorHandler.start();
                                     runWithDisplayService(
                                             (service) -> service.setCursorStream(pfds[1]));
@@ -763,12 +768,16 @@
     }
 
     static class CursorHandler extends Thread {
-        private final SurfaceView mSurfaceView;
+        private final SurfaceControl mCursor;
         private final ParcelFileDescriptor mStream;
+        private final SurfaceControl.Transaction mTransaction;
 
-        CursorHandler(SurfaceView s, ParcelFileDescriptor stream) {
-            mSurfaceView = s;
+        CursorHandler(SurfaceControl main, SurfaceControl cursor, ParcelFileDescriptor stream) {
+            mCursor = cursor;
             mStream = stream;
+            mTransaction = new SurfaceControl.Transaction();
+
+            mTransaction.reparent(cursor, main).apply();
         }
 
         @Override
@@ -795,11 +804,7 @@
                     }
                     float x = (float) (byteBuffer.getInt() & 0xFFFFFFFF);
                     float y = (float) (byteBuffer.getInt() & 0xFFFFFFFF);
-                    mSurfaceView.post(
-                            () -> {
-                                mSurfaceView.setTranslationX(x);
-                                mSurfaceView.setTranslationY(y);
-                            });
+                    mTransaction.setPosition(mCursor, x, y).apply();
                 }
             } catch (IOException e) {
                 Log.e(TAG, "failed to run CursorHandler", e);
diff --git a/build/Android.bp b/build/Android.bp
index 3b6b8b5..66cc626 100644
--- a/build/Android.bp
+++ b/build/Android.bp
@@ -18,86 +18,50 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-soong_config_module_type {
-    name: "avf_flag_aware_rust_defaults",
-    module_type: "rust_defaults",
-    config_namespace: "ANDROID",
-    bool_variables: [
-        "release_avf_enable_device_assignment",
-        "release_avf_enable_dice_changes",
-        "release_avf_enable_llpvm_changes",
-        "release_avf_enable_multi_tenant_microdroid_vm",
-        "release_avf_enable_network",
-        "release_avf_enable_remote_attestation",
-        "release_avf_enable_vendor_modules",
-        "release_avf_enable_virt_cpufreq",
-        "release_avf_support_custom_vm_with_paravirtualized_devices",
-    ],
-    properties: [
-        "cfgs",
-    ],
-}
-
-avf_flag_aware_rust_defaults {
+rust_defaults {
     name: "avf_build_flags_rust",
-    soong_config_variables: {
-        release_avf_enable_device_assignment: {
-            cfgs: ["device_assignment"],
-        },
-        release_avf_enable_dice_changes: {
-            cfgs: ["dice_changes"],
-        },
-        release_avf_enable_llpvm_changes: {
-            cfgs: ["llpvm_changes"],
-        },
-        release_avf_enable_multi_tenant_microdroid_vm: {
-            cfgs: ["multi_tenant"],
-        },
-        release_avf_enable_network: {
-            cfgs: ["network"],
-        },
-        release_avf_enable_remote_attestation: {
-            cfgs: ["remote_attestation"],
-        },
-        release_avf_enable_vendor_modules: {
-            cfgs: ["vendor_modules"],
-        },
-        release_avf_enable_virt_cpufreq: {
-            cfgs: ["virt_cpufreq"],
-        },
-        release_avf_support_custom_vm_with_paravirtualized_devices: {
-            cfgs: ["paravirtualized_devices"],
-        },
-    },
+    cfgs: select(release_flag("RELEASE_AVF_ENABLE_DEVICE_ASSIGNMENT"), {
+        true: ["device_assignment"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_DICE_CHANGES"), {
+        true: ["dice_changes"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_LLPVM_CHANGES"), {
+        true: ["llpvm_changes"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_MULTI_TENANT_MICRODROID_VM"), {
+        true: ["multi_tenant"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_NETWORK"), {
+        true: ["network"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_REMOTE_ATTESTATION"), {
+        true: ["remote_attestation"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_VENDOR_MODULES"), {
+        true: ["vendor_modules"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_VIRT_CPUFREQ"), {
+        true: ["virt_cpufreq"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_SUPPORT_CUSTOM_VM_WITH_PARAVIRTUALIZED_DEVICES"), {
+        true: ["paravirtualized_devices"],
+        default: [],
+    }),
 }
 
-soong_config_module_type {
-    name: "avf_flag_aware_cc_defaults",
-    module_type: "cc_defaults",
-    config_namespace: "ANDROID",
-    bool_variables: [
-        "release_avf_enable_dice_changes",
-        "release_avf_enable_vendor_modules",
-        "release_avf_enable_virt_cpufreq",
-    ],
-    properties: [
-        "cflags",
-    ],
-}
-
-avf_flag_aware_cc_defaults {
+cc_defaults {
     name: "avf_build_flags_cc",
-    soong_config_variables: {
-        release_avf_enable_dice_changes: {
-            cflags: ["-DAVF_OPEN_DICE_CHANGES=1"],
-        },
-        release_avf_enable_vendor_modules: {
-            cflags: ["-DAVF_ENABLE_VENDOR_MODULES=1"],
-        },
-        release_avf_enable_virt_cpufreq: {
-            cflags: ["-DAVF_ENABLE_VIRT_CPUFREQ=1"],
-        },
-    },
+    cflags: select(release_flag("RELEASE_AVF_ENABLE_DICE_CHANGES"), {
+        true: ["-DAVF_OPEN_DICE_CHANGES=1"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_VENDOR_MODULES"), {
+        true: ["-DAVF_ENABLE_VENDOR_MODULES=1"],
+        default: [],
+    }) + select(release_flag("RELEASE_AVF_ENABLE_VIRT_CPUFREQ"), {
+        true: ["-DAVF_ENABLE_VIRT_CPUFREQ=1"],
+        default: [],
+    }),
 }
 
 genrule_defaults {
diff --git a/docs/vm_remote_attestation.md b/docs/vm_remote_attestation.md
index 6dab37a..79f44b9 100644
--- a/docs/vm_remote_attestation.md
+++ b/docs/vm_remote_attestation.md
@@ -105,7 +105,11 @@
     set to true only when all the DICE certificates in the pVM DICE chain are in
     normal mode.
 -   The `vmComponents` field contains a list of all the APKs and apexes loaded
-    by the pVM.
+    by the pVM. These components are extracted from the config descriptor of the
+    last DiceChainEntry of the pVM DICE chain. Refer to
+    [dice_for_avf_guest.cddl][dice_for_avf_guest_cddl] for more information.
+
+[dice_for_avf_guest_cddl]: https://cs.android.com/android/platform/superproject/main/+/main:packages/modules/Virtualization/dice_for_avf_guest.cddl
 
 ## To Support It
 
diff --git a/guest/kernel/Android.bp b/guest/kernel/Android.bp
index 7a8af90..19cdc49 100644
--- a/guest/kernel/Android.bp
+++ b/guest/kernel/Android.bp
@@ -26,66 +26,30 @@
     // large-scale-change unable to identify any license_text files
 }
 
-soong_config_module_type {
-    name: "avf_microdroid_kernel_prebuilt",
-    module_type: "filegroup",
-    config_namespace: "ANDROID",
-    variables: [
-        "release_avf_microdroid_kernel_version",
-    ],
-    properties: [
-        "srcs",
-    ],
-}
-
-soong_config_string_variable {
-    name: "release_avf_microdroid_kernel_version",
-    values: [
-        "android14_61",
-        "android15_66",
-    ],
-}
-
-avf_microdroid_kernel_prebuilt {
+filegroup {
     name: "microdroid_kernel_prebuilt-arm64",
     // Below are properties that are conditionally set depending on value of build flags.
-    soong_config_variables: {
-        release_avf_microdroid_kernel_version: {
-            android14_61: {
-                srcs: ["android14-6.1/arm64/kernel-6.1"],
-            },
-            android15_66: {
-                srcs: ["android15-6.6/arm64/kernel-6.6"],
-            },
-            // In case release configuration doesn't specify value of the
-            // RELEASE_AVF_MICRODROID_KERNEL_VERSION fallback to the kernel we
-            // already released.
-            // TODO(b/298011555): remove this once we set the flag in all release configs.
-            conditions_default: {
-                srcs: ["android14-6.1/arm64/kernel-6.1"],
-            },
-        },
-    },
+    srcs: select(release_flag("RELEASE_AVF_MICRODROID_KERNEL_VERSION"), {
+        "android14_61": ["android14-6.1/arm64/kernel-6.1"],
+        "android15_66": ["android15-6.6/arm64/kernel-6.6"],
+        // In case release configuration doesn't specify value of the
+        // RELEASE_AVF_MICRODROID_KERNEL_VERSION fallback to the kernel we
+        // already released.
+        // TODO(b/298011555): remove this once we set the flag in all release configs.
+        default: ["android14-6.1/arm64/kernel-6.1"],
+    }),
 }
 
-avf_microdroid_kernel_prebuilt {
+filegroup {
     name: "microdroid_kernel_prebuilt-x86_64",
     // Below are properties that are conditionally set depending on value of build flags.
-    soong_config_variables: {
-        release_avf_microdroid_kernel_version: {
-            android14_61: {
-                srcs: ["android14-6.1/x86_64/kernel-6.1"],
-            },
-            android15_66: {
-                srcs: ["android15-6.6/x86_64/kernel-6.6"],
-            },
-            // In case release configuration doesn't specify value of the
-            // RELEASE_AVF_MICRODROID_KERNEL_VERSION fallback to the kernel we
-            // already released.
-            // TODO(b/298011555): remove this once we set the flag in all release configs.
-            conditions_default: {
-                srcs: ["android14-6.1/x86_64/kernel-6.1"],
-            },
-        },
-    },
+    srcs: select(release_flag("RELEASE_AVF_MICRODROID_KERNEL_VERSION"), {
+        "android14_61": ["android14-6.1/x86_64/kernel-6.1"],
+        "android15_66": ["android15-6.6/x86_64/kernel-6.6"],
+        // In case release configuration doesn't specify value of the
+        // RELEASE_AVF_MICRODROID_KERNEL_VERSION fallback to the kernel we
+        // already released.
+        // TODO(b/298011555): remove this once we set the flag in all release configs.
+        default: ["android14-6.1/x86_64/kernel-6.1"],
+    }),
 }
diff --git a/guest/rialto/src/fdt.rs b/guest/rialto/src/fdt.rs
index b220f41..e97a262 100644
--- a/guest/rialto/src/fdt.rs
+++ b/guest/rialto/src/fdt.rs
@@ -29,3 +29,10 @@
     let node = fdt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
     node.getprop(cstr!("vendor_hashtree_descriptor_root_digest"))
 }
+
+pub(crate) fn read_is_strict_boot(fdt: &Fdt) -> libfdt::Result<bool> {
+    match fdt.chosen()? {
+        Some(node) => Ok(node.getprop(cstr!("avf,strict-boot"))?.is_some()),
+        None => Ok(false),
+    }
+}
diff --git a/guest/rialto/src/main.rs b/guest/rialto/src/main.rs
index 701a287..930f4e8 100644
--- a/guest/rialto/src/main.rs
+++ b/guest/rialto/src/main.rs
@@ -26,7 +26,7 @@
 
 use crate::communication::VsockStream;
 use crate::error::{Error, Result};
-use crate::fdt::{read_dice_range_from, read_vendor_hashtree_root_digest};
+use crate::fdt::{read_dice_range_from, read_is_strict_boot, read_vendor_hashtree_root_digest};
 use alloc::boxed::Box;
 use bssl_sys::CRYPTO_library_init;
 use ciborium_io::Write;
@@ -58,16 +58,15 @@
     },
 };
 
-fn host_addr() -> VsockAddr {
-    VsockAddr { cid: VMADDR_CID_HOST, port: vm_type().port() }
+fn host_addr(fdt: &libfdt::Fdt) -> Result<VsockAddr> {
+    Ok(VsockAddr { cid: VMADDR_CID_HOST, port: vm_type(fdt)?.port() })
 }
 
-fn vm_type() -> VmType {
-    // Use MMIO support to determine whether the VM is protected.
-    if get_mmio_guard().is_some() {
-        VmType::ProtectedVm
+fn vm_type(fdt: &libfdt::Fdt) -> Result<VmType> {
+    if read_is_strict_boot(fdt)? {
+        Ok(VmType::ProtectedVm)
     } else {
-        VmType::NonProtectedVm
+        Ok(VmType::NonProtectedVm)
     }
 }
 
@@ -143,7 +142,7 @@
     unsafe {
         CRYPTO_library_init();
     }
-    let bcc_handover: Box<dyn DiceArtifacts> = match vm_type() {
+    let bcc_handover: Box<dyn DiceArtifacts> = match vm_type(fdt)? {
         VmType::ProtectedVm => {
             let dice_range = read_dice_range_from(fdt)?;
             info!("DICE range: {dice_range:#x?}");
@@ -178,7 +177,7 @@
     let request_context =
         RequestContext { dice_artifacts: bcc_handover.as_ref(), vendor_hashtree_root_digest };
 
-    let mut vsock_stream = VsockStream::new(socket_device, host_addr())?;
+    let mut vsock_stream = VsockStream::new(socket_device, host_addr(fdt)?)?;
     while let ServiceVmRequest::Process(req) = vsock_stream.read_request()? {
         info!("Received request: {}", req.name());
         let response = process_request(req, &request_context);
diff --git a/libs/libvmbase/src/hyp/hypervisor/kvm.rs b/libs/libvmbase/src/hyp/hypervisor/kvm.rs
index 8450bed..e496f09 100644
--- a/libs/libvmbase/src/hyp/hypervisor/kvm.rs
+++ b/libs/libvmbase/src/hyp/hypervisor/kvm.rs
@@ -75,7 +75,7 @@
 const VENDOR_HYP_KVM_MMIO_GUARD_UNMAP_FUNC_ID: u32 = 0xc6000008;
 
 const VENDOR_HYP_KVM_DEV_REQ_MMIO_FUNC_ID: u32 = 0xc6000012;
-const VENDOR_HYP_KVM_DEV_REQ_DMA_FUNC_ID: u32 = 0xc6000013;
+const VENDOR_HYP_KVM_DEV_REQ_DMA_FUNC_ID: u32 = 0xc600001b;
 
 pub(super) struct RegularKvmHypervisor;
 
diff --git a/libs/libvmbase/src/memory/page_table.rs b/libs/libvmbase/src/memory/page_table.rs
index dc346e7..62b52ae 100644
--- a/libs/libvmbase/src/memory/page_table.rs
+++ b/libs/libvmbase/src/memory/page_table.rs
@@ -16,23 +16,29 @@
 
 use crate::read_sysreg;
 use aarch64_paging::idmap::IdMap;
-use aarch64_paging::paging::{Attributes, Constraints, Descriptor, MemoryRegion};
+use aarch64_paging::paging::{
+    Attributes, Constraints, Descriptor, MemoryRegion, TranslationRegime,
+};
 use aarch64_paging::MapError;
 use core::result;
 
 /// Software bit used to indicate a device that should be lazily mapped.
 pub(super) const MMIO_LAZY_MAP_FLAG: Attributes = Attributes::SWFLAG_0;
 
-// We assume that:
-// - MAIR_EL1.Attr0 = "Device-nGnRE memory" (0b0000_0100)
-// - MAIR_EL1.Attr1 = "Normal memory, Outer & Inner WB Non-transient, R/W-Allocate" (0b1111_1111)
+/// We assume that MAIR_EL1.Attr0 = "Device-nGnRE memory" (0b0000_0100)
+const DEVICE_NGNRE: Attributes = Attributes::ATTRIBUTE_INDEX_0;
+
+/// We assume that MAIR_EL1.Attr1 = "Normal memory, Outer & Inner WB Non-transient, R/W-Allocate"
+/// (0b1111_1111)
+const NORMAL: Attributes = Attributes::ATTRIBUTE_INDEX_1.union(Attributes::INNER_SHAREABLE);
+
 const MEMORY: Attributes =
-    Attributes::VALID.union(Attributes::NORMAL).union(Attributes::NON_GLOBAL);
+    Attributes::VALID.union(NORMAL).union(Attributes::NON_GLOBAL).union(Attributes::ACCESSED);
 const DEVICE_LAZY: Attributes =
-    MMIO_LAZY_MAP_FLAG.union(Attributes::DEVICE_NGNRE).union(Attributes::EXECUTE_NEVER);
+    MMIO_LAZY_MAP_FLAG.union(DEVICE_NGNRE).union(Attributes::UXN).union(Attributes::ACCESSED);
 const DEVICE: Attributes = DEVICE_LAZY.union(Attributes::VALID);
 const CODE: Attributes = MEMORY.union(Attributes::READ_ONLY);
-const DATA: Attributes = MEMORY.union(Attributes::EXECUTE_NEVER);
+const DATA: Attributes = MEMORY.union(Attributes::UXN);
 const RODATA: Attributes = DATA.union(Attributes::READ_ONLY);
 const DATA_DBM: Attributes = RODATA.union(Attributes::DBM);
 
@@ -64,7 +70,7 @@
         assert_eq!((tcr_el1 >> TCR_EL1_TG0_SHIFT) & TCR_EL1_TG0_MASK, TCR_EL1_TG0_SIZE_4KB);
         assert_eq!((tcr_el1 >> TCR_EL1_T0SZ_SHIFT) & TCR_EL1_T0SZ_MASK, TCR_EL1_T0SZ_39_VA_BITS);
 
-        IdMap::new(Self::ASID, Self::ROOT_LEVEL).into()
+        IdMap::new(Self::ASID, Self::ROOT_LEVEL, TranslationRegime::El1And0).into()
     }
 }
 
diff --git a/tests/vm_accessor/accessor/Android.bp b/tests/vm_accessor/accessor/Android.bp
index d9d1026..7c0ee6d 100644
--- a/tests/vm_accessor/accessor/Android.bp
+++ b/tests/vm_accessor/accessor/Android.bp
@@ -21,11 +21,11 @@
         "libenv_logger",
         "libglob",
         "libhypervisor_props",
-        "liblibc",
         "liblog_rust",
         "libmicrodroid_payload_config",
         "librand",
         "libvmconfig",
         "libvmclient",
+        "libnix",
     ],
 }
diff --git a/tests/vm_accessor/accessor/src/run.rs b/tests/vm_accessor/accessor/src/run.rs
index 03aa80d..932baab 100644
--- a/tests/vm_accessor/accessor/src/run.rs
+++ b/tests/vm_accessor/accessor/src/run.rs
@@ -26,11 +26,10 @@
 use glob::glob;
 use log::{error, info};
 use rand::{distributions::Alphanumeric, Rng};
-use std::fs;
-use std::fs::File;
-use std::io;
-use std::os::unix::io::{AsRawFd, FromRawFd};
+use std::fs::{self, File};
+use std::io::{self, BufRead, BufReader};
 use std::path::PathBuf;
+use std::thread;
 use vmclient::{ErrorCode, VmInstance};
 use vmconfig::open_parcel_file;
 
@@ -126,9 +125,9 @@
     let vm = VmInstance::create(
         service.as_ref(),
         &vm_config,
-        Some(duplicate_fd(io::stdout())?), /* console_out */
-        None,                              /* console_in */
-        Some(duplicate_fd(io::stdout())?), /* log */
+        Some(android_log_fd()?), /* console_out */
+        None,                    /* console_in */
+        Some(android_log_fd()?), /* log */
         Some(Box::new(Callback {})),
     )
     .context("Failed to create VM")?;
@@ -159,17 +158,24 @@
     }
 }
 
-/// Safely duplicate the file descriptor.
-fn duplicate_fd<T: AsRawFd>(file: T) -> io::Result<File> {
-    let fd = file.as_raw_fd();
-    // SAFETY: This just duplicates a file descriptor which we know to be valid, and we check for an
-    // an error.
-    let dup_fd = unsafe { libc::dup(fd) };
-    if dup_fd < 0 {
-        Err(io::Error::last_os_error())
-    } else {
-        // SAFETY: We have just duplicated the file descriptor so we own it, and `from_raw_fd` takes
-        // ownership of it.
-        Ok(unsafe { File::from_raw_fd(dup_fd) })
-    }
+/// This function is only exposed for testing.
+/// Production code prefer not expose logs from VM.
+fn android_log_fd() -> io::Result<File> {
+    let (reader_fd, writer_fd) = nix::unistd::pipe()?;
+
+    let reader = File::from(reader_fd);
+    let writer = File::from(writer_fd);
+
+    thread::spawn(|| {
+        for line in BufReader::new(reader).lines() {
+            match line {
+                Ok(l) => info!("{}", l),
+                Err(e) => {
+                    error!("Failed to read line from VM: {e:?}");
+                    break;
+                }
+            }
+        }
+    });
+    Ok(writer)
 }