blob: 9d605b6a3edb77bbb4ebc109c4e0bf94fd507d63 [file] [log] [blame]
Alan Stokes0cc59ee2021-09-24 11:20:34 +01001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Rust API for lazy (aka dynamic) AIDL services.
18//! See https://source.android.com/devices/architecture/aidl/dynamic-aidl.
19
Stephen Crane44fd9bc2022-01-19 17:49:46 +000020use binder::force_lazy_services_persist;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010021use lazy_static::lazy_static;
22use std::sync::Mutex;
23
24// TODO(b/200924402): Move this class to libbinder_rs once the infrastructure needed exists.
25
26/// An RAII object to ensure a server of lazy services is not killed. During the lifetime of any of
27/// these objects the service manager will not not kill the current process even if none of its
28/// lazy services are in use.
29#[must_use]
30#[derive(Debug)]
31pub struct LazyServiceGuard {
32 // Prevent construction outside this module.
33 _private: (),
34}
35
36lazy_static! {
37 // Count of how many LazyServiceGuard objects are in existence.
38 static ref GUARD_COUNT: Mutex<u64> = Mutex::new(0);
39}
40
41impl LazyServiceGuard {
42 /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
43 /// process.
44 pub fn new() -> Self {
45 let mut count = GUARD_COUNT.lock().unwrap();
46 *count += 1;
47 if *count == 1 {
48 // It's important that we make this call with the mutex held, to make sure
49 // that multiple calls (e.g. if the count goes 1 -> 0 -> 1) are correctly
50 // sequenced. (That also means we can't just use an AtomicU64.)
51 force_lazy_services_persist(true);
52 }
53 Self { _private: () }
54 }
55}
56
57impl Drop for LazyServiceGuard {
58 fn drop(&mut self) {
59 let mut count = GUARD_COUNT.lock().unwrap();
60 *count -= 1;
61 if *count == 0 {
62 force_lazy_services_persist(false);
63 }
64 }
65}
66
67impl Clone for LazyServiceGuard {
68 fn clone(&self) -> Self {
69 Self::new()
70 }
71}
72
73impl Default for LazyServiceGuard {
74 fn default() -> Self {
75 Self::new()
76 }
77}