microdroid_manager: initial impl

It is started by init in microdroid and executes a command specified in
a VM payload config.

Bug: 189301496
Test: MicrodroidHostTestCases
  (in a microdroid, run /system/bin/microdroid_manager manulally)
Change-Id: I85c7e370d4a0dcf58b4aafbe6e9fba73e69c2a44
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 85b5e0c..30fec88 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -48,6 +48,7 @@
         "microdroid_build_prop",
         "microdroid_init_rc",
         "microdroid_launcher",
+        "microdroid_manager",
         "ueventd.rc",
         "libbinder",
         "libbinder_ndk",
diff --git a/microdroid/init.rc b/microdroid/init.rc
index 121afaa..8458291 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -110,6 +110,9 @@
 
     perform_apex_config
 
+    # TODO(b/185991357) start this earlier
+    start microdroid_manager
+
     exec_start derive_sdk
 
     start adbd
diff --git a/microdroid/microdroid_file_contexts b/microdroid/microdroid_file_contexts
index b033110..fc5e456 100644
--- a/microdroid/microdroid_file_contexts
+++ b/microdroid/microdroid_file_contexts
@@ -368,6 +368,7 @@
 /system/bin/snapuserd            u:object_r:snapuserd_exec:s0
 /system/bin/zipfuse              u:object_r:zipfuse_exec:s0
 /system/bin/microdroid_launcher  u:object_r:microdroid_launcher_exec:s0
+/system/bin/microdroid_manager   u:object_r:microdroid_manager_exec:s0
 
 #############################
 # Vendor files
diff --git a/microdroid/signature/Android.bp b/microdroid/signature/Android.bp
index 35c4e9e..1ce7805 100644
--- a/microdroid/signature/Android.bp
+++ b/microdroid/signature/Android.bp
@@ -38,6 +38,14 @@
     ],
 }
 
+rust_protobuf {
+    name: "libmicrodroid_signature_proto_rust",
+    crate_name: "microdroid_signature",
+    protos: ["microdroid_signature.proto"],
+    source_stem: "microdroid_signature",
+    host_supported: true,
+}
+
 cc_binary {
     name: "mk_payload",
     srcs: [
diff --git a/microdroid/signature/microdroid_signature.proto b/microdroid/signature/microdroid_signature.proto
index 8816aa8..6ae3756 100644
--- a/microdroid/signature/microdroid_signature.proto
+++ b/microdroid/signature/microdroid_signature.proto
@@ -27,6 +27,8 @@
   repeated ApexSignature apexes = 2;
 
   ApkSignature apk = 3;
+
+  string payload_config_path = 4;
 }
 
 message ApexSignature {
@@ -54,4 +56,4 @@
 
   string payload_partition_name = 2;
   string idsig_partition_name = 3;
-}
\ No newline at end of file
+}
diff --git a/microdroid/signature/mk_payload.cc b/microdroid/signature/mk_payload.cc
index a3501d4..9caf788 100644
--- a/microdroid/signature/mk_payload.cc
+++ b/microdroid/signature/mk_payload.cc
@@ -97,6 +97,7 @@
     std::vector<std::string> system_apexes;
     std::vector<ApexConfig> apexes;
     std::optional<ApkConfig> apk;
+    std::optional<std::string> payload_config_path;
 };
 
 #define DO(expr) \
@@ -120,6 +121,16 @@
     return ParseJson(value, *s);
 }
 
+template <typename T>
+Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
+    for (const Json::Value& value : values) {
+        T t;
+        DO(ParseJson(value, t));
+        parsed.push_back(std::move(t));
+    }
+    return {};
+}
+
 Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
     DO(ParseJson(value["name"], apex_config.name));
     DO(ParseJson(value["path"], apex_config.path));
@@ -134,20 +145,11 @@
     return {};
 }
 
-template <typename T>
-Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
-    for (const Json::Value& value : values) {
-        T t;
-        DO(ParseJson(value, t));
-        parsed.push_back(std::move(t));
-    }
-    return {};
-}
-
 Result<void> ParseJson(const Json::Value& value, Config& config) {
     DO(ParseJson(value["system_apexes"], config.system_apexes));
     DO(ParseJson(value["apexes"], config.apexes));
     DO(ParseJson(value["apk"], config.apk));
+    DO(ParseJson(value["payload_config_path"], config.payload_config_path));
     return {};
 }
 
@@ -232,6 +234,10 @@
         // TODO(jooyung): set idsig partition as well
     }
 
