blob: 52ac964f699d04b75818e42c8082950d33396707 [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};
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010029use vmconfig::get_debug_level;
Jaewan Kim61f86142023-03-28 15:12:52 +090030
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090031const CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP: &str =
32 "hypervisor.virtualizationmanager.debug_policy.path";
33const DEVICE_TREE_EMPTY_TREE_SIZE_BYTES: usize = 100; // rough estimation.
Jaewan Kim61f86142023-03-28 15:12:52 +090034
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090035struct DPPath {
36 node_path: CString,
37 prop_name: CString,
38}
39
40impl DPPath {
41 fn new(node_path: &str, prop_name: &str) -> Result<Self, NulError> {
42 Ok(Self { node_path: CString::new(node_path)?, prop_name: CString::new(prop_name)? })
43 }
44
45 fn to_path(&self) -> PathBuf {
Andrew Walbranb58d1b42023-07-07 13:54:49 +010046 // unwrap() is safe for to_str() because node_path and prop_name were &str.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090047 PathBuf::from(
48 [
Jaewan Kim1f0135b2024-01-31 14:59:47 +090049 "/proc/device-tree",
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090050 self.node_path.to_str().unwrap(),
51 "/",
52 self.prop_name.to_str().unwrap(),
53 ]
54 .concat(),
55 )
56 }
57}
58
59lazy_static! {
60 static ref DP_LOG_PATH: DPPath = DPPath::new("/avf/guest/common", "log").unwrap();
61 static ref DP_RAMDUMP_PATH: DPPath = DPPath::new("/avf/guest/common", "ramdump").unwrap();
62 static ref DP_ADB_PATH: DPPath = DPPath::new("/avf/guest/microdroid", "adb").unwrap();
63}
64
65/// Get debug policy value in bool. It's true iff the value is explicitly set to <1>.
66fn get_debug_policy_bool(path: &Path) -> Result<bool> {
67 let value = match fs::read(path) {
68 Ok(value) => value,
69 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(false),
70 Err(error) => Err(error).with_context(|| format!("Failed to read {path:?}"))?,
71 };
72
73 // DT spec uses big endian although Android is always little endian.
74 match u32::from_be_bytes(value.try_into().map_err(|_| anyhow!("Malformed value in {path:?}"))?)
75 {
76 0 => Ok(false),
77 1 => Ok(true),
78 value => Err(anyhow!("Invalid value {value} in {path:?}")),
79 }
80}
81
82/// Get property value in bool. It's true iff the value is explicitly set to <1>.
83/// It takes path as &str instead of &Path, because we don't want OsStr.
84fn get_fdt_prop_bool(fdt: &Fdt, path: &DPPath) -> Result<bool> {
85 let (node_path, prop_name) = (&path.node_path, &path.prop_name);
86 let node = match fdt.node(node_path) {
87 Ok(Some(node)) => node,
Chris Wailes9d09f572024-01-16 13:31:02 -080088 Err(error) if error != FdtError::NotFound => {
89 Err(Error::msg(error)).with_context(|| format!("Failed to get node {node_path:?}"))?
90 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +090091 _ => return Ok(false),
92 };
93
94 match node.getprop_u32(prop_name) {
95 Ok(Some(0)) => Ok(false),
96 Ok(Some(1)) => Ok(true),
97 Ok(Some(_)) => Err(anyhow!("Invalid prop value {prop_name:?} in node {node_path:?}")),
Chris Wailes9d09f572024-01-16 13:31:02 -080098 Err(error) if error != FdtError::NotFound => {
99 Err(Error::msg(error)).with_context(|| format!("Failed to get prop {prop_name:?}"))
100 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900101 _ => Ok(false),
102 }
103}
104
105/// Fdt with owned vector.
106struct OwnedFdt {
107 buffer: Vec<u8>,
108}
109
110impl OwnedFdt {
111 fn from_overlay_onto_new_fdt(overlay_file_path: &Path) -> Result<Self> {
112 let mut overlay_buf = match fs::read(overlay_file_path) {
113 Ok(fdt) => fdt,
114 Err(error) if error.kind() == ErrorKind::NotFound => Default::default(),
115 Err(error) => {
116 Err(error).with_context(|| format!("Failed to read {overlay_file_path:?}"))?
117 }
118 };
119
120 let overlay_buf_size = overlay_buf.len();
121
122 let fdt_estimated_size = overlay_buf_size + DEVICE_TREE_EMPTY_TREE_SIZE_BYTES;
123 let mut fdt_buf = vec![0_u8; fdt_estimated_size];
124 let fdt = Fdt::create_empty_tree(fdt_buf.as_mut_slice())
125 .map_err(Error::msg)
126 .context("Failed to create an empty device tree")?;
127
128 if !overlay_buf.is_empty() {
129 let overlay_fdt = Fdt::from_mut_slice(overlay_buf.as_mut_slice())
130 .map_err(Error::msg)
131 .with_context(|| "Malformed {overlay_file_path:?}")?;
132
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100133 // SAFETY: Return immediately if error happens. Damaged fdt_buf and fdt are discarded.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900134 unsafe {
135 fdt.apply_overlay(overlay_fdt).map_err(Error::msg).with_context(|| {
136 "Failed to overlay {overlay_file_path:?} onto empty device tree"
137 })?;
138 }
139 }
140
141 Ok(Self { buffer: fdt_buf })
142 }
143
144 fn as_fdt(&self) -> &Fdt {
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100145 // SAFETY: Checked validity of buffer when instantiate.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900146 unsafe { Fdt::unchecked_from_slice(&self.buffer) }
147 }
148}
Jaewan Kim61f86142023-03-28 15:12:52 +0900149
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100150/// Debug configurations for debug policy.
151#[derive(Debug, Default)]
152pub struct DebugPolicy {
153 log: bool,
154 ramdump: bool,
155 adb: bool,
156}
157
158impl DebugPolicy {
159 /// Build from the passed DTBO path.
160 pub fn from_overlay(path: &Path) -> Result<Self> {
161 let owned_fdt = OwnedFdt::from_overlay_onto_new_fdt(path)?;
162 let fdt = owned_fdt.as_fdt();
163
164 Ok(Self {
165 log: get_fdt_prop_bool(fdt, &DP_LOG_PATH)?,
166 ramdump: get_fdt_prop_bool(fdt, &DP_RAMDUMP_PATH)?,
167 adb: get_fdt_prop_bool(fdt, &DP_ADB_PATH)?,
168 })
169 }
170
171 /// Build from the /avf/guest subtree of the host DT.
172 pub fn from_host() -> Result<Self> {
173 Ok(Self {
174 log: get_debug_policy_bool(&DP_LOG_PATH.to_path())?,
175 ramdump: get_debug_policy_bool(&DP_RAMDUMP_PATH.to_path())?,
176 adb: get_debug_policy_bool(&DP_ADB_PATH.to_path())?,
177 })
178 }
179}
180
Jaewan Kim61f86142023-03-28 15:12:52 +0900181/// Debug configurations for both debug level and debug policy
Pierre-Clément Tosic57c4df2024-04-15 16:51:01 +0100182#[derive(Debug, Default)]
Jaewan Kim61f86142023-03-28 15:12:52 +0900183pub struct DebugConfig {
184 pub debug_level: DebugLevel,
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100185 debug_policy: DebugPolicy,
Jaewan Kim61f86142023-03-28 15:12:52 +0900186}
Jaewan Kimc03f6612023-02-20 00:06:26 +0900187
Jaewan Kim61f86142023-03-28 15:12:52 +0900188impl DebugConfig {
Jaewan Kimf3143242024-03-15 06:56:31 +0000189 pub fn new(config: &VirtualMachineConfig) -> Self {
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +0100190 let debug_level = get_debug_level(config).unwrap_or(DebugLevel::NONE);
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100191 let debug_policy = Self::get_debug_policy().unwrap_or_else(|| {
192 info!("Debug policy is disabled");
193 Default::default()
194 });
Jaewan Kimf3143242024-03-15 06:56:31 +0000195
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100196 Self { debug_level, debug_policy }
197 }
198
199 fn get_debug_policy() -> Option<DebugPolicy> {
Pierre-Clément Tosie4d9f392024-04-16 15:51:00 +0100200 let dp_sysprop = system_properties::read(CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP);
201 let custom_dp = dp_sysprop.unwrap_or_else(|e| {
202 warn!("Failed to read sysprop {CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP}: {e}");
203 Default::default()
204 });
205
206 match custom_dp {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100207 Some(path) if !path.is_empty() => match DebugPolicy::from_overlay(Path::new(&path)) {
208 Ok(dp) => {
209 info!("Loaded custom debug policy overlay {path}: {dp:?}");
210 Some(dp)
211 }
212 Err(err) => {
213 warn!("Failed to load custom debug policy overlay {path}: {err:?}");
214 None
215 }
216 },
217 _ => match DebugPolicy::from_host() {
218 Ok(dp) => {
219 info!("Loaded debug policy from host OS: {dp:?}");
220 Some(dp)
221 }
222 Err(err) => {
223 warn!("Failed to load debug policy from host OS: {err:?}");
224 None
225 }
226 },
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900227 }
Jaewan Kim61f86142023-03-28 15:12:52 +0900228 }
Jiyong Parked180932023-02-24 19:55:41 +0900229
Pierre-Clément Tosic57c4df2024-04-15 16:51:01 +0100230 #[cfg(test)]
231 /// Creates a new DebugConfig with debug level. Only use this for test purpose.
232 pub(crate) fn new_with_debug_level(debug_level: DebugLevel) -> Self {
233 Self { debug_level, ..Default::default() }
234 }
235
Jaewan Kim61f86142023-03-28 15:12:52 +0900236 /// Get whether console output should be configred for VM to leave console and adb log.
237 /// Caller should create pipe and prepare for receiving VM log with it.
238 pub fn should_prepare_console_output(&self) -> bool {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100239 self.debug_level != DebugLevel::NONE || self.debug_policy.log || self.debug_policy.adb
Jaewan Kim61f86142023-03-28 15:12:52 +0900240 }
Jiyong Parked180932023-02-24 19:55:41 +0900241
Jaewan Kim61f86142023-03-28 15:12:52 +0900242 /// Get whether debug apexes (MICRODROID_REQUIRED_APEXES_DEBUG) are required.
243 pub fn should_include_debug_apexes(&self) -> bool {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100244 self.debug_level != DebugLevel::NONE || self.debug_policy.adb
Jaewan Kim61f86142023-03-28 15:12:52 +0900245 }
246
247 /// Decision to support ramdump
248 pub fn is_ramdump_needed(&self) -> bool {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100249 self.debug_level != DebugLevel::NONE || self.debug_policy.ramdump
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900256
257 #[test]
Jaewan Kim46b96702023-09-07 15:24:51 +0900258 fn test_read_avf_debug_policy_with_ramdump() -> Result<()> {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100259 let debug_policy =
260 DebugPolicy::from_overlay("avf_debug_policy_with_ramdump.dtbo".as_ref()).unwrap();
Jaewan Kim46b96702023-09-07 15:24:51 +0900261
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100262 assert!(!debug_policy.log);
263 assert!(debug_policy.ramdump);
264 assert!(debug_policy.adb);
Jaewan Kim46b96702023-09-07 15:24:51 +0900265
266 Ok(())
267 }
268
269 #[test]
270 fn test_read_avf_debug_policy_without_ramdump() -> Result<()> {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100271 let debug_policy =
272 DebugPolicy::from_overlay("avf_debug_policy_without_ramdump.dtbo".as_ref()).unwrap();
Jaewan Kim46b96702023-09-07 15:24:51 +0900273
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100274 assert!(!debug_policy.log);
275 assert!(!debug_policy.ramdump);
276 assert!(debug_policy.adb);
Jaewan Kim46b96702023-09-07 15:24:51 +0900277
278 Ok(())
279 }
280
281 #[test]
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900282 fn test_read_avf_debug_policy_with_adb() -> Result<()> {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100283 let debug_policy =
284 DebugPolicy::from_overlay("avf_debug_policy_with_adb.dtbo".as_ref()).unwrap();
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900285
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100286 assert!(!debug_policy.log);
287 assert!(!debug_policy.ramdump);
288 assert!(debug_policy.adb);
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900289
290 Ok(())
291 }
292
293 #[test]
294 fn test_read_avf_debug_policy_without_adb() -> Result<()> {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100295 let debug_policy =
296 DebugPolicy::from_overlay("avf_debug_policy_without_adb.dtbo".as_ref()).unwrap();
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900297
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100298 assert!(!debug_policy.log);
299 assert!(!debug_policy.ramdump);
300 assert!(!debug_policy.adb);
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900301
302 Ok(())
303 }
304
305 #[test]
306 fn test_invalid_sysprop_disables_debug_policy() -> Result<()> {
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100307 let debug_policy =
308 DebugPolicy::from_overlay("/a/does/not/exist/path.dtbo".as_ref()).unwrap();
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900309
Pierre-Clément Tosi27fe2b62024-04-15 18:36:33 +0100310 assert!(!debug_policy.log);
311 assert!(!debug_policy.ramdump);
312 assert!(!debug_policy.adb);
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900313
314 Ok(())
315 }
Pierre-Clément Tosic57c4df2024-04-15 16:51:01 +0100316
317 #[test]
318 fn test_new_with_debug_level() -> Result<()> {
319 assert_eq!(
320 DebugConfig::new_with_debug_level(DebugLevel::NONE).debug_level,
321 DebugLevel::NONE
322 );
323 assert_eq!(
324 DebugConfig::new_with_debug_level(DebugLevel::FULL).debug_level,
325 DebugLevel::FULL
326 );
327
328 Ok(())
329 }
Jiyong Parked180932023-02-24 19:55:41 +0900330}