blob: 451d1c6a73329dd717340dc0a56553c0ae0191e6 [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
150#[derive(Debug)]
151pub 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
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900165 match system_properties::read(CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP).unwrap_or_default() {
166 Some(path) if !path.is_empty() => {
167 match Self::from_custom_debug_overlay_policy(debug_level, Path::new(&path)) {
168 Ok(debug_config) => {
169 info!("Loaded custom debug policy overlay {path}: {debug_config:?}");
170 return debug_config;
171 }
172 Err(err) => warn!("Failed to load custom debug policy overlay {path}: {err:?}"),
173 };
Jaewan Kim61f86142023-03-28 15:12:52 +0900174 }
175 _ => {
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900176 match Self::from_host(debug_level) {
177 Ok(debug_config) => {
178 info!("Loaded debug policy from host OS: {debug_config:?}");
179 return debug_config;
180 }
181 Err(err) => warn!("Failed to load debug policy from host OS: {err:?}"),
Jaewan Kim61f86142023-03-28 15:12:52 +0900182 };
Jaewan Kim61f86142023-03-28 15:12:52 +0900183 }
184 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900185
186 info!("Debug policy is disabled");
Jaewan Kimf3143242024-03-15 06:56:31 +0000187 Self::new_with_debug_level(debug_level)
188 }
189
190 /// Creates a new DebugConfig with debug level. Only use this for test purpose.
191 pub fn new_with_debug_level(debug_level: DebugLevel) -> Self {
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900192 Self {
193 debug_level,
194 debug_policy_log: false,
195 debug_policy_ramdump: false,
196 debug_policy_adb: false,
197 }
Jaewan Kim61f86142023-03-28 15:12:52 +0900198 }
Jiyong Parked180932023-02-24 19:55:41 +0900199
Jaewan Kim61f86142023-03-28 15:12:52 +0900200 /// Get whether console output should be configred for VM to leave console and adb log.
201 /// Caller should create pipe and prepare for receiving VM log with it.
202 pub fn should_prepare_console_output(&self) -> bool {
203 self.debug_level != DebugLevel::NONE || self.debug_policy_log || self.debug_policy_adb
204 }
Jiyong Parked180932023-02-24 19:55:41 +0900205
Jaewan Kim61f86142023-03-28 15:12:52 +0900206 /// Get whether debug apexes (MICRODROID_REQUIRED_APEXES_DEBUG) are required.
207 pub fn should_include_debug_apexes(&self) -> bool {
208 self.debug_level != DebugLevel::NONE || self.debug_policy_adb
209 }
210
211 /// Decision to support ramdump
212 pub fn is_ramdump_needed(&self) -> bool {
213 self.debug_level != DebugLevel::NONE || self.debug_policy_ramdump
214 }
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900215
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900216 fn from_custom_debug_overlay_policy(debug_level: DebugLevel, path: &Path) -> Result<Self> {
217 match OwnedFdt::from_overlay_onto_new_fdt(path) {
218 Ok(fdt) => Ok(Self {
219 debug_level,
220 debug_policy_log: get_fdt_prop_bool(fdt.as_fdt(), &DP_LOG_PATH)?,
221 debug_policy_ramdump: get_fdt_prop_bool(fdt.as_fdt(), &DP_RAMDUMP_PATH)?,
222 debug_policy_adb: get_fdt_prop_bool(fdt.as_fdt(), &DP_ADB_PATH)?,
223 }),
224 Err(err) => Err(err),
225 }
226 }
227
228 fn from_host(debug_level: DebugLevel) -> Result<Self> {
229 Ok(Self {
230 debug_level,
231 debug_policy_log: get_debug_policy_bool(&DP_LOG_PATH.to_path())?,
232 debug_policy_ramdump: get_debug_policy_bool(&DP_RAMDUMP_PATH.to_path())?,
233 debug_policy_adb: get_debug_policy_bool(&DP_ADB_PATH.to_path())?,
234 })
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900241
242 #[test]
Jaewan Kim46b96702023-09-07 15:24:51 +0900243 fn test_read_avf_debug_policy_with_ramdump() -> Result<()> {
244 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
245 DebugLevel::FULL,
246 "avf_debug_policy_with_ramdump.dtbo".as_ref(),
247 )
248 .unwrap();
249
250 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
251 assert!(!debug_config.debug_policy_log);
252 assert!(debug_config.debug_policy_ramdump);
253 assert!(debug_config.debug_policy_adb);
254
255 Ok(())
256 }
257
258 #[test]
259 fn test_read_avf_debug_policy_without_ramdump() -> Result<()> {
260 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
261 DebugLevel::FULL,
262 "avf_debug_policy_without_ramdump.dtbo".as_ref(),
263 )
264 .unwrap();
265
266 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
267 assert!(!debug_config.debug_policy_log);
268 assert!(!debug_config.debug_policy_ramdump);
269 assert!(debug_config.debug_policy_adb);
270
271 Ok(())
272 }
273
274 #[test]
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900275 fn test_read_avf_debug_policy_with_adb() -> Result<()> {
276 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
277 DebugLevel::FULL,
278 "avf_debug_policy_with_adb.dtbo".as_ref(),
279 )
280 .unwrap();
281
282 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
283 assert!(!debug_config.debug_policy_log);
284 assert!(!debug_config.debug_policy_ramdump);
285 assert!(debug_config.debug_policy_adb);
286
287 Ok(())
288 }
289
290 #[test]
291 fn test_read_avf_debug_policy_without_adb() -> Result<()> {
292 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
293 DebugLevel::FULL,
294 "avf_debug_policy_without_adb.dtbo".as_ref(),
295 )
296 .unwrap();
297
298 assert_eq!(DebugLevel::FULL, debug_config.debug_level);
299 assert!(!debug_config.debug_policy_log);
300 assert!(!debug_config.debug_policy_ramdump);
301 assert!(!debug_config.debug_policy_adb);
302
303 Ok(())
304 }
305
306 #[test]
307 fn test_invalid_sysprop_disables_debug_policy() -> Result<()> {
308 let debug_config = DebugConfig::from_custom_debug_overlay_policy(
309 DebugLevel::NONE,
310 "/a/does/not/exist/path.dtbo".as_ref(),
311 )
312 .unwrap();
313
314 assert_eq!(DebugLevel::NONE, debug_config.debug_level);
315 assert!(!debug_config.debug_policy_log);
316 assert!(!debug_config.debug_policy_ramdump);
317 assert!(!debug_config.debug_policy_adb);
318
319 Ok(())
320 }
Jiyong Parked180932023-02-24 19:55:41 +0900321}