Merge changes I89908434,I9e77925f
* changes:
pvmfw: Integrate verify_payload
vmbase: Add support for fputs(), stdout, stderr
diff --git a/demo/java/com/android/microdroid/demo/MainActivity.java b/demo/java/com/android/microdroid/demo/MainActivity.java
index 54d7420..c3fa55f 100644
--- a/demo/java/com/android/microdroid/demo/MainActivity.java
+++ b/demo/java/com/android/microdroid/demo/MainActivity.java
@@ -19,7 +19,6 @@
import android.app.Application;
import android.os.Bundle;
import android.os.IBinder;
-import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.system.virtualmachine.VirtualMachine;
import android.system.virtualmachine.VirtualMachineCallback;
@@ -243,7 +242,7 @@
try {
VirtualMachineConfig.Builder builder =
new VirtualMachineConfig.Builder(getApplication());
- builder.setPayloadBinaryPath("MicrodroidTestNativeLib.so");
+ builder.setPayloadBinaryName("MicrodroidTestNativeLib.so");
builder.setProtectedVm(true);
if (debug) {
builder.setDebugLevel(VirtualMachineConfig.DEBUG_LEVEL_FULL);
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/javalib/api/system-current.txt b/javalib/api/system-current.txt
index 30e437b..71bdf13 100644
--- a/javalib/api/system-current.txt
+++ b/javalib/api/system-current.txt
@@ -61,7 +61,7 @@
method @IntRange(from=0) public long getEncryptedStorageKib();
method @IntRange(from=0) public int getMemoryMib();
method @IntRange(from=1) public int getNumCpus();
- method @Nullable public String getPayloadBinaryPath();
+ method @Nullable public String getPayloadBinaryName();
method public boolean isCompatibleWith(@NonNull android.system.virtualmachine.VirtualMachineConfig);
method public boolean isEncryptedStorageEnabled();
method public boolean isProtectedVm();
@@ -77,7 +77,7 @@
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setEncryptedStorageKib(@IntRange(from=1) long);
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setMemoryMib(@IntRange(from=1) int);
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setNumCpus(@IntRange(from=1) int);
- method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryPath(@NonNull String);
+ method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setPayloadBinaryName(@NonNull String);
method @NonNull public android.system.virtualmachine.VirtualMachineConfig.Builder setProtectedVm(boolean);
}
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachine.java b/javalib/src/android/system/virtualmachine/VirtualMachine.java
index 34851e4..e319aa3 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -1226,17 +1226,15 @@
public String toString() {
VirtualMachineConfig config = getConfig();
String payloadConfigPath = config.getPayloadConfigPath();
- String payloadBinaryPath = config.getPayloadBinaryPath();
+ String payloadBinaryName = config.getPayloadBinaryName();
StringBuilder result = new StringBuilder();
result.append("VirtualMachine(")
.append("name:")
.append(getName())
.append(", ");
- if (payloadBinaryPath != null) {
- result.append("payload:")
- .append(payloadBinaryPath)
- .append(", ");
+ if (payloadBinaryName != null) {
+ result.append("payload:").append(payloadBinaryName).append(", ");
}
if (payloadConfigPath != null) {
result.append("config:")
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index 7c16798..0e9e86b 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -62,7 +62,7 @@
private static final String KEY_VERSION = "version";
private static final String KEY_APKPATH = "apkPath";
private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
- private static final String KEY_PAYLOADBINARYPATH = "payloadBinaryPath";
+ private static final String KEY_PAYLOADBINARYNAME = "payloadBinaryPath";
private static final String KEY_DEBUGLEVEL = "debugLevel";
private static final String KEY_PROTECTED_VM = "protectedVm";
private static final String KEY_MEMORY_MIB = "memoryMib";
@@ -118,10 +118,8 @@
*/
@Nullable private final String mPayloadConfigPath;
- /**
- * Path within the APK to the payload binary file that will be executed within the VM.
- */
- @Nullable private final String mPayloadBinaryPath;
+ /** Name of the payload binary file within the APK that will be executed within the VM. */
+ @Nullable private final String mPayloadBinaryName;
/** The size of storage in KiB. 0 indicates that encryptedStorage is not required */
private final long mEncryptedStorageKib;
@@ -129,7 +127,7 @@
private VirtualMachineConfig(
@NonNull String apkPath,
@Nullable String payloadConfigPath,
- @Nullable String payloadBinaryPath,
+ @Nullable String payloadBinaryName,
@DebugLevel int debugLevel,
boolean protectedVm,
int memoryMib,
@@ -138,7 +136,7 @@
// This is only called from Builder.build(); the builder handles parameter validation.
mApkPath = apkPath;
mPayloadConfigPath = payloadConfigPath;
- mPayloadBinaryPath = payloadBinaryPath;
+ mPayloadBinaryName = payloadBinaryName;
mDebugLevel = debugLevel;
mProtectedVm = protectedVm;
mMemoryMib = memoryMib;
@@ -192,7 +190,7 @@
String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
if (payloadConfigPath == null) {
- builder.setPayloadBinaryPath(b.getString(KEY_PAYLOADBINARYPATH));
+ builder.setPayloadBinaryName(b.getString(KEY_PAYLOADBINARYNAME));
} else {
builder.setPayloadConfigPath(payloadConfigPath);
}
@@ -231,7 +229,7 @@
b.putInt(KEY_VERSION, VERSION);
b.putString(KEY_APKPATH, mApkPath);
b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
- b.putString(KEY_PAYLOADBINARYPATH, mPayloadBinaryPath);
+ b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
b.putBoolean(KEY_PROTECTED_VM, mProtectedVm);
b.putInt(KEY_NUM_CPUS, mNumCpus);
@@ -269,15 +267,15 @@
}
/**
- * Returns the path within the {@code lib/<ABI>} directory of the APK to the payload binary file
+ * Returns the name of the payload binary file, in the {@code lib/<ABI>} directory of the APK,
* that will be executed within the VM.
*
* @hide
*/
@SystemApi
@Nullable
- public String getPayloadBinaryPath() {
- return mPayloadBinaryPath;
+ public String getPayloadBinaryName() {
+ return mPayloadBinaryName;
}
/**
@@ -362,7 +360,7 @@
&& this.mProtectedVm == other.mProtectedVm
&& this.mEncryptedStorageKib == other.mEncryptedStorageKib
&& Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
- && Objects.equals(this.mPayloadBinaryPath, other.mPayloadBinaryPath)
+ && Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
&& this.mApkPath.equals(other.mApkPath);
}
@@ -376,9 +374,9 @@
VirtualMachineAppConfig toVsConfig() throws FileNotFoundException {
VirtualMachineAppConfig vsConfig = new VirtualMachineAppConfig();
vsConfig.apk = ParcelFileDescriptor.open(new File(mApkPath), MODE_READ_ONLY);
- if (mPayloadBinaryPath != null) {
+ if (mPayloadBinaryName != null) {
VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
- payloadConfig.payloadPath = mPayloadBinaryPath;
+ payloadConfig.payloadBinaryName = mPayloadBinaryName;
vsConfig.payload =
VirtualMachineAppConfig.Payload.payloadConfig(payloadConfig);
} else {
@@ -411,7 +409,7 @@
@Nullable private final Context mContext;
@Nullable private String mApkPath;
@Nullable private String mPayloadConfigPath;
- @Nullable private String mPayloadBinaryPath;
+ @Nullable private String mPayloadBinaryName;
@DebugLevel private int mDebugLevel = DEBUG_LEVEL_NONE;
private boolean mProtectedVm;
private boolean mProtectedVmSet;
@@ -455,14 +453,14 @@
apkPath = mApkPath;
}
- if (mPayloadBinaryPath == null) {
+ if (mPayloadBinaryName == null) {
if (mPayloadConfigPath == null) {
- throw new IllegalStateException("setPayloadBinaryPath must be called");
+ throw new IllegalStateException("setPayloadBinaryName must be called");
}
} else {
if (mPayloadConfigPath != null) {
throw new IllegalStateException(
- "setPayloadBinaryPath and setPayloadConfigPath may not both be called");
+ "setPayloadBinaryName and setPayloadConfigPath may not both be called");
}
}
@@ -473,7 +471,7 @@
return new VirtualMachineConfig(
apkPath,
mPayloadConfigPath,
- mPayloadBinaryPath,
+ mPayloadBinaryName,
mDebugLevel,
mProtectedVm,
mMemoryMib,
@@ -515,16 +513,23 @@
}
/**
- * Sets the path within the {@code lib/<ABI>} directory of the APK to the payload binary
- * file that will be executed within the VM.
+ * 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.
+ *
+ * <p>Note that VMs only support 64-bit code, even if the owning app is running as a 32-bit
+ * process.
*
* @hide
*/
@SystemApi
@NonNull
- public Builder setPayloadBinaryPath(@NonNull String payloadBinaryPath) {
- mPayloadBinaryPath =
- requireNonNull(payloadBinaryPath, "payloadBinaryPath must not be null");
+ public Builder setPayloadBinaryName(@NonNull String payloadBinaryName) {
+ if (payloadBinaryName.contains(File.separator)) {
+ throw new IllegalArgumentException(
+ "Invalid binary file name: " + payloadBinaryName);
+ }
+ mPayloadBinaryName =
+ requireNonNull(payloadBinaryName, "payloadBinaryName must not be null");
return this;
}
diff --git a/microdroid/payload/metadata.proto b/microdroid/payload/metadata.proto
index 1d8dd8c..c74c23b 100644
--- a/microdroid/payload/metadata.proto
+++ b/microdroid/payload/metadata.proto
@@ -65,6 +65,6 @@
message PayloadConfig {
// Required.
- // Path to the payload binary file inside the APK.
- string payload_binary_path = 1;
+ // Name of the payload binary file inside the APK.
+ string payload_binary_name = 1;
}
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 4018d00..f48611b 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -259,7 +259,7 @@
// ? -71001: PayloadConfig
// }
// PayloadConfig = {
- // 1: tstr // payload_binary_path
+ // 1: tstr // payload_binary_name
// }
let mut config_desc = vec![
@@ -278,7 +278,7 @@
encode_negative_number(-71001, &mut config_desc)?;
encode_header(5, 1, &mut config_desc)?; // map(1)
encode_number(1, &mut config_desc)?;
- encode_tstr(&payload_config.payload_binary_path, &mut config_desc)?;
+ encode_tstr(&payload_config.payload_binary_name, &mut config_desc)?;
}
}
@@ -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:?}"))
@@ -757,7 +761,7 @@
PayloadMetadata::config(payload_config) => {
let task = Task {
type_: TaskType::MicrodroidLauncher,
- command: payload_config.payload_binary_path,
+ command: payload_config.payload_binary_name,
};
Ok(VmPayloadConfig {
os: OsConfig { name: "microdroid".to_owned() },
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/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
index 9cfac4e..9e4b228 100644
--- a/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
+++ b/tests/benchmark/src/java/com/android/microdroid/benchmark/MicrodroidBenchmarks.java
@@ -93,7 +93,7 @@
throws VirtualMachineException, InterruptedException, IOException {
VirtualMachineConfig normalConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_NONE)
.setMemoryMib(mem)
.build();
@@ -146,7 +146,7 @@
for (int i = 0; i < trialCount; i++) {
VirtualMachineConfig normalConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_NONE)
.setMemoryMib(256)
.build();
@@ -174,7 +174,7 @@
for (int i = 0; i < trialCount; i++) {
VirtualMachineConfig normalConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_NONE)
.setMemoryMib(256)
.setNumCpus(numCpus)
@@ -209,7 +209,7 @@
// To grab boot events from log, set debug mode to FULL
VirtualMachineConfig normalConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidIdleNativeLib.so")
+ .setPayloadBinaryName("MicrodroidIdleNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL)
.setMemoryMib(256)
.build();
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 e02f85f..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());
@@ -795,6 +792,39 @@
+ " permission");
}
+ @Test
+ public void testPathToBinaryIsRejected() throws Exception {
+ CommandRunner android = new CommandRunner(getDevice());
+
+ // Create the idsig file for the APK
+ final String apkPath = getPathForPackage(PACKAGE_NAME);
+ final String idSigPath = TEST_ROOT + "idsig";
+ android.run(VIRT_APEX + "bin/vm", "create-idsig", apkPath, idSigPath);
+
+ // Create the instance image for the VM
+ final String instanceImgPath = TEST_ROOT + "instance.img";
+ android.run(
+ VIRT_APEX + "bin/vm",
+ "create-partition",
+ "--type instance",
+ instanceImgPath,
+ Integer.toString(10 * 1024 * 1024));
+
+ final String ret =
+ android.runForResult(
+ VIRT_APEX + "bin/vm",
+ "run-app",
+ "--payload-binary-name",
+ "./MicrodroidTestNativeLib.so",
+ apkPath,
+ idSigPath,
+ instanceImgPath)
+ .getStderr()
+ .trim();
+
+ assertThat(ret).contains("Payload binary name must not specify a path");
+ }
+
@Before
public void setUp() throws Exception {
testIfDeviceIsCapable(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 2656c3b..43d822b 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -126,7 +126,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -150,7 +150,7 @@
// But we do need non-debug VMs to work, so run one.
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_NONE)
.build();
@@ -174,7 +174,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.build();
@@ -193,7 +193,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -224,7 +224,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -273,7 +273,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -321,13 +321,13 @@
public void vmConfigGetAndSetTests() {
// Minimal has as little as specified as possible; everything that can be is defaulted.
VirtualMachineConfig.Builder minimalBuilder = newVmConfigBuilder();
- VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryPath("binary/path").build();
+ VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryName("binary.so").build();
assertThat(minimal.getApkPath()).isEqualTo(getContext().getPackageCodePath());
assertThat(minimal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_NONE);
assertThat(minimal.getMemoryMib()).isEqualTo(0);
assertThat(minimal.getNumCpus()).isEqualTo(1);
- assertThat(minimal.getPayloadBinaryPath()).isEqualTo("binary/path");
+ assertThat(minimal.getPayloadBinaryName()).isEqualTo("binary.so");
assertThat(minimal.getPayloadConfigPath()).isNull();
assertThat(minimal.isProtectedVm()).isEqualTo(isProtectedVm());
assertThat(minimal.isEncryptedStorageEnabled()).isFalse();
@@ -350,7 +350,7 @@
assertThat(maximal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_FULL);
assertThat(maximal.getMemoryMib()).isEqualTo(42);
assertThat(maximal.getNumCpus()).isEqualTo(maxCpus);
- assertThat(maximal.getPayloadBinaryPath()).isNull();
+ assertThat(maximal.getPayloadBinaryName()).isNull();
assertThat(maximal.getPayloadConfigPath()).isEqualTo("config/path");
assertThat(maximal.isProtectedVm()).isEqualTo(isProtectedVm());
assertThat(maximal.isEncryptedStorageEnabled()).isTrue();
@@ -370,12 +370,14 @@
assertThrows(NullPointerException.class, () -> new VirtualMachineConfig.Builder(null));
assertThrows(NullPointerException.class, () -> builder.setApkPath(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
- assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryPath(null));
+ assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryName(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
// Individual property checks.
assertThrows(
IllegalArgumentException.class, () -> builder.setApkPath("relative/path/to.apk"));
+ assertThrows(
+ IllegalArgumentException.class, () -> builder.setPayloadBinaryName("dir/file.so"));
assertThrows(IllegalArgumentException.class, () -> builder.setDebugLevel(-1));
assertThrows(IllegalArgumentException.class, () -> builder.setMemoryMib(0));
assertThrows(IllegalArgumentException.class, () -> builder.setNumCpus(0));
@@ -384,10 +386,10 @@
// Consistency checks enforced at build time.
Exception e;
e = assertThrows(IllegalStateException.class, () -> builder.build());
- assertThat(e).hasMessageThat().contains("setPayloadBinaryPath must be called");
+ assertThat(e).hasMessageThat().contains("setPayloadBinaryName must be called");
VirtualMachineConfig.Builder protectedNotSet =
- new VirtualMachineConfig.Builder(getContext()).setPayloadBinaryPath("binary/path");
+ new VirtualMachineConfig.Builder(getContext()).setPayloadBinaryName("binary.so");
e = assertThrows(IllegalStateException.class, () -> protectedNotSet.build());
assertThat(e).hasMessageThat().contains("setProtectedVm must be called");
}
@@ -398,7 +400,7 @@
int maxCpus = Runtime.getRuntime().availableProcessors();
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path").setApkPath("/apk/path");
+ newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
VirtualMachineConfig baseline = builder.build();
// A config must be compatible with itself
@@ -412,7 +414,7 @@
// Changes that must be incompatible, since they must change the VM identity.
assertConfigCompatible(baseline, builder.setDebugLevel(DEBUG_LEVEL_FULL)).isFalse();
- assertConfigCompatible(baseline, builder.setPayloadBinaryPath("different")).isFalse();
+ assertConfigCompatible(baseline, builder.setPayloadBinaryName("different")).isFalse();
int capabilities = getVirtualMachineManager().getCapabilities();
if ((capabilities & CAPABILITY_PROTECTED_VM) != 0
&& (capabilities & CAPABILITY_NON_PROTECTED_VM) != 0) {
@@ -434,19 +436,19 @@
@CddTest(requirements = {"9.17/C-1-1"})
public void vmUnitTests() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path");
+ newVmConfigBuilder().setPayloadBinaryName("binary.so");
VirtualMachineConfig config = builder.build();
VirtualMachine vm = forceCreateNewVirtualMachine("vm_name", config);
assertThat(vm.getName()).isEqualTo("vm_name");
- assertThat(vm.getConfig().getPayloadBinaryPath()).isEqualTo("binary/path");
+ assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
assertThat(vm.getConfig().getMemoryMib()).isEqualTo(0);
VirtualMachineConfig compatibleConfig = builder.setMemoryMib(42).build();
vm.setConfig(compatibleConfig);
assertThat(vm.getName()).isEqualTo("vm_name");
- assertThat(vm.getConfig().getPayloadBinaryPath()).isEqualTo("binary/path");
+ assertThat(vm.getConfig().getPayloadBinaryName()).isEqualTo("binary.so");
assertThat(vm.getConfig().getMemoryMib()).isEqualTo(42);
assertThat(getVirtualMachineManager().get("vm_name")).isSameInstanceAs(vm);
@@ -459,7 +461,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -507,7 +509,7 @@
final int userId = ctx.getUserId();
final VirtualMachineManager vmm = ctx.getSystemService(VirtualMachineManager.class);
VirtualMachineConfig config =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path").build();
+ newVmConfigBuilder().setPayloadBinaryName("binary.so").build();
try {
VirtualMachine vm = vmm.create("vm-name", config);
// TODO(b/261430346): what about non-primary user?
@@ -526,7 +528,7 @@
final int userId = ctx.getUserId();
final VirtualMachineManager vmm = ctx.getSystemService(VirtualMachineManager.class);
VirtualMachineConfig config =
- newVmConfigBuilder().setPayloadBinaryPath("binary/path").build();
+ newVmConfigBuilder().setPayloadBinaryName("binary.so").build();
try {
VirtualMachine vm = vmm.create("vm-name", config);
// TODO(b/261430346): what about non-primary user?
@@ -578,7 +580,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.build();
@@ -605,7 +607,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setApkPath(getContext().getPackageCodePath())
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
@@ -651,7 +653,7 @@
for (int memMib : new int[]{ 10, 20, 40 }) {
VirtualMachineConfig lowMemConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(memMib)
.setDebugLevel(DEBUG_LEVEL_NONE)
.build();
@@ -695,7 +697,7 @@
VirtualMachineConfig.Builder builder =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(fromLevel);
VirtualMachineConfig normalConfig = builder.build();
forceCreateNewVirtualMachine("test_vm", normalConfig);
@@ -865,7 +867,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
forceCreateNewVirtualMachine("test_vm", config);
@@ -912,7 +914,7 @@
private RandomAccessFile prepareInstanceImage(String vmName) throws Exception {
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -985,9 +987,9 @@
}
@Test
- public void bootFailsWhenBinaryPathIsInvalid() throws Exception {
+ public void bootFailsWhenBinaryNameIsInvalid() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("DoesNotExist.so");
+ newVmConfigBuilder().setPayloadBinaryName("DoesNotExist.so");
VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
forceCreateNewVirtualMachine("test_vm_invalid_binary_path", normalConfig);
@@ -1024,7 +1026,7 @@
@Test
public void bootFailsWhenBinaryIsMissingEntryFunction() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("MicrodroidEmptyNativeLib.so");
+ newVmConfigBuilder().setPayloadBinaryName("MicrodroidEmptyNativeLib.so");
VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_missing_entry", normalConfig);
@@ -1034,7 +1036,7 @@
@Test
public void bootFailsWhenBinaryTriesToLinkAgainstPrivateLibs() throws Exception {
VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryPath("MicrodroidPrivateLinkingNativeLib.so");
+ newVmConfigBuilder().setPayloadBinaryName("MicrodroidPrivateLinkingNativeLib.so");
VirtualMachineConfig normalConfig = builder.setDebugLevel(DEBUG_LEVEL_FULL).build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm_private_linking", normalConfig);
@@ -1044,9 +1046,7 @@
@Test
public void sameInstancesShareTheSameVmObject() throws Exception {
VirtualMachineConfig config =
- newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
- .build();
+ newVmConfigBuilder().setPayloadBinaryName("MicrodroidTestNativeLib.so").build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_vm", config);
VirtualMachine vm2 = getVirtualMachineManager().get("test_vm");
@@ -1108,7 +1108,7 @@
// Arrange
VirtualMachineConfig.Builder builder =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setDebugLevel(DEBUG_LEVEL_FULL);
if (encryptedStoreEnabled) builder = builder.setEncryptedStorageKib(4096);
VirtualMachineConfig config = builder.build();
@@ -1150,7 +1150,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setEncryptedStorageKib(4096)
.setDebugLevel(DEBUG_LEVEL_FULL)
@@ -1168,7 +1168,7 @@
final VirtualMachineConfig vmConfig =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setDebugLevel(DEBUG_LEVEL_FULL)
.build();
@@ -1187,7 +1187,7 @@
VirtualMachineConfig config =
newVmConfigBuilder()
- .setPayloadBinaryPath("MicrodroidTestNativeLib.so")
+ .setPayloadBinaryName("MicrodroidTestNativeLib.so")
.setMemoryMib(minMemoryRequired())
.setEncryptedStorageKib(4096)
.setDebugLevel(DEBUG_LEVEL_FULL)
@@ -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()
+ .setPayloadBinaryName("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/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
index ed3c512..55c2f5d 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachinePayloadConfig.aidl
@@ -18,8 +18,9 @@
parcelable VirtualMachinePayloadConfig {
/**
- * Path to the payload executable code in an APK. The code is in the form of a .so with a
- * defined entry point; inside the VM this file is loaded and the entry function invoked.
+ * Name of the payload executable file in the lib/<ABI> folder of an APK. The payload is in the
+ * form of a .so with a defined entry point; inside the VM this file is loaded and the entry
+ * function invoked.
*/
- @utf8InCpp String payloadPath;
+ @utf8InCpp String payloadBinaryName;
}
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 733d9c5..0859a76 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -841,7 +841,7 @@
load_vm_payload_config_from_file(&apk_file, config_path.as_str())
.with_context(|| format!("Couldn't read config from {}", config_path))?
}
- Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config),
+ Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
};
// For now, the only supported OS is Microdroid
@@ -887,13 +887,20 @@
Ok(serde_json::from_reader(config_file)?)
}
-fn create_vm_payload_config(payload_config: &VirtualMachinePayloadConfig) -> VmPayloadConfig {
+fn create_vm_payload_config(
+ payload_config: &VirtualMachinePayloadConfig,
+) -> Result<VmPayloadConfig> {
// There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
// parameters we've been given. Microdroid will do something equivalent inside the VM using the
// payload config that we send it via the metadata file.
- let task =
- Task { type_: TaskType::MicrodroidLauncher, command: payload_config.payloadPath.clone() };
- VmPayloadConfig {
+
+ let payload_binary_name = &payload_config.payloadBinaryName;
+ if payload_binary_name.contains('/') {
+ bail!("Payload binary name must not specify a path: {payload_binary_name}");
+ }
+
+ let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
+ Ok(VmPayloadConfig {
os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
task: Some(task),
apexes: vec![],
@@ -901,7 +908,7 @@
prefer_staged: false,
export_tombstones: false,
enable_authfs: false,
- }
+ })
}
/// Generates a unique filename to use for a composite disk image.
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index eb3e9eb..02e8f8e 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -194,7 +194,7 @@
) -> Result<ParcelFileDescriptor> {
let payload_metadata = match &app_config.payload {
Payload::PayloadConfig(payload_config) => PayloadMetadata::config(PayloadConfig {
- payload_binary_path: payload_config.payloadPath.clone(),
+ payload_binary_name: payload_config.payloadBinaryName.clone(),
..Default::default()
}),
Payload::ConfigPath(config_path) => {
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 002e505..9fa805e 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -51,9 +51,10 @@
#[clap(long)]
config_path: Option<String>,
- /// Path to VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
+ /// Name of VM payload binary within APK (e.g. MicrodroidTestNativeLib.so)
#[clap(long)]
- payload_path: Option<String>,
+ #[clap(alias = "payload_path")]
+ payload_binary_name: Option<String>,
/// Name of VM
#[clap(long)]
@@ -258,7 +259,7 @@
storage,
storage_size,
config_path,
- payload_path,
+ payload_binary_name,
daemonize,
console,
log,
@@ -277,7 +278,7 @@
storage.as_deref(),
storage_size,
config_path,
- payload_path,
+ payload_binary_name,
daemonize,
console.as_deref(),
log.as_deref(),
diff --git a/vm/src/run.rs b/vm/src/run.rs
index 6096913..b99328a 100644
--- a/vm/src/run.rs
+++ b/vm/src/run.rs
@@ -48,7 +48,7 @@
storage: Option<&Path>,
storage_size: Option<u64>,
config_path: Option<String>,
- payload_path: Option<String>,
+ payload_binary_name: Option<String>,
daemonize: bool,
console_path: Option<&Path>,
log_path: Option<&Path>,
@@ -117,14 +117,16 @@
let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
let payload = if let Some(config_path) = config_path {
- if payload_path.is_some() {
- bail!("Only one of --config-path or --payload-path can be defined")
+ if payload_binary_name.is_some() {
+ bail!("Only one of --config-path or --payload-binary-name can be defined")
}
Payload::ConfigPath(config_path)
- } else if let Some(payload_path) = payload_path {
- Payload::PayloadConfig(VirtualMachinePayloadConfig { payloadPath: payload_path })
+ } else if let Some(payload_binary_name) = payload_binary_name {
+ Payload::PayloadConfig(VirtualMachinePayloadConfig {
+ payloadBinaryName: payload_binary_name,
+ })
} else {
- bail!("Either --config-path or --payload-path must be defined")
+ bail!("Either --config-path or --payload-binary-name must be defined")
};
let payload_config_str = format!("{:?}!{:?}", apk, payload);
@@ -197,7 +199,7 @@
let instance_img = work_dir.join("instance.img");
println!("instance.img path: {}", instance_img.display());
- let payload_path = "MicrodroidEmptyPayloadJniLib.so";
+ let payload_binary_name = "MicrodroidEmptyPayloadJniLib.so";
let extra_sig = [];
command_run_app(
name,
@@ -208,7 +210,7 @@
storage,
storage_size,
/* config_path= */ None,
- Some(payload_path.to_owned()),
+ Some(payload_binary_name.to_owned()),
daemonize,
console_path,
log_path,
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..365d236 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)
}
@@ -456,30 +477,40 @@
use std::fs;
use std::fs::File;
use std::io::Write;
+ use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use zip::write::FileOptions;
+ #[derive(Default)]
+ struct Options {
+ noexec: bool,
+ uid: u32,
+ gid: u32,
+ }
+
#[cfg(not(target_os = "android"))]
- fn start_fuse(zip_path: &Path, mnt_path: &Path, noexec: bool) {
+ fn start_fuse(zip_path: &Path, mnt_path: &Path, opt: Options) {
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, opt.noexec, opt.uid, opt.gid).unwrap();
});
}
#[cfg(target_os = "android")]
- fn start_fuse(zip_path: &Path, mnt_path: &Path, noexec: bool) {
+ fn start_fuse(zip_path: &Path, mnt_path: &Path, opt: Options) {
// Note: for some unknown reason, running a thread to serve fuse doesn't work on Android.
// Explicitly spawn a zipfuse process instead.
// TODO(jiyong): fix this
- let noexec = if noexec { "--noexec" } else { "" };
+ let noexec = if opt.noexec { "--noexec" } else { "" };
assert!(std::process::Command::new("sh")
.arg("-c")
.arg(format!(
- "/data/local/tmp/zipfuse {} {} {}",
+ "/data/local/tmp/zipfuse {} -u {} -g {} {} {}",
noexec,
+ opt.uid,
+ opt.gid,
zip_path.display(),
mnt_path.display()
))
@@ -508,11 +539,11 @@
// Creates a zip file, adds some files to the zip file, mounts it using zipfuse, runs the check
// routine, and finally unmounts.
fn run_test(add: fn(&mut zip::ZipWriter<File>), check: fn(&std::path::Path)) {
- run_test_noexec(false, add, check);
+ run_test_with_options(Default::default(), add, check);
}
- fn run_test_noexec(
- noexec: bool,
+ fn run_test_with_options(
+ opt: Options,
add: fn(&mut zip::ZipWriter<File>),
check: fn(&std::path::Path),
) {
@@ -532,7 +563,7 @@
let mnt_path = test_dir.path().join("mnt");
assert!(fs::create_dir(&mnt_path).is_ok());
- start_fuse(&zip_path, &mnt_path, noexec);
+ start_fuse(&zip_path, &mnt_path, opt);
let mnt_path = test_dir.path().join("mnt");
// Give some time for the fuse to boot up
@@ -629,14 +660,37 @@
});
// Mounting with noexec results in permissions denial when running an executable.
- let noexec = true;
- run_test_noexec(noexec, add_executable, |root| {
+ let opt = Options { noexec: true, ..Default::default() };
+ run_test_with_options(opt, add_executable, |root| {
let res = std::process::Command::new(root.join("executable")).status();
assert!(matches!(res.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied));
});
}
#[test]
+ fn uid_gid() {
+ const UID: u32 = 100;
+ const GID: u32 = 200;
+ run_test_with_options(
+ Options { noexec: true, uid: UID, gid: GID },
+ |zip| {
+ zip.start_file("foo", FileOptions::default()).unwrap();
+ zip.write_all(b"0123456789").unwrap();
+ },
+ |root| {
+ let path = root.join("foo");
+
+ let metadata = fs::metadata(&path);
+ assert!(metadata.is_ok());
+ let metadata = metadata.unwrap();
+
+ assert_eq!(UID, metadata.uid());
+ assert_eq!(GID, metadata.gid());
+ },
+ );
+ }
+
+ #[test]
fn single_dir() {
run_test(
|zip| {
@@ -748,8 +802,8 @@
let mnt_path = test_dir.join("mnt");
assert!(fs::create_dir(&mnt_path).is_ok());
- let noexec = false;
- start_fuse(zip_path, &mnt_path, noexec);
+ let opt = Options { noexec: false, ..Default::default() };
+ start_fuse(zip_path, &mnt_path, opt);
// Give some time for the fuse to boot up
assert!(wait_for_mount(&mnt_path).is_ok());