Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 1 | /* |
| 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 Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 17 | use anyhow::{anyhow, bail, Context, Result}; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 18 | use log::error; |
| 19 | use minijail::{self, Minijail}; |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 20 | use std::env; |
| 21 | use std::fs::{create_dir, File}; |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 22 | use std::os::unix::io::{AsRawFd, RawFd}; |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 23 | use std::path::{Path, PathBuf}; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 24 | |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 25 | use crate::fsverity; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 26 | use authfs_aidl_interface::aidl::com::android::virt::fs::{ |
Victor Hsieh | 015bcb5 | 2021-11-17 17:28:01 -0800 | [diff] [blame] | 27 | AuthFsConfig::{ |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 28 | AuthFsConfig, InputDirFdAnnotation::InputDirFdAnnotation, |
| 29 | InputFdAnnotation::InputFdAnnotation, OutputDirFdAnnotation::OutputDirFdAnnotation, |
| 30 | OutputFdAnnotation::OutputFdAnnotation, |
Victor Hsieh | 015bcb5 | 2021-11-17 17:28:01 -0800 | [diff] [blame] | 31 | }, |
| 32 | IAuthFs::IAuthFs, |
| 33 | IAuthFsService::IAuthFsService, |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 34 | }; |
| 35 | use authfs_aidl_interface::binder::{ParcelFileDescriptor, Strong}; |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 36 | use compos_aidl_interface::aidl::com::android::compos::FdAnnotation::FdAnnotation; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 37 | |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 38 | const FD_SERVER_PORT: i32 = 3264; // TODO: support dynamic port |
| 39 | |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 40 | /// The number that represents the file descriptor number expecting by the task. The number may be |
| 41 | /// meaningless in the current process. |
| 42 | pub type PseudoRawFd = i32; |
| 43 | |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 44 | pub enum CompilerOutput { |
| 45 | /// Fs-verity digests of output files, if the compiler finishes successfully. |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 46 | Digests { |
| 47 | oat: fsverity::Sha256Digest, |
| 48 | vdex: fsverity::Sha256Digest, |
| 49 | image: fsverity::Sha256Digest, |
| 50 | }, |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 51 | /// Exit code returned by the compiler, if not 0. |
| 52 | ExitCode(i8), |
| 53 | } |
| 54 | |
| 55 | struct CompilerOutputParcelFds { |
| 56 | oat: ParcelFileDescriptor, |
| 57 | vdex: ParcelFileDescriptor, |
| 58 | image: ParcelFileDescriptor, |
| 59 | } |
| 60 | |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 61 | pub 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 Hsieh | 64df53d | 2021-11-30 17:09:51 -0800 | [diff] [blame^] | 89 | 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 Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 93 | let mut staging_dir = mountpoint; |
| 94 | staging_dir.push(output_dir_fd.to_string()); |
| 95 | staging_dir.push("staging"); |
Victor Hsieh | 64df53d | 2021-11-30 17:09:51 -0800 | [diff] [blame^] | 96 | create_dir(&staging_dir) |
| 97 | .with_context(|| format!("Create staging directory {}", staging_dir.display()))?; |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 98 | |
| 99 | let args = vec![ |
| 100 | "odrefresh".to_string(), |
| 101 | format!("--zygote-arch={}", zygote_arch), |
Victor Hsieh | 64df53d | 2021-11-30 17:09:51 -0800 | [diff] [blame^] | 102 | "--no-refresh".to_string(), |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 103 | 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 Hsieh | 64df53d | 2021-11-30 17:09:51 -0800 | [diff] [blame^] | 112 | error!("odrefresh failed with exit code {}", exit_code); |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 113 | Ok(CompilerOutput::ExitCode(exit_code as i8)) |
| 114 | } |
| 115 | Err(e) => { |
| 116 | bail!("Unexpected minijail error: {}", e) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 121 | /// 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 Hsieh | 3c044c4 | 2021-10-01 17:17:10 -0700 | [diff] [blame] | 123 | pub fn compile_cmd( |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 124 | compiler_path: &Path, |
| 125 | compiler_args: &[String], |
| 126 | authfs_service: Strong<dyn IAuthFsService>, |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 127 | fd_annotation: &FdAnnotation, |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 128 | ) -> Result<CompilerOutput> { |
| 129 | // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable |
| 130 | // is out of scope. |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 131 | let authfs_config = build_authfs_config(fd_annotation); |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 132 | 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 Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 145 | 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 Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 149 | |
| 150 | match jail_result { |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 151 | Ok(()) => Ok(CompilerOutput::Digests { |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 152 | 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 Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 155 | }), |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 156 | Err(minijail::Error::ReturnCode(exit_code)) => { |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 157 | error!("dex2oat failed with exit code {}", exit_code); |
| 158 | Ok(CompilerOutput::ExitCode(exit_code as i8)) |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 159 | } |
| 160 | Err(e) => { |
| 161 | bail!("Unexpected minijail error: {}", e) |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 166 | fn 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 Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 206 | fn build_authfs_config(fd_annotation: &FdAnnotation) -> AuthFsConfig { |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 207 | AuthFsConfig { |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 208 | port: FD_SERVER_PORT, |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 209 | inputFdAnnotations: fd_annotation |
| 210 | .input_fds |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 211 | .iter() |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 212 | .map(|fd| InputFdAnnotation { fd: *fd }) |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 213 | .collect(), |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 214 | outputFdAnnotations: fd_annotation |
| 215 | .output_fds |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 216 | .iter() |
Victor Hsieh | 13333e8 | 2021-09-03 15:17:32 -0700 | [diff] [blame] | 217 | .map(|fd| OutputFdAnnotation { fd: *fd }) |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 218 | .collect(), |
Victor Hsieh | f996869 | 2021-11-18 11:34:39 -0800 | [diff] [blame] | 219 | ..Default::default() |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 220 | } |
| 221 | } |
| 222 | |
| 223 | fn 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 | |
| 246 | fn 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 | } |