1 // 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 
21 use anyhow::Result;
22 use protobuf::Message;
23 use std::io::Read;
24 use std::io::Write;
25 
26 pub use microdroid_metadata::metadata::{
27     metadata::Payload as PayloadMetadata, ApexPayload, ApkPayload, Metadata, PayloadConfig,
28 };
29 
30 /// Reads a metadata from a reader
read_metadata<T: Read>(mut r: T) -> Result<Metadata>31 pub fn read_metadata<T: Read>(mut r: T) -> Result<Metadata> {
32     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
write_metadata<T: Write>(metadata: &Metadata, mut w: T) -> Result<()>39 pub fn write_metadata<T: Write>(metadata: &Metadata, mut w: T) -> Result<()> {
40     let mut buf = Vec::new();
41     metadata.write_to_writer(&mut buf)?;
42     w.write_all(&(buf.len() as i32).to_be_bytes())?;
43     w.write_all(&buf)?;
44     Ok(())
45 }
46