• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
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 #![allow(missing_docs)]
16 use crate::common::sendmsg::send_msg;
17 use crate::common::uds::{PollNode, UdsAddr, UdsServer};
18 use crate::config::ErrCode;
19 use crate::config::HdcCommand;
20 use crate::config::TaskMessage;
21 use crate::transfer;
22 use crate::utils::hdc_log::*;
23 use libc::{POLLERR, POLLHUP, POLLIN, POLLNVAL, POLLRDHUP, SOCK_STREAM};
24 
25 use std::collections::HashMap;
26 use std::sync::Arc;
27 #[cfg(feature = "host")]
28 extern crate ylong_runtime_static as ylong_runtime;
29 use ylong_runtime::sync::waiter::Waiter;
30 use ylong_runtime::sync::Mutex;
31 
32 const JPID_SOCKET_PATH: &str = "ohjpid-control";
33 const PATH_LEN: usize = JPID_SOCKET_PATH.as_bytes().len() + 1;
34 
35 type NodeMap = Arc<Mutex<HashMap<i32, PollNode>>>;
36 type Trackers = Arc<Mutex<Vec<(u32, u32, bool)>>>;
37 
38 pub trait JdwpBase: Send + Sync + 'static {}
39 pub struct Jdwp {
40     poll_node_map: NodeMap,
41     new_process_waiter: Arc<Waiter>,
42     trackers: Trackers,
43     await_fd: i32,
44 }
45 
46 impl JdwpBase for Jdwp {}
47 
48 type JdWpShare = Arc<Jdwp>;
49 
50 impl Default for Jdwp {
default() -> Self51     fn default() -> Self {
52         Self::new()
53     }
54 }
55 
56 impl Jdwp {
get_instance() -> JdWpShare57     pub fn get_instance() -> JdWpShare {
58         static mut INSTANCE: Option<JdWpShare> = None;
59         unsafe {
60             INSTANCE
61                 .get_or_insert_with(|| Arc::new(Jdwp::new()))
62                 .clone()
63         }
64     }
65 
new() -> Self66     pub fn new() -> Self {
67         Self {
68             poll_node_map: Arc::new(Mutex::new(HashMap::default())),
69             new_process_waiter: Arc::new(Waiter::new()),
70             trackers: Arc::new(Mutex::new(Vec::new())),
71             await_fd: UdsServer::wrap_event_fd(),
72         }
73     }
74 }
75 
76 impl Jdwp {
send_fd_to_target(&self, target_pid: u32, fd: i32, parameter: &str) -> bool77     pub async fn send_fd_to_target(&self, target_pid: u32, fd: i32, parameter: &str) -> bool {
78         let map = self.poll_node_map.clone();
79         let map = map.lock().await;
80         let keys = map.keys();
81         for k in keys {
82             let v = map.get(k);
83             if let Some(node) = v {
84                 if node.ppid == target_pid {
85                     let bytes = fd.to_be_bytes();
86                     let fd_bytes = bytes.as_slice();
87                     let param_bytes = parameter.as_bytes();
88                     let param_bytes = [fd_bytes, param_bytes].concat();
89                     let param_bytes = param_bytes.as_slice();
90                     let ret = send_msg(node.fd, fd, param_bytes);
91                     crate::info!("send_fd_to_target ret:{}", ret);
92                     return ret > 0;
93                 }
94             }
95         }
96         false
97     }
98 
send_process_list(trackers: Trackers, node_map: NodeMap)99     async fn send_process_list(trackers: Trackers, node_map: NodeMap) {
100         let trackers = trackers.lock().await;
101         for (channel_id2, session_id2, is_debug) in trackers.iter() {
102             let message = Self::get_process_list_with_pkg_name(node_map.clone(), *is_debug).await;
103             let len = message.as_bytes().len();
104             let len_str = format!("{:04x}\n", len);
105             let mut header = len_str.as_bytes().to_vec();
106             let mut buffer = Vec::<u8>::new();
107             buffer.append(&mut header);
108             buffer.append(&mut message.as_str().as_bytes().to_vec());
109 
110             let data = TaskMessage {
111                 channel_id: *channel_id2,
112                 command: HdcCommand::KernelEchoRaw,
113                 payload: buffer.to_vec(),
114             };
115             transfer::put(*session_id2, data).await;
116         }
117     }
118 
add_tracker(&self, channel_id: u32, session_id: u32, debug_or_release: bool)119     pub async fn add_tracker(&self, channel_id: u32, session_id: u32, debug_or_release: bool) {
120         let mut trackers_lock = self.trackers.lock().await;
121         trackers_lock.push((channel_id, session_id, debug_or_release));
122         drop(trackers_lock);
123 
124         let node_map = self.poll_node_map.clone();
125         Self::send_process_list(self.trackers.clone(), node_map).await;
126     }
127 
get_process_list(&self) -> String128     pub async fn get_process_list(&self) -> String {
129         let mut result = String::from("");
130         let map = self.poll_node_map.clone();
131         let map = map.lock().await;
132         let keys = map.keys();
133         for key in keys {
134             let value = map.get(key);
135             if let Some(v) = value {
136                 result.push_str((v.ppid.to_string() + "\n").as_str());
137             }
138         }
139         result
140     }
141 
get_process_list_with_pkg_name(map: NodeMap, debug_or_release: bool) -> String142     pub async fn get_process_list_with_pkg_name(map: NodeMap, debug_or_release: bool) -> String {
143         let mut result = String::from("");
144         let map = map.lock().await;
145         let keys = map.keys();
146         for key in keys {
147             let value = map.get(key);
148             if let Some(v) = value {
149                 if !debug_or_release || debug_or_release == v.debug_or_release {
150                     result
151                         .push_str((v.ppid.to_string() + " " + v.pkg_name.as_str() + "\n").as_str());
152                 }
153             }
154         }
155         result
156     }
157 
handle_client(fd: i32, waiter: Arc<Waiter>, node_map: NodeMap)158     pub async fn handle_client(fd: i32, waiter: Arc<Waiter>, node_map: NodeMap) {
159         crate::info!("handle_client start...");
160         let mut buffer: [u8; 1024] = [0; 1024];
161         let size = UdsServer::wrap_recv(fd, &mut buffer);
162         let u32_size = std::mem::size_of::<u32>();
163         if size == u32_size.try_into().unwrap() {
164             let _pid = u32::from_le_bytes(buffer[0..u32_size].try_into().unwrap());
165         } else if size > u32_size.try_into().unwrap() {
166             let len = u32::from_le_bytes(buffer[0..u32_size].try_into().unwrap());
167             let pid = u32::from_le_bytes(buffer[u32_size..2 * u32_size].try_into().unwrap());
168             crate::info!("pid:{}", pid);
169             let debug_or_release =
170                 u32::from_le_bytes(buffer[u32_size * 2..3 * u32_size].try_into().unwrap()) == 1;
171             crate::info!("debug:{}", debug_or_release);
172             let pkg_name = String::from_utf8(buffer[u32_size * 3..len as usize].to_vec()).unwrap();
173             crate::info!("pkg name:{}", pkg_name);
174 
175             let node_map = node_map.clone();
176             let mut map = node_map.lock().await;
177             let node = PollNode::new(fd, pid, pkg_name.clone(), debug_or_release);
178             let mut key_ = -1;
179             for (key, value) in map.iter() {
180                 if value.pkg_name == pkg_name {
181                     key_ = *key;
182                     UdsServer::wrap_close(value.fd);
183                     break;
184                 }
185             }
186             if key_ != -1 {
187                 map.remove(&key_);
188             }
189             map.insert(fd, node);
190             drop(map);
191 
192             waiter.wake_one();
193         } else if size <= 0 {
194             crate::info!("size <= 0");
195         }
196     }
197 
jdwp_listen(&self) -> bool198     pub fn jdwp_listen(&self) -> bool {
199         let fd = UdsServer::wrap_socket(SOCK_STREAM);
200         let name = JPID_SOCKET_PATH.as_bytes();
201         let socket_name = &mut [0u8; PATH_LEN];
202         socket_name[0] = b'\0';
203         socket_name[1..].copy_from_slice(name);
204         let addr = UdsAddr::parse_abstract(&socket_name[1..]);
205         if let Ok(addr_obj) = &addr {
206             if let Err(ret) = UdsServer::wrap_bind(fd, addr_obj) {
207                 crate::error!("bind fail. {ret:?}");
208                 return false;
209             }
210             let ret = UdsServer::wrap_listen(fd);
211             if ret < 0 {
212                 crate::error!("listen fail, ret = {ret}");
213                 return false;
214             }
215             let node_map = self.poll_node_map.clone();
216             let waiter = self.new_process_waiter.clone();
217             ylong_runtime::spawn(async move {
218                 loop {
219                     let client_fd = UdsServer::wrap_accept(fd);
220                     if client_fd == -1 {
221                         crate::error!("wrap_accept failed");
222                         break;
223                     }
224                     let map = node_map.clone();
225                     let w = waiter.clone();
226                     ylong_runtime::spawn(Self::handle_client(client_fd, w, map));
227                 }
228             });
229             true
230         } else {
231             crate::info!("parse addr fail  ");
232             false
233         }
234     }
235 
start_data_looper(&self)236     pub fn start_data_looper(&self) {
237         let node_map = self.poll_node_map.clone();
238         let trackers = self.trackers.clone();
239         let await_fd = self.await_fd;
240         ylong_runtime::spawn(async move {
241             loop {
242                 let mut poll_nodes = Vec::<PollNode>::new();
243                 let mut fd_node = PollNode::new(await_fd, 0, "".to_string(), false);
244                 fd_node.revents = 0;
245                 fd_node.events = POLLIN;
246                 poll_nodes.push(fd_node);
247 
248                 let node_map_value = node_map.lock().await;
249                 let keys = node_map_value.keys();
250                 for k in keys {
251                     if let Some(n) = node_map_value.get(k) {
252                         poll_nodes.push(n.clone());
253                     }
254                 }
255                 let size = poll_nodes.len();
256 
257                 drop(node_map_value);
258                 UdsServer::wrap_poll(poll_nodes.as_mut_slice(), size.try_into().unwrap(), -1);
259                 let mut node_map_value = node_map.lock().await;
260                 for pnode in &poll_nodes {
261                     if pnode.revents & (POLLNVAL | POLLRDHUP | POLLHUP | POLLERR) != 0 {
262                         crate::info!("start_data_looper remove node:{}", pnode.pkg_name);
263                         node_map_value.remove(&pnode.fd);
264                         UdsServer::wrap_close(pnode.fd);
265                     } else if pnode.fd == await_fd && pnode.revents & POLLIN != 0 {
266                         UdsServer::wrap_read_fd(await_fd);
267                     }
268                 }
269                 drop(node_map_value);
270                 let trackers = trackers.clone();
271                 let node_map = node_map.clone();
272                 Self::send_process_list(trackers, node_map).await;
273             }
274         });
275     }
276 
create_fd_event_poll(&self)277     pub async fn create_fd_event_poll(&self) {
278         loop {
279             let waiter = self.new_process_waiter.clone();
280             waiter.wait().await;
281 
282             UdsServer::wrap_write_fd(self.await_fd);
283         }
284     }
285 
init(&self) -> ErrCode286     pub async fn init(&self) -> ErrCode {
287         if !self.jdwp_listen() {
288             crate::info!("jdwp_listen failed");
289             return ErrCode::ModuleJdwpFailed;
290         }
291 
292         self.start_data_looper();
293 
294         self.create_fd_event_poll().await;
295         ErrCode::Success
296     }
297 }
298