blob: 82eedc4d17d30307c3d5f01487830fdae3b85506 [file] [log] [blame]
Alan Stokes8c840442021-11-26 15:54:30 +00001/*
2 * Copyright 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alan Stokesda596932021-12-15 17:48:55 +000017//! Handle running odrefresh in the VM, with an async interface to allow cancellation
18
19use crate::fd_server_helper::FdServerConfig;
Alan Stokes8c840442021-11-26 15:54:30 +000020use crate::instance_starter::CompOsInstance;
Alan Stokes8c840442021-11-26 15:54:30 +000021use android_system_composd::aidl::android::system::composd::{
22 ICompilationTask::ICompilationTask, ICompilationTaskCallback::ICompilationTaskCallback,
23};
24use android_system_composd::binder::{Interface, Result as BinderResult, Strong};
Alan Stokes126fd512021-12-16 15:00:01 +000025use anyhow::{Context, Result};
Alan Stokes2d2e4db2022-01-28 16:41:52 +000026use compos_aidl_interface::aidl::com::android::compos::ICompOsService::{
27 CompilationMode::CompilationMode, ICompOsService,
28};
Alan Stokes46a1dff2021-12-14 10:56:05 +000029use compos_common::odrefresh::ExitCode;
Alan Stokes454069c2022-02-03 11:21:19 +000030use log::{error, info, warn};
Alan Stokesda596932021-12-15 17:48:55 +000031use rustutils::system_properties;
Alan Stokes35bac3c2021-12-16 14:37:24 +000032use std::fs::{remove_dir_all, File, OpenOptions};
Alan Stokesda596932021-12-15 17:48:55 +000033use std::os::unix::fs::OpenOptionsExt;
34use std::os::unix::io::AsRawFd;
35use std::path::Path;
Alan Stokes8c840442021-11-26 15:54:30 +000036use std::sync::{Arc, Mutex};
37use std::thread;
38
Alan Stokesda596932021-12-15 17:48:55 +000039const ART_APEX_DATA: &str = "/data/misc/apexdata/com.android.art";
40
Alan Stokes8c840442021-11-26 15:54:30 +000041#[derive(Clone)]
42pub struct OdrefreshTask {
43 running_task: Arc<Mutex<Option<RunningTask>>>,
44}
45
46impl Interface for OdrefreshTask {}
47
48impl ICompilationTask for OdrefreshTask {
49 fn cancel(&self) -> BinderResult<()> {
50 let task = self.take();
51 // Drop the VM, which should end compilation - and cause our thread to exit
52 drop(task);
53 Ok(())
54 }
55}
56
Alan Stokesda596932021-12-15 17:48:55 +000057struct RunningTask {
58 callback: Strong<dyn ICompilationTaskCallback>,
59 #[allow(dead_code)] // Keeps the CompOS VM alive
60 comp_os: Arc<CompOsInstance>,
61}
62
Alan Stokes8c840442021-11-26 15:54:30 +000063impl OdrefreshTask {
64 /// Return the current running task, if any, removing it from this CompilationTask.
65 /// Once removed, meaning the task has ended or been canceled, further calls will always return
66 /// None.
67 fn take(&self) -> Option<RunningTask> {
68 self.running_task.lock().unwrap().take()
69 }
70
71 pub fn start(
72 comp_os: Arc<CompOsInstance>,
Alan Stokes2d2e4db2022-01-28 16:41:52 +000073 compilation_mode: CompilationMode,
Alan Stokesac9aa1a2021-12-14 11:32:13 +000074 target_dir_name: String,
Alan Stokes8c840442021-11-26 15:54:30 +000075 callback: &Strong<dyn ICompilationTaskCallback>,
76 ) -> Result<OdrefreshTask> {
77 let service = comp_os.get_service();
78 let task = RunningTask { comp_os, callback: callback.clone() };
79 let task = OdrefreshTask { running_task: Arc::new(Mutex::new(Some(task))) };
80
Alan Stokes2d2e4db2022-01-28 16:41:52 +000081 task.clone().start_thread(service, compilation_mode, target_dir_name);
Alan Stokes8c840442021-11-26 15:54:30 +000082
83 Ok(task)
84 }
85
Alan Stokes2d2e4db2022-01-28 16:41:52 +000086 fn start_thread(
87 self,
88 service: Strong<dyn ICompOsService>,
89 compilation_mode: CompilationMode,
90 target_dir_name: String,
91 ) {
Alan Stokes8c840442021-11-26 15:54:30 +000092 thread::spawn(move || {
Alan Stokes2d2e4db2022-01-28 16:41:52 +000093 let exit_code = run_in_vm(service, compilation_mode, &target_dir_name);
Alan Stokes8c840442021-11-26 15:54:30 +000094
95 let task = self.take();
96 // We don't do the callback if cancel has already happened.
97 if let Some(task) = task {
98 let result = match exit_code {
Alan Stokes454069c2022-02-03 11:21:19 +000099 Ok(ExitCode::CompilationSuccess) => {
100 info!("CompilationSuccess");
101 task.callback.onSuccess()
102 }
Alan Stokes8c840442021-11-26 15:54:30 +0000103 Ok(exit_code) => {
104 error!("Unexpected odrefresh result: {:?}", exit_code);
105 task.callback.onFailure()
106 }
107 Err(e) => {
108 error!("Running odrefresh failed: {:?}", e);
109 task.callback.onFailure()
110 }
111 };
112 if let Err(e) = result {
113 warn!("Failed to deliver callback: {:?}", e);
114 }
115 }
116 });
117 }
118}
119
Alan Stokes2d2e4db2022-01-28 16:41:52 +0000120fn run_in_vm(
121 service: Strong<dyn ICompOsService>,
122 compilation_mode: CompilationMode,
123 target_dir_name: &str,
124) -> Result<ExitCode> {
Alan Stokes35bac3c2021-12-16 14:37:24 +0000125 let output_root = Path::new(ART_APEX_DATA);
126
127 // We need to remove the target directory because odrefresh running in compos will create it
128 // (and can't see the existing one, since authfs doesn't show it existing files in an output
129 // directory).
130 let target_path = output_root.join(target_dir_name);
Alan Stokesa4542ec2021-12-20 09:39:33 +0000131 if target_path.exists() {
132 remove_dir_all(&target_path)
133 .with_context(|| format!("Failed to delete {}", target_path.display()))?;
134 }
Alan Stokes35bac3c2021-12-16 14:37:24 +0000135
Alan Stokesda596932021-12-15 17:48:55 +0000136 let staging_dir = open_dir(composd_native::palette_create_odrefresh_staging_directory()?)?;
137 let system_dir = open_dir(Path::new("/system"))?;
Alan Stokes35bac3c2021-12-16 14:37:24 +0000138 let output_dir = open_dir(output_root)?;
Alan Stokesda596932021-12-15 17:48:55 +0000139
140 // Spawn a fd_server to serve the FDs.
141 let fd_server_config = FdServerConfig {
142 ro_dir_fds: vec![system_dir.as_raw_fd()],
143 rw_dir_fds: vec![staging_dir.as_raw_fd(), output_dir.as_raw_fd()],
144 ..Default::default()
145 };
146 let fd_server_raii = fd_server_config.into_fd_server()?;
147
148 let zygote_arch = system_properties::read("ro.zygote")?;
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800149 let system_server_compiler_filter =
150 system_properties::read("dalvik.vm.systemservercompilerfilter").unwrap_or_default();
Alan Stokesda596932021-12-15 17:48:55 +0000151 let exit_code = service.odrefresh(
Alan Stokes2d2e4db2022-01-28 16:41:52 +0000152 compilation_mode,
Alan Stokesda596932021-12-15 17:48:55 +0000153 system_dir.as_raw_fd(),
154 output_dir.as_raw_fd(),
155 staging_dir.as_raw_fd(),
156 target_dir_name,
157 &zygote_arch,
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800158 &system_server_compiler_filter,
Alan Stokesda596932021-12-15 17:48:55 +0000159 )?;
160
161 drop(fd_server_raii);
Alan Stokes126fd512021-12-16 15:00:01 +0000162 ExitCode::from_i32(exit_code.into())
Alan Stokesda596932021-12-15 17:48:55 +0000163}
164
165/// Returns an owned FD of the directory. It currently returns a `File` as a FD owner, but
166/// it's better to use `std::os::unix::io::OwnedFd` once/if it becomes standard.
167fn open_dir(path: &Path) -> Result<File> {
168 OpenOptions::new()
169 .custom_flags(libc::O_DIRECTORY)
170 .read(true) // O_DIRECTORY can only be opened with read
171 .open(path)
172 .with_context(|| format!("Failed to open {:?} directory as path fd", path))
Alan Stokes8c840442021-11-26 15:54:30 +0000173}