Merge "Only accept binary name not path"
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/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index b237bab..f48611b 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -488,6 +488,8 @@
 }
 
 impl Zipfuse {
+    const MICRODROID_PAYLOAD_UID: u32 = 0; // TODO(b/264861173) should be non-root
+    const MICRODROID_PAYLOAD_GID: u32 = 0; // TODO(b/264861173) should be non-root
     fn mount(
         &mut self,
         noexec: MountForExec,
@@ -501,6 +503,8 @@
             cmd.arg("--noexec");
         }
         cmd.args(["-p", &ready_prop, "-o", option]);
+        cmd.args(["-u", &Self::MICRODROID_PAYLOAD_UID.to_string()]);
+        cmd.args(["-g", &Self::MICRODROID_PAYLOAD_GID.to_string()]);
         cmd.arg(zip_path).arg(mount_dir);
         self.ready_properties.push(ready_prop);
         cmd.spawn().with_context(|| format!("Failed to run zipfuse for {mount_dir:?}"))
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index b6db601..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),
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/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 157a03f..617c300 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -678,9 +678,6 @@
         // Check if the native library in the APK is has correct filesystem info
         final String[] abis = microdroid.run("getprop", "ro.product.cpu.abilist").split(",");
         assertThat(abis).hasLength(1);
-        final String testLib = "/mnt/apk/lib/" + abis[0] + "/MicrodroidTestNativeLib.so";
-        final String label = "u:object_r:system_file:s0";
-        assertThat(microdroid.run("ls", "-Z", testLib)).isEqualTo(label + " " + testLib);
 
         // Check that no denials have happened so far
         CommandRunner android = new CommandRunner(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 b206056..c1c4b53 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -1203,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);
@@ -1321,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/zipfuse/src/inode.rs b/zipfuse/src/inode.rs
index 5d52922..3edbc49 100644
--- a/zipfuse/src/inode.rs
+++ b/zipfuse/src/inode.rs
@@ -31,6 +31,11 @@
 const INVALID: Inode = 0;
 const ROOT: Inode = 1;
 
+const DEFAULT_DIR_MODE: u32 = libc::S_IRUSR | libc::S_IXUSR;
+// b/264668376 some files in APK don't have unix permissions specified. Default to 400
+// otherwise those files won't be readable even by the owner.
+const DEFAULT_FILE_MODE: u32 = libc::S_IRUSR;
+
 /// `InodeData` represents an inode which has metadata about a file or a directory
 #[derive(Debug)]
 pub struct InodeData {
@@ -96,7 +101,7 @@
 
     fn new_file(zip_index: ZipIndex, zip_file: &zip::read::ZipFile) -> InodeData {
         InodeData {
-            mode: zip_file.unix_mode().unwrap_or(0),
+            mode: zip_file.unix_mode().unwrap_or(DEFAULT_FILE_MODE),
             size: zip_file.size(),
             data: InodeDataData::File(zip_index),
         }
@@ -169,7 +174,7 @@
 
         // Add the inodes for the invalid and the root directory
         assert_eq!(INVALID, table.put(InodeData::new_dir(0)));
-        assert_eq!(ROOT, table.put(InodeData::new_dir(0)));
+        assert_eq!(ROOT, table.put(InodeData::new_dir(DEFAULT_DIR_MODE)));
 
         // For each zip file in the archive, create an inode and add it to the table. If the file's
         // parent directories don't have corresponding inodes in the table, handle them too.
@@ -200,13 +205,11 @@
                     // Update the mode if this is a directory leaf.
                     if !is_file && is_leaf {
                         let mut inode = table.get_mut(parent).unwrap();
-                        inode.mode = file.unix_mode().unwrap_or(0);
+                        inode.mode = file.unix_mode().unwrap_or(DEFAULT_DIR_MODE);
                     }
                     continue;
                 }
 
-                const DEFAULT_DIR_MODE: u32 = libc::S_IRUSR | libc::S_IXUSR;
-
                 // No inode found. Create a new inode and add it to the inode table.
                 let inode = if is_file {
                     InodeData::new_file(i, &file)
diff --git a/zipfuse/src/main.rs b/zipfuse/src/main.rs
index 9411759..ffa0a4a 100644
--- a/zipfuse/src/main.rs
+++ b/zipfuse/src/main.rs
@@ -59,6 +59,18 @@
                 .takes_value(true)
                 .help("Specify a property to be set when mount is ready"),
         )
+        .arg(
+            Arg::with_name("uid")
+                .short('u')
+                .takes_value(true)
+                .help("numeric UID who's the owner of the files"),
+        )
+        .arg(
+            Arg::with_name("gid")
+                .short('g')
+                .takes_value(true)
+                .help("numeric GID who's the group of the files"),
+        )
         .arg(Arg::with_name("ZIPFILE").required(true))
         .arg(Arg::with_name("MOUNTPOINT").required(true))
         .get_matches();
@@ -68,7 +80,9 @@
     let options = matches.value_of("options");
     let noexec = matches.is_present("noexec");
     let ready_prop = matches.value_of("readyprop");
-    run_fuse(zip_file, mount_point, options, noexec, ready_prop)?;
+    let uid: u32 = matches.value_of("uid").map_or(0, |s| s.parse().unwrap());
+    let gid: u32 = matches.value_of("gid").map_or(0, |s| s.parse().unwrap());
+    run_fuse(zip_file, mount_point, options, noexec, ready_prop, uid, gid)?;
     Ok(())
 }
 
