blob: f00391af2672de71740ba8e589d3fe436a742687 [file] [log] [blame]
Jooyung Hanf1e00862021-06-25 12:02:33 +09001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Read/write metadata blob for VM payload image. The blob is supposed to be used as a metadata
16//! partition in the VM payload image.
17//! The layout of metadata blob is like:
18//! 4 bytes : size(N) in big endian
19//! N bytes : protobuf message for Metadata
20
Jooyung Han14e5a8e2021-07-06 20:48:38 +090021use anyhow::Result;
Jooyung Hanf1e00862021-06-25 12:02:33 +090022use protobuf::Message;
Jooyung Hanf1e00862021-06-25 12:02:33 +090023use std::io::Read;
24use std::io::Write;
25
Alan Stokes0d1ef782022-09-27 13:46:35 +010026pub use microdroid_metadata::metadata::{
Ludovic Barman93ee3082023-06-20 12:18:43 +000027 metadata::Payload as PayloadMetadata, ApexPayload, ApkPayload, Metadata, PayloadConfig,
Alan Stokes0d1ef782022-09-27 13:46:35 +010028};
Jooyung Hanf1e00862021-06-25 12:02:33 +090029
30/// Reads a metadata from a reader
Jooyung Han14e5a8e2021-07-06 20:48:38 +090031pub fn read_metadata<T: Read>(mut r: T) -> Result<Metadata> {
Jooyung Hanf1e00862021-06-25 12:02:33 +090032 let mut buf = [0u8; 4];
33 r.read_exact(&mut buf)?;
34 let size = i32::from_be_bytes(buf);
35 Ok(Metadata::parse_from_reader(&mut r.take(size as u64))?)
36}
37
38/// Writes a metadata to a writer
Jooyung Han14e5a8e2021-07-06 20:48:38 +090039pub fn write_metadata<T: Write>(metadata: &Metadata, mut w: T) -> Result<()> {
Jooyung Hanf1e00862021-06-25 12:02:33 +090040 let mut buf = Vec::new();
41 metadata.write_to_writer(&mut buf)?;
42 w.write_all(&(buf.len() as i32).to_be_bytes())?;
Jooyung Han14e5a8e2021-07-06 20:48:38 +090043 w.write_all(&buf)?;
44 Ok(())
Jooyung Hanf1e00862021-06-25 12:02:33 +090045}