blob: af7a9b4ce71fb5e76d84a429bbb84eabdd8e8092 [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 Stokes92472512022-01-04 11:48:38 +000018use log::{debug, error, info, warn};
Victor Hsieh51789de2021-08-06 16:50:49 -070019use minijail::{self, Minijail};
Alan Stokes92472512022-01-04 11:48:38 +000020use regex::Regex;
Victor Hsiehf9968692021-11-18 11:34:39 -080021use std::env;
Alan Stokes92472512022-01-04 11:48:38 +000022use std::ffi::OsString;
Alan Stokes46a1dff2021-12-14 10:56:05 +000023use std::fs::{read_dir, File};
Victor Hsieh6e340382021-08-13 12:18:02 -070024use std::os::unix::io::{AsRawFd, RawFd};
Alan Stokes35bac3c2021-12-16 14:37:24 +000025use std::path::{self, Path, PathBuf};
Alan Stokes92472512022-01-04 11:48:38 +000026use std::process::Command;
Victor Hsieh51789de2021-08-06 16:50:49 -070027
Alan Stokes46a1dff2021-12-14 10:56:05 +000028use crate::artifact_signer::ArtifactSigner;
29use crate::compos_key_service::Signer;
Victor Hsieh9ed27182021-08-25 15:52:42 -070030use crate::fsverity;
Victor Hsieh51789de2021-08-06 16:50:49 -070031use authfs_aidl_interface::aidl::com::android::virt::fs::{
Victor Hsieh015bcb52021-11-17 17:28:01 -080032 AuthFsConfig::{
Victor Hsiehf9968692021-11-18 11:34:39 -080033 AuthFsConfig, InputDirFdAnnotation::InputDirFdAnnotation,
34 InputFdAnnotation::InputFdAnnotation, OutputDirFdAnnotation::OutputDirFdAnnotation,
35 OutputFdAnnotation::OutputFdAnnotation,
Victor Hsieh015bcb52021-11-17 17:28:01 -080036 },
37 IAuthFs::IAuthFs,
38 IAuthFsService::IAuthFsService,
Victor Hsieh51789de2021-08-06 16:50:49 -070039};
40use authfs_aidl_interface::binder::{ParcelFileDescriptor, Strong};
Victor Hsieh13333e82021-09-03 15:17:32 -070041use compos_aidl_interface::aidl::com::android::compos::FdAnnotation::FdAnnotation;
Alan Stokes46a1dff2021-12-14 10:56:05 +000042use compos_common::odrefresh::ExitCode;
Victor Hsieh51789de2021-08-06 16:50:49 -070043
Victor Hsiehf9968692021-11-18 11:34:39 -080044const FD_SERVER_PORT: i32 = 3264; // TODO: support dynamic port
45
Victor Hsieh51789de2021-08-06 16:50:49 -070046/// The number that represents the file descriptor number expecting by the task. The number may be
47/// meaningless in the current process.
48pub type PseudoRawFd = i32;
49
Victor Hsieh6e340382021-08-13 12:18:02 -070050pub enum CompilerOutput {
51 /// Fs-verity digests of output files, if the compiler finishes successfully.
Victor Hsieh9ed27182021-08-25 15:52:42 -070052 Digests {
53 oat: fsverity::Sha256Digest,
54 vdex: fsverity::Sha256Digest,
55 image: fsverity::Sha256Digest,
56 },
Victor Hsieh6e340382021-08-13 12:18:02 -070057 /// Exit code returned by the compiler, if not 0.
58 ExitCode(i8),
59}
60
61struct CompilerOutputParcelFds {
62 oat: ParcelFileDescriptor,
63 vdex: ParcelFileDescriptor,
64 image: ParcelFileDescriptor,
65}
66
Alan Stokes46a1dff2021-12-14 10:56:05 +000067pub struct OdrefreshContext<'a> {
Victor Hsiehf9968692021-11-18 11:34:39 -080068 system_dir_fd: i32,
69 output_dir_fd: i32,
Alan Stokes9646db92021-12-14 13:22:33 +000070 staging_dir_fd: i32,
Alan Stokes46a1dff2021-12-14 10:56:05 +000071 target_dir_name: &'a str,
72 zygote_arch: &'a str,
73}
74
75impl<'a> OdrefreshContext<'a> {
76 pub fn new(
77 system_dir_fd: i32,
78 output_dir_fd: i32,
79 staging_dir_fd: i32,
80 target_dir_name: &'a str,
81 zygote_arch: &'a str,
82 ) -> Result<Self> {
83 if system_dir_fd < 0 || output_dir_fd < 0 || staging_dir_fd < 0 {
84 bail!("The remote FDs are expected to be non-negative");
85 }
86 if zygote_arch != "zygote64" && zygote_arch != "zygote64_32" {
87 bail!("Invalid zygote arch");
88 }
Alan Stokes35bac3c2021-12-16 14:37:24 +000089 // Disallow any sort of path traversal
90 if target_dir_name.contains(path::MAIN_SEPARATOR) {
91 bail!("Invalid target directory {}", target_dir_name);
92 }
93
Alan Stokes46a1dff2021-12-14 10:56:05 +000094 Ok(Self { system_dir_fd, output_dir_fd, staging_dir_fd, target_dir_name, zygote_arch })
95 }
96}
97
98pub fn odrefresh(
99 odrefresh_path: &Path,
100 context: OdrefreshContext,
Victor Hsiehf9968692021-11-18 11:34:39 -0800101 authfs_service: Strong<dyn IAuthFsService>,
Alan Stokes46a1dff2021-12-14 10:56:05 +0000102 signer: Signer,
103) -> Result<ExitCode> {
Victor Hsiehf9968692021-11-18 11:34:39 -0800104 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
105 // is out of scope.
106 let authfs_config = AuthFsConfig {
107 port: FD_SERVER_PORT,
108 inputDirFdAnnotations: vec![InputDirFdAnnotation {
Alan Stokes46a1dff2021-12-14 10:56:05 +0000109 fd: context.system_dir_fd,
Victor Hsiehf9968692021-11-18 11:34:39 -0800110 // TODO(206869687): Replace /dev/null with the real path when possible.
111 manifestPath: "/dev/null".to_string(),
112 prefix: "/system".to_string(),
113 }],
Alan Stokes9646db92021-12-14 13:22:33 +0000114 outputDirFdAnnotations: vec![
Alan Stokes46a1dff2021-12-14 10:56:05 +0000115 OutputDirFdAnnotation { fd: context.output_dir_fd },
116 OutputDirFdAnnotation { fd: context.staging_dir_fd },
Alan Stokes9646db92021-12-14 13:22:33 +0000117 ],
Victor Hsiehf9968692021-11-18 11:34:39 -0800118 ..Default::default()
119 };
120 let authfs = authfs_service.mount(&authfs_config)?;
121 let mountpoint = PathBuf::from(authfs.getMountPoint()?);
122
123 let mut android_root = mountpoint.clone();
Alan Stokes46a1dff2021-12-14 10:56:05 +0000124 android_root.push(context.system_dir_fd.to_string());
Victor Hsiehf9968692021-11-18 11:34:39 -0800125 android_root.push("system");
126 env::set_var("ANDROID_ROOT", &android_root);
Alan Stokes46a1dff2021-12-14 10:56:05 +0000127 debug!("ANDROID_ROOT={:?}", &android_root);
Victor Hsiehf9968692021-11-18 11:34:39 -0800128
Alan Stokes46a1dff2021-12-14 10:56:05 +0000129 let art_apex_data = mountpoint.join(context.output_dir_fd.to_string());
Victor Hsieh64df53d2021-11-30 17:09:51 -0800130 env::set_var("ART_APEX_DATA", &art_apex_data);
Alan Stokes46a1dff2021-12-14 10:56:05 +0000131 debug!("ART_APEX_DATA={:?}", &art_apex_data);
Victor Hsieh64df53d2021-11-30 17:09:51 -0800132
Alan Stokes46a1dff2021-12-14 10:56:05 +0000133 let staging_dir = mountpoint.join(context.staging_dir_fd.to_string());
Victor Hsiehf9968692021-11-18 11:34:39 -0800134
Alan Stokes92472512022-01-04 11:48:38 +0000135 set_classpaths(&android_root)?;
136
Victor Hsiehf9968692021-11-18 11:34:39 -0800137 let args = vec![
138 "odrefresh".to_string(),
Alan Stokes46a1dff2021-12-14 10:56:05 +0000139 format!("--zygote-arch={}", context.zygote_arch),
140 format!("--dalvik-cache={}", context.target_dir_name),
Victor Hsieh64df53d2021-11-30 17:09:51 -0800141 "--no-refresh".to_string(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800142 format!("--staging-dir={}", staging_dir.display()),
143 "--force-compile".to_string(),
144 ];
Alan Stokes9646db92021-12-14 13:22:33 +0000145 debug!("Running odrefresh with args: {:?}", &args);
Victor Hsiehf9968692021-11-18 11:34:39 -0800146 let jail = spawn_jailed_task(odrefresh_path, &args, Vec::new() /* fd_mapping */)
147 .context("Spawn odrefresh")?;
Alan Stokes46a1dff2021-12-14 10:56:05 +0000148 let exit_code = match jail.wait() {
149 Ok(_) => Result::<u8>::Ok(0),
150 Err(minijail::Error::ReturnCode(exit_code)) => Ok(exit_code),
Victor Hsiehf9968692021-11-18 11:34:39 -0800151 Err(e) => {
152 bail!("Unexpected minijail error: {}", e)
153 }
Alan Stokes46a1dff2021-12-14 10:56:05 +0000154 }?;
155
Alan Stokes126fd512021-12-16 15:00:01 +0000156 let exit_code = ExitCode::from_i32(exit_code.into())?;
Alan Stokes46a1dff2021-12-14 10:56:05 +0000157 info!("odrefresh exited with {:?}", exit_code);
158
159 if exit_code == ExitCode::CompilationSuccess {
160 // authfs only shows us the files we created, so it's ok to just sign everything under
161 // the target directory.
162 let target_dir = art_apex_data.join(context.target_dir_name);
163 let mut artifact_signer = ArtifactSigner::new(&target_dir);
164 add_artifacts(&target_dir, &mut artifact_signer)?;
165
166 artifact_signer.write_info_and_signature(signer, &target_dir.join("compos.info"))?;
Victor Hsiehf9968692021-11-18 11:34:39 -0800167 }
Alan Stokes46a1dff2021-12-14 10:56:05 +0000168
169 Ok(exit_code)
170}
171
Alan Stokes92472512022-01-04 11:48:38 +0000172fn set_classpaths(android_root: &Path) -> Result<()> {
173 let export_lines = run_derive_classpath(android_root)?;
174 load_classpath_vars(&export_lines)
175}
176
177fn run_derive_classpath(android_root: &Path) -> Result<String> {
178 let classpaths_root = android_root.join("etc/classpaths");
179
180 let mut bootclasspath_arg = OsString::new();
181 bootclasspath_arg.push("--bootclasspath-fragment=");
182 bootclasspath_arg.push(classpaths_root.join("bootclasspath.pb"));
183
184 let mut systemserverclasspath_arg = OsString::new();
185 systemserverclasspath_arg.push("--systemserverclasspath-fragment=");
186 systemserverclasspath_arg.push(classpaths_root.join("systemserverclasspath.pb"));
187
188 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
189 .arg(bootclasspath_arg)
190 .arg(systemserverclasspath_arg)
191 .arg("/proc/self/fd/1")
192 .output()
193 .context("Failed to run derive_classpath")?;
194
195 if !result.status.success() {
196 bail!("derive_classpath returned {}", result.status);
197 }
198
199 String::from_utf8(result.stdout).context("Converting derive_classpath output")
200}
201
202fn load_classpath_vars(export_lines: &str) -> Result<()> {
203 // Each line should be in the format "export <var name> <value>"
204 let pattern = Regex::new(r"^export ([^ ]+) ([^ ]+)$").context("Failed to construct Regex")?;
205 for line in export_lines.lines() {
206 if let Some(captures) = pattern.captures(line) {
207 let name = &captures[1];
208 let value = &captures[2];
209 // TODO(b/213416778) Don't modify our env, construct a fresh one for odrefresh
210 env::set_var(name, value);
211 } else {
212 warn!("Malformed line from derive_classpath: {}", line);
213 }
214 }
215
216 Ok(())
217}
218
Alan Stokes46a1dff2021-12-14 10:56:05 +0000219fn add_artifacts(target_dir: &Path, artifact_signer: &mut ArtifactSigner) -> Result<()> {
220 for entry in
221 read_dir(&target_dir).with_context(|| format!("Traversing {}", target_dir.display()))?
222 {
223 let entry = entry?;
224 let file_type = entry.file_type()?;
225 if file_type.is_dir() {
226 add_artifacts(&entry.path(), artifact_signer)?;
227 } else if file_type.is_file() {
228 artifact_signer.add_artifact(&entry.path())?;
229 } else {
230 // authfs shouldn't create anything else, but just in case
231 bail!("Unexpected file type in artifacts: {:?}", entry);
232 }
233 }
234 Ok(())
Victor Hsiehf9968692021-11-18 11:34:39 -0800235}
236
Victor Hsieh13333e82021-09-03 15:17:32 -0700237/// Runs the compiler with given flags with file descriptors described in `fd_annotation` retrieved
238/// via `authfs_service`. Returns exit code of the compiler process.
Victor Hsieh3c044c42021-10-01 17:17:10 -0700239pub fn compile_cmd(
Victor Hsieh51789de2021-08-06 16:50:49 -0700240 compiler_path: &Path,
241 compiler_args: &[String],
242 authfs_service: Strong<dyn IAuthFsService>,
Victor Hsieh13333e82021-09-03 15:17:32 -0700243 fd_annotation: &FdAnnotation,
Victor Hsieh6e340382021-08-13 12:18:02 -0700244) -> Result<CompilerOutput> {
245 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
246 // is out of scope.
Victor Hsieh13333e82021-09-03 15:17:32 -0700247 let authfs_config = build_authfs_config(fd_annotation);
Victor Hsieh51789de2021-08-06 16:50:49 -0700248 let authfs = authfs_service.mount(&authfs_config)?;
249
250 // The task expects to receive FD numbers that match its flags (e.g. --zip-fd=42) prepared
251 // on the host side. Since the local FD opened from authfs (e.g. /authfs/42) may not match
252 // the task's expectation, prepare a FD mapping and let minijail prepare the correct FD
253 // setup.
254 let fd_mapping =
255 open_authfs_files_for_fd_mapping(&authfs, &authfs_config).context("Open on authfs")?;
256
257 let jail =
258 spawn_jailed_task(compiler_path, compiler_args, fd_mapping).context("Spawn dex2oat")?;
259 let jail_result = jail.wait();
260
Victor Hsieh6e340382021-08-13 12:18:02 -0700261 let parcel_fds = parse_compiler_args(&authfs, compiler_args)?;
262 let oat_file: &File = parcel_fds.oat.as_ref();
263 let vdex_file: &File = parcel_fds.vdex.as_ref();
264 let image_file: &File = parcel_fds.image.as_ref();
Victor Hsieh51789de2021-08-06 16:50:49 -0700265
266 match jail_result {
Victor Hsieh6e340382021-08-13 12:18:02 -0700267 Ok(()) => Ok(CompilerOutput::Digests {
Victor Hsieh9ed27182021-08-25 15:52:42 -0700268 oat: fsverity::measure(oat_file.as_raw_fd())?,
269 vdex: fsverity::measure(vdex_file.as_raw_fd())?,
270 image: fsverity::measure(image_file.as_raw_fd())?,
Victor Hsieh6e340382021-08-13 12:18:02 -0700271 }),
Victor Hsieh51789de2021-08-06 16:50:49 -0700272 Err(minijail::Error::ReturnCode(exit_code)) => {
Victor Hsieh6e340382021-08-13 12:18:02 -0700273 error!("dex2oat failed with exit code {}", exit_code);
274 Ok(CompilerOutput::ExitCode(exit_code as i8))
Victor Hsieh51789de2021-08-06 16:50:49 -0700275 }
276 Err(e) => {
277 bail!("Unexpected minijail error: {}", e)
278 }
279 }
280}
281
Victor Hsieh6e340382021-08-13 12:18:02 -0700282fn parse_compiler_args(
283 authfs: &Strong<dyn IAuthFs>,
284 args: &[String],
285) -> Result<CompilerOutputParcelFds> {
286 const OAT_FD_PREFIX: &str = "--oat-fd=";
287 const VDEX_FD_PREFIX: &str = "--output-vdex-fd=";
288 const IMAGE_FD_PREFIX: &str = "--image-fd=";
289 const APP_IMAGE_FD_PREFIX: &str = "--app-image-fd=";
290
291 let mut oat = None;
292 let mut vdex = None;
293 let mut image = None;
294
295 for arg in args {
296 if let Some(value) = arg.strip_prefix(OAT_FD_PREFIX) {
297 let fd = value.parse::<RawFd>().context("Invalid --oat-fd flag")?;
298 debug_assert!(oat.is_none());
299 oat = Some(authfs.openFile(fd, false)?);
300 } else if let Some(value) = arg.strip_prefix(VDEX_FD_PREFIX) {
301 let fd = value.parse::<RawFd>().context("Invalid --output-vdex-fd flag")?;
302 debug_assert!(vdex.is_none());
303 vdex = Some(authfs.openFile(fd, false)?);
304 } else if let Some(value) = arg.strip_prefix(IMAGE_FD_PREFIX) {
305 let fd = value.parse::<RawFd>().context("Invalid --image-fd flag")?;
306 debug_assert!(image.is_none());
307 image = Some(authfs.openFile(fd, false)?);
308 } else if let Some(value) = arg.strip_prefix(APP_IMAGE_FD_PREFIX) {
309 let fd = value.parse::<RawFd>().context("Invalid --app-image-fd flag")?;
310 debug_assert!(image.is_none());
311 image = Some(authfs.openFile(fd, false)?);
312 }
313 }
314
315 Ok(CompilerOutputParcelFds {
316 oat: oat.ok_or_else(|| anyhow!("Missing --oat-fd"))?,
317 vdex: vdex.ok_or_else(|| anyhow!("Missing --vdex-fd"))?,
318 image: image.ok_or_else(|| anyhow!("Missing --image-fd or --app-image-fd"))?,
319 })
320}
321
Victor Hsieh13333e82021-09-03 15:17:32 -0700322fn build_authfs_config(fd_annotation: &FdAnnotation) -> AuthFsConfig {
Victor Hsieh51789de2021-08-06 16:50:49 -0700323 AuthFsConfig {
Victor Hsiehf9968692021-11-18 11:34:39 -0800324 port: FD_SERVER_PORT,
Victor Hsieh13333e82021-09-03 15:17:32 -0700325 inputFdAnnotations: fd_annotation
326 .input_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700327 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700328 .map(|fd| InputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700329 .collect(),
Victor Hsieh13333e82021-09-03 15:17:32 -0700330 outputFdAnnotations: fd_annotation
331 .output_fds
Victor Hsieh51789de2021-08-06 16:50:49 -0700332 .iter()
Victor Hsieh13333e82021-09-03 15:17:32 -0700333 .map(|fd| OutputFdAnnotation { fd: *fd })
Victor Hsieh51789de2021-08-06 16:50:49 -0700334 .collect(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800335 ..Default::default()
Victor Hsieh51789de2021-08-06 16:50:49 -0700336 }
337}
338
339fn open_authfs_files_for_fd_mapping(
340 authfs: &Strong<dyn IAuthFs>,
341 config: &AuthFsConfig,
342) -> Result<Vec<(ParcelFileDescriptor, PseudoRawFd)>> {
343 let mut fd_mapping = Vec::new();
344
345 let results: Result<Vec<_>> = config
346 .inputFdAnnotations
347 .iter()
348 .map(|annotation| Ok((authfs.openFile(annotation.fd, false)?, annotation.fd)))
349 .collect();
350 fd_mapping.append(&mut results?);
351
352 let results: Result<Vec<_>> = config
353 .outputFdAnnotations
354 .iter()
355 .map(|annotation| Ok((authfs.openFile(annotation.fd, true)?, annotation.fd)))
356 .collect();
357 fd_mapping.append(&mut results?);
358
359 Ok(fd_mapping)
360}
361
362fn spawn_jailed_task(
363 executable: &Path,
364 args: &[String],
365 fd_mapping: Vec<(ParcelFileDescriptor, PseudoRawFd)>,
366) -> Result<Minijail> {
367 // TODO(b/185175567): Run in a more restricted sandbox.
368 let jail = Minijail::new()?;
369 let preserve_fds: Vec<_> = fd_mapping.iter().map(|(f, id)| (f.as_raw_fd(), *id)).collect();
370 let _pid = jail.run_remap(executable, preserve_fds.as_slice(), args)?;
371 Ok(jail)
372}