Merge "authfs: use the new fsverity-utils git repo URL"
diff --git a/apkdmverity/src/main.rs b/apkdmverity/src/main.rs
index 50b6069..b9b88d4 100644
--- a/apkdmverity/src/main.rs
+++ b/apkdmverity/src/main.rs
@@ -69,7 +69,7 @@
optional; idsig file's root hash will be used if specified as \"none\"."
)
.action(ArgAction::Append)
- .value_names(&["apk_path", "idsig_path", "name", "root_hash"]),
+ .value_names(["apk_path", "idsig_path", "name", "root_hash"]),
)
.arg(
Arg::new("verbose")
diff --git a/avmd/src/main.rs b/avmd/src/main.rs
index 740e9aa..8d7cb57 100644
--- a/avmd/src/main.rs
+++ b/avmd/src/main.rs
@@ -128,21 +128,21 @@
.arg(
Arg::new("vbmeta")
.long("vbmeta")
- .value_names(&namespace_name_file)
+ .value_names(namespace_name_file)
.num_args(3)
.action(ArgAction::Append),
)
.arg(
Arg::new("apk")
.long("apk")
- .value_names(&namespace_name_file)
+ .value_names(namespace_name_file)
.num_args(3)
.action(ArgAction::Append),
)
.arg(
Arg::new("apex-payload")
.long("apex-payload")
- .value_names(&namespace_name_file)
+ .value_names(namespace_name_file)
.num_args(3)
.action(ArgAction::Append),
),
diff --git a/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java b/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java
index c25de71..b884b9e 100644
--- a/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java
+++ b/compos/benchmark/src/java/com/android/compos/benchmark/ComposBenchmark.java
@@ -17,6 +17,7 @@
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertTrue;
@@ -136,9 +137,7 @@
Long compileStartTime = System.nanoTime();
String output = executeCommand(command);
Long compileEndTime = System.nanoTime();
- Pattern pattern = Pattern.compile("All Ok");
- Matcher matcher = pattern.matcher(output);
- assertTrue(matcher.find());
+ assertThat(output).containsMatch("All Ok");
double elapsedSec = (compileEndTime - compileStartTime) / NANOS_IN_SEC;
Log.i(TAG, "Compile time in guest took " + elapsedSec + "s");
getMetricsRunnable.stop();
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index 888485b..2f54534 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -63,7 +63,7 @@
fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
ensure!(
- std::fs::metadata(&blkdevice)
+ std::fs::metadata(blkdevice)
.context(format!("Failed to get metadata of {:?}", blkdevice))?
.file_type()
.is_block_device(),
diff --git a/javalib/32/public/api/android.system.virtualmachine-removed.txt b/javalib/32/public/api/android.system.virtualmachine-removed.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/public/api/android.system.virtualmachine-removed.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/32/public/api/android.system.virtualmachine.txt b/javalib/32/public/api/android.system.virtualmachine.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/public/api/android.system.virtualmachine.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/32/system/api/android.system.virtualmachine-removed.txt b/javalib/32/system/api/android.system.virtualmachine-removed.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/system/api/android.system.virtualmachine-removed.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/32/system/api/android.system.virtualmachine.txt b/javalib/32/system/api/android.system.virtualmachine.txt
deleted file mode 100644
index d802177..0000000
--- a/javalib/32/system/api/android.system.virtualmachine.txt
+++ /dev/null
@@ -1 +0,0 @@
-// Signature format: 2.0
diff --git a/javalib/Android.bp b/javalib/Android.bp
index 118b648..a124af7 100644
--- a/javalib/Android.bp
+++ b/javalib/Android.bp
@@ -52,11 +52,6 @@
],
}
-prebuilt_apis {
- name: "android-virtualization-framework-sdk",
- api_dirs: ["32"],
-}
-
java_api_contribution {
name: "framework-virtualization-public-stubs",
api_surface: "public",
@@ -65,3 +60,30 @@
"//build/orchestrator/apis",
],
}
+
+java_api_contribution {
+ name: "framework-virtualization-system-stubs",
+ api_surface: "system",
+ api_file: "api/system-current.txt",
+ visibility: [
+ "//build/orchestrator/apis",
+ ],
+}
+
+java_api_contribution {
+ name: "framework-virtualization-test-stubs",
+ api_surface: "test",
+ api_file: "api/test-current.txt",
+ visibility: [
+ "//build/orchestrator/apis",
+ ],
+}
+
+java_api_contribution {
+ name: "framework-virtualization-module-lib-stubs",
+ api_surface: "module-lib",
+ api_file: "api/module-lib-current.txt",
+ visibility: [
+ "//build/orchestrator/apis",
+ ],
+}
diff --git a/javalib/api/system-current.txt b/javalib/api/system-current.txt
index 1977321..fe9943d 100644
--- a/javalib/api/system-current.txt
+++ b/javalib/api/system-current.txt
@@ -56,7 +56,7 @@
}
public final class VirtualMachineConfig {
- method @NonNull public String getApkPath();
+ method @Nullable public String getApkPath();
method @NonNull public int getDebugLevel();
method @IntRange(from=0) public long getEncryptedStorageKib();
method @IntRange(from=0) public int getMemoryMib();
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachine.java b/javalib/src/android/system/virtualmachine/VirtualMachine.java
index 1f0c8ea..7c7f4b5 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -40,6 +40,7 @@
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_SHUTDOWN;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_START_FAILED;
import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_UNKNOWN;
+import static android.system.virtualmachine.VirtualMachineCallback.STOP_REASON_VIRTUALIZATION_SERVICE_DIED;
import static java.util.Objects.requireNonNull;
@@ -768,7 +769,7 @@
}
} catch (IOException e) {
// If the file already exists, exception is not thrown.
- throw new VirtualMachineException("failed to create idsig file", e);
+ throw new VirtualMachineException("Failed to create APK signature file", e);
}
IVirtualizationService service = mVirtualizationService.connect();
@@ -778,95 +779,25 @@
createVmPipes();
}
- VirtualMachineAppConfig appConfig = getConfig().toVsConfig();
+ VirtualMachineAppConfig appConfig =
+ getConfig().toVsConfig(mContext.getPackageManager());
appConfig.name = mName;
- // Fill the idsig file by hashing the apk
- service.createOrUpdateIdsigFile(
- appConfig.apk, ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_WRITE));
-
- for (ExtraApkSpec extraApk : mExtraApks) {
- service.createOrUpdateIdsigFile(
- ParcelFileDescriptor.open(extraApk.apk, MODE_READ_ONLY),
- ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_WRITE));
+ try {
+ createIdSigs(service, appConfig);
+ } catch (FileNotFoundException e) {
+ throw new VirtualMachineException("Failed to generate APK signature", e);
}
- // Re-open idsig file in read-only mode
- appConfig.idsig = ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_ONLY);
- appConfig.instanceImage =
- ParcelFileDescriptor.open(mInstanceFilePath, MODE_READ_WRITE);
- if (mEncryptedStoreFilePath != null) {
- appConfig.encryptedStorageImage =
- ParcelFileDescriptor.open(mEncryptedStoreFilePath, MODE_READ_WRITE);
- }
- List<ParcelFileDescriptor> extraIdsigs = new ArrayList<>();
- for (ExtraApkSpec extraApk : mExtraApks) {
- extraIdsigs.add(ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_ONLY));
- }
- appConfig.extraIdsigs = extraIdsigs;
-
android.system.virtualizationservice.VirtualMachineConfig vmConfigParcel =
android.system.virtualizationservice.VirtualMachineConfig.appConfig(
appConfig);
- // The VM should only be observed to die once
- AtomicBoolean onDiedCalled = new AtomicBoolean(false);
-
- IBinder.DeathRecipient deathRecipient = () -> {
- if (onDiedCalled.compareAndSet(false, true)) {
- executeCallback((cb) -> cb.onStopped(VirtualMachine.this,
- VirtualMachineCallback.STOP_REASON_VIRTUALIZATION_SERVICE_DIED));
- }
- };
-
mVirtualMachine = service.createVm(vmConfigParcel, mConsoleWriter, mLogWriter);
- mVirtualMachine.registerCallback(
- new IVirtualMachineCallback.Stub() {
- @Override
- public void onPayloadStarted(int cid) {
- executeCallback((cb) -> cb.onPayloadStarted(VirtualMachine.this));
- }
-
- @Override
- public void onPayloadReady(int cid) {
- executeCallback((cb) -> cb.onPayloadReady(VirtualMachine.this));
- }
-
- @Override
- public void onPayloadFinished(int cid, int exitCode) {
- executeCallback(
- (cb) ->
- cb.onPayloadFinished(
- VirtualMachine.this, exitCode));
- }
-
- @Override
- public void onError(int cid, int errorCode, String message) {
- int translatedError = getTranslatedError(errorCode);
- executeCallback(
- (cb) ->
- cb.onError(
- VirtualMachine.this,
- translatedError,
- message));
- }
-
- @Override
- public void onDied(int cid, int reason) {
- service.asBinder().unlinkToDeath(deathRecipient, 0);
- int translatedReason = getTranslatedReason(reason);
- if (onDiedCalled.compareAndSet(false, true)) {
- executeCallback(
- (cb) ->
- cb.onStopped(
- VirtualMachine.this, translatedReason));
- }
- }
- });
+ mVirtualMachine.registerCallback(new CallbackTranslator(service));
mContext.registerComponentCallbacks(mMemoryManagementCallbacks);
- service.asBinder().linkToDeath(deathRecipient, 0);
mVirtualMachine.start();
- } catch (IOException | IllegalStateException | ServiceSpecificException e) {
+ } catch (IllegalStateException | ServiceSpecificException e) {
throw new VirtualMachineException(e);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
@@ -874,6 +805,32 @@
}
}
+ private void createIdSigs(IVirtualizationService service, VirtualMachineAppConfig appConfig)
+ throws RemoteException, FileNotFoundException {
+ // Fill the idsig file by hashing the apk
+ service.createOrUpdateIdsigFile(
+ appConfig.apk, ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_WRITE));
+
+ for (ExtraApkSpec extraApk : mExtraApks) {
+ service.createOrUpdateIdsigFile(
+ ParcelFileDescriptor.open(extraApk.apk, MODE_READ_ONLY),
+ ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_WRITE));
+ }
+
+ // Re-open idsig files in read-only mode
+ appConfig.idsig = ParcelFileDescriptor.open(mIdsigFilePath, MODE_READ_ONLY);
+ appConfig.instanceImage = ParcelFileDescriptor.open(mInstanceFilePath, MODE_READ_WRITE);
+ if (mEncryptedStoreFilePath != null) {
+ appConfig.encryptedStorageImage =
+ ParcelFileDescriptor.open(mEncryptedStoreFilePath, MODE_READ_WRITE);
+ }
+ List<ParcelFileDescriptor> extraIdsigs = new ArrayList<>();
+ for (ExtraApkSpec extraApk : mExtraApks) {
+ extraIdsigs.add(ParcelFileDescriptor.open(extraApk.idsig, MODE_READ_ONLY));
+ }
+ appConfig.extraIdsigs = extraIdsigs;
+ }
+
@GuardedBy("mLock")
private void createVmPipes() throws VirtualMachineException {
try {
@@ -1187,60 +1144,6 @@
}
}
- @VirtualMachineCallback.ErrorCode
- private int getTranslatedError(int reason) {
- switch (reason) {
- case ErrorCode.PAYLOAD_VERIFICATION_FAILED:
- return ERROR_PAYLOAD_VERIFICATION_FAILED;
- case ErrorCode.PAYLOAD_CHANGED:
- return ERROR_PAYLOAD_CHANGED;
- case ErrorCode.PAYLOAD_CONFIG_INVALID:
- return ERROR_PAYLOAD_INVALID_CONFIG;
- default:
- return ERROR_UNKNOWN;
- }
- }
-
- @VirtualMachineCallback.StopReason
- private int getTranslatedReason(int reason) {
- switch (reason) {
- case DeathReason.INFRASTRUCTURE_ERROR:
- return STOP_REASON_INFRASTRUCTURE_ERROR;
- case DeathReason.KILLED:
- return STOP_REASON_KILLED;
- case DeathReason.SHUTDOWN:
- return STOP_REASON_SHUTDOWN;
- case DeathReason.START_FAILED:
- return STOP_REASON_START_FAILED;
- case DeathReason.REBOOT:
- return STOP_REASON_REBOOT;
- case DeathReason.CRASH:
- return STOP_REASON_CRASH;
- case DeathReason.PVM_FIRMWARE_PUBLIC_KEY_MISMATCH:
- return STOP_REASON_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH;
- case DeathReason.PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED:
- return STOP_REASON_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED;
- case DeathReason.BOOTLOADER_PUBLIC_KEY_MISMATCH:
- return STOP_REASON_BOOTLOADER_PUBLIC_KEY_MISMATCH;
- case DeathReason.BOOTLOADER_INSTANCE_IMAGE_CHANGED:
- return STOP_REASON_BOOTLOADER_INSTANCE_IMAGE_CHANGED;
- case DeathReason.MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE:
- return STOP_REASON_MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE;
- case DeathReason.MICRODROID_PAYLOAD_HAS_CHANGED:
- return STOP_REASON_MICRODROID_PAYLOAD_HAS_CHANGED;
- case DeathReason.MICRODROID_PAYLOAD_VERIFICATION_FAILED:
- return STOP_REASON_MICRODROID_PAYLOAD_VERIFICATION_FAILED;
- case DeathReason.MICRODROID_INVALID_PAYLOAD_CONFIG:
- return STOP_REASON_MICRODROID_INVALID_PAYLOAD_CONFIG;
- case DeathReason.MICRODROID_UNKNOWN_RUNTIME_ERROR:
- return STOP_REASON_MICRODROID_UNKNOWN_RUNTIME_ERROR;
- case DeathReason.HANGUP:
- return STOP_REASON_HANGUP;
- default:
- return STOP_REASON_UNKNOWN;
- }
- }
-
@Override
public String toString() {
VirtualMachineConfig config = getConfig();
@@ -1354,4 +1257,107 @@
throw new VirtualMachineException("failed to transfer encryptedstore image", e);
}
}
+
+ /** Map the raw AIDL (& binder) callbacks to what the client expects. */
+ private class CallbackTranslator extends IVirtualMachineCallback.Stub {
+ private final IVirtualizationService mService;
+ private final DeathRecipient mDeathRecipient;
+
+ // The VM should only be observed to die once
+ private final AtomicBoolean mOnDiedCalled = new AtomicBoolean(false);
+
+ public CallbackTranslator(IVirtualizationService service) throws RemoteException {
+ this.mService = service;
+ this.mDeathRecipient = () -> reportStopped(STOP_REASON_VIRTUALIZATION_SERVICE_DIED);
+ service.asBinder().linkToDeath(mDeathRecipient, 0);
+ }
+
+ @Override
+ public void onPayloadStarted(int cid) {
+ executeCallback((cb) -> cb.onPayloadStarted(VirtualMachine.this));
+ }
+
+ @Override
+ public void onPayloadReady(int cid) {
+ executeCallback((cb) -> cb.onPayloadReady(VirtualMachine.this));
+ }
+
+ @Override
+ public void onPayloadFinished(int cid, int exitCode) {
+ executeCallback((cb) -> cb.onPayloadFinished(VirtualMachine.this, exitCode));
+ }
+
+ @Override
+ public void onError(int cid, int errorCode, String message) {
+ int translatedError = getTranslatedError(errorCode);
+ executeCallback((cb) -> cb.onError(VirtualMachine.this, translatedError, message));
+ }
+
+ @Override
+ public void onDied(int cid, int reason) {
+ int translatedReason = getTranslatedReason(reason);
+ reportStopped(translatedReason);
+ mService.asBinder().unlinkToDeath(mDeathRecipient, 0);
+ }
+
+ private void reportStopped(@VirtualMachineCallback.StopReason int reason) {
+ if (mOnDiedCalled.compareAndSet(false, true)) {
+ executeCallback((cb) -> cb.onStopped(VirtualMachine.this, reason));
+ }
+ }
+
+ @VirtualMachineCallback.ErrorCode
+ private int getTranslatedError(int reason) {
+ switch (reason) {
+ case ErrorCode.PAYLOAD_VERIFICATION_FAILED:
+ return ERROR_PAYLOAD_VERIFICATION_FAILED;
+ case ErrorCode.PAYLOAD_CHANGED:
+ return ERROR_PAYLOAD_CHANGED;
+ case ErrorCode.PAYLOAD_CONFIG_INVALID:
+ return ERROR_PAYLOAD_INVALID_CONFIG;
+ default:
+ return ERROR_UNKNOWN;
+ }
+ }
+
+ @VirtualMachineCallback.StopReason
+ private int getTranslatedReason(int reason) {
+ switch (reason) {
+ case DeathReason.INFRASTRUCTURE_ERROR:
+ return STOP_REASON_INFRASTRUCTURE_ERROR;
+ case DeathReason.KILLED:
+ return STOP_REASON_KILLED;
+ case DeathReason.SHUTDOWN:
+ return STOP_REASON_SHUTDOWN;
+ case DeathReason.START_FAILED:
+ return STOP_REASON_START_FAILED;
+ case DeathReason.REBOOT:
+ return STOP_REASON_REBOOT;
+ case DeathReason.CRASH:
+ return STOP_REASON_CRASH;
+ case DeathReason.PVM_FIRMWARE_PUBLIC_KEY_MISMATCH:
+ return STOP_REASON_PVM_FIRMWARE_PUBLIC_KEY_MISMATCH;
+ case DeathReason.PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED:
+ return STOP_REASON_PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED;
+ case DeathReason.BOOTLOADER_PUBLIC_KEY_MISMATCH:
+ return STOP_REASON_BOOTLOADER_PUBLIC_KEY_MISMATCH;
+ case DeathReason.BOOTLOADER_INSTANCE_IMAGE_CHANGED:
+ return STOP_REASON_BOOTLOADER_INSTANCE_IMAGE_CHANGED;
+ case DeathReason.MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE:
+ return STOP_REASON_MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE;
+ case DeathReason.MICRODROID_PAYLOAD_HAS_CHANGED:
+ return STOP_REASON_MICRODROID_PAYLOAD_HAS_CHANGED;
+ case DeathReason.MICRODROID_PAYLOAD_VERIFICATION_FAILED:
+ return STOP_REASON_MICRODROID_PAYLOAD_VERIFICATION_FAILED;
+ case DeathReason.MICRODROID_INVALID_PAYLOAD_CONFIG:
+ return STOP_REASON_MICRODROID_INVALID_PAYLOAD_CONFIG;
+ case DeathReason.MICRODROID_UNKNOWN_RUNTIME_ERROR:
+ return STOP_REASON_MICRODROID_UNKNOWN_RUNTIME_ERROR;
+ case DeathReason.HANGUP:
+ return STOP_REASON_HANGUP;
+ default:
+ return STOP_REASON_UNKNOWN;
+ }
+ }
+ }
}
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index f5c3cd2..b358f9e 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -29,6 +29,8 @@
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
import android.os.ParcelFileDescriptor;
import android.os.PersistableBundle;
import android.sysprop.HypervisorProperties;
@@ -58,8 +60,9 @@
private static final String[] EMPTY_STRING_ARRAY = {};
// These define the schema of the config file persisted on disk.
- private static final int VERSION = 3;
+ private static final int VERSION = 4;
private static final String KEY_VERSION = "version";
+ private static final String KEY_PACKAGENAME = "packageName";
private static final String KEY_APKPATH = "apkPath";
private static final String KEY_PAYLOADCONFIGPATH = "payloadConfigPath";
private static final String KEY_PAYLOADBINARYNAME = "payloadBinaryPath";
@@ -94,8 +97,11 @@
*/
@SystemApi public static final int DEBUG_LEVEL_FULL = 1;
+ /** Name of a package whose primary APK contains the VM payload. */
+ @Nullable private final String mPackageName;
+
/** Absolute path to the APK file containing the VM payload. */
- @NonNull private final String mApkPath;
+ @Nullable private final String mApkPath;
@DebugLevel private final int mDebugLevel;
@@ -129,7 +135,8 @@
private final boolean mVmOutputCaptured;
private VirtualMachineConfig(
- @NonNull String apkPath,
+ @Nullable String packageName,
+ @Nullable String apkPath,
@Nullable String payloadConfigPath,
@Nullable String payloadBinaryName,
@DebugLevel int debugLevel,
@@ -139,6 +146,7 @@
long encryptedStorageKib,
boolean vmOutputCaptured) {
// This is only called from Builder.build(); the builder handles parameter validation.
+ mPackageName = packageName;
mApkPath = apkPath;
mPayloadConfigPath = payloadConfigPath;
mPayloadBinaryName = payloadBinaryName;
@@ -191,8 +199,13 @@
"Version " + version + " too high; current is " + VERSION);
}
- Builder builder = new Builder();
- builder.setApkPath(b.getString(KEY_APKPATH));
+ String packageName = b.getString(KEY_PACKAGENAME);
+ Builder builder = new Builder(packageName);
+
+ String apkPath = b.getString(KEY_APKPATH);
+ if (apkPath != null) {
+ builder.setApkPath(apkPath);
+ }
String payloadConfigPath = b.getString(KEY_PAYLOADCONFIGPATH);
if (payloadConfigPath == null) {
@@ -234,7 +247,12 @@
private void serializeOutputStream(@NonNull OutputStream output) throws IOException {
PersistableBundle b = new PersistableBundle();
b.putInt(KEY_VERSION, VERSION);
- b.putString(KEY_APKPATH, mApkPath);
+ if (mPackageName != null) {
+ b.putString(KEY_PACKAGENAME, mPackageName);
+ }
+ if (mApkPath != null) {
+ b.putString(KEY_APKPATH, mApkPath);
+ }
b.putString(KEY_PAYLOADCONFIGPATH, mPayloadConfigPath);
b.putString(KEY_PAYLOADBINARYNAME, mPayloadBinaryName);
b.putInt(KEY_DEBUGLEVEL, mDebugLevel);
@@ -252,12 +270,13 @@
/**
* Returns the absolute path of the APK which should contain the binary payload that will
- * execute within the VM.
+ * execute within the VM. Returns null if no specific path has been set, so the primary APK will
+ * be used.
*
* @hide
*/
@SystemApi
- @NonNull
+ @Nullable
public String getApkPath() {
return mApkPath;
}
@@ -383,7 +402,8 @@
&& this.mVmOutputCaptured == other.mVmOutputCaptured
&& Objects.equals(this.mPayloadConfigPath, other.mPayloadConfigPath)
&& Objects.equals(this.mPayloadBinaryName, other.mPayloadBinaryName)
- && this.mApkPath.equals(other.mApkPath);
+ && Objects.equals(this.mPackageName, other.mPackageName)
+ && Objects.equals(this.mApkPath, other.mApkPath);
}
/**
@@ -393,9 +413,28 @@
* app-owned files and that could be abused to run a VM with software that the calling
* application doesn't own.
*/
- VirtualMachineAppConfig toVsConfig() throws FileNotFoundException {
+ VirtualMachineAppConfig toVsConfig(@NonNull PackageManager packageManager)
+ throws VirtualMachineException {
VirtualMachineAppConfig vsConfig = new VirtualMachineAppConfig();
- vsConfig.apk = ParcelFileDescriptor.open(new File(mApkPath), MODE_READ_ONLY);
+
+ String apkPath = mApkPath;
+ if (apkPath == null) {
+ try {
+ ApplicationInfo appInfo =
+ packageManager.getApplicationInfo(
+ mPackageName, PackageManager.ApplicationInfoFlags.of(0));
+ // This really is the path to the APK, not a directory.
+ apkPath = appInfo.sourceDir;
+ } catch (PackageManager.NameNotFoundException e) {
+ throw new VirtualMachineException("Package not found", e);
+ }
+ }
+
+ try {
+ vsConfig.apk = ParcelFileDescriptor.open(new File(apkPath), MODE_READ_ONLY);
+ } catch (FileNotFoundException e) {
+ throw new VirtualMachineException("Failed to open APK", e);
+ }
if (mPayloadBinaryName != null) {
VirtualMachinePayloadConfig payloadConfig = new VirtualMachinePayloadConfig();
payloadConfig.payloadBinaryName = mPayloadBinaryName;
@@ -428,7 +467,7 @@
*/
@SystemApi
public static final class Builder {
- @Nullable private final Context mContext;
+ @Nullable private final String mPackageName;
@Nullable private String mApkPath;
@Nullable private String mPayloadConfigPath;
@Nullable private String mPayloadBinaryName;
@@ -447,15 +486,15 @@
*/
@SystemApi
public Builder(@NonNull Context context) {
- mContext = requireNonNull(context, "context must not be null");
+ mPackageName = requireNonNull(context, "context must not be null").getPackageName();
}
/**
- * Creates a builder with no associated context; {@link #setApkPath} must be called to
- * specify which APK contains the payload.
+ * Creates a builder for a specific package. If packageName is null, {@link #setApkPath}
+ * must be called to specify the APK containing the payload.
*/
- private Builder() {
- mContext = null;
+ private Builder(@Nullable String packageName) {
+ mPackageName = packageName;
}
/**
@@ -466,14 +505,16 @@
@SystemApi
@NonNull
public VirtualMachineConfig build() {
- String apkPath;
- if (mApkPath == null) {
- if (mContext == null) {
- throw new IllegalStateException("apkPath must be specified");
- }
- apkPath = mContext.getPackageCodePath();
- } else {
+ String apkPath = null;
+ String packageName = null;
+
+ if (mApkPath != null) {
apkPath = mApkPath;
+ } else if (mPackageName != null) {
+ packageName = mPackageName;
+ } else {
+ // This should never happen, unless we're deserializing a bad config
+ throw new IllegalStateException("apkPath or packageName must be specified");
}
if (mPayloadBinaryName == null) {
@@ -496,6 +537,7 @@
}
return new VirtualMachineConfig(
+ packageName,
apkPath,
mPayloadConfigPath,
mPayloadBinaryName,
diff --git a/libs/fdtpci/src/lib.rs b/libs/fdtpci/src/lib.rs
index 1ddda9f..e32e16d 100644
--- a/libs/fdtpci/src/lib.rs
+++ b/libs/fdtpci/src/lib.rs
@@ -91,7 +91,7 @@
}
/// Information about the PCI bus parsed from the device tree.
-#[derive(Debug)]
+#[derive(Clone, Debug)]
pub struct PciInfo {
/// The MMIO range used by the memory-mapped PCI CAM.
pub cam_range: Range<usize>,
diff --git a/libs/libfdt/src/lib.rs b/libs/libfdt/src/lib.rs
index 7c72fab..8fd1879 100644
--- a/libs/libfdt/src/lib.rs
+++ b/libs/libfdt/src/lib.rs
@@ -16,7 +16,6 @@
//! to a bare-metal environment.
#![no_std]
-#![feature(let_else)] // Stabilized in 1.65.0
mod iterators;
@@ -508,6 +507,19 @@
fdt_err_expect_zero(ret)
}
+ /// Applies a DT overlay on the base DT.
+ ///
+ /// # Safety
+ ///
+ /// On failure, the library corrupts the DT and overlay so both must be discarded.
+ pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
+ fdt_err_expect_zero(libfdt_bindgen::fdt_overlay_apply(
+ self.as_mut_ptr(),
+ overlay.as_mut_ptr(),
+ ))?;
+ Ok(self)
+ }
+
/// Return an iterator of memory banks specified the "/memory" node.
///
/// NOTE: This does not support individual "/memory@XXXX" banks.
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index f5e214e..21f84a5 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -18,6 +18,7 @@
"libfdtpci",
"liblibfdt",
"liblog_rust_nostd",
+ "libonce_cell_nostd",
"libpvmfw_avb_nostd",
"libpvmfw_embedded_key",
"libtinyvec_nostd",
diff --git a/pvmfw/README.md b/pvmfw/README.md
index e5ba88b..1e4b605 100644
--- a/pvmfw/README.md
+++ b/pvmfw/README.md
@@ -1,12 +1,107 @@
# Protected Virtual Machine Firmware
-## Configuration Data Format
+In the context of the [Android Virtualization Framework][AVF], a hypervisor
+(_e.g._ [pKVM]) enforces full memory isolation between its virtual machines
+(VMs) and the host. As a result, the host is only allowed to access memory that
+has been explicitly shared back by a VM. Such _protected VMs_ (“pVMs”) are
+therefore able to manipulate secrets without being at risk of an attacker
+stealing them by compromising the Android host.
-pvmfw will expect a [header] to have been appended to its loaded binary image
-at the next 4KiB boundary. It describes the configuration data entries that
-pvmfw will use and, being loaded by the pvmfw loader, is necessarily trusted.
+As pVMs are started dynamically by a _virtual machine manager_ (“VMM”) running
+as a host process and as pVMs must not trust the host (see [_Why
+AVF?_][why-avf]), the virtual machine it configures can't be trusted either.
+Furthermore, even though the isolation mentioned above allows pVMs to protect
+their secrets from the host, it does not help with provisioning them during
+boot. In particular, the threat model would prohibit the host from ever having
+access to those secrets, preventing the VMM from passing them to the pVM.
-The layout of the configuration data is as follows:
+To address these concerns the hypervisor securely loads the pVM firmware
+(“pvmfw”) in the pVM from a protected memory region (this prevents the host or
+any pVM from tampering with it), setting it as the entry point of the virtual
+machine. As a result, pvmfw becomes the very first code that gets executed in
+the pVM, allowing it to validate the environment and abort the boot sequence if
+necessary. This process takes place whenever the VMM places a VM in protected
+mode and can’t be prevented by the host.
+
+Given the threat model, pvmfw is not allowed to trust the devices or device
+layout provided by the virtual platform it is running on as those are configured
+by the VMM. Instead, it performs all the necessary checks to ensure that the pVM
+was set up as expected. For functional purposes, the interface with the
+hypervisor, although trusted, is also validated.
+
+Once it has been determined that the platform can be trusted, pvmfw derives
+unique secrets for the guest through the [_Boot Certificate Chain_][BCC]
+("BCC", see [Open Profile for DICE][open-dice]) that can be used to prove the
+identity of the pVM to local and remote actors. If any operation or check fails,
+or in case of a missing prerequisite, pvmfw will abort the boot process of the
+pVM, effectively preventing non-compliant pVMs and/or guests from running.
+Otherwise, it hands over the pVM to the guest kernel by jumping to its first
+instruction, similarly to a bootloader.
+
+pvmfw currently only supports AArch64.
+
+[AVF]: https://source.android.com/docs/core/virtualization
+[why-avf]: https://source.android.com/docs/core/virtualization/whyavf
+[BCC]: https://pigweed.googlesource.com/open-dice/+/master/src/android/README.md
+[pKVM]: https://source.android.com/docs/core/virtualization/architecture#hypervisor
+[open-dice]: https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/specification.md
+
+## Integration
+
+### pvmfw Loading
+
+When running pKVM, the physical memory from which the hypervisor loads pvmfw
+into guest address space is not initially populated by the hypervisor itself.
+Instead, it receives a pre-loaded memory region from a trusted pvmfw loader and
+only then becomes responsible for protecting it. As a result, the hypervisor is
+kept generic (beyond AVF) and small as it is not expected (nor necessary) for it
+to know how to interpret or obtain the content of that region.
+
+#### Android Bootloader (ABL) Support
+
+Starting in Android T, the `PRODUCT_BUILD_PVMFW_IMAGE` build variable controls
+the generation of `pvmfw.img`, a new [ABL partition][ABL-part] containing the
+pvmfw binary and following the internal format of the [`boot`][boot-img]
+partition, intended to be verified and loaded by ABL on AVF-compatible devices.
+
+To support pKVM, ABL is expected to describe the region using a reserved memory
+device tree node where both address and size have been properly aligned to the
+page size used by the hypervisor. For example, the following node describes a
+region of size `0x40000` at address `0x80000000`:
+```
+reserved-memory {
+ ...
+ pkvm_guest_firmware {
+ compatible = "linux,pkvm-guest-firmware-memory";
+ reg = <0x0 0x80000000 0x40000>;
+ no-map;
+ }
+}
+```
+
+[ABL-part]: https://source.android.com/docs/core/architecture/bootloader/partitions
+[boot-img]: https://source.android.com/docs/core/architecture/bootloader/boot-image-header
+
+### Configuration Data
+
+As part of the process of loading pvmfw, the loader (typically the Android
+Bootloader, "ABL") is expected to pass device-specific pvmfw configuration data
+by appending it to the pvmfw binary and including it in the region passed to the
+hypervisor. As a result, the hypervisor will give the same protection to this
+data as it does to pvmfw and will transparently load it in guest memory, making
+it available to pvmfw at runtime. This enables pvmfw to be kept device-agnostic,
+simplifying its adoption and distribution as a centralized signed binary, while
+also being able to support device-specific details.
+
+The configuration data will be read by pvmfw at the next 4KiB boundary from the
+end of its loaded binary. Even if the pvmfw is position-independent, it will be
+expected for it to also have been loaded at a 4-KiB boundary. As a result, the
+location of the configuration data is implicitly passed to pvmfw and known to it
+at build time.
+
+#### Configuration Data Format
+
+The configuration data is described using the following [header]:
```
+===============================+
@@ -64,9 +159,64 @@
The header format itself is agnostic of the internal format of the individual
blos it refers to. In version 1.0, it describes two blobs:
-- entry 0 must point to a valid [BCC Handover]
+- entry 0 must point to a valid BCC Handover (see below)
- entry 1 may point to a [DTBO] to be applied to the pVM device tree
[header]: src/config.rs
-[BCC Handover]: https://pigweed.googlesource.com/open-dice/+/825e3beb6c6efcd8c35506d818c18d1e73b9834a/src/android/bcc.c#260
[DTBO]: https://android.googlesource.com/platform/external/dtc/+/refs/heads/master/Documentation/dt-object-internal.txt
+
+#### Virtual Platform Boot Certificate Chain Handover
+
+The format of the BCC entry mentioned above, compatible with the
+[`BccHandover`][BccHandover] defined by the Open Profile for DICE reference
+implementation, is described by the following [CDDL][CDDL]:
+```
+PvmfwBccHandover = {
+ 1 : bstr .size 32, ; CDI_Attest
+ 2 : bstr .size 32, ; CDI_Seal
+ 3 : Bcc, ; Certificate chain
+}
+```
+
+and contains the _Compound Device Identifiers_ ("CDIs"), used to derive the
+next-stage secret, and a certificate chain, intended for pVM attestation. Note
+that it differs from the `BccHandover` defined by the specification in that its
+`Bcc` field is mandatory (while optional in the original).
+
+The handover expected by pvmfw can be generated as follows:
+
+- by passing a `BccHandover` received from a previous boot stage (_e.g._ Trusted
+ Firmware, ROM bootloader, ...) to
+ [`BccHandoverMainFlow`][BccHandoverMainFlow];
+
+- by generating a `BccHandover` (as an example, see [Trusty][Trusty-BCC]) with
+ both CDIs set to an arbitrary constant value and no `Bcc`, and pass it to
+ `BccHandoverMainFlow`, which will both derive the pvmfw CDIs and start a
+ valid certificate chain, making the pvmfw loader the root of the BCC.
+
+The recommended DICE inputs at this stage are:
+
+- **Code**: hash of the pvmfw image, hypervisor (`boot.img`), and other target
+ code relevant to the secure execution of pvmfw (_e.g._ `vendor_boot.img`)
+- **Configuration Data**: any extra input relevant to pvmfw security
+- **Authority Data**: must cover all the public keys used to sign and verify the
+ code contributing to the **Code** input
+- **Mode Decision**: Set according to the [specification][dice-mode]. In
+ particular, should only be `Normal` if secure boot is being properly enforced
+ (_e.g._ locked device in [Android Verified Boot][AVB])
+- **Hidden Inputs**: Factory Reset Secret (FRS, stored in a tamper evident
+ storage and changes during every factory reset) or similar that changes as
+ part of the device lifecycle (_e.g._ reset)
+
+The resulting `BccHandover` is then used by pvmfw in a similar way to derive
+another [DICE layer][Layering], passed to the guest through a `/reserved-memory`
+device tree node marked as [`compatible=”google,open-dice”`][dice-dt].
+
+[AVB]: https://source.android.com/docs/security/features/verifiedboot/boot-flow
+[BccHandover]: https://pigweed.googlesource.com/open-dice/+/825e3beb6c/src/android/bcc.c#260
+[BccHandoverMainFlow]: https://pigweed.googlesource.com/open-dice/+/825e3beb6c/src/android/bcc.c#199
+[CDDL]: https://datatracker.ietf.org/doc/rfc8610
+[dice-mode]: https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/specification.md#Mode-Value-Details
+[dice-dt]: https://www.kernel.org/doc/Documentation/devicetree/bindings/reserved-memory/google%2Copen-dice.yaml
+[Layering]: https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/specification.md#layering-details
+[Trusty-BCC]: https://android.googlesource.com/trusty/lib/+/1696be0a8f3a7103/lib/hwbcc/common/swbcc.c#554
diff --git a/pvmfw/avb/fuzz/Android.bp b/pvmfw/avb/fuzz/Android.bp
new file mode 100644
index 0000000..451fd8a
--- /dev/null
+++ b/pvmfw/avb/fuzz/Android.bp
@@ -0,0 +1,34 @@
+// Copyright 2023, 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 {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_fuzz {
+ name: "avb_kernel_without_footer_verify_fuzzer",
+ srcs: ["without_footer_verify_fuzzer.rs"],
+ rustlibs: [
+ "libpvmfw_avb_nostd",
+ ],
+ fuzz_config: {
+ cc: [
+ "android-kvm@google.com",
+ ],
+ fuzz_on_haiku_device: true,
+ fuzz_on_haiku_host: true,
+ },
+}
+
+// TODO(b/260574387): Add avb_kernel_with_footer_verify_fuzzer
diff --git a/pvmfw/avb/fuzz/without_footer_verify_fuzzer.rs b/pvmfw/avb/fuzz/without_footer_verify_fuzzer.rs
new file mode 100644
index 0000000..fc8fa85
--- /dev/null
+++ b/pvmfw/avb/fuzz/without_footer_verify_fuzzer.rs
@@ -0,0 +1,28 @@
+// Copyright 2023, 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.
+
+#![allow(missing_docs)]
+#![no_main]
+
+use libfuzzer_sys::fuzz_target;
+use pvmfw_avb::verify_payload;
+
+fuzz_target!(|kernel: &[u8]| {
+ // This fuzzer is mostly supposed to catch the memory corruption in
+ // AVB footer parsing. It is unlikely that the randomly generated
+ // kernel can pass the kernel verification, so the value of `initrd`
+ // is not so important as we won't reach initrd verification with
+ // this fuzzer.
+ let _ = verify_payload(kernel, /*initrd=*/ None, &[0u8; 64]);
+});
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 8142674..a1e3ee0 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -19,9 +19,10 @@
#![feature(mixed_integer_ops)]
mod error;
+mod ops;
mod partition;
mod utils;
mod verify;
pub use error::AvbSlotVerifyError;
-pub use verify::verify_payload;
+pub use verify::{verify_payload, DebugLevel};
diff --git a/pvmfw/avb/src/ops.rs b/pvmfw/avb/src/ops.rs
new file mode 100644
index 0000000..e7f0ac7
--- /dev/null
+++ b/pvmfw/avb/src/ops.rs
@@ -0,0 +1,339 @@
+// Copyright 2023, 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.
+
+//! Structs and functions relating to `AvbOps`.
+
+use crate::error::{
+ slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError,
+};
+use crate::partition::PartitionName;
+use crate::utils::{self, as_ref, is_not_null, to_nonnull, write};
+use avb_bindgen::{
+ avb_slot_verify, avb_slot_verify_data_free, AvbHashtreeErrorMode, AvbIOResult, AvbOps,
+ AvbPartitionData, AvbSlotVerifyData, AvbSlotVerifyFlags, AvbVBMetaData,
+};
+use core::{
+ ffi::{c_char, c_void, CStr},
+ mem::MaybeUninit,
+ ptr, slice,
+};
+
+const NULL_BYTE: &[u8] = b"\0";
+
+pub(crate) struct Payload<'a> {
+ kernel: &'a [u8],
+ initrd: Option<&'a [u8]>,
+ trusted_public_key: &'a [u8],
+}
+
+impl<'a> AsRef<Payload<'a>> for AvbOps {
+ fn as_ref(&self) -> &Payload<'a> {
+ let payload = self.user_data as *const Payload;
+ // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
+ // pointer to a valid value of Payload in user_data when creating AvbOps.
+ unsafe { &*payload }
+ }
+}
+
+impl<'a> Payload<'a> {
+ pub(crate) fn new(
+ kernel: &'a [u8],
+ initrd: Option<&'a [u8]>,
+ trusted_public_key: &'a [u8],
+ ) -> Self {
+ Self { kernel, initrd, trusted_public_key }
+ }
+
+ fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
+ match partition_name.try_into()? {
+ PartitionName::Kernel => Ok(self.kernel),
+ PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
+ self.initrd.ok_or(AvbIOError::NoSuchPartition)
+ }
+ }
+ }
+}
+
+/// `Ops` wraps the class `AvbOps` in libavb. It provides pvmfw customized
+/// operations used in the verification.
+pub(crate) struct Ops(AvbOps);
+
+impl<'a> From<&mut Payload<'a>> for Ops {
+ fn from(payload: &mut Payload<'a>) -> Self {
+ let avb_ops = AvbOps {
+ user_data: payload as *mut _ as *mut c_void,
+ ab_ops: ptr::null_mut(),
+ atx_ops: ptr::null_mut(),
+ read_from_partition: Some(read_from_partition),
+ get_preloaded_partition: Some(get_preloaded_partition),
+ write_to_partition: None,
+ validate_vbmeta_public_key: Some(validate_vbmeta_public_key),
+ read_rollback_index: Some(read_rollback_index),
+ write_rollback_index: None,
+ read_is_device_unlocked: Some(read_is_device_unlocked),
+ get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
+ get_size_of_partition: Some(get_size_of_partition),
+ read_persistent_value: None,
+ write_persistent_value: None,
+ validate_public_key_for_partition: None,
+ };
+ Self(avb_ops)
+ }
+}
+
+impl Ops {
+ pub(crate) fn verify_partition(
+ &mut self,
+ partition_name: &CStr,
+ ) -> Result<AvbSlotVerifyDataWrap, AvbSlotVerifyError> {
+ let requested_partitions = [partition_name.as_ptr(), ptr::null()];
+ let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
+ let mut out_data = MaybeUninit::uninit();
+ // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
+ // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
+ // initialized.
+ let result = unsafe {
+ avb_slot_verify(
+ &mut self.0,
+ requested_partitions.as_ptr(),
+ ab_suffix.as_ptr(),
+ AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NONE,
+ AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
+ out_data.as_mut_ptr(),
+ )
+ };
+ slot_verify_result_to_verify_payload_result(result)?;
+ // SAFETY: This is safe because `out_data` has been properly initialized after
+ // calling `avb_slot_verify` and it returns OK.
+ let out_data = unsafe { out_data.assume_init() };
+ out_data.try_into()
+ }
+}
+
+extern "C" fn read_is_device_unlocked(
+ _ops: *mut AvbOps,
+ out_is_unlocked: *mut bool,
+) -> AvbIOResult {
+ to_avb_io_result(write(out_is_unlocked, false))
+}
+
+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,
+) -> utils::Result<()> {
+ let ops = as_ref(ops)?;
+ let partition = ops.as_ref().get_partition(partition)?;
+ write(out_pointer, partition.as_ptr() as *mut u8)?;
+ write(out_num_bytes_preloaded, partition.len().min(num_bytes))
+}
+
+extern "C" fn read_from_partition(
+ ops: *mut AvbOps,
+ partition: *const c_char,
+ offset: i64,
+ num_bytes: usize,
+ buffer: *mut c_void,
+ out_num_read: *mut usize,
+) -> AvbIOResult {
+ to_avb_io_result(try_read_from_partition(
+ ops,
+ partition,
+ offset,
+ num_bytes,
+ buffer,
+ out_num_read,
+ ))
+}
+
+fn try_read_from_partition(
+ ops: *mut AvbOps,
+ partition: *const c_char,
+ offset: i64,
+ num_bytes: usize,
+ buffer: *mut c_void,
+ out_num_read: *mut usize,
+) -> utils::Result<()> {
+ let ops = as_ref(ops)?;
+ let partition = ops.as_ref().get_partition(partition)?;
+ let buffer = to_nonnull(buffer)?;
+ // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
+ // is created to point to the `num_bytes` of bytes in memory.
+ let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
+ copy_data_to_dst(partition, offset, buffer_slice)?;
+ write(out_num_read, buffer_slice.len())
+}
+
+fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> utils::Result<()> {
+ let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
+ let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
+ dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
+ Ok(())
+}
+
+fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
+ usize::try_from(offset)
+ .ok()
+ .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
+}
+
+extern "C" fn get_size_of_partition(
+ ops: *mut AvbOps,
+ partition: *const c_char,
+ out_size_num_bytes: *mut u64,
+) -> AvbIOResult {
+ to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
+}
+
+fn try_get_size_of_partition(
+ ops: *mut AvbOps,
+ partition: *const c_char,
+ out_size_num_bytes: *mut u64,
+) -> utils::Result<()> {
+ let ops = as_ref(ops)?;
+ let partition = ops.as_ref().get_partition(partition)?;
+ let partition_size =
+ u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
+ write(out_size_num_bytes, partition_size)
+}
+
+extern "C" fn read_rollback_index(
+ _ops: *mut AvbOps,
+ _rollback_index_location: usize,
+ out_rollback_index: *mut u64,
+) -> AvbIOResult {
+ // Rollback protection is not yet implemented, but this method is required by
+ // `avb_slot_verify()`.
+ // We set `out_rollback_index` to 0 to ensure that the default rollback index (0)
+ // is never smaller than it, thus the rollback index check will pass.
+ to_avb_io_result(write(out_rollback_index, 0))
+}
+
+extern "C" fn get_unique_guid_for_partition(
+ _ops: *mut AvbOps,
+ _partition: *const c_char,
+ _guid_buf: *mut c_char,
+ _guid_buf_size: usize,
+) -> AvbIOResult {
+ // TODO(b/256148034): Check if it's possible to throw an error here instead of having
+ // an empty method.
+ // This method is required by `avb_slot_verify()`.
+ AvbIOResult::AVB_IO_RESULT_OK
+}
+
+extern "C" fn validate_vbmeta_public_key(
+ ops: *mut AvbOps,
+ public_key_data: *const u8,
+ public_key_length: usize,
+ public_key_metadata: *const u8,
+ public_key_metadata_length: usize,
+ out_is_trusted: *mut bool,
+) -> AvbIOResult {
+ to_avb_io_result(try_validate_vbmeta_public_key(
+ ops,
+ public_key_data,
+ public_key_length,
+ public_key_metadata,
+ public_key_metadata_length,
+ out_is_trusted,
+ ))
+}
+
+fn try_validate_vbmeta_public_key(
+ ops: *mut AvbOps,
+ public_key_data: *const u8,
+ public_key_length: usize,
+ _public_key_metadata: *const u8,
+ _public_key_metadata_length: usize,
+ out_is_trusted: *mut bool,
+) -> utils::Result<()> {
+ // The public key metadata is not used when we build the VBMeta.
+ is_not_null(public_key_data)?;
+ // SAFETY: It is safe to create a slice with the given pointer and length as
+ // `public_key_data` is a valid pointer and it points to an array of length
+ // `public_key_length`.
+ let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
+ let ops = as_ref(ops)?;
+ let trusted_public_key = ops.as_ref().trusted_public_key;
+ write(out_is_trusted, public_key == trusted_public_key)
+}
+
+pub(crate) struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData);
+
+impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
+ type Error = AvbSlotVerifyError;
+
+ fn try_from(data: *mut AvbSlotVerifyData) -> Result<Self, Self::Error> {
+ is_not_null(data).map_err(|_| AvbSlotVerifyError::Io)?;
+ Ok(Self(data))
+ }
+}
+
+impl Drop for AvbSlotVerifyDataWrap {
+ fn drop(&mut self) {
+ // SAFETY: This is safe because `self.0` is checked nonnull when the
+ // instance is created. We can free this pointer when the instance is
+ // no longer needed.
+ unsafe {
+ avb_slot_verify_data_free(self.0);
+ }
+ }
+}
+
+impl AsRef<AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
+ fn as_ref(&self) -> &AvbSlotVerifyData {
+ // This is safe because `self.0` is checked nonnull when the instance is created.
+ as_ref(self.0).unwrap()
+ }
+}
+
+impl AvbSlotVerifyDataWrap {
+ pub(crate) fn vbmeta_images(&self) -> Result<&[AvbVBMetaData], AvbSlotVerifyError> {
+ let data = self.as_ref();
+ is_not_null(data.vbmeta_images).map_err(|_| AvbSlotVerifyError::Io)?;
+ // SAFETY: It is safe as the raw pointer `data.vbmeta_images` is a nonnull pointer.
+ let vbmeta_images =
+ unsafe { slice::from_raw_parts(data.vbmeta_images, data.num_vbmeta_images) };
+ Ok(vbmeta_images)
+ }
+
+ pub(crate) fn loaded_partitions(&self) -> Result<&[AvbPartitionData], AvbSlotVerifyError> {
+ let data = self.as_ref();
+ is_not_null(data.loaded_partitions).map_err(|_| AvbSlotVerifyError::Io)?;
+ // SAFETY: It is safe as the raw pointer `data.loaded_partitions` is a nonnull pointer and
+ // is guaranteed by libavb to point to a valid `AvbPartitionData` array as part of the
+ // `AvbSlotVerifyData` struct.
+ let loaded_partitions =
+ unsafe { slice::from_raw_parts(data.loaded_partitions, data.num_loaded_partitions) };
+ Ok(loaded_partitions)
+ }
+}
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
index bb27497..1b35c22 100644
--- a/pvmfw/avb/src/utils.rs
+++ b/pvmfw/avb/src/utils.rs
@@ -16,8 +16,11 @@
use crate::error::AvbIOError;
use core::ptr::NonNull;
+use core::result;
-pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
+pub(crate) type Result<T> = result::Result<T, AvbIOError>;
+
+pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<()> {
let ptr = to_nonnull(ptr)?;
// SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
unsafe {
@@ -26,17 +29,17 @@
Ok(())
}
-pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
+pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T> {
let ptr = to_nonnull(ptr)?;
// SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
unsafe { Ok(ptr.as_ref()) }
}
-pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
+pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>> {
NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
}
-pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
+pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<()> {
if ptr.is_null() {
Err(AvbIOError::NoSuchValue)
} else {
@@ -44,10 +47,10 @@
}
}
-pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize, AvbIOError> {
+pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize> {
num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
}
-pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize, AvbIOError> {
+pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize> {
x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index b6519cd..a062061 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,192 +14,27 @@
//! This module handles the pvmfw payload verification.
-use crate::error::{
- slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError,
-};
+use crate::error::{AvbIOError, AvbSlotVerifyError};
+use crate::ops::{Ops, Payload};
use crate::partition::PartitionName;
-use crate::utils::{as_ref, is_not_null, to_nonnull, to_usize, usize_checked_add, write};
+use crate::utils::{is_not_null, to_usize, usize_checked_add, write};
use avb_bindgen::{
- avb_descriptor_foreach, avb_hash_descriptor_validate_and_byteswap, avb_slot_verify,
- avb_slot_verify_data_free, AvbDescriptor, AvbHashDescriptor, AvbHashtreeErrorMode, AvbIOResult,
- AvbOps, AvbSlotVerifyData, AvbSlotVerifyFlags, AvbVBMetaData,
+ avb_descriptor_foreach, avb_hash_descriptor_validate_and_byteswap, AvbDescriptor,
+ AvbHashDescriptor, AvbPartitionData, AvbVBMetaData,
};
use core::{
- ffi::{c_char, c_void, CStr},
+ ffi::{c_char, c_void},
mem::{size_of, MaybeUninit},
- ptr, slice,
+ slice,
};
-const NULL_BYTE: &[u8] = b"\0";
-
-extern "C" fn read_is_device_unlocked(
- _ops: *mut AvbOps,
- out_is_unlocked: *mut bool,
-) -> AvbIOResult {
- to_avb_io_result(write(out_is_unlocked, false))
-}
-
-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_ref(ops)?;
- let partition = ops.as_ref().get_partition(partition)?;
- write(out_pointer, partition.as_ptr() as *mut u8)?;
- write(out_num_bytes_preloaded, partition.len().min(num_bytes))
-}
-
-extern "C" fn read_from_partition(
- ops: *mut AvbOps,
- partition: *const c_char,
- offset: i64,
- num_bytes: usize,
- buffer: *mut c_void,
- out_num_read: *mut usize,
-) -> AvbIOResult {
- to_avb_io_result(try_read_from_partition(
- ops,
- partition,
- offset,
- num_bytes,
- buffer,
- out_num_read,
- ))
-}
-
-fn try_read_from_partition(
- ops: *mut AvbOps,
- partition: *const c_char,
- offset: i64,
- num_bytes: usize,
- buffer: *mut c_void,
- out_num_read: *mut usize,
-) -> Result<(), AvbIOError> {
- let ops = as_ref(ops)?;
- let partition = ops.as_ref().get_partition(partition)?;
- let buffer = to_nonnull(buffer)?;
- // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
- // is created to point to the `num_bytes` of bytes in memory.
- let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
- copy_data_to_dst(partition, offset, buffer_slice)?;
- write(out_num_read, buffer_slice.len())
-}
-
-fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
- let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
- let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
- dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
- Ok(())
-}
-
-fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
- usize::try_from(offset)
- .ok()
- .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
-}
-
-extern "C" fn get_size_of_partition(
- ops: *mut AvbOps,
- partition: *const c_char,
- out_size_num_bytes: *mut u64,
-) -> AvbIOResult {
- to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
-}
-
-fn try_get_size_of_partition(
- ops: *mut AvbOps,
- partition: *const c_char,
- out_size_num_bytes: *mut u64,
-) -> Result<(), AvbIOError> {
- let ops = as_ref(ops)?;
- let partition = ops.as_ref().get_partition(partition)?;
- let partition_size =
- u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
- write(out_size_num_bytes, partition_size)
-}
-
-extern "C" fn read_rollback_index(
- _ops: *mut AvbOps,
- _rollback_index_location: usize,
- _out_rollback_index: *mut u64,
-) -> AvbIOResult {
- // Rollback protection is not yet implemented, but
- // this method is required by `avb_slot_verify()`.
- AvbIOResult::AVB_IO_RESULT_OK
-}
-
-extern "C" fn get_unique_guid_for_partition(
- _ops: *mut AvbOps,
- _partition: *const c_char,
- _guid_buf: *mut c_char,
- _guid_buf_size: usize,
-) -> AvbIOResult {
- // This method is required by `avb_slot_verify()`.
- AvbIOResult::AVB_IO_RESULT_OK
-}
-
-extern "C" fn validate_public_key_for_partition(
- ops: *mut AvbOps,
- partition: *const c_char,
- public_key_data: *const u8,
- public_key_length: usize,
- public_key_metadata: *const u8,
- public_key_metadata_length: usize,
- out_is_trusted: *mut bool,
- out_rollback_index_location: *mut u32,
-) -> AvbIOResult {
- to_avb_io_result(try_validate_public_key_for_partition(
- ops,
- partition,
- public_key_data,
- public_key_length,
- public_key_metadata,
- public_key_metadata_length,
- out_is_trusted,
- out_rollback_index_location,
- ))
-}
-
-#[allow(clippy::too_many_arguments)]
-fn try_validate_public_key_for_partition(
- ops: *mut AvbOps,
- partition: *const c_char,
- public_key_data: *const u8,
- public_key_length: usize,
- _public_key_metadata: *const u8,
- _public_key_metadata_length: usize,
- out_is_trusted: *mut bool,
- _out_rollback_index_location: *mut u32,
-) -> Result<(), AvbIOError> {
- is_not_null(public_key_data)?;
- // SAFETY: It is safe to create a slice with the given pointer and length as
- // `public_key_data` is a valid pointer and it points to an array of length
- // `public_key_length`.
- let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
- let ops = as_ref(ops)?;
- // Verifies the public key for the known partitions only.
- ops.as_ref().get_partition(partition)?;
- let trusted_public_key = ops.as_ref().trusted_public_key;
- write(out_is_trusted, public_key == trusted_public_key)
+/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum DebugLevel {
+ /// Not debuggable at all.
+ None,
+ /// Fully debuggable.
+ Full,
}
extern "C" fn search_initrd_hash_descriptor(
@@ -277,119 +112,6 @@
}
}
-struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData);
-
-impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
- type Error = AvbSlotVerifyError;
-
- fn try_from(data: *mut AvbSlotVerifyData) -> Result<Self, Self::Error> {
- is_not_null(data).map_err(|_| AvbSlotVerifyError::Io)?;
- Ok(Self(data))
- }
-}
-
-impl Drop for AvbSlotVerifyDataWrap {
- fn drop(&mut self) {
- // SAFETY: This is safe because `self.0` is checked nonnull when the
- // instance is created. We can free this pointer when the instance is
- // no longer needed.
- unsafe {
- avb_slot_verify_data_free(self.0);
- }
- }
-}
-
-impl AsRef<AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
- fn as_ref(&self) -> &AvbSlotVerifyData {
- // This is safe because `self.0` is checked nonnull when the instance is created.
- as_ref(self.0).unwrap()
- }
-}
-
-impl AvbSlotVerifyDataWrap {
- fn vbmeta_images(&self) -> Result<&[AvbVBMetaData], AvbSlotVerifyError> {
- let data = self.as_ref();
- is_not_null(data.vbmeta_images).map_err(|_| AvbSlotVerifyError::Io)?;
- // SAFETY: It is safe as the raw pointer `data.vbmeta_images` is a nonnull pointer.
- let vbmeta_images =
- unsafe { slice::from_raw_parts(data.vbmeta_images, data.num_vbmeta_images) };
- Ok(vbmeta_images)
- }
-}
-
-struct Payload<'a> {
- kernel: &'a [u8],
- initrd: Option<&'a [u8]>,
- trusted_public_key: &'a [u8],
-}
-
-impl<'a> AsRef<Payload<'a>> for AvbOps {
- fn as_ref(&self) -> &Payload<'a> {
- let payload = self.user_data as *const Payload;
- // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
- // pointer to a valid value of Payload in user_data when creating AvbOps, and
- // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
- // belongs to.
- unsafe { &*payload }
- }
-}
-
-impl<'a> Payload<'a> {
- fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
- match partition_name.try_into()? {
- PartitionName::Kernel => Ok(self.kernel),
- PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
- self.initrd.ok_or(AvbIOError::NoSuchPartition)
- }
- }
- }
-
- fn verify_partition(
- &mut self,
- partition_name: &CStr,
- ) -> Result<AvbSlotVerifyDataWrap, AvbSlotVerifyError> {
- let requested_partitions = [partition_name.as_ptr(), ptr::null()];
- let mut avb_ops = AvbOps {
- user_data: self as *mut _ as *mut c_void,
- ab_ops: ptr::null_mut(),
- atx_ops: ptr::null_mut(),
- read_from_partition: Some(read_from_partition),
- get_preloaded_partition: Some(get_preloaded_partition),
- write_to_partition: None,
- validate_vbmeta_public_key: None,
- read_rollback_index: Some(read_rollback_index),
- write_rollback_index: None,
- read_is_device_unlocked: Some(read_is_device_unlocked),
- get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
- get_size_of_partition: Some(get_size_of_partition),
- read_persistent_value: None,
- write_persistent_value: None,
- validate_public_key_for_partition: Some(validate_public_key_for_partition),
- };
- let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
- let mut out_data = MaybeUninit::uninit();
- // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
- // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
- // initialized. The last argument `out_data` is allowed to be null so that nothing
- // will be written to it.
- let result = unsafe {
- avb_slot_verify(
- &mut avb_ops,
- requested_partitions.as_ptr(),
- ab_suffix.as_ptr(),
- AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
- AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
- out_data.as_mut_ptr(),
- )
- };
- slot_verify_result_to_verify_payload_result(result)?;
- // SAFETY: This is safe because `out_data` has been properly initialized after
- // calling `avb_slot_verify` and it returns OK.
- let out_data = unsafe { out_data.assume_init() };
- out_data.try_into()
- }
-}
-
fn verify_vbmeta_has_no_initrd_descriptor(
vbmeta_image: &AvbVBMetaData,
) -> Result<(), AvbSlotVerifyError> {
@@ -413,6 +135,16 @@
}
}
+fn verify_only_one_vbmeta_exists(
+ vbmeta_images: &[AvbVBMetaData],
+) -> Result<(), AvbSlotVerifyError> {
+ if vbmeta_images.len() == 1 {
+ Ok(())
+ } else {
+ Err(AvbSlotVerifyError::InvalidMetadata)
+ }
+}
+
fn verify_vbmeta_is_from_kernel_partition(
vbmeta_image: &AvbVBMetaData,
) -> Result<(), AvbSlotVerifyError> {
@@ -422,25 +154,65 @@
}
}
+fn verify_loaded_partition_has_expected_length(
+ loaded_partitions: &[AvbPartitionData],
+ partition_name: PartitionName,
+ expected_len: usize,
+) -> Result<(), AvbSlotVerifyError> {
+ if loaded_partitions.len() != 1 {
+ // Only one partition should be loaded in each verify result.
+ return Err(AvbSlotVerifyError::Io);
+ }
+ let loaded_partition = loaded_partitions[0];
+ if !PartitionName::try_from(loaded_partition.partition_name as *const c_char)
+ .map_or(false, |p| p == partition_name)
+ {
+ // Only the requested partition should be loaded.
+ return Err(AvbSlotVerifyError::Io);
+ }
+ if loaded_partition.data_size == expected_len {
+ Ok(())
+ } else {
+ Err(AvbSlotVerifyError::Verification)
+ }
+}
+
/// Verifies the payload (signed kernel + initrd) against the trusted public key.
pub fn verify_payload(
kernel: &[u8],
initrd: Option<&[u8]>,
trusted_public_key: &[u8],
-) -> Result<(), AvbSlotVerifyError> {
- let mut payload = Payload { kernel, initrd, trusted_public_key };
- let kernel_verify_result = payload.verify_partition(PartitionName::Kernel.as_cstr())?;
+) -> Result<DebugLevel, AvbSlotVerifyError> {
+ let mut payload = Payload::new(kernel, initrd, trusted_public_key);
+ let mut ops = Ops::from(&mut payload);
+ let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
+
let vbmeta_images = kernel_verify_result.vbmeta_images()?;
- if vbmeta_images.len() != 1 {
- // There can only be one VBMeta.
- return Err(AvbSlotVerifyError::InvalidMetadata);
- }
+ verify_only_one_vbmeta_exists(vbmeta_images)?;
let vbmeta_image = vbmeta_images[0];
verify_vbmeta_is_from_kernel_partition(&vbmeta_image)?;
- if payload.initrd.is_none() {
+
+ if initrd.is_none() {
verify_vbmeta_has_no_initrd_descriptor(&vbmeta_image)?;
+ return Ok(DebugLevel::None);
}
// TODO(b/256148034): Check the vbmeta doesn't have hash descriptors other than
// boot, initrd_normal, initrd_debug.
- Ok(())
+
+ let initrd = initrd.unwrap();
+ let (debug_level, initrd_verify_result, initrd_partition_name) =
+ if let Ok(result) = ops.verify_partition(PartitionName::InitrdNormal.as_cstr()) {
+ (DebugLevel::None, result, PartitionName::InitrdNormal)
+ } else if let Ok(result) = ops.verify_partition(PartitionName::InitrdDebug.as_cstr()) {
+ (DebugLevel::Full, result, PartitionName::InitrdDebug)
+ } else {
+ return Err(AvbSlotVerifyError::Verification);
+ };
+ let loaded_partitions = initrd_verify_result.loaded_partitions()?;
+ verify_loaded_partition_has_expected_length(
+ loaded_partitions,
+ initrd_partition_name,
+ initrd.len(),
+ )?;
+ Ok(debug_level)
}
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
index 6b98dfb..0572789 100644
--- a/pvmfw/avb/tests/api_test.rs
+++ b/pvmfw/avb/tests/api_test.rs
@@ -18,7 +18,7 @@
use anyhow::Result;
use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
-use pvmfw_avb::AvbSlotVerifyError;
+use pvmfw_avb::{AvbSlotVerifyError, DebugLevel};
use std::{fs, mem::size_of, ptr};
use utils::*;
@@ -37,7 +37,7 @@
&load_latest_signed_kernel()?,
&load_latest_initrd_normal()?,
&load_trusted_public_key()?,
- Ok(()),
+ Ok(DebugLevel::None),
)
}
@@ -47,7 +47,7 @@
&load_latest_signed_kernel()?,
&load_latest_initrd_debug()?,
&load_trusted_public_key()?,
- Ok(()),
+ Ok(DebugLevel::Full),
)
}
@@ -57,7 +57,7 @@
&fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?,
/*initrd=*/ None,
&load_trusted_public_key()?,
- Ok(()),
+ Ok(DebugLevel::None),
)
}
@@ -67,7 +67,7 @@
&fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
/*initrd=*/ None,
&load_trusted_public_key()?,
- Ok(()),
+ Ok(DebugLevel::None),
)
}
@@ -122,6 +122,16 @@
}
#[test]
+fn payload_with_an_invalid_initrd_fails_verification() -> Result<()> {
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ /*initrd=*/ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Verification),
+ )
+}
+
+#[test]
fn unsigned_kernel_fails_verification() -> Result<()> {
assert_payload_verification_with_initrd_eq(
&fs::read(UNSIGNED_TEST_IMG_PATH)?,
@@ -192,6 +202,19 @@
}
#[test]
+fn extended_initrd_fails_verification() -> Result<()> {
+ let mut initrd = load_latest_initrd_normal()?;
+ initrd.extend(b"androidboot.vbmeta.digest=1111");
+
+ assert_payload_verification_with_initrd_eq(
+ &load_latest_signed_kernel()?,
+ &initrd,
+ &load_trusted_public_key()?,
+ Err(AvbSlotVerifyError::Verification),
+ )
+}
+
+#[test]
fn tampered_vbmeta_fails_verification() -> Result<()> {
let mut kernel = load_latest_signed_kernel()?;
let footer = extract_avb_footer(&kernel)?;
diff --git a/pvmfw/avb/tests/utils.rs b/pvmfw/avb/tests/utils.rs
index aa40bb8..0a2eac6 100644
--- a/pvmfw/avb/tests/utils.rs
+++ b/pvmfw/avb/tests/utils.rs
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-//! Utility methods used by API tests.
+//! Utility functions used by API tests.
use anyhow::Result;
use avb_bindgen::{
avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
AvbVBMetaImageHeader,
};
-use pvmfw_avb::{verify_payload, AvbSlotVerifyError};
+use pvmfw_avb::{verify_payload, AvbSlotVerifyError, DebugLevel};
use std::{
fs,
mem::{size_of, transmute, MaybeUninit},
@@ -38,7 +38,7 @@
kernel: &[u8],
initrd: &[u8],
trusted_public_key: &[u8],
- expected_result: Result<(), AvbSlotVerifyError>,
+ expected_result: Result<DebugLevel, AvbSlotVerifyError>,
) -> Result<()> {
assert_payload_verification_eq(kernel, Some(initrd), trusted_public_key, expected_result)
}
@@ -47,7 +47,7 @@
kernel: &[u8],
initrd: Option<&[u8]>,
trusted_public_key: &[u8],
- expected_result: Result<(), AvbSlotVerifyError>,
+ expected_result: Result<DebugLevel, AvbSlotVerifyError>,
) -> Result<()> {
assert_eq!(expected_result, verify_payload(kernel, initrd, trusted_public_key));
Ok(())
diff --git a/pvmfw/src/entry.rs b/pvmfw/src/entry.rs
index bfcb423..4f30902 100644
--- a/pvmfw/src/entry.rs
+++ b/pvmfw/src/entry.rs
@@ -178,6 +178,37 @@
}
}
+/// Applies the debug policy device tree overlay to the pVM DT.
+///
+/// # Safety
+///
+/// When an error is returned by this function, the input `Fdt` should be discarded as it may have
+/// have been partially corrupted during the overlay application process.
+unsafe fn apply_debug_policy(
+ fdt: &mut libfdt::Fdt,
+ debug_policy: &mut [u8],
+) -> Result<(), RebootReason> {
+ let overlay = libfdt::Fdt::from_mut_slice(debug_policy).map_err(|e| {
+ error!("Failed to load the debug policy overlay: {e}");
+ RebootReason::InvalidConfig
+ })?;
+
+ fdt.unpack().map_err(|e| {
+ error!("Failed to unpack DT for debug policy: {e}");
+ RebootReason::InternalError
+ })?;
+
+ let fdt = fdt.apply_overlay(overlay).map_err(|e| {
+ error!("Failed to apply the debug policy overlay: {e}");
+ RebootReason::InvalidConfig
+ })?;
+
+ fdt.pack().map_err(|e| {
+ error!("Failed to re-pack DT after debug policy: {e}");
+ RebootReason::InternalError
+ })
+}
+
/// Sets up the environment for main() and wraps its result for start().
///
/// Provide the abstractions necessary for start() to abort the pVM boot and for main() to run with
@@ -252,6 +283,11 @@
helpers::flushed_zeroize(bcc_slice);
helpers::flush(slices.fdt.as_slice());
+ if let Some(debug_policy) = appended.get_debug_policy() {
+ // SAFETY - As we `?` the result, there is no risk of re-using a bad `slices.fdt`.
+ unsafe { apply_debug_policy(slices.fdt, debug_policy) }?;
+ }
+
info!("Expecting a bug making MMIO_GUARD_UNMAP return NOT_SUPPORTED on success");
memory.mmio_unmap_all().map_err(|e| {
error!("Failed to unshare MMIO ranges: {e}");
diff --git a/pvmfw/src/heap.rs b/pvmfw/src/heap.rs
index acc903a..e04451f 100644
--- a/pvmfw/src/heap.rs
+++ b/pvmfw/src/heap.rs
@@ -30,7 +30,9 @@
#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();
-static mut HEAP: [u8; 131072] = [0; 131072];
+/// 128 KiB
+const HEAP_SIZE: usize = 0x20000;
+static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
pub unsafe fn init() {
HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len());
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index 8633595..24c36b3 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -17,7 +17,6 @@
#![no_main]
#![no_std]
#![feature(default_alloc_error_handler)]
-#![feature(ptr_const_cast)] // Stabilized in 1.65.0
extern crate alloc;
@@ -46,7 +45,7 @@
helpers::flush,
helpers::GUEST_PAGE_SIZE,
memory::MemoryTracker,
- virtio::pci::{find_virtio_devices, map_mmio},
+ virtio::pci::{self, find_virtio_devices},
};
use ::dice::bcc;
use fdtpci::{PciError, PciInfo};
@@ -77,10 +76,7 @@
// Set up PCI bus for VirtIO devices.
let pci_info = PciInfo::from_fdt(fdt).map_err(handle_pci_error)?;
debug!("PCI: {:#x?}", pci_info);
- map_mmio(&pci_info, memory)?;
- // Safety: This is the only place where we call make_pci_root, and this main function is only
- // called once.
- let mut pci_root = unsafe { pci_info.make_pci_root() };
+ let mut pci_root = pci::initialise(pci_info, memory)?;
find_virtio_devices(&mut pci_root).map_err(handle_pci_error)?;
verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
diff --git a/pvmfw/src/memory.rs b/pvmfw/src/memory.rs
index 604aa80..7eecb97 100644
--- a/pvmfw/src/memory.rs
+++ b/pvmfw/src/memory.rs
@@ -321,8 +321,7 @@
handle_alloc_error(layout);
};
- let vaddr = buffer.as_ptr() as usize;
- let paddr = virt_to_phys(vaddr);
+ let paddr = virt_to_phys(buffer);
// If share_range fails then we will leak the allocation, but that seems better than having it
// be reused while maybe still partially shared with the host.
share_range(&(paddr..paddr + layout.size()), granule)?;
@@ -338,7 +337,7 @@
///
/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
/// deallocated.
-pub unsafe fn dealloc_shared(vaddr: usize, size: usize) -> smccc::Result<()> {
+pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> smccc::Result<()> {
let layout = shared_buffer_layout(size)?;
let granule = layout.align();
@@ -346,7 +345,7 @@
unshare_range(&(paddr..paddr + layout.size()), granule)?;
// Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
// the layout is the same as was used then.
- unsafe { dealloc(vaddr as *mut u8, layout) };
+ unsafe { dealloc(vaddr.as_ptr(), layout) };
Ok(())
}
@@ -372,8 +371,16 @@
/// Returns the intermediate physical address corresponding to the given virtual address.
///
-/// As we use identity mapping for everything, this is just the identity function, but it's useful
-/// to use it to be explicit about where we are converting from virtual to physical address.
-pub fn virt_to_phys(vaddr: usize) -> usize {
- vaddr
+/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
+/// explicit about where we are converting from virtual to physical address.
+pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
+ vaddr.as_ptr() as _
+}
+
+/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
+/// physical address.
+///
+/// Panics if `paddr` is 0.
+pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
+ NonNull::new(paddr as _).unwrap()
}
diff --git a/pvmfw/src/virtio/hal.rs b/pvmfw/src/virtio/hal.rs
index c1c8ae6..5f70b33 100644
--- a/pvmfw/src/virtio/hal.rs
+++ b/pvmfw/src/virtio/hal.rs
@@ -1,23 +1,26 @@
-use crate::memory::{alloc_shared, dealloc_shared, virt_to_phys};
-use core::ptr::{copy_nonoverlapping, NonNull};
+use super::pci::PCI_INFO;
+use crate::memory::{alloc_shared, dealloc_shared, phys_to_virt, virt_to_phys};
+use core::{
+ ops::Range,
+ ptr::{copy_nonoverlapping, NonNull},
+};
use log::debug;
-use virtio_drivers::{BufferDirection, Hal, PhysAddr, VirtAddr, PAGE_SIZE};
+use virtio_drivers::{BufferDirection, Hal, PhysAddr, PAGE_SIZE};
pub struct HalImpl;
impl Hal for HalImpl {
- fn dma_alloc(pages: usize) -> PhysAddr {
+ fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
debug!("dma_alloc: pages={}", pages);
let size = pages * PAGE_SIZE;
- let vaddr = alloc_shared(size)
- .expect("Failed to allocate and share VirtIO DMA range with host")
- .as_ptr() as VirtAddr;
- virt_to_phys(vaddr)
+ let vaddr =
+ alloc_shared(size).expect("Failed to allocate and share VirtIO DMA range with host");
+ let paddr = virt_to_phys(vaddr);
+ (paddr, vaddr)
}
- fn dma_dealloc(paddr: PhysAddr, pages: usize) -> i32 {
+ fn dma_dealloc(paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
debug!("dma_dealloc: paddr={:#x}, pages={}", paddr, pages);
- let vaddr = Self::phys_to_virt(paddr);
let size = pages * PAGE_SIZE;
// Safe because the memory was allocated by `dma_alloc` above using the same allocator, and
// the layout is the same as was used then.
@@ -27,8 +30,22 @@
0
}
- fn phys_to_virt(paddr: PhysAddr) -> VirtAddr {
- paddr
+ fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
+ let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialised");
+ // Check that the region is within the PCI MMIO range that we read from the device tree. If
+ // not, the host is probably trying to do something malicious.
+ if !contains_range(
+ &pci_info.bar_range,
+ &(paddr.try_into().expect("PCI MMIO region start was outside of 32-bit address space")
+ ..paddr
+ .checked_add(size)
+ .expect("PCI MMIO region end overflowed")
+ .try_into()
+ .expect("PCI MMIO region end was outside of 32-bit address space")),
+ ) {
+ panic!("PCI MMIO region was outside of expected BAR range.");
+ }
+ phys_to_virt(paddr)
}
fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
@@ -43,11 +60,11 @@
copy_nonoverlapping(buffer.as_ptr() as *mut u8, copy.as_ptr(), size);
}
}
- virt_to_phys(copy.as_ptr() as VirtAddr)
+ virt_to_phys(copy)
}
fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
- let vaddr = Self::phys_to_virt(paddr);
+ let vaddr = phys_to_virt(paddr);
let size = buffer.len();
if direction == BufferDirection::DeviceToDriver {
debug!(
@@ -56,7 +73,7 @@
buffer.as_ptr() as *mut u8 as usize
);
unsafe {
- copy_nonoverlapping(vaddr as *const u8, buffer.as_ptr() as *mut u8, size);
+ copy_nonoverlapping(vaddr.as_ptr(), buffer.as_ptr() as *mut u8, size);
}
}
@@ -69,3 +86,8 @@
}
}
}
+
+/// Returns true if `inner` is entirely contained within `outer`.
+fn contains_range(outer: &Range<u32>, inner: &Range<u32>) -> bool {
+ inner.start >= outer.start && inner.end <= outer.end
+}
diff --git a/pvmfw/src/virtio/pci.rs b/pvmfw/src/virtio/pci.rs
index f9d36c6..d3b3124 100644
--- a/pvmfw/src/virtio/pci.rs
+++ b/pvmfw/src/virtio/pci.rs
@@ -16,8 +16,10 @@
use super::hal::HalImpl;
use crate::{entry::RebootReason, memory::MemoryTracker};
+use alloc::boxed::Box;
use fdtpci::{PciError, PciInfo};
use log::{debug, error, info};
+use once_cell::race::OnceBox;
use virtio_drivers::{
device::blk::VirtIOBlk,
transport::{
@@ -26,8 +28,29 @@
},
};
+pub(super) static PCI_INFO: OnceBox<PciInfo> = OnceBox::new();
+
+/// Prepares to use VirtIO PCI devices.
+///
+/// In particular:
+///
+/// 1. Maps the PCI CAM and BAR range in the page table and MMIO guard.
+/// 2. Stores the `PciInfo` for the VirtIO HAL to use later.
+/// 3. Creates and returns a `PciRoot`.
+///
+/// This must only be called once; it will panic if it is called a second time.
+pub fn initialise(pci_info: PciInfo, memory: &mut MemoryTracker) -> Result<PciRoot, RebootReason> {
+ map_mmio(&pci_info, memory)?;
+
+ PCI_INFO.set(Box::new(pci_info.clone())).expect("Tried to set PCI_INFO a second time");
+
+ // Safety: This is the only place where we call make_pci_root, and `PCI_INFO.set` above will
+ // panic if it is called a second time.
+ Ok(unsafe { pci_info.make_pci_root() })
+}
+
/// Maps the CAM and BAR range in the page table and MMIO guard.
-pub fn map_mmio(pci_info: &PciInfo, memory: &mut MemoryTracker) -> Result<(), RebootReason> {
+fn map_mmio(pci_info: &PciInfo, memory: &mut MemoryTracker) -> Result<(), RebootReason> {
memory.map_mmio_range(pci_info.cam_range.clone()).map_err(|e| {
error!("Failed to map PCI CAM: {}", e);
RebootReason::InternalError
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 e1a2e40..7bd5f08 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -31,6 +31,7 @@
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import android.content.Context;
+import android.content.ContextWrapper;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.os.ParcelFileDescriptor.AutoCloseInputStream;
@@ -342,7 +343,7 @@
VirtualMachineConfig.Builder minimalBuilder = newVmConfigBuilder();
VirtualMachineConfig minimal = minimalBuilder.setPayloadBinaryName("binary.so").build();
- assertThat(minimal.getApkPath()).isEqualTo(getContext().getPackageCodePath());
+ assertThat(minimal.getApkPath()).isNull();
assertThat(minimal.getDebugLevel()).isEqualTo(DEBUG_LEVEL_NONE);
assertThat(minimal.getMemoryMib()).isEqualTo(0);
assertThat(minimal.getNumCpus()).isEqualTo(1);
@@ -425,13 +426,9 @@
assertThat(e).hasMessageThat().contains("debug level must be FULL to capture output");
}
- private VirtualMachineConfig.Builder newBaselineBuilder() {
- return newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
- }
-
@Test
@CddTest(requirements = {"9.17/C-1-1"})
- public void compatibleConfigTests() throws Exception {
+ public void compatibleConfigTests() {
int maxCpus = Runtime.getRuntime().availableProcessors();
VirtualMachineConfig baseline = newBaselineBuilder().build();
@@ -467,6 +464,31 @@
newBaselineBuilder().setDebugLevel(DEBUG_LEVEL_FULL);
VirtualMachineConfig debuggable = debuggableBuilder.build();
assertConfigCompatible(debuggable, debuggableBuilder.setVmOutputCaptured(true)).isFalse();
+
+ VirtualMachineConfig currentContextConfig =
+ new VirtualMachineConfig.Builder(getContext())
+ .setProtectedVm(isProtectedVm())
+ .setPayloadBinaryName("binary.so")
+ .build();
+
+ // packageName is not directly exposed by the config, so we have to be a bit creative
+ // to modify it.
+ Context otherContext =
+ new ContextWrapper(getContext()) {
+ @Override
+ public String getPackageName() {
+ return "other.package.name";
+ }
+ };
+ VirtualMachineConfig.Builder otherContextBuilder =
+ new VirtualMachineConfig.Builder(otherContext)
+ .setProtectedVm(isProtectedVm())
+ .setPayloadBinaryName("binary.so");
+ assertConfigCompatible(currentContextConfig, otherContextBuilder).isFalse();
+ }
+
+ private VirtualMachineConfig.Builder newBaselineBuilder() {
+ return newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
}
private BooleanSubject assertConfigCompatible(
diff --git a/virtualizationmanager/src/crosvm.rs b/virtualizationmanager/src/crosvm.rs
index 98e7d99..c1ac20f 100644
--- a/virtualizationmanager/src/crosvm.rs
+++ b/virtualizationmanager/src/crosvm.rs
@@ -376,7 +376,7 @@
&self.name,
death_reason,
exit_signal,
- &*vm_metric,
+ &vm_metric,
);
// Delete temporary files. The folder itself is removed by VirtualizationServiceInternal.
@@ -678,7 +678,7 @@
// Configure the logger for the crosvm process to silence logs from the disk crate which
// don't provide much information to us (but do spamming us).
.arg("--log-level")
- .arg("info,disk=off")
+ .arg("info,disk=warn")
.arg("run")
.arg("--disable-sandbox")
.arg("--cid")
diff --git a/vmbase/example/src/pci.rs b/vmbase/example/src/pci.rs
index 438ff9e..c0a2d2b 100644
--- a/vmbase/example/src/pci.rs
+++ b/vmbase/example/src/pci.rs
@@ -15,7 +15,7 @@
//! Functions to scan the PCI bus for VirtIO device.
use aarch64_paging::paging::MemoryRegion;
-use alloc::alloc::{alloc, dealloc, Layout};
+use alloc::alloc::{alloc, dealloc, handle_alloc_error, Layout};
use core::{mem::size_of, ptr::NonNull};
use fdtpci::PciInfo;
use log::{debug, info};
@@ -25,7 +25,7 @@
pci::{bus::PciRoot, virtio_device_type, PciTransport},
DeviceType, Transport,
},
- BufferDirection, Hal, PhysAddr, VirtAddr, PAGE_SIZE,
+ BufferDirection, Hal, PhysAddr, PAGE_SIZE,
};
/// The standard sector size of a VirtIO block device, in bytes.
@@ -87,32 +87,34 @@
struct HalImpl;
impl Hal for HalImpl {
- fn dma_alloc(pages: usize) -> PhysAddr {
+ fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
debug!("dma_alloc: pages={}", pages);
let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
// Safe because the layout has a non-zero size.
- let vaddr = unsafe { alloc(layout) } as VirtAddr;
- virt_to_phys(vaddr)
+ let vaddr = unsafe { alloc(layout) };
+ let vaddr =
+ if let Some(vaddr) = NonNull::new(vaddr) { vaddr } else { handle_alloc_error(layout) };
+ let paddr = virt_to_phys(vaddr);
+ (paddr, vaddr)
}
- fn dma_dealloc(paddr: PhysAddr, pages: usize) -> i32 {
+ fn dma_dealloc(paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
debug!("dma_dealloc: paddr={:#x}, pages={}", paddr, pages);
- let vaddr = Self::phys_to_virt(paddr);
let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
// Safe because the memory was allocated by `dma_alloc` above using the same allocator, and
// the layout is the same as was used then.
unsafe {
- dealloc(vaddr as *mut u8, layout);
+ dealloc(vaddr.as_ptr(), layout);
}
0
}
- fn phys_to_virt(paddr: PhysAddr) -> VirtAddr {
- paddr
+ fn mmio_phys_to_virt(paddr: PhysAddr, _size: usize) -> NonNull<u8> {
+ NonNull::new(paddr as _).unwrap()
}
fn share(buffer: NonNull<[u8]>, _direction: BufferDirection) -> PhysAddr {
- let vaddr = buffer.as_ptr() as *mut u8 as usize;
+ let vaddr = buffer.cast();
// Nothing to do, as the host already has access to all memory.
virt_to_phys(vaddr)
}
@@ -123,6 +125,6 @@
}
}
-fn virt_to_phys(vaddr: VirtAddr) -> PhysAddr {
- vaddr
+fn virt_to_phys(vaddr: NonNull<u8>) -> PhysAddr {
+ vaddr.as_ptr() as _
}