blob: cf6f30a7969df7ab1e25681fb3b907e04616c1e8 [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};
Alan Stokes9646db92021-12-14 13:22:33 +000018use log::{debug, error, info};
Victor Hsieh51789de2021-08-06 16:50:49 -070019use minijail::{self, Minijail};
Victor Hsiehf9968692021-11-18 11:34:39 -080020use std::env;
Alan Stokes46a1dff2021-12-14 10:56:05 +000021use std::fs::{read_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
Alan Stokes46a1dff2021-12-14 10:56:05 +000025use crate::artifact_signer::ArtifactSigner;
26use crate::compos_key_service::Signer;
Victor Hsieh9ed27182021-08-25 15:52:42 -070027use crate::fsverity;
Victor Hsieh51789de2021-08-06 16:50:49 -070028use authfs_aidl_interface::aidl::com::android::virt::fs::{
Victor Hsieh015bcb52021-11-17 17:28:01 -080029 AuthFsConfig::{
Victor Hsiehf9968692021-11-18 11:34:39 -080030 AuthFsConfig, InputDirFdAnnotation::InputDirFdAnnotation,
31 InputFdAnnotation::InputFdAnnotation, OutputDirFdAnnotation::OutputDirFdAnnotation,
32 OutputFdAnnotation::OutputFdAnnotation,
Victor Hsieh015bcb52021-11-17 17:28:01 -080033 },
34 IAuthFs::IAuthFs,
35 IAuthFsService::IAuthFsService,
Victor Hsieh51789de2021-08-06 16:50:49 -070036};
37use authfs_aidl_interface::binder::{ParcelFileDescriptor, Strong};
Victor Hsieh13333e82021-09-03 15:17:32 -070038use compos_aidl_interface::aidl::com::android::compos::FdAnnotation::FdAnnotation;
Alan Stokes46a1dff2021-12-14 10:56:05 +000039use compos_common::odrefresh::ExitCode;
Victor Hsieh51789de2021-08-06 16:50:49 -070040
Victor Hsiehf9968692021-11-18 11:34:39 -080041const FD_SERVER_PORT: i32 = 3264; // TODO: support dynamic port
42
Victor Hsieh51789de2021-08-06 16:50:49 -070043/// The number that represents the file descriptor number expecting by the task. The number may be
44/// meaningless in the current process.
45pub type PseudoRawFd = i32;
46
Victor Hsieh6e340382021-08-13 12:18:02 -070047pub enum CompilerOutput {
48 /// Fs-verity digests of output files, if the compiler finishes successfully.
Victor Hsieh9ed27182021-08-25 15:52:42 -070049 Digests {
50 oat: fsverity::Sha256Digest,
51 vdex: fsverity::Sha256Digest,
52 image: fsverity::Sha256Digest,
53 },
Victor Hsieh6e340382021-08-13 12:18:02 -070054 /// Exit code returned by the compiler, if not 0.
55 ExitCode(i8),
56}
57
58struct CompilerOutputParcelFds {
59 oat: ParcelFileDescriptor,
60 vdex: ParcelFileDescriptor,
61 image: ParcelFileDescriptor,
62}
63
Alan Stokes46a1dff2021-12-14 10:56:05 +000064pub struct OdrefreshContext<'a> {
Victor Hsiehf9968692021-11-18 11:34:39 -080065 system_dir_fd: i32,
66 output_dir_fd: i32,
Alan Stokes9646db92021-12-14 13:22:33 +000067 staging_dir_fd: i32,
Alan Stokes46a1dff2021-12-14 10:56:05 +000068 target_dir_name: &'a str,
69 zygote_arch: &'a str,
70}
71
72impl<'a> OdrefreshContext<'a> {
73 pub fn new(
74 system_dir_fd: i32,
75 output_dir_fd: i32,
76 staging_dir_fd: i32,
77 target_dir_name: &'a str,
78 zygote_arch: &'a str,
79 ) -> Result<Self> {
80 if system_dir_fd < 0 || output_dir_fd < 0 || staging_dir_fd < 0 {
81 bail!("The remote FDs are expected to be non-negative");
82 }
83 if zygote_arch != "zygote64" && zygote_arch != "zygote64_32" {
84 bail!("Invalid zygote arch");
85 }
86 Ok(Self { system_dir_fd, output_dir_fd, staging_dir_fd, target_dir_name, zygote_arch })
87 }
88}
89
90pub fn odrefresh(
91 odrefresh_path: &Path,
92 context: OdrefreshContext,
Victor Hsiehf9968692021-11-18 11:34:39 -080093 authfs_service: Strong<dyn IAuthFsService>,
Alan Stokes46a1dff2021-12-14 10:56:05 +000094 signer: Signer,
95) -> Result<ExitCode> {
Victor Hsiehf9968692021-11-18 11:34:39 -080096 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
97 // is out of scope.
98 let authfs_config = AuthFsConfig {
99 port: FD_SERVER_PORT,
100 inputDirFdAnnotations: vec![InputDirFdAnnotation {
Alan Stokes46a1dff2021-12-14 10:56:05 +0000101 fd: context.system_dir_fd,
Victor Hsiehf9968692021-11-18 11:34:39 -0800102 // TODO(206869687): Replace /dev/null with the real path when possible.
103 manifestPath: "/dev/null".to_string(),
104 prefix: "/system".to_string(),
105 }],
Alan Stokes9646db92021-12-14 13:22:33 +0000106 outputDirFdAnnotations: vec![
Alan Stokes46a1dff2021-12-14 10:56:05 +0000107 OutputDirFdAnnotation { fd: context.output_dir_fd },
108 OutputDirFdAnnotation { fd: context.staging_dir_fd },
Alan Stokes9646db92021-12-14 13:22:33 +0000109 ],
Victor Hsiehf9968692021-11-18 11:34:39 -0800110 ..Default::default()
111 };
112 let authfs = authfs_service.mount(&authfs_config)?;
113 let mountpoint = PathBuf::from(authfs.getMountPoint()?);
114
115 let mut android_root = mountpoint.clone();
Alan Stokes46a1dff2021-12-14 10:56:05 +0000116 android_root.push(context.system_dir_fd.to_string());
Victor Hsiehf9968692021-11-18 11:34:39 -0800117 android_root.push("system");
118 env::set_var("ANDROID_ROOT", &android_root);
Alan Stokes46a1dff2021-12-14 10:56:05 +0000119 debug!("ANDROID_ROOT={:?}", &android_root);
Victor Hsiehf9968692021-11-18 11:34:39 -0800120
Alan Stokes46a1dff2021-12-14 10:56:05 +0000121 let art_apex_data = mountpoint.join(context.output_dir_fd.to_string());
Victor Hsieh64df53d2021-11-30 17:09:51 -0800122 env::set_var("ART_APEX_DATA", &art_apex_data);
Alan Stokes46a1dff2021-12-14 10:56:05 +0000123 debug!("ART_APEX_DATA={:?}", &art_apex_data);
Victor Hsieh64df53d2021-11-30 17:09:51 -0800124
Alan Stokes46a1dff2021-12-14 10:56:05 +0000125 let staging_dir = mountpoint.join(context.staging_dir_fd.to_string());
Victor Hsiehf9968692021-11-18 11:34:39 -0800126
127 let args = vec![
128 "odrefresh".to_string(),
Alan Stokes46a1dff2021-12-14 10:56:05 +0000129 format!("--zygote-arch={}", context.zygote_arch),
130 format!("--dalvik-cache={}", context.target_dir_name),
Victor Hsieh64df53d2021-11-30 17:09:51 -0800131 "--no-refresh".to_string(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800132 format!("--staging-dir={}", staging_dir.display()),
133 "--force-compile".to_string(),
134 ];
Alan Stokes9646db92021-12-14 13:22:33 +0000135 debug!("Running odrefresh with args: {:?}", &args);
Victor Hsiehf9968692021-11-18 11:34:39 -0800136 let jail = spawn_jailed_task(odrefresh_path, &args, Vec::new() /* fd_mapping */)
137 .context("Spawn odrefresh")?;
Alan Stokes46a1dff2021-12-14 10:56:05 +0000138 let exit_code = match jail.wait() {
139 Ok(_) => Result::<u8>::Ok(0),
140 Err(minijail::Error::ReturnCode(exit_code)) => Ok(exit_code),
Victor Hsiehf9968692021-11-18 11:34:39 -0800141 Err(e) => {
142 bail!("Unexpected minijail error: {}", e)
143 }
Alan Stokes46a1dff2021-12-14 10:56:05 +0000144 }?;
145
146 let exit_code = ExitCode::from_i32(exit_code.into())
147 .ok_or_else(|| anyhow!("Unexpected odrefresh exit code: {}", exit_code))?;
148 info!("odrefresh exited with {:?}", exit_code);
149
150 if exit_code == ExitCode::CompilationSuccess {
151 // authfs only shows us the files we created, so it's ok to just sign everything under
152 // the target directory.
153 let target_dir = art_apex_data.join(context.target_dir_name);
154 let mut artifact_signer = ArtifactSigner::new(&target_dir);
155 add_artifacts(&target_dir, &mut artifact_signer)?;
156
157 artifact_signer.write_info_and_signature(signer, &target_dir.join("compos.info"))?;
Victor Hsiehf9968692021-11-18 11:34:39 -0800158 }
Alan Stokes46a1dff2021-12-14 10:56:05 +0000159
160 Ok(exit_code)
161}
162
163fn add_artifacts(target_dir: &Path, artifact_signer: &mut ArtifactSigner) -> Result<()> {
164 for entry in
165 read_dir(&target_dir).with_context(|| format!("Traversing {}", target_dir.display()))?
166 {
167 let entry = entry?;
168 let file_type = entry.file_type()?;
169 if file_type.is_dir() {
170 add_artifacts(&entry.path(), artifact_signer)?;
171 } else if file_type.is_file() {
172 artifact_signer.add_artifact(&entry.path())?;
173 } else {
174 // authfs shouldn't create anything else, but just in case
175 bail!("Unexpected file type in artifacts: {:?}", entry);
176 }
177 }
178 Ok(())
Victor Hsiehf9968692021-11-18 11:34:39 -0800179}
180
Victor Hsieh13333e82021-09-03 15:17:32 -0700181/// Runs the compiler with given flags with file descriptors described in `fd_annotation` retrieved
182/// via `authfs_service`. Returns exit code of the compiler process.
Victor Hsieh3c044c42021-10-01 17:17:10 -0700183pub fn compile_cmd(
Victor Hsieh51789de2021-08-06 16:50:49 -0700184 compiler_path: &Path,
185 compiler_args: &[String],
186 authfs_service: Strong<dyn IAuthFsService>,
Victor Hsieh13333e82021-09-03 15:17:32 -0700187 fd_annotation: &FdAnnotation,
Victor Hsieh6e340382021-08-13 12:18:02 -0700188) -> Result<CompilerOutput> {
189 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
190 // is out of scope.
Victor Hsieh13333e82021-09-03 15:17:32 -0700191 let authfs_config = build_authfs_config(fd_annotation);
Victor Hsieh51789de2021-08-06 16:50:49 -0700192 let authfs = authfs_service.mount(&authfs_config)?;
193
194 // The task expects to receive FD numbers that match its flags (e.g. --zip-fd=42) prepared
195 // on the host side. Since the local FD opened from authfs (e.g. /authfs/42) may not match
196 // the task's expectation, prepare a FD mapping and let minijail prepare the correct FD
197 // setup.
198 let fd_mapping =
199 open_authfs_files_for_fd_mapping(&authfs, &authfs_config).context("Open on authfs")?;
200
201 let jail =
202 spawn_jailed_task(compiler_path, compiler_args, fd_mapping).context("Spawn dex2oat")?;
203 let jail_result = jail.wait();
204
Victor Hsieh6e340382021-08-13 12:18:02 -0700205 let parcel_fds = parse_compiler_args(&authfs, compiler_args)?;
206 let oat_file: &File = parcel_fds.oat.as_ref();
207 let vdex_file: &File = parcel_fds.vdex.as_ref();
208 let image_file: &File = parcel_fds.image.as_ref();
Victor Hsieh51789de2021-08-06 16:50:49 -0700209
210 match jail_result {
Victor Hsieh6e340382021-08-13 12:18:02 -0700211 Ok(()) => Ok(CompilerOutput::Digests {
Victor Hsieh9ed27182021-08-25 15:52:42 -0700212 oat: fsverity::measure(oat_file.as_raw_fd())?,
213 vdex: fsverity::measure(vdex_file.as_raw_fd())?,
214 image: fsverity::measure(image_file.as_raw_fd())?,
Victor Hsieh6e340382021-08-13 12:18:02 -0700215 }),
Victor Hsieh51789de2021-08-06 16:50:49 -0700216 Err(minijail::Error::ReturnCode(exit_code)) => {
Victor Hsieh6e340382021-08-13 12:18:02 -0700217 error!("dex2oat failed with exit code {}", exit_code);
218 Ok(CompilerOutput::ExitCode(exit_code as i8))
Victor Hsieh51789de2021-08-06 16:50:49 -0700219 }
220 Err(e) => {
221 bail!("Unexpected minijail error: {}", e)
222 }
223 }
224}
225
Victor Hsieh6e340382021-08-13 12:18:02 -0700226fn parse_compiler_args(
227 authfs: &Strong<dyn IAuthFs>,
228 args: &[String],
229) -> Result<CompilerOutputParcelFds> {
230 const OAT_FD_PREFIX: &str = "--oat-fd=";
231 const VDEX_FD_PREFIX: &str = "--output-vdex-fd=";
232 const IMAGE_FD_PREFIX: &str = "--image-fd=";
233 const APP_IMAGE_FD_PREFIX: &str = "--app-image-fd=";
234
235 let mut oat = None;
236 let mut vdex = None;
237 let mut image = None;
238
239 for arg in args {
240 if let Some(value) = arg.strip_prefix(OAT_FD_PREFIX) {
241 let fd = value.parse::<RawFd>().context("Invalid --oat-fd flag")?;
242 debug_assert!(oat.is_none());
243 oat = Some(authfs.openFile(fd, false)?);
244 } else if let Some(value) = arg.strip_prefix(VDEX_FD_PREFIX) {
245 let fd = value.parse::<RawFd>().context("Invalid --output-vdex-fd flag")?;
246 debug_assert!(vdex.is_none());
247 vdex = Some(authfs.openFile(fd, false)?);
248 } else if let Some(value) = arg.strip_prefix(IMAGE_FD_PREFIX) {
249 let fd = value.parse::<RawFd>().context("Invalid --image-fd flag")?;
250 debug_assert!(image.is_none());
251 image = Some(authfs.openFile(fd, false)?);
252 } else if let Some(value) = arg.strip_prefix(APP_IMAGE_FD_PREFIX) {
253 let fd = value.parse::<RawFd>().context("Invalid --app-image-fd flag")?;
254 debug_assert!(image.is_none());
255 image = Some(authfs.openFile(fd, false)?);
256 }
257 }
258
259 Ok(CompilerOutputParcelFds {
260 oat: oat.ok_or_else(|| anyhow!("Missing --oat-fd"))?,
261 vdex: vdex.ok_or_else(|| anyhow!("Missing --vdex-fd"))?,
262 image: image.ok_or_else(|| anyhow!("Missing --image-fd or --app-image-fd"))?,
263 })
264}
265
Victor Hsieh13333e82021-09-03 15:17:32 -0700266fn build_authfs_config(fd_annotation: &FdAnnotation) -> AuthFsConfig {
Victor Hsieh51789de2021-08-06 16:50:49 -0700267 AuthFsConfig {
Victor Hsiehf9968692021-11-18 11:34:39 -0800268 port: FD_SERVER_PORT,
Victor Hsieh13333e82021-09-03 15:17:32 -0700269 inputFdAnnotations: fd_annotation
270 .input_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700271 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700272 .map(|fd| InputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700273 .collect(),
Victor Hsieh13333e82021-09-03 15:17:32 -0700274 outputFdAnnotations: fd_annotation
275 .output_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700276 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700277 .map(|fd| OutputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700278 .collect(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800279 ..Default::default()
Victor Hsieh51789de2021-08-06 16:50:49 -0700280 }
281}
282
283fn open_authfs_files_for_fd_mapping(
284 authfs: &Strong<dyn IAuthFs>,
285 config: &AuthFsConfig,
286) -> Result<Vec<(ParcelFileDescriptor, PseudoRawFd)>> {
287 let mut fd_mapping = Vec::new();
288
289 let results: Result<Vec<_>> = config
290 .inputFdAnnotations
291 .iter()
292 .map(|annotation| Ok((authfs.openFile(annotation.fd, false)?, annotation.fd)))
293 .collect();
294 fd_mapping.append(&mut results?);
295
296 let results: Result<Vec<_>> = config
297 .outputFdAnnotations
298 .iter()
299 .map(|annotation| Ok((authfs.openFile(annotation.fd, true)?, annotation.fd)))
300 .collect();
301 fd_mapping.append(&mut results?);
302
303 Ok(fd_mapping)
304}
305
306fn spawn_jailed_task(
307 executable: &Path,
308 args: &[String],
309 fd_mapping: Vec<(ParcelFileDescriptor, PseudoRawFd)>,
310) -> Result<Minijail> {
311 // TODO(b/185175567): Run in a more restricted sandbox.
312 let jail = Minijail::new()?;
313 let preserve_fds: Vec<_> = fd_mapping.iter().map(|(f, id)| (f.as_raw_fd(), *id)).collect();
314 let _pid = jail.run_remap(executable, preserve_fds.as_slice(), args)?;
315 Ok(jail)
316}