@@ -79,6 +93,8 @@
     extra_options: Option<&str>,
     noexec: bool,
     ready_prop: Option<&str>,
+    uid: u32,
+    gid: u32,
 ) -> Result<()> {
     const MAX_READ: u32 = 1 << 20; // TODO(jiyong): tune this
     const MAX_WRITE: u32 = 1 << 13; // This is a read-only filesystem
@@ -87,6 +103,7 @@
 
     let mut mount_options = vec![
         MountOption::FD(dev_fuse.as_raw_fd()),
+        MountOption::DefaultPermissions,
         MountOption::RootMode(libc::S_IFDIR | libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH),
         MountOption::AllowOther,
         MountOption::UserId(0),
@@ -110,7 +127,7 @@
 
     let mut config = fuse::FuseConfig::new();
     config.dev_fuse(dev_fuse).max_write(MAX_WRITE).max_read(MAX_READ);
-    Ok(config.enter_message_loop(ZipFuse::new(zip_file)?)?)
+    Ok(config.enter_message_loop(ZipFuse::new(zip_file, uid, gid)?)?)
 }
 
 struct ZipFuse {
@@ -119,6 +136,8 @@
     inode_table: InodeTable,
     open_files: Mutex<HashMap<Handle, OpenFile>>,
     open_dirs: Mutex<HashMap<Handle, OpenDirBuf>>,
+    uid: u32,
+    gid: u32,
 }
 
 /// Represents a [`ZipFile`] that is opened.
@@ -151,7 +170,7 @@
 }
 
 impl ZipFuse {
-    fn new(zip_file: &Path) -> Result<ZipFuse> {
+    fn new(zip_file: &Path, uid: u32, gid: u32) -> Result<ZipFuse> {
         // TODO(jiyong): Use O_DIRECT to avoid double caching.
         // `.custom_flags(nix::fcntl::OFlag::O_DIRECT.bits())` currently doesn't work.
         let f = File::open(zip_file)?;
@@ -166,6 +185,8 @@
             inode_table: it,
             open_files: Mutex::new(HashMap::new()),
             open_dirs: Mutex::new(HashMap::new()),
+            uid,
+            gid,
         })
     }
 
@@ -188,8 +209,8 @@
         st.st_ino = inode;
         st.st_mode = if inode_data.is_dir() { libc::S_IFDIR } else { libc::S_IFREG };
         st.st_mode |= inode_data.mode;
-        st.st_uid = 0;
-        st.st_gid = 0;
+        st.st_uid = self.uid;
+        st.st_gid = self.gid;
         st.st_size = i64::try_from(inode_data.size).unwrap_or(i64::MAX);
         Ok(st)
     }
@@ -465,7 +486,7 @@
         let zip_path = PathBuf::from(zip_path);
         let mnt_path = PathBuf::from(mnt_path);
         std::thread::spawn(move || {
-            crate::run_fuse(&zip_path, &mnt_path, None, noexec).unwrap();
+            crate::run_fuse(&zip_path, &mnt_path, None, noexec, 0, 0).unwrap();
         });
     }