blob: fec82a68cf87ddf62b51b8492ee98509d5aa361d [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 Hsieh6e340382021-08-13 12:18:02 -070020use std::fs::File;
Victor Hsieh6e340382021-08-13 12:18:02 -070021use std::os::unix::io::{AsRawFd, RawFd};
Victor Hsieh51789de2021-08-06 16:50:49 -070022use std::path::Path;
23
Victor Hsieh9ed27182021-08-25 15:52:42 -070024use crate::fsverity;
Victor Hsieh51789de2021-08-06 16:50:49 -070025use authfs_aidl_interface::aidl::com::android::virt::fs::{
26 AuthFsConfig::AuthFsConfig, IAuthFs::IAuthFs, IAuthFsService::IAuthFsService,
27 InputFdAnnotation::InputFdAnnotation, OutputFdAnnotation::OutputFdAnnotation,
28};
29use authfs_aidl_interface::binder::{ParcelFileDescriptor, Strong};
Victor Hsieh13333e82021-09-03 15:17:32 -070030use compos_aidl_interface::aidl::com::android::compos::FdAnnotation::FdAnnotation;
Victor Hsieh51789de2021-08-06 16:50:49 -070031
32/// The number that represents the file descriptor number expecting by the task. The number may be
33/// meaningless in the current process.
34pub type PseudoRawFd = i32;
35
Victor Hsieh6e340382021-08-13 12:18:02 -070036pub enum CompilerOutput {
37 /// Fs-verity digests of output files, if the compiler finishes successfully.
Victor Hsieh9ed27182021-08-25 15:52:42 -070038 Digests {
39 oat: fsverity::Sha256Digest,
40 vdex: fsverity::Sha256Digest,
41 image: fsverity::Sha256Digest,
42 },
Victor Hsieh6e340382021-08-13 12:18:02 -070043 /// Exit code returned by the compiler, if not 0.
44 ExitCode(i8),
45}
46
47struct CompilerOutputParcelFds {
48 oat: ParcelFileDescriptor,
49 vdex: ParcelFileDescriptor,
50 image: ParcelFileDescriptor,
51}
52
Victor Hsieh13333e82021-09-03 15:17:32 -070053/// Runs the compiler with given flags with file descriptors described in `fd_annotation` retrieved
54/// via `authfs_service`. Returns exit code of the compiler process.
Victor Hsieh51789de2021-08-06 16:50:49 -070055pub fn compile(
56 compiler_path: &Path,
57 compiler_args: &[String],
58 authfs_service: Strong<dyn IAuthFsService>,
Victor Hsieh13333e82021-09-03 15:17:32 -070059 fd_annotation: &FdAnnotation,
Victor Hsieh6e340382021-08-13 12:18:02 -070060) -> Result<CompilerOutput> {
61 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
62 // is out of scope.
Victor Hsieh13333e82021-09-03 15:17:32 -070063 let authfs_config = build_authfs_config(fd_annotation);
Victor Hsieh51789de2021-08-06 16:50:49 -070064 let authfs = authfs_service.mount(&authfs_config)?;
65
66 // The task expects to receive FD numbers that match its flags (e.g. --zip-fd=42) prepared
67 // on the host side. Since the local FD opened from authfs (e.g. /authfs/42) may not match
68 // the task's expectation, prepare a FD mapping and let minijail prepare the correct FD
69 // setup.
70 let fd_mapping =
71 open_authfs_files_for_fd_mapping(&authfs, &authfs_config).context("Open on authfs")?;
72
73 let jail =
74 spawn_jailed_task(compiler_path, compiler_args, fd_mapping).context("Spawn dex2oat")?;
75 let jail_result = jail.wait();
76
Victor Hsieh6e340382021-08-13 12:18:02 -070077 let parcel_fds = parse_compiler_args(&authfs, compiler_args)?;
78 let oat_file: &File = parcel_fds.oat.as_ref();
79 let vdex_file: &File = parcel_fds.vdex.as_ref();
80 let image_file: &File = parcel_fds.image.as_ref();
Victor Hsieh51789de2021-08-06 16:50:49 -070081
82 match jail_result {
Victor Hsieh6e340382021-08-13 12:18:02 -070083 Ok(()) => Ok(CompilerOutput::Digests {
Victor Hsieh9ed27182021-08-25 15:52:42 -070084 oat: fsverity::measure(oat_file.as_raw_fd())?,
85 vdex: fsverity::measure(vdex_file.as_raw_fd())?,
86 image: fsverity::measure(image_file.as_raw_fd())?,
Victor Hsieh6e340382021-08-13 12:18:02 -070087 }),
Victor Hsieh51789de2021-08-06 16:50:49 -070088 Err(minijail::Error::ReturnCode(exit_code)) => {
Victor Hsieh6e340382021-08-13 12:18:02 -070089 error!("dex2oat failed with exit code {}", exit_code);
90 Ok(CompilerOutput::ExitCode(exit_code as i8))
Victor Hsieh51789de2021-08-06 16:50:49 -070091 }
92 Err(e) => {
93 bail!("Unexpected minijail error: {}", e)
94 }
95 }
96}
97
Victor Hsieh6e340382021-08-13 12:18:02 -070098fn parse_compiler_args(
99 authfs: &Strong<dyn IAuthFs>,
100 args: &[String],
101) -> Result<CompilerOutputParcelFds> {
102 const OAT_FD_PREFIX: &str = "--oat-fd=";
103 const VDEX_FD_PREFIX: &str = "--output-vdex-fd=";
104 const IMAGE_FD_PREFIX: &str = "--image-fd=";
105 const APP_IMAGE_FD_PREFIX: &str = "--app-image-fd=";
106
107 let mut oat = None;
108 let mut vdex = None;
109 let mut image = None;
110
111 for arg in args {
112 if let Some(value) = arg.strip_prefix(OAT_FD_PREFIX) {
113 let fd = value.parse::<RawFd>().context("Invalid --oat-fd flag")?;
114 debug_assert!(oat.is_none());
115 oat = Some(authfs.openFile(fd, false)?);
116 } else if let Some(value) = arg.strip_prefix(VDEX_FD_PREFIX) {
117 let fd = value.parse::<RawFd>().context("Invalid --output-vdex-fd flag")?;
118 debug_assert!(vdex.is_none());
119 vdex = Some(authfs.openFile(fd, false)?);
120 } else if let Some(value) = arg.strip_prefix(IMAGE_FD_PREFIX) {
121 let fd = value.parse::<RawFd>().context("Invalid --image-fd flag")?;
122 debug_assert!(image.is_none());
123 image = Some(authfs.openFile(fd, false)?);
124 } else if let Some(value) = arg.strip_prefix(APP_IMAGE_FD_PREFIX) {
125 let fd = value.parse::<RawFd>().context("Invalid --app-image-fd flag")?;
126 debug_assert!(image.is_none());
127 image = Some(authfs.openFile(fd, false)?);
128 }
129 }
130
131 Ok(CompilerOutputParcelFds {
132 oat: oat.ok_or_else(|| anyhow!("Missing --oat-fd"))?,
133 vdex: vdex.ok_or_else(|| anyhow!("Missing --vdex-fd"))?,
134 image: image.ok_or_else(|| anyhow!("Missing --image-fd or --app-image-fd"))?,
135 })
136}
137
Victor Hsieh13333e82021-09-03 15:17:32 -0700138fn build_authfs_config(fd_annotation: &FdAnnotation) -> AuthFsConfig {
Victor Hsieh51789de2021-08-06 16:50:49 -0700139 AuthFsConfig {
140 port: 3264, // TODO: support dynamic port
Victor Hsieh13333e82021-09-03 15:17:32 -0700141 inputFdAnnotations: fd_annotation
142 .input_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700143 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700144 .map(|fd| InputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700145 .collect(),
Victor Hsieh13333e82021-09-03 15:17:32 -0700146 outputFdAnnotations: fd_annotation
147 .output_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700148 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700149 .map(|fd| OutputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700150 .collect(),
151 }
152}
153
154fn open_authfs_files_for_fd_mapping(
155 authfs: &Strong<dyn IAuthFs>,
156 config: &AuthFsConfig,
157) -> Result<Vec<(ParcelFileDescriptor, PseudoRawFd)>> {
158 let mut fd_mapping = Vec::new();
159
160 let results: Result<Vec<_>> = config
161 .inputFdAnnotations
162 .iter()
163 .map(|annotation| Ok((authfs.openFile(annotation.fd, false)?, annotation.fd)))
164 .collect();
165 fd_mapping.append(&mut results?);
166
167 let results: Result<Vec<_>> = config
168 .outputFdAnnotations
169 .iter()
170 .map(|annotation| Ok((authfs.openFile(annotation.fd, true)?, annotation.fd)))
171 .collect();
172 fd_mapping.append(&mut results?);
173
174 Ok(fd_mapping)
175}
176
177fn spawn_jailed_task(
178 executable: &Path,
179 args: &[String],
180 fd_mapping: Vec<(ParcelFileDescriptor, PseudoRawFd)>,
181) -> Result<Minijail> {
182 // TODO(b/185175567): Run in a more restricted sandbox.
183 let jail = Minijail::new()?;
184 let preserve_fds: Vec<_> = fd_mapping.iter().map(|(f, id)| (f.as_raw_fd(), *id)).collect();
185 let _pid = jail.run_remap(executable, preserve_fds.as_slice(), args)?;
186 Ok(jail)
187}