base/
lib.rs

1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Safe, cross-platform-compatible wrappers for system interfaces.
6
7mod alloc;
8mod clock;
9pub mod custom_serde;
10pub mod descriptor;
11pub mod descriptor_reflection;
12mod errno;
13mod event;
14mod file_traits;
15mod iobuf;
16mod mmap;
17mod notifiers;
18mod periodic_logger;
19mod shm;
20pub mod syslog;
21pub mod test_utils;
22mod timer;
23mod tube;
24mod types;
25mod volatile_memory;
26mod wait_context;
27mod worker_thread;
28mod write_zeroes;
29
30pub mod sys;
31pub use alloc::LayoutAllocation;
32
33pub use clock::Clock;
34pub use clock::FakeClock;
35pub use errno::errno_result;
36pub use errno::Error;
37pub use errno::Result;
38pub use event::Event;
39pub use event::EventWaitResult;
40pub use file_traits::FileAllocate;
41pub use file_traits::FileGetLen;
42pub use file_traits::FileReadWriteAtVolatile;
43pub use file_traits::FileReadWriteVolatile;
44pub use file_traits::FileSetLen;
45pub use file_traits::FileSync;
46pub use iobuf::IoBufMut;
47pub use mmap::Error as MmapError;
48pub use mmap::ExternalMapping;
49pub use mmap::MappedRegion;
50pub use mmap::MemoryMapping;
51pub use mmap::MemoryMappingBuilder;
52pub use mmap::Result as MmapResult;
53pub use notifiers::CloseNotifier;
54pub use notifiers::ReadNotifier;
55pub use platform::ioctl::ioctl;
56pub use platform::ioctl::ioctl_with_mut_ptr;
57pub use platform::ioctl::ioctl_with_mut_ref;
58pub use platform::ioctl::ioctl_with_ptr;
59pub use platform::ioctl::ioctl_with_ref;
60pub use platform::ioctl::ioctl_with_val;
61pub use platform::ioctl::IoctlNr;
62pub use shm::SharedMemory;
63use sys::platform;
64pub use timer::FakeTimer;
65pub use timer::Timer;
66pub use timer::TimerTrait;
67pub use tube::Error as TubeError;
68#[cfg(any(windows, feature = "proto_tube"))]
69pub use tube::ProtoTube;
70pub use tube::RecvTube;
71pub use tube::Result as TubeResult;
72pub use tube::SendTube;
73pub use tube::Tube;
74pub use types::fold_into_i32;
75pub use types::NegativeI32;
76pub use types::U31;
77pub use volatile_memory::VolatileMemory;
78pub use volatile_memory::VolatileMemoryError;
79pub use volatile_memory::VolatileMemoryResult;
80pub use volatile_memory::VolatileSlice;
81pub use wait_context::EventToken;
82pub use wait_context::EventType;
83pub use wait_context::TriggeredEvent;
84pub use wait_context::WaitContext;
85pub use worker_thread::WorkerThread;
86pub use write_zeroes::PunchHole;
87pub use write_zeroes::WriteZeroesAt;
88
89// TODO(b/233233301): reorganize platform specific exports under platform
90// namespaces instead of exposing them directly in base::.
91cfg_if::cfg_if! {
92    if #[cfg(any(target_os = "android", target_os = "linux"))] {
93        pub use sys::linux;
94
95        // descriptor/fd related exports.
96        pub use linux::{
97            clear_descriptor_cloexec, clone_descriptor, open_how, openat2,
98            safe_descriptor_from_cmdline_fd, safe_descriptor_from_path, validate_raw_descriptor,
99        };
100
101        // Event/signal related exports.
102        pub use linux::{
103            block_signal, clear_signal, get_blocked_signals, new_pipe_full,
104            register_rt_signal_handler, signal, unblock_signal, Killable, SIGRTMIN,
105            SignalFd, Terminal,
106        };
107
108        pub use linux::{
109            drop_capabilities, pipe, read_raw_stdin
110        };
111        pub use linux::{enable_core_scheduling, set_rt_prio_limit, set_rt_round_robin};
112        pub use linux::{flock, FlockOperation};
113        pub use linux::{getegid, geteuid};
114        pub use linux::{gettid, kill_process_group, reap_child};
115        pub use linux::logical_core_capacity;
116        pub use linux::logical_core_cluster_id;
117        pub use linux::logical_core_frequencies_khz;
118        pub use linux::logical_core_max_freq_khz;
119        pub use linux::is_cpu_online;
120        pub use linux::sched_attr;
121        pub use linux::sched_setattr;
122        pub use linux::UnlinkUnixListener;
123        pub use linux::EventExt;
124        pub use linux::Gid;
125    }
126}
127
128cfg_if::cfg_if! {
129     if #[cfg(windows)] {
130        pub use sys::windows;
131
132        pub use windows::{EventTrigger, EventExt, WaitContextExt};
133        pub use windows::IoBuf;
134        pub use windows::MemoryMappingBuilderWindows;
135        pub use windows::set_thread_priority;
136        pub use windows::{give_foregrounding_permission, Console};
137        pub use windows::{named_pipes, named_pipes::PipeConnection};
138        pub use windows::{SafeMultimediaHandle, MAXIMUM_WAIT_OBJECTS};
139        pub use windows::set_sparse_file;
140        pub use windows::ioctl::ioctl_with_ptr_sized;
141        pub use windows::create_overlapped;
142        pub use windows::device_io_control;
143        pub use windows::is_cpu_online;
144        pub use windows::number_of_logical_cores;
145        pub use windows::number_of_online_cores;
146        pub use windows::pagesize;
147        pub use windows::read_overlapped_blocking;
148
149        pub use tube::{
150            deserialize_and_recv, serialize_and_send, set_alias_pid, set_duplicate_handle_tube,
151            DuplicateHandleRequest, DuplicateHandleResponse, DuplicateHandleTube
152        };
153        pub use tube::PipeTube;
154        pub use tube::FlushOnDropTube;
155        pub use windows::{set_audio_thread_priority, thread};
156        pub use windows::Pid;
157        pub use windows::Terminal;
158    }
159}
160
161cfg_if::cfg_if! {
162    if #[cfg(unix)] {
163        pub use sys::unix;
164
165        pub use unix::IoBuf;
166        pub use unix::net::UnixSeqpacket;
167        pub use unix::net::UnixSeqpacketListener;
168        pub use unix::net::UnlinkUnixSeqpacketListener;
169        pub use unix::ScmSocket;
170        pub use unix::SCM_SOCKET_MAX_FD_COUNT;
171        pub use unix::add_fd_flags;
172        pub use unix::clear_fd_flags;
173        pub use unix::number_of_logical_cores;
174        pub use unix::number_of_online_cores;
175        pub use unix::pagesize;
176        pub use unix::Pid;
177    }
178}
179
180pub use descriptor_reflection::deserialize_with_descriptors;
181pub use descriptor_reflection::with_as_descriptor;
182pub use descriptor_reflection::with_raw_descriptor;
183pub use descriptor_reflection::FileSerdeWrapper;
184pub use descriptor_reflection::SerializeDescriptors;
185pub use log::debug;
186pub use log::error;
187pub use log::info;
188pub use log::trace;
189pub use log::warn;
190pub use mmap::Protection;
191pub use platform::get_cpu_affinity;
192pub use platform::getpid;
193pub use platform::open_file_or_duplicate;
194pub use platform::platform_timer_resolution::enable_high_res_timers;
195pub use platform::set_cpu_affinity;
196pub use platform::set_thread_name;
197pub use platform::BlockingMode;
198pub use platform::EventContext;
199pub use platform::FramingMode;
200pub use platform::MemoryMappingArena;
201pub use platform::RawDescriptor;
202pub use platform::StreamChannel;
203pub use platform::INVALID_DESCRIPTOR;
204use uuid::Uuid;
205
206pub use crate::descriptor::AsRawDescriptor;
207pub use crate::descriptor::AsRawDescriptors;
208pub use crate::descriptor::Descriptor;
209pub use crate::descriptor::FromRawDescriptor;
210pub use crate::descriptor::IntoRawDescriptor;
211pub use crate::descriptor::SafeDescriptor;
212
213/// An empty trait that helps reset timer resolution to its previous state.
214// TODO(b:232103460): Maybe this needs to be thought through.
215pub trait EnabledHighResTimer {}
216
217/// Creates a UUID.
218pub fn generate_uuid() -> String {
219    let mut buf = Uuid::encode_buffer();
220    Uuid::new_v4()
221        .as_hyphenated()
222        .encode_lower(&mut buf)
223        .to_owned()
224}
225
226use serde::Deserialize;
227use serde::Serialize;
228#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
229pub enum VmEventType {
230    Exit,
231    Reset,
232    DeviceCrashed,
233    Crash,
234    GuestPanic,
235    Panic(u8),
236    WatchdogReset,
237}
238
239/// Uses the system's page size in bytes to round the given value up to the nearest page boundary.
240#[inline(always)]
241pub fn round_up_to_page_size(v: usize) -> usize {
242    let page_mask = pagesize() - 1;
243    (v + page_mask) & !page_mask
244}