Use LazyLock rather than lazy_static.
Bug: 364211748
Test: m virtmgr virtualizationservice libcompos_common libservice_vm_manager libvm_payload_rs
Change-Id: I3e92489a925709c3ab91968d1a38c9b52a54f3c5
diff --git a/android/virtmgr/Android.bp b/android/virtmgr/Android.bp
index 4828057..62ff8d8 100644
--- a/android/virtmgr/Android.bp
+++ b/android/virtmgr/Android.bp
@@ -44,7 +44,6 @@
"libglob",
"libhex",
"libhypervisor_props",
- "liblazy_static",
"liblibc",
"liblog_rust",
"libmicrodroid_metadata",
diff --git a/android/virtmgr/src/aidl.rs b/android/virtmgr/src/aidl.rs
index 7a357f3..158c564 100644
--- a/android/virtmgr/src/aidl.rs
+++ b/android/virtmgr/src/aidl.rs
@@ -67,7 +67,6 @@
};
use cstr::cstr;
use glob::glob;
-use lazy_static::lazy_static;
use log::{debug, error, info, warn};
use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
use nix::unistd::pipe;
@@ -86,7 +85,7 @@
use std::os::unix::io::{AsRawFd, IntoRawFd};
use std::os::unix::raw::pid_t;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex, Weak};
+use std::sync::{Arc, Mutex, Weak, LazyLock};
use vbmeta::VbMetaImage;
use vmconfig::{VmConfig, get_debug_level};
use vsock::VsockStream;
@@ -119,13 +118,13 @@
const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
-lazy_static! {
- pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
+pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
+ LazyLock::new(|| {
wait_for_interface(BINDER_SERVICE_IDENTIFIER)
- .expect("Could not connect to VirtualizationServiceInternal");
- static ref SUPPORTED_OS_NAMES: HashSet<String> =
- get_supported_os_names().expect("Failed to get list of supported os names");
-}
+ .expect("Could not connect to VirtualizationServiceInternal")
+ });
+static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
+ LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
fn create_or_update_idsig_file(
input_fd: &ParcelFileDescriptor,
diff --git a/android/virtmgr/src/crosvm.rs b/android/virtmgr/src/crosvm.rs
index 08a9e47..fff0399 100644
--- a/android/virtmgr/src/crosvm.rs
+++ b/android/virtmgr/src/crosvm.rs
@@ -20,7 +20,6 @@
use anyhow::{anyhow, bail, Context, Error, Result};
use binder::ParcelFileDescriptor;
use command_fds::CommandFdExt;
-use lazy_static::lazy_static;
use libc::{sysconf, _SC_CLK_TCK};
use log::{debug, error, info};
use semver::{Version, VersionReq};
@@ -39,7 +38,7 @@
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
-use std::sync::{Arc, Condvar, Mutex};
+use std::sync::{Arc, Condvar, Mutex, LazyLock};
use std::time::{Duration, SystemTime};
use std::thread::{self, JoinHandle};
use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
@@ -89,16 +88,16 @@
/// Serial (emulated uart)
const CONSOLE_TTYS0: &str = "ttyS0";
-lazy_static! {
- /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
- /// triggered.
- static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
+/// If the VM doesn't move to the Started state within this amount time, a hang-up error is
+/// triggered.
+static BOOT_HANGUP_TIMEOUT: LazyLock<Duration> = LazyLock::new(|| {
+ if nested_virt::is_nested_virtualization().unwrap() {
// Nested virtualization is slow, so we need a longer timeout.
Duration::from_secs(300)
} else {
Duration::from_secs(30)
- };
-}
+ }
+});
/// Configuration for a VM to run with crosvm.
#[derive(Debug)]
diff --git a/android/virtmgr/src/debug_config.rs b/android/virtmgr/src/debug_config.rs
index 52ac964..74559de 100644
--- a/android/virtmgr/src/debug_config.rs
+++ b/android/virtmgr/src/debug_config.rs
@@ -18,7 +18,6 @@
VirtualMachineAppConfig::DebugLevel::DebugLevel, VirtualMachineConfig::VirtualMachineConfig,
};
use anyhow::{anyhow, Context, Error, Result};
-use lazy_static::lazy_static;
use libfdt::{Fdt, FdtError};
use log::{info, warn};
use rustutils::system_properties;
@@ -26,6 +25,7 @@
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
+use std::sync::LazyLock;
use vmconfig::get_debug_level;
const CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP: &str =
@@ -56,11 +56,12 @@
}
}
-lazy_static! {
- static ref DP_LOG_PATH: DPPath = DPPath::new("/avf/guest/common", "log").unwrap();
- static ref DP_RAMDUMP_PATH: DPPath = DPPath::new("/avf/guest/common", "ramdump").unwrap();
- static ref DP_ADB_PATH: DPPath = DPPath::new("/avf/guest/microdroid", "adb").unwrap();
-}
+static DP_LOG_PATH: LazyLock<DPPath> =
+ LazyLock::new(|| DPPath::new("/avf/guest/common", "log").unwrap());
+static DP_RAMDUMP_PATH: LazyLock<DPPath> =
+ LazyLock::new(|| DPPath::new("/avf/guest/common", "ramdump").unwrap());
+static DP_ADB_PATH: LazyLock<DPPath> =
+ LazyLock::new(|| DPPath::new("/avf/guest/microdroid", "adb").unwrap());
/// Get debug policy value in bool. It's true iff the value is explicitly set to <1>.
fn get_debug_policy_bool(path: &Path) -> Result<bool> {
diff --git a/android/virtmgr/src/main.rs b/android/virtmgr/src/main.rs
index 7d29685..a4e75a7 100644
--- a/android/virtmgr/src/main.rs
+++ b/android/virtmgr/src/main.rs
@@ -27,10 +27,10 @@
use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::BnVirtualizationService;
use anyhow::{bail, Result};
use binder::{BinderFeatures, ProcessState};
-use lazy_static::lazy_static;
use log::{info, LevelFilter};
use rpcbinder::{FileDescriptorTransportMode, RpcServer};
use std::os::unix::io::{AsFd, RawFd};
+use std::sync::LazyLock;
use clap::Parser;
use nix::unistd::{write, Pid, Uid};
use std::os::unix::raw::{pid_t, uid_t};
@@ -38,11 +38,9 @@
const LOG_TAG: &str = "virtmgr";
-lazy_static! {
- static ref PID_CURRENT: Pid = Pid::this();
- static ref PID_PARENT: Pid = Pid::parent();
- static ref UID_CURRENT: Uid = Uid::current();
-}
+static PID_CURRENT: LazyLock<Pid> = LazyLock::new(Pid::this);
+static PID_PARENT: LazyLock<Pid> = LazyLock::new(Pid::parent);
+static UID_CURRENT: LazyLock<Uid> = LazyLock::new(Uid::current);
fn get_this_pid() -> pid_t {
// Return the process ID of this process.
diff --git a/android/virtualizationservice/Android.bp b/android/virtualizationservice/Android.bp
index f9034af..fb6e39a 100644
--- a/android/virtualizationservice/Android.bp
+++ b/android/virtualizationservice/Android.bp
@@ -38,7 +38,6 @@
"libbinder_rs",
"libhex",
"libhypervisor_props",
- "liblazy_static",
"liblibc",
"liblibsqlite3_sys",
"liblog_rust",
diff --git a/android/virtualizationservice/src/aidl.rs b/android/virtualizationservice/src/aidl.rs
index acdb53a..0f16291 100644
--- a/android/virtualizationservice/src/aidl.rs
+++ b/android/virtualizationservice/src/aidl.rs
@@ -33,7 +33,6 @@
self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, IntoBinderResult,
LazyServiceGuard, ParcelFileDescriptor, Status, Strong,
};
-use lazy_static::lazy_static;
use libc::{VMADDR_CID_HOST, VMADDR_CID_HYPERVISOR, VMADDR_CID_LOCAL};
use log::{error, info, warn};
use nix::unistd::{chown, Uid};
@@ -52,7 +51,7 @@
use std::os::unix::fs::PermissionsExt;
use std::os::unix::raw::{pid_t, uid_t};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Condvar, Mutex, Weak};
+use std::sync::{Arc, Condvar, LazyLock, Mutex, Weak};
use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
use virtualizationcommon::Certificate::Certificate;
use virtualizationmaintenance::{
@@ -157,18 +156,18 @@
0xb9, 0x0f,
];
-lazy_static! {
- static ref FAKE_PROVISIONED_KEY_BLOB_FOR_TESTING: Mutex<Option<Vec<u8>>> = Mutex::new(None);
- static ref VFIO_SERVICE: Strong<dyn IVfioHandler> =
- wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())
- .expect("Could not connect to VfioHandler");
- static ref NETWORK_SERVICE: Strong<dyn IVmnic> =
- wait_for_interface(<BpVmnic as IVmnic>::get_descriptor())
- .expect("Could not connect to Vmnic");
- static ref TETHERING_SERVICE: Strong<dyn IVmTethering> =
- wait_for_interface(<BpVmTethering as IVmTethering>::get_descriptor())
- .expect("Could not connect to VmTethering");
-}
+static FAKE_PROVISIONED_KEY_BLOB_FOR_TESTING: Mutex<Option<Vec<u8>>> = Mutex::new(None);
+static VFIO_SERVICE: LazyLock<Strong<dyn IVfioHandler>> = LazyLock::new(|| {
+ wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())
+ .expect("Could not connect to VfioHandler")
+});
+static NETWORK_SERVICE: LazyLock<Strong<dyn IVmnic>> = LazyLock::new(|| {
+ wait_for_interface(<BpVmnic as IVmnic>::get_descriptor()).expect("Could not connect to Vmnic")
+});
+static TETHERING_SERVICE: LazyLock<Strong<dyn IVmTethering>> = LazyLock::new(|| {
+ wait_for_interface(<BpVmTethering as IVmTethering>::get_descriptor())
+ .expect("Could not connect to VmTethering")
+});
fn is_valid_guest_cid(cid: Cid) -> bool {
(GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
diff --git a/android/virtualizationservice/vfio_handler/Android.bp b/android/virtualizationservice/vfio_handler/Android.bp
index 66fc2ee..3635cf1 100644
--- a/android/virtualizationservice/vfio_handler/Android.bp
+++ b/android/virtualizationservice/vfio_handler/Android.bp
@@ -25,7 +25,6 @@
"libandroid_logger",
"libanyhow",
"libbinder_rs",
- "liblazy_static",
"liblog_rust",
"libnix",
"librustutils",
diff --git a/android/virtualizationservice/vfio_handler/src/aidl.rs b/android/virtualizationservice/vfio_handler/src/aidl.rs
index b527260..3b4d0c5 100644
--- a/android/virtualizationservice/vfio_handler/src/aidl.rs
+++ b/android/virtualizationservice/vfio_handler/src/aidl.rs
@@ -20,11 +20,11 @@
use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::VfioDev::VfioDev;
use android_system_virtualizationservice_internal::binder::ParcelFileDescriptor;
use binder::{self, BinderFeatures, ExceptionCode, Interface, IntoBinderResult, Strong};
-use lazy_static::lazy_static;
use log::error;
use std::fs::{read_link, write, File};
use std::io::{Read, Seek, SeekFrom, Write};
use std::mem::size_of;
+use std::sync::LazyLock;
use std::path::{Path, PathBuf};
use rustutils::system_properties;
use zerocopy::{
@@ -169,10 +169,9 @@
_custom: [U32<BigEndian>; 4],
}
-lazy_static! {
- static ref IS_VFIO_SUPPORTED: bool =
- Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists();
-}
+static IS_VFIO_SUPPORTED: LazyLock<bool> = LazyLock::new(|| {
+ Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists()
+});
fn check_platform_device(path: &Path) -> binder::Result<()> {
if !path.exists() {
diff --git a/libs/libcompos_common/Android.bp b/libs/libcompos_common/Android.bp
index 72cb5e1..01836ae 100644
--- a/libs/libcompos_common/Android.bp
+++ b/libs/libcompos_common/Android.bp
@@ -14,7 +14,6 @@
"libanyhow",
"libbinder_rs",
"libglob",
- "liblazy_static",
"liblog_rust",
"libnested_virt",
"libnum_traits",
diff --git a/libs/libcompos_common/timeouts.rs b/libs/libcompos_common/timeouts.rs
index 7bd7679..d22f7f7 100644
--- a/libs/libcompos_common/timeouts.rs
+++ b/libs/libcompos_common/timeouts.rs
@@ -17,7 +17,7 @@
//! Timeouts for common situations, with support for longer timeouts when using nested
//! virtualization.
-use lazy_static::lazy_static;
+use std::sync::LazyLock;
use std::time::Duration;
/// Holder for the various timeouts we use.
@@ -31,15 +31,15 @@
pub vm_max_time_to_exit: Duration,
}
-lazy_static! {
/// The timeouts that are appropriate on the current platform.
-pub static ref TIMEOUTS: Timeouts = if nested_virt::is_nested_virtualization().unwrap() {
- // Nested virtualization is slow.
- EXTENDED_TIMEOUTS
-} else {
- NORMAL_TIMEOUTS
-};
-}
+pub static TIMEOUTS: LazyLock<Timeouts> = LazyLock::new(|| {
+ if nested_virt::is_nested_virtualization().unwrap() {
+ // Nested virtualization is slow.
+ EXTENDED_TIMEOUTS
+ } else {
+ NORMAL_TIMEOUTS
+ }
+});
/// The timeouts that we use normally.
const NORMAL_TIMEOUTS: Timeouts = Timeouts {
diff --git a/libs/libservice_vm_manager/Android.bp b/libs/libservice_vm_manager/Android.bp
index 6469212..b3618a6 100644
--- a/libs/libservice_vm_manager/Android.bp
+++ b/libs/libservice_vm_manager/Android.bp
@@ -12,7 +12,6 @@
"android.system.virtualizationservice-rust",
"libanyhow",
"libciborium",
- "liblazy_static",
"liblog_rust",
"libnix",
"libservice_vm_comm",
diff --git a/libs/libservice_vm_manager/src/lib.rs b/libs/libservice_vm_manager/src/lib.rs
index d3d86e9..d7b4dd6 100644
--- a/libs/libservice_vm_manager/src/lib.rs
+++ b/libs/libservice_vm_manager/src/lib.rs
@@ -25,7 +25,6 @@
binder::ParcelFileDescriptor,
};
use anyhow::{anyhow, ensure, Context, Result};
-use lazy_static::lazy_static;
use log::{info, warn};
use service_vm_comm::{Request, Response, ServiceVmRequest, VmType};
use std::fs::{self, File, OpenOptions};
@@ -48,11 +47,10 @@
const WRITE_BUFFER_CAPACITY: usize = 512;
const READ_TIMEOUT: Duration = Duration::from_secs(10);
const WRITE_TIMEOUT: Duration = Duration::from_secs(10);
-lazy_static! {
- static ref PENDING_REQUESTS: AtomicCounter = AtomicCounter::default();
- static ref SERVICE_VM: Mutex<Option<ServiceVm>> = Mutex::new(None);
- static ref SERVICE_VM_SHUTDOWN: Condvar = Condvar::new();
-}
+
+static PENDING_REQUESTS: AtomicCounter = AtomicCounter::new();
+static SERVICE_VM: Mutex<Option<ServiceVm>> = Mutex::new(None);
+static SERVICE_VM_SHUTDOWN: Condvar = Condvar::new();
/// Atomic counter with a condition variable that is used to wait for the counter
/// to become positive within a timeout.
@@ -63,6 +61,10 @@
}
impl AtomicCounter {
+ const fn new() -> Self {
+ Self { num: Mutex::new(0), num_increased: Condvar::new() }
+ }
+
/// Checks if the counter becomes positive within the given timeout.
fn is_positive_within_timeout(&self, timeout: Duration) -> bool {
let (guard, _wait_result) = self
diff --git a/libs/libvm_payload/Android.bp b/libs/libvm_payload/Android.bp
index cf2a002..bb91737 100644
--- a/libs/libvm_payload/Android.bp
+++ b/libs/libvm_payload/Android.bp
@@ -16,7 +16,6 @@
"libandroid_logger",
"libanyhow",
"libbinder_rs",
- "liblazy_static",
"liblibc",
"liblog_rust",
"libopenssl",
diff --git a/libs/libvm_payload/src/lib.rs b/libs/libvm_payload/src/lib.rs
index 13c6e76..40f7b79 100644
--- a/libs/libvm_payload/src/lib.rs
+++ b/libs/libvm_payload/src/lib.rs
@@ -23,7 +23,6 @@
unstable_api::{new_spibinder, AIBinder},
Strong, ExceptionCode,
};
-use lazy_static::lazy_static;
use log::{error, info, LevelFilter};
use rpcbinder::{RpcServer, RpcSession};
use openssl::{ec::EcKey, sha::sha256, ecdsa::EcdsaSig};
@@ -35,6 +34,7 @@
use std::ptr::{self, NonNull};
use std::sync::{
atomic::{AtomicBool, Ordering},
+ LazyLock,
Mutex,
};
use vm_payload_status_bindgen::AVmAttestationStatus;
@@ -42,13 +42,11 @@
/// Maximum size of an ECDSA signature for EC P-256 key is 72 bytes.
const MAX_ECDSA_P256_SIGNATURE_SIZE: usize = 72;
-lazy_static! {
- static ref VM_APK_CONTENTS_PATH_C: CString =
- CString::new(VM_APK_CONTENTS_PATH).expect("CString::new failed");
- static ref PAYLOAD_CONNECTION: Mutex<Option<Strong<dyn IVmPayloadService>>> = Mutex::default();
- static ref VM_ENCRYPTED_STORAGE_PATH_C: CString =
- CString::new(ENCRYPTEDSTORE_MOUNTPOINT).expect("CString::new failed");
-}
+static VM_APK_CONTENTS_PATH_C: LazyLock<CString> =
+ LazyLock::new(|| CString::new(VM_APK_CONTENTS_PATH).expect("CString::new failed"));
+static PAYLOAD_CONNECTION: Mutex<Option<Strong<dyn IVmPayloadService>>> = Mutex::new(None);
+static VM_ENCRYPTED_STORAGE_PATH_C: LazyLock<CString> =
+ LazyLock::new(|| CString::new(ENCRYPTEDSTORE_MOUNTPOINT).expect("CString::new failed"));
static ALREADY_NOTIFIED: AtomicBool = AtomicBool::new(false);