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            clone_descriptor, safe_descriptor_from_path,
98            validate_raw_descriptor, clear_descriptor_cloexec,
99            safe_descriptor_from_cmdline_fd,
100        };
101
102        // Event/signal related exports.
103        pub use linux::{
104            block_signal, clear_signal, get_blocked_signals, new_pipe_full,
105            register_rt_signal_handler, signal, unblock_signal, Killable, SIGRTMIN,
106            AcpiNotifyEvent, NetlinkGenericSocket, SignalFd, Terminal,
107        };
108
109        pub use linux::{
110            drop_capabilities, pipe, read_raw_stdin
111        };
112        pub use linux::{enable_core_scheduling, set_rt_prio_limit, set_rt_round_robin};
113        pub use linux::{flock, FlockOperation};
114        pub use linux::{getegid, geteuid};
115        pub use linux::{gettid, kill_process_group, reap_child};
116        pub use linux::logical_core_capacity;
117        pub use linux::logical_core_cluster_id;
118        pub use linux::logical_core_frequencies_khz;
119        pub use linux::logical_core_max_freq_khz;
120        pub use linux::is_cpu_online;
121        pub use linux::sched_attr;
122        pub use linux::sched_setattr;
123        pub use linux::UnlinkUnixListener;
124        pub use linux::EventExt;
125        pub use linux::Gid;
126    }
127}
128
129cfg_if::cfg_if! {
130     if #[cfg(windows)] {
131        pub use sys::windows;
132
133        pub use windows::{EventTrigger, EventExt, WaitContextExt};
134        pub use windows::IoBuf;
135        pub use windows::MemoryMappingBuilderWindows;
136        pub use windows::set_thread_priority;
137        pub use windows::{give_foregrounding_permission, Console};
138        pub use windows::{named_pipes, named_pipes::PipeConnection};
139        pub use windows::{SafeMultimediaHandle, MAXIMUM_WAIT_OBJECTS};
140        pub use windows::set_sparse_file;
141        pub use windows::ioctl::ioctl_with_ptr_sized;
142        pub use windows::create_overlapped;
143        pub use windows::device_io_control;
144        pub use windows::is_cpu_online;
145        pub use windows::number_of_logical_cores;
146        pub use windows::number_of_online_cores;
147        pub use windows::pagesize;
148        pub use windows::read_overlapped_blocking;
149
150        pub use tube::{
151            deserialize_and_recv, serialize_and_send, set_alias_pid, set_duplicate_handle_tube,
152            DuplicateHandleRequest, DuplicateHandleResponse, DuplicateHandleTube
153        };
154        pub use tube::PipeTube;
155        pub use tube::FlushOnDropTube;
156        pub use windows::{set_audio_thread_priority, thread};
157        pub use windows::Pid;
158        pub use windows::Terminal;
159    }
160}
161
162cfg_if::cfg_if! {
163    if #[cfg(unix)] {
164        pub use sys::unix;
165
166        pub use unix::IoBuf;
167        pub use unix::net::UnixSeqpacket;
168        pub use unix::net::UnixSeqpacketListener;
169        pub use unix::net::UnlinkUnixSeqpacketListener;
170        pub use unix::ScmSocket;
171        pub use unix::SCM_SOCKET_MAX_FD_COUNT;
172        pub use unix::add_fd_flags;
173        pub use unix::clear_fd_flags;
174        pub use unix::number_of_logical_cores;
175        pub use unix::number_of_online_cores;
176        pub use unix::pagesize;
177        pub use unix::Pid;
178    }
179}
180
181pub use descriptor_reflection::deserialize_with_descriptors;
182pub use descriptor_reflection::with_as_descriptor;
183pub use descriptor_reflection::with_raw_descriptor;
184pub use descriptor_reflection::FileSerdeWrapper;
185pub use descriptor_reflection::SerializeDescriptors;
186pub use log::debug;
187pub use log::error;
188pub use log::info;
189pub use log::trace;
190pub use log::warn;
191pub use mmap::Protection;
192pub use platform::get_cpu_affinity;
193pub use platform::getpid;
194pub use platform::open_file_or_duplicate;
195pub use platform::platform_timer_resolution::enable_high_res_timers;
196pub use platform::set_cpu_affinity;
197pub use platform::set_thread_name;
198pub use platform::BlockingMode;
199pub use platform::EventContext;
200pub use platform::FramingMode;
201pub use platform::MemoryMappingArena;
202pub use platform::RawDescriptor;
203pub use platform::StreamChannel;
204pub use platform::INVALID_DESCRIPTOR;
205use uuid::Uuid;
206
207pub use crate::descriptor::AsRawDescriptor;
208pub use crate::descriptor::AsRawDescriptors;
209pub use crate::descriptor::Descriptor;
210pub use crate::descriptor::FromRawDescriptor;
211pub use crate::descriptor::IntoRawDescriptor;
212pub use crate::descriptor::SafeDescriptor;
213
214/// An empty trait that helps reset timer resolution to its previous state.
215// TODO(b:232103460): Maybe this needs to be thought through.
216pub trait EnabledHighResTimer {}
217
218/// Creates a UUID.
219pub fn generate_uuid() -> String {
220    let mut buf = Uuid::encode_buffer();
221    Uuid::new_v4()
222        .as_hyphenated()
223        .encode_lower(&mut buf)
224        .to_owned()
225}
226
227use serde::Deserialize;
228use serde::Serialize;
229#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
230pub enum VmEventType {
231    Exit,
232    Reset,
233    DeviceCrashed,
234    Crash,
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}