blob: a2ea40d2ab6afb32ecdcf37524934051cc53db5a [file] [log] [blame]
Jaewan Kimc03f6612023-02-20 00:06:26 +09001// Copyright 2023, 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//! Functions for AVF debug policy and debug level
16
17use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jaewan Kimf3143242024-03-15 06:56:31 +000018 VirtualMachineAppConfig::DebugLevel::DebugLevel, VirtualMachineConfig::VirtualMachineConfig,
Jaewan Kimc03f6612023-02-20 00:06:26 +090019};
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090020use anyhow::{anyhow, Context, Error, Result};
Jaewan Kimf3143242024-03-15 06:56:31 +000021use lazy_static::lazy_static;
22use libfdt::{Fdt, FdtError};
23use log::{info, warn};
24use rustutils::system_properties;
25use std::ffi::{CString, NulError};
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090026use std::fs;
27use std::io::ErrorKind;
28use std::path::{Path, PathBuf};
Jaewan Kim61f86142023-03-28 15:12:52 +090029
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090030const CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP: &str =
31 "hypervisor.virtualizationmanager.debug_policy.path";
32const DEVICE_TREE_EMPTY_TREE_SIZE_BYTES: usize = 100; // rough estimation.
Jaewan Kim61f86142023-03-28 15:12:52 +090033
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090034struct DPPath {
35 node_path: CString,
36 prop_name: CString,
37}
38
39impl DPPath {
40 fn new(node_path: &str, prop_name: &str) -> Result<Self, NulError> {
41 Ok(Self { node_path: CString::new(node_path)?, prop_name: CString::new(prop_name)? })
42 }
43
44 fn to_path(&self) -> PathBuf {
Andrew Walbranb58d1b42023-07-07 13:54:49 +010045 // unwrap() is safe for to_str() because node_path and prop_name were &str.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090046 PathBuf::from(
47 [
Jaewan Kim1f0135b2024-01-31 14:59:47 +090048 "/proc/device-tree",
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090049 self.node_path.to_str().unwrap(),
50 "/",
51 self.prop_name.to_str().unwrap(),
52 ]
53 .concat(),
54 )
55 }
56}
57
58lazy_static! {
59 static ref DP_LOG_PATH: DPPath = DPPath::new("/avf/guest/common", "log").unwrap();
60 static ref DP_RAMDUMP_PATH: DPPath = DPPath::new("/avf/guest/common", "ramdump").unwrap();
61 static ref DP_ADB_PATH: DPPath = DPPath::new("/avf/guest/microdroid", "adb").unwrap();
62}
63
64/// Get debug policy value in bool. It's true iff the value is explicitly set to <1>.
65fn get_debug_policy_bool(path: &Path) -> Result<bool> {
66 let value = match fs::read(path) {
67 Ok(value) => value,
68 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(false),
69 Err(error) => Err(error).with_context(|| format!("Failed to read {path:?}"))?,
70 };
71
72 // DT spec uses big endian although Android is always little endian.
73 match u32::from_be_bytes(value.try_into().map_err(|_| anyhow!("Malformed value in {path:?}"))?)
74 {
75 0 => Ok(false),
76 1 => Ok(true),
77 value => Err(anyhow!("Invalid value {value} in {path:?}")),
78 }
79}
80
81/// Get property value in bool. It's true iff the value is explicitly set to <1>.
82/// It takes path as &str instead of &Path, because we don't want OsStr.
83fn get_fdt_prop_bool(fdt: &Fdt, path: &DPPath) -> Result<bool> {
84 let (node_path, prop_name) = (&path.node_path, &path.prop_name);
85 let node = match fdt.node(node_path) {
86 Ok(Some(node)) => node,
Chris Wailes9d09f572024-01-16 13:31:02 -080087 Err(error) if error != FdtError::NotFound => {
88 Err(Error::msg(error)).with_context(|| format!("Failed to get node {node_path:?}"))?
89 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090090 _ => return Ok(false),
91 };
92
93 match node.getprop_u32(prop_name) {
94 Ok(Some(0)) => Ok(false),
95 Ok(Some(1)) => Ok(true),
96 Ok(Some(_)) => Err(anyhow!("Invalid prop value {prop_name:?} in node {node_path:?}")),
Chris Wailes9d09f572024-01-16 13:31:02 -080097 Err(error) if error != FdtError::NotFound => {
98 Err(Error::msg(error)).with_context(|| format!("Failed to get prop {prop_name:?}"))
99 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900100 _ => Ok(false),
101 }
102}
103
104/// Fdt with owned vector.
105struct OwnedFdt {
106 buffer: Vec<u8>,
107}
108
109impl OwnedFdt {
110 fn from_overlay_onto_new_fdt(overlay_file_path: &Path) -> Result<Self> {
111 let mut overlay_buf = match fs::read(overlay_file_path) {
112 Ok(fdt) => fdt,
113 Err(error) if error.kind() == ErrorKind::NotFound => Default::default(),
114 Err(error) => {
115 Err(error).with_context(|| format!("Failed to read {overlay_file_path:?}"))?
116 }
117 };
118
119 let overlay_buf_size = overlay_buf.len();
120
121 let fdt_estimated_size = overlay_buf_size + DEVICE_TREE_EMPTY_TREE_SIZE_BYTES;
122 let mut fdt_buf = vec![0_u8; fdt_estimated_size];
123 let fdt = Fdt::create_empty_tree(fdt_buf.as_mut_slice())
124 .map_err(Error::msg)
125 .context("Failed to create an empty device tree")?;
126
127 if !overlay_buf.is_empty() {
128 let overlay_fdt = Fdt::from_mut_slice(overlay_buf.as_mut_slice())
129 .map_err(Error::msg)
130 .with_context(|| "Malformed {overlay_file_path:?}")?;
131
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100132 // SAFETY: Return immediately if error happens. Damaged fdt_buf and fdt are discarded.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900133 unsafe {
134 fdt.apply_overlay(overlay_fdt).map_err(Error::msg).with_context(|| {
135 "Failed to overlay {overlay_file_path:?} onto empty device tree"
136 })?;
137 }
138 }
139
140 Ok(Self { buffer: fdt_buf })
141 }
142
143 fn as_fdt(&self) -> &Fdt {
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100144 // SAFETY: Checked validity of buffer when instantiate.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900145 unsafe { Fdt::unchecked_from_slice(&self.buffer) }
146 }
147}
Jaewan Kim61f86142023-03-28 15:12:52 +0900148
149/// Debug configurations for both debug level and debug policy
Pierre-Clément Tosic57c4df2024-04-15 16:51:01 +0100150#[derive(Debug, Default)]
Jaewan Kim61f86142023-03-28 15:12:52 +0900151pub struct DebugConfig {
152 pub debug_level: DebugLevel,
153 debug_policy_log: bool,
154 debug_policy_ramdump: bool,
155 debug_policy_adb: bool,
156}
Jaewan Kimc03f6612023-02-20 00:06:26 +0900157
Jaewan Kim61f86142023-03-28 15:12:52 +0900158impl DebugConfig {
Jaewan Kimf3143242024-03-15 06:56:31 +0000159 pub fn new(config: &VirtualMachineConfig) -> Self {
160 let debug_level = match config {
161 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
162 _ => DebugLevel::NONE,
163 };
164
Pierre-Clément Tosie4d9f392024-04-16 15:51:00 +0100165 let dp_sysprop = system_properties::read(CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP);
166 let custom_dp = dp_sysprop.unwrap_or_else(|e| {
167 warn!("Failed to read sysprop {CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP}: {e}");
168 Default::default()
169 });
170
171 match custom_dp {
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900172 Some(path) if !path.is_empty() => {
173 match Self::from_custom_debug_overlay_policy(debug_level, Path::new(&path)) {
174 Ok(debug_config) => {
175 info!("Loaded custom debug policy overlay {path}: {debug_config:?}");
176 return debug_config;
177 }
178 Err(err) => warn!("Failed to load custom debug policy overlay {path}: {err:?}"),
179 };
Jaewan Kim61f86142023-03-28 15:12:52 +0900180 }
181 _ => {
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900182 match Self::from_host(debug_level) {
183 Ok(debug_config) => {
184 info!("Loaded debug policy from host OS: {debug_config:?}");
185 return debug_config;
186 }
187 Err(err) => warn!("Failed to load debug policy from host OS: {err:?}"),
Jaewan Kim61f86142023-03-28 15:12:52 +0900188 };
Jaewan Kim61f86142023-03-28 15:12:52 +0900189 }
190 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900191
192 info!("Debug policy is disabled");
193 Self {
194 debug_level,
195 debug_policy_log: false,
196 debug_policy_ramdump: false,
197 debug_policy_adb: false,
198 }
Jaewan Kim61f86142023-03-28 15:12:52 +0900199 }
Jiyong Parked180932023-02-24 19:55:41 +0900200
Pierre-Clément Tosic57c4df2024-04-15 16:51:01 +0100201 #[cfg(test)]
202 /// Creates a new DebugConfig with debug level. Only use this for test purpose.
203 pub(crate) fn new_with_debug_level(debug_level: DebugLevel) -> Self {
204 Self { debug_level, ..Default::default() }
205 }
206
Jaewan Kim61f86142023-03-28 15:12:52 +0900207 /// Get whether console output should be configred for VM to leave console and adb log.
208 /// Caller should create pipe and prepare for receiving VM log with it.
209 pub fn should_prepare_console_output(&self) -> bool {
210 self.debug_level != DebugLevel::NONE || self.debug_policy_log || self.debug_policy_adb
211 }
Jiyong Parked180932023-02-24 19:55:41 +0900212
Jaewan Kim61f86142023-03-28 15:12:52 +0900213 /// Get whether debug apexes (MICRODROID_REQUIRED_APEXES_DEBUG) are required.
214 pub fn should_include_debug_apexes(&self) -> bool {
215 self.debug_level != DebugLevel::NONE || self.debug_policy_adb
216 }
217
218 /// Decision to support ramdump
219 pub fn is_ramdump_needed(&self) -> bool {
220 self.debug_level != DebugLevel::NONE || self.debug_policy_ramdump
221 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900222
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900223 fn from_custom_debug_overlay_policy(debug_level: DebugLevel, path: &Path) -> Result<Self> {
Pierre-Clément Tosi01c83132024-04-15 16:48:57 +0100224 let owned_fdt = OwnedFdt::from_overlay_onto_new_fdt(path)?;
225 let fdt = owned_fdt.as_fdt();
226
227 Ok(Self {
228 debug_level,
229 debug_policy_log: get_fdt_prop_bool(fdt, &DP_LOG_PATH)?,
230 debug_policy_ramdump: get_fdt_prop_bool(fdt, &DP_RAMDUMP_PATH)?,
231 debug_policy_adb: get_fdt_prop_bool(fdt, &DP_ADB_PATH)?,
232 })
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900233 }
234
235 fn from_host(debug_level: DebugLevel) -> Result<Self> {
236 Ok(Self {
237 debug_level,
238 debug_policy_log: get_debug_policy_bool(&DP_LOG_PATH.to_path())?,
239 debug_policy_ramdump: get_debug_policy_bool(&DP_RAMDUMP_PATH.to_path())?,
240 debug_policy_adb: get_debug_policy_bool(&DP_ADB_PATH.to_path())?,
241 })
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900248
249 #[test]
Jaewan Kim46b96702023-09-07 15:24:51 +0900250 fn test_read_avf_debug_policy_with_ramdump() -> Result<()> {
251 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
252 DebugLevel::FULL,
253 "avf_debug_policy_with_ramdump.dtbo".as_ref(),
254 )
255 .unwrap();
256
257 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
258 assert!(!debug_config.debug_policy_log);
259 assert!(debug_config.debug_policy_ramdump);
260 assert!(debug_config.debug_policy_adb);
261
262 Ok(())
263 }
264
265 #[test]
266 fn test_read_avf_debug_policy_without_ramdump() -> Result<()> {
267 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
268 DebugLevel::FULL,
269 "avf_debug_policy_without_ramdump.dtbo".as_ref(),
270 )
271 .unwrap();
272
273 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
274 assert!(!debug_config.debug_policy_log);
275 assert!(!debug_config.debug_policy_ramdump);
276 assert!(debug_config.debug_policy_adb);
277
278 Ok(())
279 }
280
281 #[test]
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900282 fn test_read_avf_debug_policy_with_adb() -> Result<()> {
283 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
284 DebugLevel::FULL,
285 "avf_debug_policy_with_adb.dtbo".as_ref(),
286 )
287 .unwrap();
288
289 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
290 assert!(!debug_config.debug_policy_log);
291 assert!(!debug_config.debug_policy_ramdump);
292 assert!(debug_config.debug_policy_adb);
293
294 Ok(())
295 }
296
297 #[test]
298 fn test_read_avf_debug_policy_without_adb() -> Result<()> {
299 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
300 DebugLevel::FULL,
301 "avf_debug_policy_without_adb.dtbo".as_ref(),
302 )
303 .unwrap();
304
305 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
306 assert!(!debug_config.debug_policy_log);
307 assert!(!debug_config.debug_policy_ramdump);
308 assert!(!debug_config.debug_policy_adb);
309
310 Ok(())
311 }
312
313 #[test]
314 fn test_invalid_sysprop_disables_debug_policy() -> Result<()> {
315 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
316 DebugLevel::NONE,
317 "/a/does/not/exist/path.dtbo".as_ref(),
318 )
319 .unwrap();
320
321 assert_eq!(DebugLevel::NONE, debug_config.debug_level);
322 assert!(!debug_config.debug_policy_log);
323 assert!(!debug_config.debug_policy_ramdump);
324 assert!(!debug_config.debug_policy_adb);
325
326 Ok(())
327 }
Pierre-Clément Tosic57c4df2024-04-15 16:51:01 +0100328
329 #[test]
330 fn test_new_with_debug_level() -> Result<()> {
331 assert_eq!(
332 DebugConfig::new_with_debug_level(DebugLevel::NONE).debug_level,
333 DebugLevel::NONE
334 );
335 assert_eq!(
336 DebugConfig::new_with_debug_level(DebugLevel::FULL).debug_level,
337 DebugLevel::FULL
338 );
339
340 Ok(())
341 }
Jiyong Parked180932023-02-24 19:55:41 +0900342}