1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Implementation of Dispatcher and related methods.
16 
17 use crate::notification_manager_android::NotificationManagerAndroidBuilder;
18 
19 use std::collections::HashMap;
20 use std::ops::Deref;
21 use std::sync::{Arc, RwLock, RwLockReadGuard};
22 
23 use jni::objects::{GlobalRef, JObject, JString};
24 use jni::{JNIEnv, JavaVM, MonitorGuard};
25 use log::error;
26 use tokio::runtime::{Builder as RuntimeBuilder, Runtime};
27 use uci_hal_android::uci_hal_android::UciHalAndroid;
28 use uwb_core::error::{Error, Result};
29 use uwb_core::uci::pcapng_uci_logger_factory::PcapngUciLoggerFactoryBuilder;
30 use uwb_core::uci::uci_logger::UciLoggerMode;
31 use uwb_core::uci::uci_logger_factory::UciLoggerFactory;
32 use uwb_core::uci::uci_manager_sync::UciManagerSync;
33 use uwb_core::uci::UciManagerImpl;
34 
35 /// Shared unique dispatcher that may be created and deleted during runtime.
36 static DISPATCHER: RwLock<Option<Dispatcher>> = RwLock::new(None);
37 
38 /// Dispatcher is managed by Java side. Construction and Destruction are provoked by JNI function
39 /// nativeDispatcherNew and nativeDispatcherDestroy respectively.
40 /// Destruction does NOT wait until the spawned threads are closed.
41 pub(crate) struct Dispatcher {
42     pub manager_map: HashMap<String, UciManagerSync<UciManagerImpl>>,
43     _runtime: Runtime,
44 }
45 impl Dispatcher {
46     /// Constructs Dispatcher.
new<T: AsRef<str>>( vm: &'static Arc<JavaVM>, class_loader_obj: GlobalRef, callback_obj: GlobalRef, chip_ids: &[T], ) -> Result<Dispatcher>47     fn new<T: AsRef<str>>(
48         vm: &'static Arc<JavaVM>,
49         class_loader_obj: GlobalRef,
50         callback_obj: GlobalRef,
51         chip_ids: &[T],
52     ) -> Result<Dispatcher> {
53         let runtime = RuntimeBuilder::new_multi_thread()
54             .thread_name("UwbService")
55             .enable_all()
56             .build()
57             .map_err(|_| Error::ForeignFunctionInterface)?;
58         let mut manager_map = HashMap::<String, UciManagerSync<UciManagerImpl>>::new();
59         let mut log_file_factory = PcapngUciLoggerFactoryBuilder::new()
60             .log_path("/data/misc/apexdata/com.android.uwb/log".into())
61             .filename_prefix("uwb_uci".to_owned())
62             .runtime_handle(runtime.handle().to_owned())
63             .build()
64             .ok_or(Error::Unknown)?;
65         for chip_id in chip_ids {
66             let logger = log_file_factory.build_logger(chip_id.as_ref()).ok_or(Error::Unknown)?;
67             let manager = UciManagerSync::new(
68                 UciHalAndroid::new(chip_id.as_ref()),
69                 NotificationManagerAndroidBuilder {
70                     chip_id: chip_id.as_ref().to_owned(),
71                     vm,
72                     class_loader_obj: class_loader_obj.clone(),
73                     callback_obj: callback_obj.clone(),
74                 },
75                 logger,
76                 UciLoggerMode::Filtered,
77                 runtime.handle().to_owned(),
78             )?;
79             manager_map.insert(chip_id.as_ref().to_string(), manager);
80         }
81         Ok(Self { manager_map, _runtime: runtime })
82     }
83 
84     /// Sets log mode for all chips.
set_logger_mode(&self, logger_mode: UciLoggerMode) -> Result<()>85     pub fn set_logger_mode(&self, logger_mode: UciLoggerMode) -> Result<()> {
86         for (_, manager) in self.manager_map.iter() {
87             manager.set_logger_mode(logger_mode.clone())?;
88         }
89         Ok(())
90     }
91 
92     /// Constructs the unique dispatcher.
new_dispatcher<T: AsRef<str>>( vm: &'static Arc<JavaVM>, class_loader_obj: GlobalRef, callback_obj: GlobalRef, chip_ids: &[T], ) -> Result<()>93     pub fn new_dispatcher<T: AsRef<str>>(
94         vm: &'static Arc<JavaVM>,
95         class_loader_obj: GlobalRef,
96         callback_obj: GlobalRef,
97         chip_ids: &[T],
98     ) -> Result<()> {
99         if DISPATCHER.try_read().map_err(|_| Error::Unknown)?.is_some() {
100             error!("UCI JNI: Dispatcher already exists when trying to create.");
101             return Err(Error::BadParameters);
102         }
103         let dispatcher = Dispatcher::new(vm, class_loader_obj, callback_obj, chip_ids)?;
104         DISPATCHER.write().map_err(|_| Error::Unknown)?.replace(dispatcher);
105         Ok(())
106     }
107 
108     /// Gets pointer value of the unique dispatcher
get_dispatcher_ptr() -> Result<*const Dispatcher>109     pub fn get_dispatcher_ptr() -> Result<*const Dispatcher> {
110         let read_lock = DISPATCHER.read().map_err(|_| Error::Unknown)?;
111         match &*read_lock {
112             Some(dispatcher_ref) => Ok(dispatcher_ref),
113             None => Err(Error::BadParameters),
114         }
115     }
116 
117     /// Destroys the unique Dispather.
destroy_dispatcher() -> Result<()>118     pub fn destroy_dispatcher() -> Result<()> {
119         if DISPATCHER.try_read().map_err(|_| Error::Unknown)?.is_none() {
120             error!("UCI JNI: Dispatcher already does not exist when trying to destroy.");
121             return Err(Error::BadParameters);
122         }
123         let _ = DISPATCHER.write().map_err(|_| Error::Unknown)?.take();
124         Ok(())
125     }
126 
127     /// Gets reference to the unique Dispatcher.
get_dispatcher<'a>(env: JNIEnv<'a>, obj: JObject<'a>) -> Result<GuardedDispatcher<'a>>128     pub fn get_dispatcher<'a>(env: JNIEnv<'a>, obj: JObject<'a>) -> Result<GuardedDispatcher<'a>> {
129         let jni_guard = env.lock_obj(obj).map_err(|_| Error::ForeignFunctionInterface)?;
130         let read_lock = DISPATCHER.read().map_err(|_| Error::Unknown)?;
131         GuardedDispatcher::new(jni_guard, read_lock)
132     }
133 
134     /// Gets reference to UciManagerSync with chip_id.
get_uci_manager<'a>( env: JNIEnv<'a>, obj: JObject<'a>, chip_id: JString, ) -> Result<GuardedUciManager<'a>>135     pub fn get_uci_manager<'a>(
136         env: JNIEnv<'a>,
137         obj: JObject<'a>,
138         chip_id: JString,
139     ) -> Result<GuardedUciManager<'a>> {
140         let guarded_dispatcher = Self::get_dispatcher(env, obj)?;
141         let chip_id_str =
142             String::from(env.get_string(chip_id).map_err(|_| Error::ForeignFunctionInterface)?);
143         guarded_dispatcher.into_guarded_uci_manager(&chip_id_str)
144     }
145 }
146 
147 /// Lifetimed reference to UciManagerSync that locks Java object while reference is alive.
148 pub(crate) struct GuardedUciManager<'a> {
149     _jni_guard: MonitorGuard<'a>,
150     read_lock: RwLockReadGuard<'a, Option<Dispatcher>>,
151     chip_id: String,
152 }
153 
154 impl<'a> Deref for GuardedUciManager<'a> {
155     type Target = UciManagerSync<UciManagerImpl>;
deref(&self) -> &Self::Target156     fn deref(&self) -> &Self::Target {
157         // Unwrap GuardedUciManager will not panic since content is checked at creation.
158         self.read_lock.as_ref().unwrap().manager_map.get(&self.chip_id).unwrap()
159     }
160 }
161 
162 /// Lifetimed reference to Dispatcher that locks Java object while reference is alive.
163 pub(crate) struct GuardedDispatcher<'a> {
164     _jni_guard: MonitorGuard<'a>,
165     read_lock: RwLockReadGuard<'a, Option<Dispatcher>>,
166 }
167 
168 impl<'a> GuardedDispatcher<'a> {
169     /// Constructor:
new( jni_guard: MonitorGuard<'a>, read_lock: RwLockReadGuard<'a, Option<Dispatcher>>, ) -> Result<Self>170     pub fn new(
171         jni_guard: MonitorGuard<'a>,
172         read_lock: RwLockReadGuard<'a, Option<Dispatcher>>,
173     ) -> Result<Self> {
174         // Check RwLockReadGuard contains Dispatcher:
175         if read_lock.is_none() {
176             return Err(Error::BadParameters);
177         };
178         Ok(GuardedDispatcher { _jni_guard: jni_guard, read_lock })
179     }
180 
181     /// Conversion to GuardedUciManager:
into_guarded_uci_manager(self, chip_id: &str) -> Result<GuardedUciManager<'a>>182     pub fn into_guarded_uci_manager(self, chip_id: &str) -> Result<GuardedUciManager<'a>> {
183         let _uci_manager = self.manager_map.get(chip_id).ok_or(Error::BadParameters)?;
184         Ok(GuardedUciManager {
185             _jni_guard: self._jni_guard,
186             read_lock: self.read_lock,
187             chip_id: chip_id.to_owned(),
188         })
189     }
190 }
191 
192 impl<'a> Deref for GuardedDispatcher<'a> {
193     type Target = Dispatcher;
deref(&self) -> &Self::Target194     fn deref(&self) -> &Self::Target {
195         // Unwrap GuardedDispatcher will not panic since content is checked at creation.
196         self.read_lock.as_ref().unwrap()
197     }
198 }
199