+    if (config.payload_config_path.has_value()) {
+        *signature.mutable_payload_config_path() = config.payload_config_path.value();
+    }
+
     std::ofstream out(filename);
     return WriteMicrodroidSignature(signature, out);
 }
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
new file mode 100644
index 0000000..2c79196
--- /dev/null
+++ b/microdroid_manager/Android.bp
@@ -0,0 +1,21 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_binary {
+    name: "microdroid_manager",
+    crate_name: "microdroid_manager",
+    srcs: ["src/main.rs"],
+    edition: "2018",
+    prefer_rlib: true,
+    rustlibs: [
+        "libandroid_logger",
+        "libanyhow",
+        "liblog_rust",
+        "libmicrodroid_signature_proto_rust",
+        "libprotobuf",
+        "libserde_json",
+        "libserde",
+    ],
+    init_rc: ["microdroid_manager.rc"],
+}
diff --git a/microdroid_manager/microdroid_manager.rc b/microdroid_manager/microdroid_manager.rc
new file mode 100644
index 0000000..c800002
--- /dev/null
+++ b/microdroid_manager/microdroid_manager.rc
@@ -0,0 +1,4 @@
+service microdroid_manager /system/bin/microdroid_manager
+    disabled
+    # TODO(jooyung) remove this when microdroid_manager becomes a daemon
+    oneshot
\ No newline at end of file
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
new file mode 100644
index 0000000..4f87a40
--- /dev/null
+++ b/microdroid_manager/src/main.rs
@@ -0,0 +1,51 @@
+// Copyright 2021, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Microdroid Manager
+
+mod payload_config;
+mod signature;
+
+use android_logger::Config;
+use log::{info, Level};
+use payload_config::{Task, VmPayloadConfig};
+use std::io;
+use std::process::Command;
+
+const LOG_TAG: &str = "MicrodroidManager";
+
+fn main() -> io::Result<()> {
+    android_logger::init_once(Config::default().with_tag(LOG_TAG).with_min_level(Level::Debug));
+
+    info!("started.");
+
+    let signature = signature::load()?;
+    if !signature.payload_config_path.is_empty() {
+        let config = VmPayloadConfig::load_from(&signature.payload_config_path)?;
+        if let Some(main_task) = &config.task {
+            exec(main_task)?;
+        }
+    }
+
+    Ok(())
+}
+
+/// executes a task
+/// TODO(jooyung): fork a child process
+fn exec(task: &Task) -> io::Result<()> {
+    info!("executing main task {} {:?}...", task.command, task.args);
+    let exit_status = Command::new(&task.command).args(&task.args).status()?;
+    info!("exit with {}", &exit_status);
+    Ok(())
+}
diff --git a/microdroid_manager/src/payload_config.rs b/microdroid_manager/src/payload_config.rs
new file mode 100644
index 0000000..1dd6d92
--- /dev/null
+++ b/microdroid_manager/src/payload_config.rs
@@ -0,0 +1,41 @@
+// Copyright 2021, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! VM Payload Config
+
+use log::info;
+use serde::{Deserialize, Serialize};
+use std::fs::File;
+use std::io;
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct VmPayloadConfig {
+    #[serde(default)]
+    pub task: Option<Task>,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct Task {
+    pub command: String,
+    #[serde(default)]
+    pub args: Vec<String>,
+}
+
+impl VmPayloadConfig {
+    pub fn load_from(path: &str) -> io::Result<VmPayloadConfig> {
+        info!("loading config from {}...", path);
+        let file = File::open(path)?;
+        Ok(serde_json::from_reader(file)?)
+    }
+}
diff --git a/microdroid_manager/src/signature.rs b/microdroid_manager/src/signature.rs
new file mode 100644
index 0000000..4f06885
--- /dev/null
+++ b/microdroid_manager/src/signature.rs
@@ -0,0 +1,40 @@
+// Copyright 2021, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! MicrodroidSignature from /dev/block/by-name/signature
+//! TODO(jooyung): migrate to "metadata" partition
+
+use log::info;
+use microdroid_signature::microdroid_signature::MicrodroidSignature;
+use protobuf::Message;
+use std::fs::File;
+use std::io;
+use std::io::Read;
+
+const SIGNATURE_PATH: &str = "/dev/block/by-name/signature";
+
+/// loads microdroid_signature from /dev/block/by-name/signature
+pub fn load() -> io::Result<MicrodroidSignature> {
+    info!("loading signature...");
+
+    let mut f = File::open(SIGNATURE_PATH)?;
+    // signature partition is
+    //  4 bytes : size(N) in big endian
+    //  N bytes : message for MicrodroidSignature
+    let mut buf = [0u8; 4];
+    f.read_exact(&mut buf)?;
+    let size = i32::from_be_bytes(buf);
+
+    Ok(MicrodroidSignature::parse_from_reader(&mut f.take(size as u64))?)
+}