blob: cd0b3a27e00805bd922282c7a24fe8594b6852bd [file]
/*
* Copyright (C) 2026 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(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(missing_docs)]
#![allow(dead_code)]
use std::collections::HashMap;
use std::ffi::CString;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use std::os::raw::{c_char, c_int, c_void};
use std::ptr::{self, NonNull};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::Instant;
// SAFETY: Declaration of external C symbol provided by liblog. Callers must ensure `tag` and `fmt` (and any variadic string arguments) are valid pointers to null-terminated C strings that outlive the call.
unsafe extern "C" {
fn __android_log_print(prio: c_int, tag: *const c_char, fmt: *const c_char, ...) -> c_int;
}
macro_rules! alogd {
($($arg:tt)*) => {
let tag = CString::new("MemoryBudgetWatcher").unwrap();
let msg = CString::new(format!($($arg)*)).unwrap();
let fmt = CString::new("%s").unwrap();
// SAFETY: tag, fmt, and msg are valid, freshly allocated null-terminated CStrings that outlive this call.
unsafe {
__android_log_print(3, tag.as_ptr(), fmt.as_ptr(), msg.as_ptr());
}
};
}
macro_rules! aloge {
($($arg:tt)*) => {
let tag = CString::new("MemoryBudgetWatcher").unwrap();
let msg = CString::new(format!($($arg)*)).unwrap();
let fmt = CString::new("%s").unwrap();
// SAFETY: tag, fmt, and msg are valid, freshly allocated null-terminated CStrings that outlive this call.
unsafe {
__android_log_print(6, tag.as_ptr(), fmt.as_ptr(), msg.as_ptr());
}
};
}
use memory_budget_service_aidl::aidl::android::app::IMemoryBudgetService::IMemoryBudgetService;
// Re-export the types from bindgen.
pub use memorybudgetmanager_bindgen::{
MemoryBudgetEvent, MemoryBudgetResult, MemoryBudgetWatcherEventMask,
};
// Import variants of MemoryBudgetResult for easier use.
use MemoryBudgetResult::*;
/// A safe, reference-counted wrapper around Android's `Looper`
pub struct Looper {
ptr: NonNull<sys::RustLooper>,
}
// SAFETY: Looper is thread-safe by design in Android.
unsafe impl Send for Looper {}
// SAFETY: Looper is thread-safe by design in Android.
unsafe impl Sync for Looper {}
impl Looper {
/// Wraps a raw `Looper` pointer.
///
/// # Safety
///
/// `ptr` must reference a valid `ALooper` / `RustLooper` instance or be null.
pub unsafe fn acquire_raw(ptr: *mut c_void) -> Option<Self> {
// SAFETY: The caller guarantees `ptr` is a valid pointer to a `RustLooper` or null.
let ptr = unsafe { sys::RustLooper_fromRaw(ptr) };
let ptr = NonNull::new(ptr)?;
Some(Self { ptr })
}
/// Gets the looper associated with the current thread, if one exists.
pub fn for_thread() -> Option<Self> {
// SAFETY: `RustLooper_getForThread` safely accesses the thread-local Looper pointer without preconditions.
let ptr = unsafe { sys::RustLooper_getForThread() };
let ptr = NonNull::new(ptr)?;
Some(Self { ptr })
}
/// Checks if the current executing thread is the one driving this Looper.
pub fn is_current_thread(&self) -> bool {
// SAFETY: `self.ptr` is guaranteed to be a valid non-null `RustLooper` pointer.
unsafe { sys::RustLooper_isCurrentThread(self.ptr.as_ptr()) }
}
/// Adds a file descriptor to be polled by the looper.
///
/// # Safety
///
/// - `fd` must be an open, valid file descriptor.
/// - `callback` (if provided) must be safe to call with `data` whenever events are dispatched.
pub unsafe fn add_fd(
&self,
fd: c_int,
ident: c_int,
events: c_int,
callback: sys::Looper_callbackFunc,
data: *mut c_void,
) -> c_int {
// SAFETY: `self.ptr` is a valid `RustLooper` pointer, and the caller guarantees `fd`, `callback`, and `data` safety preconditions.
unsafe { sys::RustLooper_addFd(self.ptr.as_ptr(), fd, ident, events, callback, data) }
}
/// Removes a file descriptor from the looper.
///
/// # Safety
///
/// `fd` must be the file descriptor previously added to this looper.
pub unsafe fn remove_fd(&self, fd: c_int) -> c_int {
// SAFETY: `self.ptr` is a valid `RustLooper` pointer.
unsafe { sys::RustLooper_removeFd(self.ptr.as_ptr(), fd) }
}
}
impl Clone for Looper {
fn clone(&self) -> Self {
// SAFETY: `self.ptr` is a valid non-null `RustLooper` pointer.
let ptr = unsafe { sys::RustLooper_clone(self.ptr.as_ptr()) };
let ptr = NonNull::new(ptr).expect("RustLooper_clone returned null");
Self { ptr }
}
}
impl Drop for Looper {
fn drop(&mut self) {
// SAFETY: `self.ptr` is a valid non-null `RustLooper` pointer being released.
unsafe { sys::RustLooper_free(self.ptr.as_ptr()) };
}
}
mod sys {
use std::os::raw::{c_int, c_void};
// Opaque type
#[repr(C)]
pub struct RustLooper {
_unused: [u8; 0],
}
pub type Looper_callbackFunc =
Option<unsafe extern "C" fn(fd: c_int, events: c_int, data: *mut c_void) -> c_int>;
pub const ALOOPER_POLL_CALLBACK: c_int = -2;
pub const ALOOPER_EVENT_INPUT: c_int = 1 << 0;
pub const ALOOPER_EVENT_ERROR: c_int = 1 << 2;
pub const ALOOPER_EVENT_HANGUP: c_int = 1 << 3;
// SAFETY: Declarations of external C symbols provided by libmemorybudgetmanager_looper_wrapper.
unsafe extern "C" {
pub fn RustLooper_getForThread() -> *mut RustLooper;
pub fn RustLooper_fromRaw(ptr: *mut c_void) -> *mut RustLooper;
pub fn RustLooper_clone(looper: *mut RustLooper) -> *mut RustLooper;
pub fn RustLooper_free(looper: *mut RustLooper);
pub fn RustLooper_isCurrentThread(looper: *mut RustLooper) -> bool;
pub fn RustLooper_addFd(
looper: *mut RustLooper,
fd: c_int,
ident: c_int,
events: c_int,
callback: Looper_callbackFunc,
data: *mut c_void,
) -> c_int;
pub fn RustLooper_removeFd(looper: *mut RustLooper, fd: c_int) -> c_int;
}
}
// Opaque struct for C.
pub struct MemoryBudgetWatcher {
inner: Arc<WatcherInner>,
}
type MemoryBudgetWatcher_onEventsCallback = Option<
unsafe extern "C" fn(event_mask: i32, event: *const MemoryBudgetEvent, userdata: *mut c_void),
>;
struct WatcherInner {
id: usize,
looper: Looper,
fd_mask: i32,
debounce_millis: u32,
user_callback: MemoryBudgetWatcher_onEventsCallback,
user_data: *mut c_void,
inotify_fd: OwnedFd,
package_wd: Option<c_int>,
process_wd: Option<c_int>,
package_fd: Option<OwnedFd>,
process_fd: Option<OwnedFd>,
state: Mutex<WatcherState>,
cv: Condvar,
}
struct WatcherState {
package_last_trigger_time: Option<Instant>,
process_last_trigger_time: Option<Instant>,
active_callbacks: i32,
destroyed: bool,
delete_pending: bool,
}
// SAFETY: WatcherInner only contains thread-safe types and synchronization primitives.
unsafe impl Send for WatcherInner {}
// SAFETY: WatcherInner state is protected by a Mutex and Looper is thread-safe.
unsafe impl Sync for WatcherInner {}
type WatcherRegistry = Mutex<HashMap<usize, Arc<WatcherInner>>>;
static G_WATCHERS: OnceLock<WatcherRegistry> = OnceLock::new();
fn get_watchers_registry() -> &'static WatcherRegistry {
G_WATCHERS.get_or_init(|| Mutex::new(HashMap::new()))
}
static G_NEXT_WATCHER_ID: Mutex<usize> = Mutex::new(1);
const AID_ISOLATED_START: u32 = 90000;
const AID_ISOLATED_END: u32 = 99999;
const AID_USER_OFFSET: u32 = 100000;
fn is_isolated_process() -> bool {
let uid = rustix::process::getuid().as_raw();
let app_id = uid % AID_USER_OFFSET;
(AID_ISOLATED_START..=AID_ISOLATED_END).contains(&app_id)
}
fn get_cgroup_dir_fd() -> Result<RawFd, MemoryBudgetResult> {
let fd = processgroup::processgroup::cgroup::get_attribute_path_file_descriptor();
if fd < 0 { Err(MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET) } else { Ok(fd) }
}
fn safe_openat(dir_fd: BorrowedFd<'_>, path: &str) -> Result<OwnedFd, c_int> {
rustix::fs::openat(
dir_fd,
path,
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.map_err(|e| e.raw_os_error())
}
fn read_budget_value(mut file: &File) -> std::io::Result<i64> {
file.seek(SeekFrom::Start(0))?;
let mut buf = [0; 64];
let n = file.read(&mut buf)?;
if n == 0 {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "empty file"));
}
let s = std::str::from_utf8(&buf[..n])
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid utf8"))?;
let val_str = s.trim();
if val_str == "max" {
return Ok(i64::MAX);
}
val_str.parse::<i64>().map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
// MemoryBudgetResult implementation
fn status_to_result(val: i32) -> MemoryBudgetResult {
match val {
0 => MEMORY_BUDGET_RESULT_SUCCESS,
-1 => MEMORY_BUDGET_RESULT_LIMIT_IS_DISABLED,
-2 => MEMORY_BUDGET_RESULT_ERROR_INVALID_ARGUMENT,
-3 => MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
-4 => MEMORY_BUDGET_RESULT_ERROR_EXCEEDS_LIMIT,
-5 => MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET,
_ => MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET,
}
}
fn get_user_attribute_path(attr: &str) -> Result<String, c_int> {
let path_opt = processgroup::processgroup::cgroup::get_relative_attribute_path_for_user(attr)
.map_err(|_| libc::ENOTSUP)?;
path_opt.ok_or(libc::ENOTSUP)
}
fn get_process_attribute_path(attr: &str, pid: libc::pid_t) -> Result<String, c_int> {
let path_opt =
processgroup::processgroup::cgroup::get_relative_attribute_path_for_process(attr, pid)
.map_err(|_| libc::ENOTSUP)?;
path_opt.ok_or(libc::ENOTSUP)
}
fn get_memory_budget_service() -> Option<binder::Strong<dyn IMemoryBudgetService>> {
binder::get_interface("memory_budget").ok()
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_setPackageBudgetBytes(
budget_bytes: u64,
) -> MemoryBudgetResult {
if budget_bytes > i64::MAX as u64 {
return MEMORY_BUDGET_RESULT_ERROR_EXCEEDS_LIMIT;
}
let service = match get_memory_budget_service() {
Some(s) => s,
None => return MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
};
match service.setPackageBudget(budget_bytes as i64) {
Ok(result) => status_to_result(result),
Err(_) => MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_setProcessBudgetBytes(
budget_bytes: u64,
) -> MemoryBudgetResult {
if budget_bytes > i64::MAX as u64 {
return MEMORY_BUDGET_RESULT_ERROR_EXCEEDS_LIMIT;
}
let service = match get_memory_budget_service() {
Some(s) => s,
None => return MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
};
match service.setProcessBudget(budget_bytes as i64) {
Ok(result) => status_to_result(result),
Err(_) => MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_clearPackageBudget() -> MemoryBudgetResult {
let service = match get_memory_budget_service() {
Some(s) => s,
None => return MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
};
match service.clearPackageBudget() {
Ok(result) => status_to_result(result),
Err(_) => MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_clearProcessBudget() -> MemoryBudgetResult {
let service = match get_memory_budget_service() {
Some(s) => s,
None => return MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
};
match service.clearProcessBudget() {
Ok(result) => status_to_result(result),
Err(_) => MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED,
}
}
fn get_package_budget_bytes() -> Result<i64, MemoryBudgetResult> {
let dir_fd = get_cgroup_dir_fd()?;
let path_str = get_user_attribute_path("MemHigh")
.map_err(|_| MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET)?;
// SAFETY: `get_attribute_path_file_descriptor()` in libprocessgroup opens and caches the root cgroup directory FD statically for the process lifetime.
let borrowed_dir_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(dir_fd) };
let file = safe_openat(borrowed_dir_fd, &path_str)
.map_err(|_| MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET)?;
let file = File::from(file);
let value = read_budget_value(&file).map_err(|_| MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET)?;
if value == i64::MAX {
return Err(MEMORY_BUDGET_RESULT_LIMIT_IS_DISABLED);
}
Ok(value)
}
/// Gets the package memory budget in bytes.
///
/// # Safety
///
/// `budget_bytes` must be a valid, aligned, non-null pointer pointing to writable memory suitable
/// for storing a `u64`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn MemoryBudgetManager_getPackageBudgetBytes(
budget_bytes: *mut u64,
) -> MemoryBudgetResult {
if budget_bytes.is_null() {
return MEMORY_BUDGET_RESULT_ERROR_INVALID_ARGUMENT;
}
if is_isolated_process() {
return MEMORY_BUDGET_RESULT_ERROR_PERMISSION_DENIED;
}
match get_package_budget_bytes() {
Ok(bb) => {
// SAFETY: The caller guarantees `budget_bytes` is a valid, aligned, non-null pointer to writable memory.
unsafe { *budget_bytes = bb as u64 };
MEMORY_BUDGET_RESULT_SUCCESS
}
Err(err) => err,
}
}
fn get_process_budget_bytes() -> Result<i64, MemoryBudgetResult> {
let dir_fd = get_cgroup_dir_fd()?;
let pid = std::process::id() as libc::pid_t;
let path_str = get_process_attribute_path("MemHigh", pid)
.map_err(|_| MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET)?;
// SAFETY: `get_attribute_path_file_descriptor()` in libprocessgroup opens and caches the root cgroup directory FD statically for the process lifetime.
let borrowed_dir_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(dir_fd) };
let file = safe_openat(borrowed_dir_fd, &path_str)
.map_err(|_| MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET)?;
let file = File::from(file);
let value = read_budget_value(&file).map_err(|_| MEMORY_BUDGET_RESULT_ERROR_READING_BUDGET)?;
if value == i64::MAX {
return Err(MEMORY_BUDGET_RESULT_LIMIT_IS_DISABLED);
}
Ok(value)
}
/// Gets the process memory budget in bytes.
///
/// # Safety
///
/// `budget_bytes` must be a valid, aligned, non-null pointer pointing to writable memory suitable
/// for storing a `u64`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn MemoryBudgetManager_getProcessBudgetBytes(
budget_bytes: *mut u64,
) -> MemoryBudgetResult {
if budget_bytes.is_null() {
return MEMORY_BUDGET_RESULT_ERROR_INVALID_ARGUMENT;
}
match get_process_budget_bytes() {
Ok(bb) => {
// SAFETY: The caller guarantees `budget_bytes` is a valid, aligned, non-null pointer to writable memory.
unsafe { *budget_bytes = bb as u64 };
MEMORY_BUDGET_RESULT_SUCCESS
}
Err(err) => err,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_resultToString(result: i32) -> *const c_char {
let s = match result {
0 => c"Success",
-1 => c"Limit is disabled",
-2 => c"Invalid argument",
-3 => c"Permission denied",
-4 => c"Exceeds manifest or system limit",
-5 => c"Error reading the package or process budget",
_ => c"Unknown AMemoryBudgetResult",
};
s.as_ptr()
}
fn get_package_current_usage_bytes() -> Result<i64, c_int> {
let dir_fd = get_cgroup_dir_fd().map_err(|_| libc::EBADF)?;
let path_str = get_user_attribute_path("MemCurrent")?;
// SAFETY: `get_attribute_path_file_descriptor()` in libprocessgroup opens and caches the root cgroup directory FD statically for the process lifetime.
let borrowed_dir_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(dir_fd) };
let file = match safe_openat(borrowed_dir_fd, &path_str) {
Ok(f) => f,
Err(err) => {
return Err(if err == libc::ENOENT { libc::ENOTSUP } else { err });
}
};
let file = File::from(file);
read_budget_value(&file).map_err(|err| err.raw_os_error().unwrap_or(libc::EINVAL))
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_getPackageCurrentUsageBytes() -> i64 {
if is_isolated_process() {
return -(libc::EPERM as i64);
}
match get_package_current_usage_bytes() {
Ok(val) => val,
Err(err) => -err as i64,
}
}
fn get_process_current_usage_bytes() -> Result<i64, c_int> {
let dir_fd = get_cgroup_dir_fd().map_err(|_| libc::EBADF)?;
let pid = std::process::id() as libc::pid_t;
let path_str = get_process_attribute_path("MemCurrent", pid)?;
// SAFETY: `get_attribute_path_file_descriptor()` in libprocessgroup opens and caches the root cgroup directory FD statically for the process lifetime.
let borrowed_dir_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(dir_fd) };
let file = match safe_openat(borrowed_dir_fd, &path_str) {
Ok(f) => f,
Err(err) => {
return Err(if err == libc::ENOENT { libc::ENOTSUP } else { err });
}
};
let file = File::from(file);
read_budget_value(&file).map_err(|err| err.raw_os_error().unwrap_or(libc::EINVAL))
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_getProcessCurrentUsageBytes() -> i64 {
match get_process_current_usage_bytes() {
Ok(val) => val,
Err(err) => -err as i64,
}
}
fn get_package_memory_events_fd() -> Result<RawFd, c_int> {
let dir_fd = get_cgroup_dir_fd().map_err(|_| libc::EBADF)?;
let path_str = get_user_attribute_path("MemEvents")?;
// SAFETY: `get_attribute_path_file_descriptor()` in libprocessgroup opens and caches the root cgroup directory FD statically for the process lifetime.
let borrowed_dir_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(dir_fd) };
let file = safe_openat(borrowed_dir_fd, &path_str)?;
Ok(file.into_raw_fd())
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_getPackageMemoryEventsFd() -> c_int {
if is_isolated_process() {
return -libc::EPERM;
}
match get_package_memory_events_fd() {
Ok(fd) => fd,
Err(err) => {
if err == libc::ENOENT {
-libc::ENOTSUP
} else {
-err
}
}
}
}
fn get_process_memory_events_fd() -> Result<RawFd, c_int> {
let dir_fd = get_cgroup_dir_fd().map_err(|_| libc::EBADF)?;
let pid = std::process::id() as libc::pid_t;
let path_str = get_process_attribute_path("MemEventsLocal", pid)?;
// SAFETY: `get_attribute_path_file_descriptor()` in libprocessgroup opens and caches the root cgroup directory FD statically for the process lifetime.
let borrowed_dir_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(dir_fd) };
let file = safe_openat(borrowed_dir_fd, &path_str)?;
Ok(file.into_raw_fd())
}
#[unsafe(no_mangle)]
pub extern "C" fn MemoryBudgetManager_getProcessMemoryEventsFd() -> c_int {
match get_process_memory_events_fd() {
Ok(fd) => fd,
Err(err) => {
if err == libc::ENOENT {
-libc::ENOTSUP
} else {
-err
}
}
}
}
fn parse_events_safe(file: &mut File, out_event: &mut MemoryBudgetEvent) -> Result<(), c_int> {
file.seek(SeekFrom::Start(0)).map_err(|err| err.raw_os_error().unwrap_or(libc::EBADF))?;
let mut buf = [0u8; 512];
let n = file.read(&mut buf).map_err(|err| err.raw_os_error().unwrap_or(libc::EIO))?;
if n == 0 {
return Err(libc::EINVAL);
}
let s = std::str::from_utf8(&buf[..n]).map_err(|_| libc::EINVAL)?;
let mut event =
MemoryBudgetEvent { low: 0, high: 0, max: 0, oom: 0, oom_kill: 0, oom_group_kill: 0 };
let mut parsed_count = 0;
for line in s.lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() != 2 {
continue;
}
let key = parts[0];
let val: i64 = match parts[1].parse() {
Ok(v) => v,
Err(_) => continue,
};
match key {
"low" => {
event.low = val;
parsed_count += 1;
}
"high" => {
event.high = val;
parsed_count += 1;
}
"max" => {
event.max = val;
parsed_count += 1;
}
"oom" => {
event.oom = val;
parsed_count += 1;
}
"oom_kill" => {
event.oom_kill = val;
parsed_count += 1;
}
"oom_group_kill" => {
event.oom_group_kill = val;
parsed_count += 1;
}
_ => {}
}
}
if parsed_count == 0 {
return Err(libc::EINVAL);
}
*out_event = event;
Ok(())
}
/// Parses memory budget events from a given cgroup event file descriptor.
///
/// # Safety
///
/// - `fd` must be a valid open file descriptor readable and seekable for memory event data.
/// - `out_event` must be a valid, aligned, non-null pointer pointing to writable memory suitable
/// for storing a `MemoryBudgetEvent`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn MemoryBudgetEvent_parseEvents(
fd: c_int,
out_event: *mut MemoryBudgetEvent,
) -> c_int {
if out_event.is_null() {
return -libc::EINVAL;
}
// SAFETY: `fd` is guaranteed by caller safety contract to be a valid open file descriptor.
let mut file = unsafe { File::from_raw_fd(fd) };
// SAFETY: `out_event` is checked for null and guaranteed by caller safety contract to be valid and aligned.
let res = match parse_events_safe(&mut file, unsafe { &mut *out_event }) {
Ok(_) => 0,
Err(err) => -err,
};
let _ = file.into_raw_fd(); // Prevent close
res
}
fn trigger_event(watcher: &Arc<WatcherInner>, is_package: bool) {
{
let state = watcher.state.lock().unwrap();
if state.destroyed || state.delete_pending {
return;
}
}
let target_fd = if is_package {
watcher.package_fd.as_ref().unwrap().as_raw_fd()
} else {
watcher.process_fd.as_ref().unwrap().as_raw_fd()
};
alogd!("trigger_event called for watcher {}, package={}", watcher.id, is_package);
let mut memevents =
MemoryBudgetEvent { low: 0, high: 0, max: 0, oom: 0, oom_kill: 0, oom_group_kill: 0 };
// SAFETY: `target_fd` is an open, valid file descriptor owned by `watcher.package_fd` or `watcher.process_fd`, and `memevents` is a valid stack-allocated MemoryBudgetEvent struct.
let ret = unsafe { MemoryBudgetEvent_parseEvents(target_fd, &mut memevents) };
if ret >= 0 {
let mut state = watcher.state.lock().unwrap();
if state.destroyed || state.delete_pending {
return;
}
let (fd_mask, last_trigger_time) = if is_package {
(
MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PACKAGE.0,
state.package_last_trigger_time,
)
} else {
(
MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PROCESS.0,
state.process_last_trigger_time,
)
};
let mut should_trigger = true;
if watcher.debounce_millis > 0 {
let now = Instant::now();
if let Some(last) = last_trigger_time {
let duration = now.duration_since(last).as_millis() as u32;
if duration < watcher.debounce_millis {
should_trigger = false;
alogd!(
"Watcher {} event debounced. Duration: {}ms, Debounce: {}ms",
watcher.id,
duration,
watcher.debounce_millis
);
} else if is_package {
state.package_last_trigger_time = Some(now);
} else {
state.process_last_trigger_time = Some(now);
}
} else if is_package {
state.package_last_trigger_time = Some(now);
} else {
state.process_last_trigger_time = Some(now);
}
}
if should_trigger {
drop(state);
if let Some(cb) = watcher.user_callback {
alogd!("Watcher {} calling user callback with mask {}", watcher.id, fd_mask);
// SAFETY: `cb` is the non-null user callback function pointer registered during watcher creation, and `memevents` is a valid reference that outlives this synchronous call.
unsafe {
cb(fd_mask, &memevents, watcher.user_data);
}
}
}
} else {
aloge!("Watcher {} parseEvents failed with ret {}", watcher.id, ret);
}
}
/// Looper callback invoked when events are available on the watched inotify descriptor.
///
/// # Safety
///
/// - `fd` must be the valid, open file descriptor registered with the looper.
/// - `events` must be a valid bitmask of ALOOPER_EVENT_* flags passed by the looper framework.
/// - `data` must be the watcher ID (as `usize`) registered with `Looper::add_fd`.
unsafe extern "C" fn memory_budget_manager_looper_callback(
fd: c_int,
events: c_int,
data: *mut c_void,
) -> c_int {
let watcher_id = data as usize;
let watcher = {
let registry = get_watchers_registry().lock().unwrap();
match registry.get(&watcher_id) {
Some(w) => {
let mut state = w.state.lock().unwrap();
state.active_callbacks += 1;
w.clone()
}
None => return 0,
}
};
alogd!("looper_callback called for watcher {}, events {}", watcher.id, events);
let mut retval = 1;
if (events & sys::ALOOPER_EVENT_HANGUP) != 0
|| ((events & sys::ALOOPER_EVENT_ERROR) != 0 && (events & sys::ALOOPER_EVENT_INPUT) == 0)
{
alogd!("Watcher {} looper hangup/error, unregistering", watcher.id);
retval = 0;
watcher_callback_cleanup(&watcher);
return retval;
}
// SAFETY: The looper framework guarantees `fd` is the open and valid inotify file descriptor for the duration of this callback.
let borrowed_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(fd) };
#[repr(align(4))]
struct AlignedBuffer([u8; 1024]);
let mut buf = AlignedBuffer([0; 1024]);
let len = match rustix::io::read(borrowed_fd, &mut buf.0) {
Ok(len) => {
alogd!("Watcher {} read {} bytes from inotify fd", watcher.id, len);
len
}
Err(rustix::io::Errno::AGAIN) => {
watcher_callback_cleanup(&watcher);
return 1;
}
Err(err) => {
aloge!("Watcher {} read inotify fd failed: {:?}", watcher.id, err);
watcher_callback_cleanup(&watcher);
return 0; // Unregister on real error
}
};
let mut pos = 0;
let mut package_changed = false;
let mut process_changed = false;
while pos + std::mem::size_of::<libc::inotify_event>() <= len {
// SAFETY: pos + size_of::<inotify_event>() <= len <= 1024, so the pointer is within bounds.
// The buffer is aligned to 4 bytes, and inotify_event requires 4-byte alignment.
let event = unsafe { &*(buf.0.as_ptr().add(pos) as *const libc::inotify_event) };
let wd = event.wd;
alogd!("Watcher {} received inotify event for wd {}", watcher.id, wd);
if watcher.package_wd.is_some_and(|w| w == wd) {
package_changed = true;
}
if watcher.process_wd.is_some_and(|w| w == wd) {
process_changed = true;
}
let event_len = event.len as usize;
if let Some(next_pos) =
pos.checked_add(std::mem::size_of::<libc::inotify_event>() + event_len)
{
pos = next_pos;
} else {
break; // Overflow
}
}
alogd!(
"Watcher {} package_changed={}, process_changed={}",
watcher.id,
package_changed,
process_changed
);
if package_changed {
trigger_event(&watcher, true);
}
if process_changed {
trigger_event(&watcher, false);
}
watcher_callback_cleanup(&watcher);
retval
}
fn watcher_callback_cleanup(watcher: &Arc<WatcherInner>) {
let mut registry = get_watchers_registry().lock().unwrap();
let mut state = watcher.state.lock().unwrap();
state.active_callbacks -= 1;
if state.delete_pending && state.active_callbacks == 0 {
registry.remove(&watcher.id);
} else {
watcher.cv.notify_all();
}
}
/// Creates a new `MemoryBudgetWatcher` registered with the specified looper.
///
/// # Safety
///
/// - `looper_ptr` must be a valid pointer to an `ALooper` / `android::Looper` instance, or null.
/// - `callback` (if provided) must be a thread-safe, valid C callback function pointer that can be safely
/// invoked from the looper callback thread.
/// - `userdata` must remain valid for the lifetime of the watcher or until callback execution completes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn MemoryBudgetWatcher_create(
looper_ptr: *mut c_void,
event_mask: i32,
debounce_millis: u32,
callback: MemoryBudgetWatcher_onEventsCallback,
userdata: *mut c_void,
) -> *mut MemoryBudgetWatcher {
if looper_ptr.is_null() {
return ptr::null_mut();
}
if callback.is_none() {
return ptr::null_mut();
}
if is_isolated_process()
&& (event_mask & MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PACKAGE.0) != 0
{
return ptr::null_mut();
}
// SAFETY: looper_ptr is non-null and guaranteed by caller safety contract to be a valid looper pointer.
let looper = unsafe { Looper::acquire_raw(looper_ptr) };
let looper = match looper {
Some(l) => l,
None => return ptr::null_mut(),
};
let mask_all = (MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PACKAGE
| MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PROCESS)
.0;
if event_mask == 0 || (event_mask & !mask_all) != 0 {
return ptr::null_mut();
}
// Initialize inotify
// SAFETY: `libc::inotify_init1` takes valid bitflags (IN_CLOEXEC | IN_NONBLOCK) and performs no memory access.
let inotify_fd = unsafe { libc::inotify_init1(libc::IN_CLOEXEC | libc::IN_NONBLOCK) };
if inotify_fd < 0 {
return ptr::null_mut();
}
// SAFETY: `inotify_init1` returned a non-negative file descriptor representing a newly allocated kernel inotify instance that we exclusively own.
let inotify_fd = unsafe { OwnedFd::from_raw_fd(inotify_fd) };
let mut package_wd: Option<c_int> = None;
let mut package_fd: Option<OwnedFd> = None;
if (event_mask & MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PACKAGE.0) != 0 {
let fd = MemoryBudgetManager_getPackageMemoryEventsFd();
if fd < 0 {
return ptr::null_mut();
}
// SAFETY: `MemoryBudgetManager_getPackageMemoryEventsFd` returned a valid newly opened file descriptor from cgroupfs that we exclusively take ownership of.
let owned_fd = unsafe { OwnedFd::from_raw_fd(fd) };
let path_str = format!("/proc/self/fd/{}", owned_fd.as_raw_fd());
let path_c = CString::new(path_str.clone()).unwrap();
// SAFETY: `inotify_fd` is a valid inotify file descriptor, `path_c` is a valid null-terminated CString that outlives this call, and IN_MODIFY is a valid inotify watch flag.
let wd = unsafe {
libc::inotify_add_watch(inotify_fd.as_raw_fd(), path_c.as_ptr(), libc::IN_MODIFY)
};
if wd < 0 {
aloge!(
"Failed to add package watch for path {}: {}",
path_str,
std::io::Error::last_os_error()
);
return ptr::null_mut();
}
alogd!("Added package watch for path {} -> wd {}", path_str, wd);
package_wd = Some(wd);
package_fd = Some(owned_fd);
}
let mut process_wd: Option<c_int> = None;
let mut process_fd: Option<OwnedFd> = None;
if (event_mask & MemoryBudgetWatcherEventMask::MEMORY_BUDGET_MANAGER_EVENT_PROCESS.0) != 0 {
let fd = MemoryBudgetManager_getProcessMemoryEventsFd();
if fd < 0 {
aloge!("Failed to get process memory events fd: {}", fd);
return ptr::null_mut();
}
// SAFETY: `MemoryBudgetManager_getProcessMemoryEventsFd` returned a valid newly opened file descriptor from cgroupfs that we exclusively take ownership of.
let owned_fd = unsafe { OwnedFd::from_raw_fd(fd) };
let path_str = format!("/proc/self/fd/{}", owned_fd.as_raw_fd());
let path_c = CString::new(path_str.clone()).unwrap();
// SAFETY: `inotify_fd` is a valid inotify file descriptor, `path_c` is a valid null-terminated CString that outlives this call, and IN_MODIFY is a valid inotify watch flag.
let wd = unsafe {
libc::inotify_add_watch(inotify_fd.as_raw_fd(), path_c.as_ptr(), libc::IN_MODIFY)
};
if wd < 0 {
aloge!(
"Failed to add process watch for path {}: {}",
path_str,
std::io::Error::last_os_error()
);
return ptr::null_mut();
}
alogd!("Added process watch for path {} -> wd {}", path_str, wd);
process_wd = Some(wd);
process_fd = Some(owned_fd);
}
let id = {
let mut next_id = G_NEXT_WATCHER_ID.lock().unwrap();
let id = *next_id;
*next_id += 1;
id
};
alogd!("Creating watcher ID {} with mask {}, debounce {}", id, event_mask, debounce_millis);
let watcher_inner = Arc::new(WatcherInner {
id,
looper: looper.clone(),
fd_mask: event_mask,
debounce_millis,
user_callback: callback,
user_data: userdata,
inotify_fd,
package_wd,
process_wd,
package_fd,
process_fd,
state: Mutex::new(WatcherState {
package_last_trigger_time: None,
process_last_trigger_time: None,
active_callbacks: 0,
destroyed: false,
delete_pending: false,
}),
cv: Condvar::new(),
});
{
let mut registry = get_watchers_registry().lock().unwrap();
registry.insert(id, watcher_inner.clone());
}
// SAFETY: `watcher_inner.looper` is a valid Looper, `inotify_fd` is a valid open file descriptor owned by `watcher_inner`, and `id` as `*mut c_void` matches the entry inserted into `G_WATCHERS` for callback lookup.
let success = unsafe {
watcher_inner.looper.add_fd(
watcher_inner.inotify_fd.as_raw_fd(),
sys::ALOOPER_POLL_CALLBACK,
sys::ALOOPER_EVENT_INPUT,
Some(memory_budget_manager_looper_callback),
id as *mut c_void,
)
} == 1;
if !success {
{
let mut registry = get_watchers_registry().lock().unwrap();
registry.remove(&id);
}
return ptr::null_mut();
}
Box::into_raw(Box::new(MemoryBudgetWatcher { inner: watcher_inner }))
}
/// Destroys a `MemoryBudgetWatcher` previously created by `MemoryBudgetWatcher_create`.
///
/// # Safety
///
/// `watcher` must be a valid pointer to a `MemoryBudgetWatcher` previously allocated by
/// `MemoryBudgetWatcher_create` that has not yet been destroyed, or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn MemoryBudgetWatcher_destroy(watcher: *mut MemoryBudgetWatcher) {
if watcher.is_null() {
return;
}
// SAFETY: watcher is a valid pointer to MemoryBudgetWatcher, originally allocated by Box::into_raw in create.
let watcher = unsafe { Box::from_raw(watcher) };
let inner = &watcher.inner;
// SAFETY: `inner.looper` is a valid Looper instance and `inner.inotify_fd` is the open descriptor previously added to this looper during watcher creation.
unsafe {
inner.looper.remove_fd(inner.inotify_fd.as_raw_fd());
}
let is_looper_thread = inner.looper.is_current_thread();
let mut should_delete = false;
{
let mut state = inner.state.lock().unwrap();
state.destroyed = true;
if state.active_callbacks > 0 {
if is_looper_thread {
state.delete_pending = true;
} else {
while state.active_callbacks > 0 {
state = inner.cv.wait(state).unwrap();
}
should_delete = true;
}
} else {
should_delete = true;
}
}
if should_delete {
let mut registry = get_watchers_registry().lock().unwrap();
registry.remove(&inner.id);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::write;
#[test]
fn test_read_budget_value() {
let mut temp_path = std::env::temp_dir();
temp_path.push("test_budget_val");
// Test "max"
write(&temp_path, "max").unwrap();
let file = File::open(&temp_path).unwrap();
assert_eq!(read_budget_value(&file).unwrap(), i64::MAX);
// Test integer
write(&temp_path, "12345\n").unwrap();
let file = File::open(&temp_path).unwrap();
assert_eq!(read_budget_value(&file).unwrap(), 12345);
// Test invalid
write(&temp_path, "invalid").unwrap();
let file = File::open(&temp_path).unwrap();
assert!(read_budget_value(&file).is_err());
// Clean up
let _ = std::fs::remove_file(temp_path);
}
}