Merge "Remove unnecessary mount points"
diff --git a/apex/Android.bp b/apex/Android.bp
index 0985577..50c17f6 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -29,6 +29,7 @@
binaries: [
"assemble_cvd",
"virtmanager",
+ "vm",
],
filesystems: ["microdroid"],
}
diff --git a/authfs/src/main.rs b/authfs/src/main.rs
index 74553f5..41b922d 100644
--- a/authfs/src/main.rs
+++ b/authfs/src/main.rs
@@ -27,7 +27,7 @@
//! Regardless of the actual file name, the exposed file names through AuthFS are currently integer,
//! e.g. /mountpoint/42.
-use anyhow::{anyhow, bail, Result};
+use anyhow::{bail, Context, Result};
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Read;
@@ -180,9 +180,7 @@
fn new_config_remote_verified_file(remote_id: i32, file_size: u64) -> Result<FileConfig> {
let service = remote_file::server::get_local_service();
- let signature = service
- .readFsveritySignature(remote_id)
- .map_err(|e| anyhow!("Failed to read signature: {}", e.get_description()))?;
+ let signature = service.readFsveritySignature(remote_id).context("Failed to read signature")?;
let service = Arc::new(Mutex::new(service));
let authenticator = FakeAuthenticator::always_succeed();
diff --git a/virtmanager/src/aidl.rs b/virtmanager/src/aidl.rs
new file mode 100644
index 0000000..8394e36
--- /dev/null
+++ b/virtmanager/src/aidl.rs
@@ -0,0 +1,96 @@
+// Copyright 2021, 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.
+
+//! Implementation of the AIDL interface of the Virt Manager.
+
+use crate::config::load_vm_config;
+use crate::crosvm::VmInstance;
+use crate::{Cid, FIRST_GUEST_CID};
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
+ BnVirtualMachine, IVirtualMachine,
+};
+use android_system_virtmanager::binder::{self, Interface, StatusCode, Strong};
+use log::error;
+use std::sync::{Arc, Mutex};
+
+pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
+
+/// Implementation of `IVirtManager`, the entry point of the AIDL service.
+#[derive(Debug, Default)]
+pub struct VirtManager {
+ state: Mutex<State>,
+}
+
+impl Interface for VirtManager {}
+
+impl IVirtManager for VirtManager {
+ /// Create and start a new VM with the given configuration, assigning it the next available CID.
+ ///
+ /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
+ fn startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> {
+ let state = &mut *self.state.lock().unwrap();
+ let cid = state.next_cid;
+ let instance = start_vm(config_path, cid)?;
+ // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
+ state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
+ Ok(VirtualMachine::create(Arc::new(instance)))
+ }
+}
+
+/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
+#[derive(Debug)]
+struct VirtualMachine {
+ instance: Arc<VmInstance>,
+}
+
+impl VirtualMachine {
+ fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
+ let binder = VirtualMachine { instance };
+ BnVirtualMachine::new_binder(binder)
+ }
+}
+
+impl Interface for VirtualMachine {}
+
+impl IVirtualMachine for VirtualMachine {
+ fn getCid(&self) -> binder::Result<i32> {
+ Ok(self.instance.cid as i32)
+ }
+}
+
+/// The mutable state of the Virt Manager. There should only be one instance of this struct.
+#[derive(Debug)]
+struct State {
+ next_cid: Cid,
+}
+
+impl Default for State {
+ fn default() -> Self {
+ State { next_cid: FIRST_GUEST_CID }
+ }
+}
+
+/// Start a new VM instance from the given VM config filename. This assumes the VM is not already
+/// running.
+fn start_vm(config_path: &str, cid: Cid) -> binder::Result<VmInstance> {
+ let config = load_vm_config(config_path).map_err(|e| {
+ error!("Failed to load VM config {}: {:?}", config_path, e);
+ StatusCode::BAD_VALUE
+ })?;
+ Ok(VmInstance::start(&config, cid).map_err(|e| {
+ error!("Failed to start VM {}: {:?}", config_path, e);
+ StatusCode::UNKNOWN_ERROR
+ })?)
+}
diff --git a/virtmanager/src/config.rs b/virtmanager/src/config.rs
new file mode 100644
index 0000000..c0d23f0
--- /dev/null
+++ b/virtmanager/src/config.rs
@@ -0,0 +1,68 @@
+// Copyright 2021, 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.
+
+//! Function and types for VM configuration.
+
+use anyhow::{bail, Context, Error};
+use serde::{Deserialize, Serialize};
+use std::fs::File;
+use std::io::BufReader;
+
+/// Configuration for a particular VM to be started.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct VmConfig {
+ /// The filename of the kernel image, if any.
+ pub kernel: Option<String>,
+ /// The filename of the initial ramdisk for the kernel, if any.
+ pub initrd: Option<String>,
+ /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
+ /// just a string, but typically it will contain multiple parameters separated by spaces.
+ pub params: Option<String>,
+ /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
+ /// the bootloader is instead responsibly for loading the kernel from one of the disks.
+ pub bootloader: Option<String>,
+ /// Disk images to be made available to the VM.
+ #[serde(default)]
+ pub disks: Vec<DiskImage>,
+}
+
+impl VmConfig {
+ /// Ensure that the configuration has a valid combination of fields set, or return an error if
+ /// not.
+ pub fn validate(&self) -> Result<(), Error> {
+ if self.bootloader.is_none() && self.kernel.is_none() {
+ bail!("VM must have either a bootloader or a kernel image.");
+ }
+ if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
+ bail!("Can't have both bootloader and kernel/initrd image.");
+ }
+ Ok(())
+ }
+}
+
+/// A disk image to be made available to the VM.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct DiskImage {
+ /// The filename of the disk image.
+ pub image: String,
+ /// Whether this disk should be writable by the VM.
+ pub writable: bool,
+}
+
+/// Load the configuration for the VM with the given ID from a JSON file.
+pub fn load_vm_config(path: &str) -> Result<VmConfig, Error> {
+ let file = File::open(path).with_context(|| format!("Failed to open {}", path))?;
+ let buffered = BufReader::new(file);
+ Ok(serde_json::from_reader(buffered)?)
+}
diff --git a/virtmanager/src/crosvm.rs b/virtmanager/src/crosvm.rs
new file mode 100644
index 0000000..057b791
--- /dev/null
+++ b/virtmanager/src/crosvm.rs
@@ -0,0 +1,90 @@
+// Copyright 2021, 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.
+
+//! Functions for running instances of `crosvm`.
+
+use crate::config::VmConfig;
+use crate::Cid;
+use anyhow::Error;
+use log::{debug, error, info};
+use std::process::{Child, Command};
+
+const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
+
+/// Information about a particular instance of a VM which is running.
+#[derive(Debug)]
+pub struct VmInstance {
+ /// The crosvm child process.
+ child: Child,
+ /// The CID assigned to the VM for vsock communication.
+ pub cid: Cid,
+}
+
+impl VmInstance {
+ /// Create a new `VmInstance` for the given process.
+ fn new(child: Child, cid: Cid) -> VmInstance {
+ VmInstance { child, cid }
+ }
+
+ /// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
+ /// the `VmInstance` is dropped.
+ pub fn start(config: &VmConfig, cid: Cid) -> Result<VmInstance, Error> {
+ let child = run_vm(config, cid)?;
+ Ok(VmInstance::new(child, cid))
+ }
+}
+
+impl Drop for VmInstance {
+ fn drop(&mut self) {
+ debug!("Dropping {:?}", self);
+ // TODO: Talk to crosvm to shutdown cleanly.
+ if let Err(e) = self.child.kill() {
+ error!("Error killing crosvm instance: {}", e);
+ }
+ // We need to wait on the process after killing it to avoid zombies.
+ match self.child.wait() {
+ Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
+ Ok(status) => info!("Crosvm exited with status {}", status),
+ }
+ }
+}
+
+/// Start an instance of `crosvm` to manage a new VM.
+fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, Error> {
+ config.validate()?;
+
+ let mut command = Command::new(CROSVM_PATH);
+ // TODO(qwandor): Remove --disable-sandbox.
+ command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
+ // TODO(jiyong): Don't redirect console to the host syslog
+ command.arg("--serial=type=syslog");
+ if let Some(bootloader) = &config.bootloader {
+ command.arg("--bios").arg(bootloader);
+ }
+ if let Some(initrd) = &config.initrd {
+ command.arg("--initrd").arg(initrd);
+ }
+ if let Some(params) = &config.params {
+ command.arg("--params").arg(params);
+ }
+ for disk in &config.disks {
+ command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(&disk.image);
+ }
+ if let Some(kernel) = &config.kernel {
+ command.arg(kernel);
+ }
+ info!("Running {:?}", command);
+ // TODO: Monitor child process, and remove from VM map if it dies.
+ Ok(command.spawn()?)
+}
diff --git a/virtmanager/src/main.rs b/virtmanager/src/main.rs
index bdb89d2..7cca4a9 100644
--- a/virtmanager/src/main.rs
+++ b/virtmanager/src/main.rs
@@ -14,200 +14,27 @@
//! Android Virt Manager
-use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::{
- BnVirtManager, IVirtManager,
-};
-use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
- BnVirtualMachine, IVirtualMachine,
-};
-use android_system_virtmanager::binder::{self, add_service, Interface, StatusCode, Strong};
-use anyhow::{bail, Context, Error};
-use log::{debug, error, info};
-use serde::{Deserialize, Serialize};
-use std::fs::File;
-use std::io::BufReader;
-use std::process::{Child, Command};
-use std::sync::{Arc, Mutex};
+mod aidl;
+mod config;
+mod crosvm;
+
+use crate::aidl::{VirtManager, BINDER_SERVICE_IDENTIFIER};
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::BnVirtManager;
+use android_system_virtmanager::binder::{add_service, ProcessState};
+use log::info;
/// The first CID to assign to a guest VM managed by the Virt Manager. CIDs lower than this are
/// reserved for the host or other usage.
const FIRST_GUEST_CID: Cid = 10;
-const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
-const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
-
/// The unique ID of a VM used (together with a port number) for vsock communication.
type Cid = u32;
-/// Configuration for a particular VM to be started.
-#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
-struct VmConfig {
- kernel: Option<String>,
- initrd: Option<String>,
- params: Option<String>,
- bootloader: Option<String>,
- #[serde(default)]
- disks: Vec<DiskImage>,
-}
-
-/// A disk image to be made available to the VM.
-#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
-struct DiskImage {
- image: String,
- writable: bool,
-}
-
fn main() {
env_logger::init();
- let state = Arc::new(Mutex::new(State::new()));
- let virt_manager = VirtManager::new(state);
+ let virt_manager = VirtManager::default();
let virt_manager = BnVirtManager::new_binder(virt_manager);
add_service(BINDER_SERVICE_IDENTIFIER, virt_manager.as_binder()).unwrap();
info!("Registered Binder service, joining threadpool.");
- binder::ProcessState::join_thread_pool();
-}
-
-#[derive(Debug)]
-struct VirtManager {
- state: Arc<Mutex<State>>,
-}
-
-impl VirtManager {
- fn new(state: Arc<Mutex<State>>) -> Self {
- VirtManager { state }
- }
-}
-
-impl Interface for VirtManager {}
-
-impl IVirtManager for VirtManager {
- /// Create and start a new VM with the given configuration, assigning it the next available CID.
- ///
- /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
- fn startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> {
- let state = &mut *self.state.lock().unwrap();
- let cid = state.next_cid;
- let child = start_vm(config_path, cid)?;
- // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
- state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
- Ok(VirtualMachine::create(Arc::new(VmInstance::new(child, cid))))
- }
-}
-
-/// Implementation of the AIDL IVirtualMachine interface. Used as a handle to a VM.
-#[derive(Debug)]
-struct VirtualMachine {
- instance: Arc<VmInstance>,
-}
-
-impl VirtualMachine {
- fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
- let binder = VirtualMachine { instance };
- BnVirtualMachine::new_binder(binder)
- }
-}
-
-impl Interface for VirtualMachine {}
-
-impl IVirtualMachine for VirtualMachine {
- fn getCid(&self) -> binder::Result<i32> {
- Ok(self.instance.cid as i32)
- }
-}
-
-/// Information about a particular instance of a VM which is running.
-#[derive(Debug)]
-struct VmInstance {
- /// The crosvm child process.
- child: Child,
- /// The CID assigned to the VM for vsock communication.
- cid: Cid,
-}
-
-impl VmInstance {
- /// Create a new `VmInstance` with a single reference for the given process.
- fn new(child: Child, cid: Cid) -> VmInstance {
- VmInstance { child, cid }
- }
-}
-
-impl Drop for VmInstance {
- fn drop(&mut self) {
- debug!("Dropping {:?}", self);
- // TODO: Talk to crosvm to shutdown cleanly.
- if let Err(e) = self.child.kill() {
- error!("Error killing crosvm instance: {}", e);
- }
- // We need to wait on the process after killing it to avoid zombies.
- match self.child.wait() {
- Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
- Ok(status) => info!("Crosvm exited with status {}", status),
- }
- }
-}
-
-/// The mutable state of the Virt Manager. There should only be one instance of this struct.
-#[derive(Debug)]
-struct State {
- next_cid: Cid,
-}
-
-impl State {
- fn new() -> Self {
- State { next_cid: FIRST_GUEST_CID }
- }
-}
-
-/// Start a new VM instance from the given VM config filename. This assumes the VM is not already
-/// running.
-fn start_vm(config_path: &str, cid: Cid) -> binder::Result<Child> {
- let config = load_vm_config(config_path).map_err(|e| {
- error!("Failed to load VM config {}: {:?}", config_path, e);
- StatusCode::BAD_VALUE
- })?;
- Ok(run_vm(&config, cid).map_err(|e| {
- error!("Failed to start VM {}: {:?}", config_path, e);
- StatusCode::UNKNOWN_ERROR
- })?)
-}
-
-/// Load the configuration for the VM with the given ID from a JSON file.
-fn load_vm_config(path: &str) -> Result<VmConfig, Error> {
- let file = File::open(path).with_context(|| format!("Failed to open {}", path))?;
- let buffered = BufReader::new(file);
- Ok(serde_json::from_reader(buffered)?)
-}
-
-/// Start an instance of `crosvm` to manage a new VM.
-fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, Error> {
- if config.bootloader.is_none() && config.kernel.is_none() {
- bail!("VM must have either a bootloader or a kernel image.");
- }
- if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
- bail!("Can't have both bootloader and kernel/initrd image.");
- }
-
- let mut command = Command::new(CROSVM_PATH);
- // TODO(qwandor): Remove --disable-sandbox.
- command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
- // TODO(jiyong): Don't redirect console to the host syslog
- command.arg("--serial=type=syslog");
- if let Some(bootloader) = &config.bootloader {
- command.arg("--bios").arg(bootloader);
- }
- if let Some(initrd) = &config.initrd {
- command.arg("--initrd").arg(initrd);
- }
- if let Some(params) = &config.params {
- command.arg("--params").arg(params);
- }
- for disk in &config.disks {
- command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(&disk.image);
- }
- if let Some(kernel) = &config.kernel {
- command.arg(kernel);
- }
- info!("Running {:?}", command);
- // TODO: Monitor child process, and remove from VM map if it dies.
- Ok(command.spawn()?)
+ ProcessState::join_thread_pool();
}
diff --git a/vm/Android.bp b/vm/Android.bp
new file mode 100644
index 0000000..8fe7ae9
--- /dev/null
+++ b/vm/Android.bp
@@ -0,0 +1,16 @@
+rust_binary {
+ name: "vm",
+ crate_name: "vm",
+ srcs: ["src/main.rs"],
+ edition: "2018",
+ rustlibs: [
+ "android.system.virtmanager-rust",
+ "libanyhow",
+ "libbinder_rs",
+ "libenv_logger",
+ "liblog_rust",
+ ],
+ apex_available: [
+ "com.android.virt",
+ ],
+}
diff --git a/vm/src/main.rs b/vm/src/main.rs
new file mode 100644
index 0000000..1e642cb
--- /dev/null
+++ b/vm/src/main.rs
@@ -0,0 +1,78 @@
+// Copyright 2021, 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.
+
+//! Android VM control tool.
+
+mod sync;
+
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
+use android_system_virtmanager::binder::{get_interface, ProcessState, Strong};
+use anyhow::{bail, Context, Error};
+// TODO: Import these via android_system_virtmanager::binder once https://r.android.com/1619403 is
+// submitted.
+use binder::{DeathRecipient, IBinder};
+use std::env;
+use std::process::exit;
+use sync::AtomicFlag;
+
+const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
+
+fn main() -> Result<(), Error> {
+ env_logger::init();
+
+ let args: Vec<_> = env::args().collect();
+ if args.len() < 2 {
+ eprintln!("Usage:");
+ eprintln!(" {} run <vm_config.json>", args[0]);
+ exit(1);
+ }
+
+ // We need to start the thread pool for Binder to work properly, especially link_to_death.
+ ProcessState::start_thread_pool();
+
+ match args[1].as_ref() {
+ "run" if args.len() == 3 => command_run(&args[2]),
+ command => bail!("Invalid command '{}' or wrong number of arguments", command),
+ }
+}
+
+/// Run a VM from the given configuration file.
+fn command_run(config_filename: &str) -> Result<(), Error> {
+ let virt_manager: Strong<dyn IVirtManager> =
+ get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
+ .with_context(|| "Failed to find Virt Manager service")?;
+ let vm = virt_manager.startVm(config_filename).with_context(|| "Failed to start VM")?;
+ let cid = vm.getCid().with_context(|| "Failed to get CID")?;
+ println!("Started VM from {} with CID {}.", config_filename, cid);
+
+ // Wait until the VM dies. If we just returned immediately then the IVirtualMachine Binder
+ // object would be dropped and the VM would be killed.
+ wait_for_death(&mut vm.as_binder())?;
+ println!("VM died");
+ Ok(())
+}
+
+/// Block until the given Binder object dies.
+fn wait_for_death(binder: &mut impl IBinder) -> Result<(), Error> {
+ let dead = AtomicFlag::default();
+ let mut death_recipient = {
+ let dead = dead.clone();
+ DeathRecipient::new(move || {
+ dead.raise();
+ })
+ };
+ binder.link_to_death(&mut death_recipient)?;
+ dead.wait();
+ Ok(())
+}
diff --git a/vm/src/sync.rs b/vm/src/sync.rs
new file mode 100644
index 0000000..82839b3
--- /dev/null
+++ b/vm/src/sync.rs
@@ -0,0 +1,46 @@
+// Copyright 2021, 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.
+
+//! Synchronisation utilities.
+
+use std::sync::{Arc, Condvar, Mutex};
+
+/// A flag which one thread can use to notify other threads when a condition becomes true. This is
+/// something like a single-use binary semaphore.
+#[derive(Clone, Debug)]
+pub struct AtomicFlag {
+ state: Arc<(Mutex<bool>, Condvar)>,
+}
+
+impl Default for AtomicFlag {
+ #[allow(clippy::mutex_atomic)]
+ fn default() -> Self {
+ Self { state: Arc::new((Mutex::new(false), Condvar::new())) }
+ }
+}
+
+#[allow(clippy::mutex_atomic)]
+impl AtomicFlag {
+ /// Wait until the flag is set.
+ pub fn wait(&self) {
+ let _flag = self.state.1.wait_while(self.state.0.lock().unwrap(), |flag| !*flag).unwrap();
+ }
+
+ /// Set the flag, and notify all waiting threads.
+ pub fn raise(&self) {
+ let mut flag = self.state.0.lock().unwrap();
+ *flag = true;
+ self.state.1.notify_all();
+ }
+}