blob: 44b40495871c36f2d879489c20f98c1990ec6e29 [file] [log] [blame]
Victor Hsieh51789de2021-08-06 16:50:49 -07001/*
2 * Copyright (C) 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
Victor Hsieh6e340382021-08-13 12:18:02 -070017use anyhow::{anyhow, bail, Context, Result};
Victor Hsieh51789de2021-08-06 16:50:49 -070018use log::error;
19use minijail::{self, Minijail};
Victor Hsiehf9968692021-11-18 11:34:39 -080020use std::env;
21use std::fs::{create_dir, File};
Victor Hsieh6e340382021-08-13 12:18:02 -070022use std::os::unix::io::{AsRawFd, RawFd};
Victor Hsiehf9968692021-11-18 11:34:39 -080023use std::path::{Path, PathBuf};
Victor Hsieh51789de2021-08-06 16:50:49 -070024
Victor Hsieh9ed27182021-08-25 15:52:42 -070025use crate::fsverity;
Victor Hsieh51789de2021-08-06 16:50:49 -070026use authfs_aidl_interface::aidl::com::android::virt::fs::{
Victor Hsieh015bcb52021-11-17 17:28:01 -080027 AuthFsConfig::{
Victor Hsiehf9968692021-11-18 11:34:39 -080028 AuthFsConfig, InputDirFdAnnotation::InputDirFdAnnotation,
29 InputFdAnnotation::InputFdAnnotation, OutputDirFdAnnotation::OutputDirFdAnnotation,
30 OutputFdAnnotation::OutputFdAnnotation,
Victor Hsieh015bcb52021-11-17 17:28:01 -080031 },
32 IAuthFs::IAuthFs,
33 IAuthFsService::IAuthFsService,
Victor Hsieh51789de2021-08-06 16:50:49 -070034};
35use authfs_aidl_interface::binder::{ParcelFileDescriptor, Strong};
Victor Hsieh13333e82021-09-03 15:17:32 -070036use compos_aidl_interface::aidl::com::android::compos::FdAnnotation::FdAnnotation;
Victor Hsieh51789de2021-08-06 16:50:49 -070037
Victor Hsiehf9968692021-11-18 11:34:39 -080038const FD_SERVER_PORT: i32 = 3264; // TODO: support dynamic port
39
Victor Hsieh51789de2021-08-06 16:50:49 -070040/// The number that represents the file descriptor number expecting by the task. The number may be
41/// meaningless in the current process.
42pub type PseudoRawFd = i32;
43
Victor Hsieh6e340382021-08-13 12:18:02 -070044pub enum CompilerOutput {
45 /// Fs-verity digests of output files, if the compiler finishes successfully.
Victor Hsieh9ed27182021-08-25 15:52:42 -070046 Digests {
47 oat: fsverity::Sha256Digest,
48 vdex: fsverity::Sha256Digest,
49 image: fsverity::Sha256Digest,
50 },
Victor Hsieh6e340382021-08-13 12:18:02 -070051 /// Exit code returned by the compiler, if not 0.
52 ExitCode(i8),
53}
54
55struct CompilerOutputParcelFds {
56 oat: ParcelFileDescriptor,
57 vdex: ParcelFileDescriptor,
58 image: ParcelFileDescriptor,
59}
60
Victor Hsiehf9968692021-11-18 11:34:39 -080061pub fn odrefresh(
62 odrefresh_path: &Path,
63 system_dir_fd: i32,
64 output_dir_fd: i32,
65 zygote_arch: &str,
66 authfs_service: Strong<dyn IAuthFsService>,
67) -> Result<CompilerOutput> {
68 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
69 // is out of scope.
70 let authfs_config = AuthFsConfig {
71 port: FD_SERVER_PORT,
72 inputDirFdAnnotations: vec![InputDirFdAnnotation {
73 fd: system_dir_fd,
74 // TODO(206869687): Replace /dev/null with the real path when possible.
75 manifestPath: "/dev/null".to_string(),
76 prefix: "/system".to_string(),
77 }],
78 outputDirFdAnnotations: vec![OutputDirFdAnnotation { fd: output_dir_fd }],
79 ..Default::default()
80 };
81 let authfs = authfs_service.mount(&authfs_config)?;
82 let mountpoint = PathBuf::from(authfs.getMountPoint()?);
83
84 let mut android_root = mountpoint.clone();
85 android_root.push(system_dir_fd.to_string());
86 android_root.push("system");
87 env::set_var("ANDROID_ROOT", &android_root);
88
Victor Hsieh64df53d2021-11-30 17:09:51 -080089 let mut art_apex_data = mountpoint.clone();
90 art_apex_data.push(output_dir_fd.to_string());
91 env::set_var("ART_APEX_DATA", &art_apex_data);
92
Victor Hsiehf9968692021-11-18 11:34:39 -080093 let mut staging_dir = mountpoint;
94 staging_dir.push(output_dir_fd.to_string());
95 staging_dir.push("staging");
Victor Hsieh64df53d2021-11-30 17:09:51 -080096 create_dir(&staging_dir)
97 .with_context(|| format!("Create staging directory {}", staging_dir.display()))?;
Victor Hsiehf9968692021-11-18 11:34:39 -080098
99 let args = vec![
100 "odrefresh".to_string(),
101 format!("--zygote-arch={}", zygote_arch),
Victor Hsieh64df53d2021-11-30 17:09:51 -0800102 "--no-refresh".to_string(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800103 format!("--staging-dir={}", staging_dir.display()),
104 "--force-compile".to_string(),
105 ];
106 let jail = spawn_jailed_task(odrefresh_path, &args, Vec::new() /* fd_mapping */)
107 .context("Spawn odrefresh")?;
108 match jail.wait() {
109 // TODO(161471326): On success, sign all files in the output directory.
110 Ok(()) => Ok(CompilerOutput::ExitCode(0)),
111 Err(minijail::Error::ReturnCode(exit_code)) => {
Victor Hsieh64df53d2021-11-30 17:09:51 -0800112 error!("odrefresh failed with exit code {}", exit_code);
Victor Hsiehf9968692021-11-18 11:34:39 -0800113 Ok(CompilerOutput::ExitCode(exit_code as i8))
114 }
115 Err(e) => {
116 bail!("Unexpected minijail error: {}", e)
117 }
118 }
119}
120
Victor Hsieh13333e82021-09-03 15:17:32 -0700121/// Runs the compiler with given flags with file descriptors described in `fd_annotation` retrieved
122/// via `authfs_service`. Returns exit code of the compiler process.
Victor Hsieh3c044c42021-10-01 17:17:10 -0700123pub fn compile_cmd(
Victor Hsieh51789de2021-08-06 16:50:49 -0700124 compiler_path: &Path,
125 compiler_args: &[String],
126 authfs_service: Strong<dyn IAuthFsService>,
Victor Hsieh13333e82021-09-03 15:17:32 -0700127 fd_annotation: &FdAnnotation,
Victor Hsieh6e340382021-08-13 12:18:02 -0700128) -> Result<CompilerOutput> {
129 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
130 // is out of scope.
Victor Hsieh13333e82021-09-03 15:17:32 -0700131 let authfs_config = build_authfs_config(fd_annotation);
Victor Hsieh51789de2021-08-06 16:50:49 -0700132 let authfs = authfs_service.mount(&authfs_config)?;
133
134 // The task expects to receive FD numbers that match its flags (e.g. --zip-fd=42) prepared
135 // on the host side. Since the local FD opened from authfs (e.g. /authfs/42) may not match
136 // the task's expectation, prepare a FD mapping and let minijail prepare the correct FD
137 // setup.
138 let fd_mapping =
139 open_authfs_files_for_fd_mapping(&authfs, &authfs_config).context("Open on authfs")?;
140
141 let jail =
142 spawn_jailed_task(compiler_path, compiler_args, fd_mapping).context("Spawn dex2oat")?;
143 let jail_result = jail.wait();
144
Victor Hsieh6e340382021-08-13 12:18:02 -0700145 let parcel_fds = parse_compiler_args(&authfs, compiler_args)?;
146 let oat_file: &File = parcel_fds.oat.as_ref();
147 let vdex_file: &File = parcel_fds.vdex.as_ref();
148 let image_file: &File = parcel_fds.image.as_ref();
Victor Hsieh51789de2021-08-06 16:50:49 -0700149
150 match jail_result {
Victor Hsieh6e340382021-08-13 12:18:02 -0700151 Ok(()) => Ok(CompilerOutput::Digests {
Victor Hsieh9ed27182021-08-25 15:52:42 -0700152 oat: fsverity::measure(oat_file.as_raw_fd())?,
153 vdex: fsverity::measure(vdex_file.as_raw_fd())?,
154 image: fsverity::measure(image_file.as_raw_fd())?,
Victor Hsieh6e340382021-08-13 12:18:02 -0700155 }),
Victor Hsieh51789de2021-08-06 16:50:49 -0700156 Err(minijail::Error::ReturnCode(exit_code)) => {
Victor Hsieh6e340382021-08-13 12:18:02 -0700157 error!("dex2oat failed with exit code {}", exit_code);
158 Ok(CompilerOutput::ExitCode(exit_code as i8))
Victor Hsieh51789de2021-08-06 16:50:49 -0700159 }
160 Err(e) => {
161 bail!("Unexpected minijail error: {}", e)
162 }
163 }
164}
165
Victor Hsieh6e340382021-08-13 12:18:02 -0700166fn parse_compiler_args(
167 authfs: &Strong<dyn IAuthFs>,
168 args: &[String],
169) -> Result<CompilerOutputParcelFds> {
170 const OAT_FD_PREFIX: &str = "--oat-fd=";
171 const VDEX_FD_PREFIX: &str = "--output-vdex-fd=";
172 const IMAGE_FD_PREFIX: &str = "--image-fd=";
173 const APP_IMAGE_FD_PREFIX: &str = "--app-image-fd=";
174
175 let mut oat = None;
176 let mut vdex = None;
177 let mut image = None;
178
179 for arg in args {
180 if let Some(value) = arg.strip_prefix(OAT_FD_PREFIX) {
181 let fd = value.parse::<RawFd>().context("Invalid --oat-fd flag")?;
182 debug_assert!(oat.is_none());
183 oat = Some(authfs.openFile(fd, false)?);
184 } else if let Some(value) = arg.strip_prefix(VDEX_FD_PREFIX) {
185 let fd = value.parse::<RawFd>().context("Invalid --output-vdex-fd flag")?;
186 debug_assert!(vdex.is_none());
187 vdex = Some(authfs.openFile(fd, false)?);
188 } else if let Some(value) = arg.strip_prefix(IMAGE_FD_PREFIX) {
189 let fd = value.parse::<RawFd>().context("Invalid --image-fd flag")?;
190 debug_assert!(image.is_none());
191 image = Some(authfs.openFile(fd, false)?);
192 } else if let Some(value) = arg.strip_prefix(APP_IMAGE_FD_PREFIX) {
193 let fd = value.parse::<RawFd>().context("Invalid --app-image-fd flag")?;
194 debug_assert!(image.is_none());
195 image = Some(authfs.openFile(fd, false)?);
196 }
197 }
198
199 Ok(CompilerOutputParcelFds {
200 oat: oat.ok_or_else(|| anyhow!("Missing --oat-fd"))?,
201 vdex: vdex.ok_or_else(|| anyhow!("Missing --vdex-fd"))?,
202 image: image.ok_or_else(|| anyhow!("Missing --image-fd or --app-image-fd"))?,
203 })
204}
205
Victor Hsieh13333e82021-09-03 15:17:32 -0700206fn build_authfs_config(fd_annotation: &FdAnnotation) -> AuthFsConfig {
Victor Hsieh51789de2021-08-06 16:50:49 -0700207 AuthFsConfig {
Victor Hsiehf9968692021-11-18 11:34:39 -0800208 port: FD_SERVER_PORT,
Victor Hsieh13333e82021-09-03 15:17:32 -0700209 inputFdAnnotations: fd_annotation
210 .input_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700211 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700212 .map(|fd| InputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700213 .collect(),
Victor Hsieh13333e82021-09-03 15:17:32 -0700214 outputFdAnnotations: fd_annotation
215 .output_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700216 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700217 .map(|fd| OutputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700218 .collect(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800219 ..Default::default()
Victor Hsieh51789de2021-08-06 16:50:49 -0700220 }
221}
222
223fn open_authfs_files_for_fd_mapping(
224 authfs: &Strong<dyn IAuthFs>,
225 config: &AuthFsConfig,
226) -> Result<Vec<(ParcelFileDescriptor, PseudoRawFd)>> {
227 let mut fd_mapping = Vec::new();
228
229 let results: Result<Vec<_>> = config
230 .inputFdAnnotations
231 .iter()
232 .map(|annotation| Ok((authfs.openFile(annotation.fd, false)?, annotation.fd)))
233 .collect();
234 fd_mapping.append(&mut results?);
235
236 let results: Result<Vec<_>> = config
237 .outputFdAnnotations
238 .iter()
239 .map(|annotation| Ok((authfs.openFile(annotation.fd, true)?, annotation.fd)))
240 .collect();
241 fd_mapping.append(&mut results?);
242
243 Ok(fd_mapping)
244}
245
246fn spawn_jailed_task(
247 executable: &Path,
248 args: &[String],
249 fd_mapping: Vec<(ParcelFileDescriptor, PseudoRawFd)>,
250) -> Result<Minijail> {
251 // TODO(b/185175567): Run in a more restricted sandbox.
252 let jail = Minijail::new()?;
253 let preserve_fds: Vec<_> = fd_mapping.iter().map(|(f, id)| (f.as_raw_fd(), *id)).collect();
254 let _pid = jail.run_remap(executable, preserve_fds.as_slice(), args)?;
255 Ok(jail)
256}