blob: b726a1ea80fd2fe42ee16bba500f2e71cd0b7a54 [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
89 let mut staging_dir = mountpoint;
90 staging_dir.push(output_dir_fd.to_string());
91 staging_dir.push("staging");
92 create_dir(&staging_dir).context("Create staging directory")?;
93
94 let args = vec![
95 "odrefresh".to_string(),
96 format!("--zygote-arch={}", zygote_arch),
97 format!("--staging-dir={}", staging_dir.display()),
98 "--force-compile".to_string(),
99 ];
100 let jail = spawn_jailed_task(odrefresh_path, &args, Vec::new() /* fd_mapping */)
101 .context("Spawn odrefresh")?;
102 match jail.wait() {
103 // TODO(161471326): On success, sign all files in the output directory.
104 Ok(()) => Ok(CompilerOutput::ExitCode(0)),
105 Err(minijail::Error::ReturnCode(exit_code)) => {
106 error!("dex2oat failed with exit code {}", exit_code);
107 Ok(CompilerOutput::ExitCode(exit_code as i8))
108 }
109 Err(e) => {
110 bail!("Unexpected minijail error: {}", e)
111 }
112 }
113}
114
Victor Hsieh13333e82021-09-03 15:17:32 -0700115/// Runs the compiler with given flags with file descriptors described in `fd_annotation` retrieved
116/// via `authfs_service`. Returns exit code of the compiler process.
Victor Hsieh3c044c42021-10-01 17:17:10 -0700117pub fn compile_cmd(
Victor Hsieh51789de2021-08-06 16:50:49 -0700118 compiler_path: &Path,
119 compiler_args: &[String],
120 authfs_service: Strong<dyn IAuthFsService>,
Victor Hsieh13333e82021-09-03 15:17:32 -0700121 fd_annotation: &FdAnnotation,
Victor Hsieh6e340382021-08-13 12:18:02 -0700122) -> Result<CompilerOutput> {
123 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
124 // is out of scope.
Victor Hsieh13333e82021-09-03 15:17:32 -0700125 let authfs_config = build_authfs_config(fd_annotation);
Victor Hsieh51789de2021-08-06 16:50:49 -0700126 let authfs = authfs_service.mount(&authfs_config)?;
127
128 // The task expects to receive FD numbers that match its flags (e.g. --zip-fd=42) prepared
129 // on the host side. Since the local FD opened from authfs (e.g. /authfs/42) may not match
130 // the task's expectation, prepare a FD mapping and let minijail prepare the correct FD
131 // setup.
132 let fd_mapping =
133 open_authfs_files_for_fd_mapping(&authfs, &authfs_config).context("Open on authfs")?;
134
135 let jail =
136 spawn_jailed_task(compiler_path, compiler_args, fd_mapping).context("Spawn dex2oat")?;
137 let jail_result = jail.wait();
138
Victor Hsieh6e340382021-08-13 12:18:02 -0700139 let parcel_fds = parse_compiler_args(&authfs, compiler_args)?;
140 let oat_file: &File = parcel_fds.oat.as_ref();
141 let vdex_file: &File = parcel_fds.vdex.as_ref();
142 let image_file: &File = parcel_fds.image.as_ref();
Victor Hsieh51789de2021-08-06 16:50:49 -0700143
144 match jail_result {
Victor Hsieh6e340382021-08-13 12:18:02 -0700145 Ok(()) => Ok(CompilerOutput::Digests {
Victor Hsieh9ed27182021-08-25 15:52:42 -0700146 oat: fsverity::measure(oat_file.as_raw_fd())?,
147 vdex: fsverity::measure(vdex_file.as_raw_fd())?,
148 image: fsverity::measure(image_file.as_raw_fd())?,
Victor Hsieh6e340382021-08-13 12:18:02 -0700149 }),
Victor Hsieh51789de2021-08-06 16:50:49 -0700150 Err(minijail::Error::ReturnCode(exit_code)) => {
Victor Hsieh6e340382021-08-13 12:18:02 -0700151 error!("dex2oat failed with exit code {}", exit_code);
152 Ok(CompilerOutput::ExitCode(exit_code as i8))
Victor Hsieh51789de2021-08-06 16:50:49 -0700153 }
154 Err(e) => {
155 bail!("Unexpected minijail error: {}", e)
156 }
157 }
158}
159
Victor Hsieh6e340382021-08-13 12:18:02 -0700160fn parse_compiler_args(
161 authfs: &Strong<dyn IAuthFs>,
162 args: &[String],
163) -> Result<CompilerOutputParcelFds> {
164 const OAT_FD_PREFIX: &str = "--oat-fd=";
165 const VDEX_FD_PREFIX: &str = "--output-vdex-fd=";
166 const IMAGE_FD_PREFIX: &str = "--image-fd=";
167 const APP_IMAGE_FD_PREFIX: &str = "--app-image-fd=";
168
169 let mut oat = None;
170 let mut vdex = None;
171 let mut image = None;
172
173 for arg in args {
174 if let Some(value) = arg.strip_prefix(OAT_FD_PREFIX) {
175 let fd = value.parse::<RawFd>().context("Invalid --oat-fd flag")?;
176 debug_assert!(oat.is_none());
177 oat = Some(authfs.openFile(fd, false)?);
178 } else if let Some(value) = arg.strip_prefix(VDEX_FD_PREFIX) {
179 let fd = value.parse::<RawFd>().context("Invalid --output-vdex-fd flag")?;
180 debug_assert!(vdex.is_none());
181 vdex = Some(authfs.openFile(fd, false)?);
182 } else if let Some(value) = arg.strip_prefix(IMAGE_FD_PREFIX) {
183 let fd = value.parse::<RawFd>().context("Invalid --image-fd flag")?;
184 debug_assert!(image.is_none());
185 image = Some(authfs.openFile(fd, false)?);
186 } else if let Some(value) = arg.strip_prefix(APP_IMAGE_FD_PREFIX) {
187 let fd = value.parse::<RawFd>().context("Invalid --app-image-fd flag")?;
188 debug_assert!(image.is_none());
189 image = Some(authfs.openFile(fd, false)?);
190 }
191 }
192
193 Ok(CompilerOutputParcelFds {
194 oat: oat.ok_or_else(|| anyhow!("Missing --oat-fd"))?,
195 vdex: vdex.ok_or_else(|| anyhow!("Missing --vdex-fd"))?,
196 image: image.ok_or_else(|| anyhow!("Missing --image-fd or --app-image-fd"))?,
197 })
198}
199
Victor Hsieh13333e82021-09-03 15:17:32 -0700200fn build_authfs_config(fd_annotation: &FdAnnotation) -> AuthFsConfig {
Victor Hsieh51789de2021-08-06 16:50:49 -0700201 AuthFsConfig {
Victor Hsiehf9968692021-11-18 11:34:39 -0800202 port: FD_SERVER_PORT,
Victor Hsieh13333e82021-09-03 15:17:32 -0700203 inputFdAnnotations: fd_annotation
204 .input_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700205 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700206 .map(|fd| InputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700207 .collect(),
Victor Hsieh13333e82021-09-03 15:17:32 -0700208 outputFdAnnotations: fd_annotation
209 .output_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700210 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700211 .map(|fd| OutputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700212 .collect(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800213 ..Default::default()
Victor Hsieh51789de2021-08-06 16:50:49 -0700214 }
215}
216
217fn open_authfs_files_for_fd_mapping(
218 authfs: &Strong<dyn IAuthFs>,
219 config: &AuthFsConfig,
220) -> Result<Vec<(ParcelFileDescriptor, PseudoRawFd)>> {
221 let mut fd_mapping = Vec::new();
222
223 let results: Result<Vec<_>> = config
224 .inputFdAnnotations
225 .iter()
226 .map(|annotation| Ok((authfs.openFile(annotation.fd, false)?, annotation.fd)))
227 .collect();
228 fd_mapping.append(&mut results?);
229
230 let results: Result<Vec<_>> = config
231 .outputFdAnnotations
232 .iter()
233 .map(|annotation| Ok((authfs.openFile(annotation.fd, true)?, annotation.fd)))
234 .collect();
235 fd_mapping.append(&mut results?);
236
237 Ok(fd_mapping)
238}
239
240fn spawn_jailed_task(
241 executable: &Path,
242 args: &[String],
243 fd_mapping: Vec<(ParcelFileDescriptor, PseudoRawFd)>,
244) -> Result<Minijail> {
245 // TODO(b/185175567): Run in a more restricted sandbox.
246 let jail = Minijail::new()?;
247 let preserve_fds: Vec<_> = fd_mapping.iter().map(|(f, id)| (f.as_raw_fd(), *id)).collect();
248 let _pid = jail.run_remap(executable, preserve_fds.as_slice(), args)?;
249 Ok(jail)
250}