[refactor] Split the message macro in a standalone library for reuse

This simplifies the task of creating an independent library of
rkpd_client later.

Test: atest keystore2_test
Bug: 241428146
Change-Id: Idddf37d14580e691fde5a494e54297465cb693b6
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index dd036c2..03dfd45 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -55,6 +55,7 @@
         "liblibc",
         "liblog_event_list",
         "liblog_rust",
+        "libmessage_macro",
         "librand",
         "librustutils",
         "libserde",
diff --git a/keystore2/message_macro/Android.bp b/keystore2/message_macro/Android.bp
new file mode 100644
index 0000000..f1fbad7
--- /dev/null
+++ b/keystore2/message_macro/Android.bp
@@ -0,0 +1,37 @@
+// Copyright 2023, 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.
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_security_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_security_license"],
+}
+
+rust_defaults {
+    name: "libmessage_macro_defaults",
+    crate_name: "message_macro",
+    srcs: ["src/lib.rs"],
+}
+
+rust_library {
+    name: "libmessage_macro",
+    defaults: ["libmessage_macro_defaults"],
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.virt",
+    ],
+}
diff --git a/keystore2/src/ks_err.rs b/keystore2/message_macro/src/lib.rs
similarity index 76%
rename from keystore2/src/ks_err.rs
rename to keystore2/message_macro/src/lib.rs
index c9c38c0..d8cfab0 100644
--- a/keystore2/src/ks_err.rs
+++ b/keystore2/message_macro/src/lib.rs
@@ -12,20 +12,20 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! A ks_err macro that expands error messages to include the file and line number
+//! A macro that generates a message containing the current source file name
+//! and line number.
 
+/// Generates a message containing the current source file name and line number.
 ///
 /// # Examples
 ///
 /// ```
-/// use crate::ks_err;
-///
-/// ks_err!("Key is expired.");
+/// source_location_msg!("Key is expired.");
 /// Result:
 /// "src/lib.rs:7 Key is expired."
 /// ```
 #[macro_export]
-macro_rules! ks_err {
+macro_rules! source_location_msg {
     { $($arg:tt)+ } => {
         format!("{}:{}: {}", file!(), line!(), format_args!($($arg)+))
     };
diff --git a/keystore2/src/lib.rs b/keystore2/src/lib.rs
index 8c08d3e..e51a319 100644
--- a/keystore2/src/lib.rs
+++ b/keystore2/src/lib.rs
@@ -28,7 +28,6 @@
 pub mod id_rotation;
 /// Internal Representation of Key Parameter and convenience functions.
 pub mod key_parameter;
-pub mod ks_err;
 pub mod legacy_blob;
 pub mod legacy_importer;
 pub mod maintenance;
@@ -51,3 +50,5 @@
 mod super_key;
 mod sw_keyblob;
 mod watchdog_helper;
+
+use message_macro::source_location_msg as ks_err;
diff --git a/keystore2/src/rkpd_client.rs b/keystore2/src/rkpd_client.rs
index 5f92d82..9317824 100644
--- a/keystore2/src/rkpd_client.rs
+++ b/keystore2/src/rkpd_client.rs
@@ -15,7 +15,6 @@
 //! Helper wrapper around RKPD interface.
 
 use crate::error::{map_binder_status_code, Error, ResponseCode};
-use crate::ks_err;
 use crate::watchdog_helper::watchdog as wd;
 use android_security_rkp_aidl::aidl::android::security::rkp::{
     IGetKeyCallback::BnGetKeyCallback, IGetKeyCallback::ErrorCode::ErrorCode as GetKeyErrorCode,
@@ -28,6 +27,7 @@
 };
 use android_security_rkp_aidl::binder::{BinderFeatures, Interface, Strong};
 use anyhow::{Context, Result};
+use message_macro::source_location_msg;
 use std::sync::Mutex;
 use std::time::Duration;
 use tokio::sync::oneshot;
@@ -91,17 +91,17 @@
         log::warn!("IGetRegistrationCallback cancelled");
         self.registration_tx.send(
             Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
-                .context(ks_err!("GetRegistrationCallback cancelled.")),
+                .context(source_location_msg!("GetRegistrationCallback cancelled.")),
         );
         Ok(())
     }
     fn onError(&self, description: &str) -> binder::Result<()> {
         let _wp = wd::watch_millis("IGetRegistrationCallback::onError", 500);
         log::error!("IGetRegistrationCallback failed: '{description}'");
-        self.registration_tx.send(
-            Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
-                .context(ks_err!("GetRegistrationCallback failed: {:?}", description)),
-        );
+        self.registration_tx
+            .send(Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR)).context(
+                source_location_msg!("GetRegistrationCallback failed: {:?}", description),
+            ));
         Ok(())
     }
 }
@@ -110,19 +110,18 @@
 async fn get_rkpd_registration(rpc_name: &str) -> Result<binder::Strong<dyn IRegistration>> {
     let remote_provisioning: Strong<dyn IRemoteProvisioning> =
         map_binder_status_code(binder::get_interface("remote_provisioning"))
-            .context(ks_err!("Trying to connect to IRemoteProvisioning service."))?;
+            .context(source_location_msg!("Trying to connect to IRemoteProvisioning service."))?;
 
     let (tx, rx) = oneshot::channel();
     let cb = GetRegistrationCallback::new_native_binder(tx);
 
     remote_provisioning
         .getRegistration(rpc_name, &cb)
-        .context(ks_err!("Trying to get registration."))?;
+        .context(source_location_msg!("Trying to get registration."))?;
 
     match timeout(RKPD_TIMEOUT, rx).await {
-        Err(e) => {
-            Err(Error::Rc(ResponseCode::SYSTEM_ERROR)).context(ks_err!("Waiting for RKPD: {:?}", e))
-        }
+        Err(e) => Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
+            .context(source_location_msg!("Waiting for RKPD: {:?}", e)),
         Ok(v) => v.unwrap(),
     }
 }
@@ -156,7 +155,7 @@
         log::warn!("IGetKeyCallback cancelled");
         self.key_tx.send(
             Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
-                .context(ks_err!("GetKeyCallback cancelled.")),
+                .context(source_location_msg!("GetKeyCallback cancelled.")),
         );
         Ok(())
     }
@@ -177,7 +176,7 @@
                 ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR
             }
         };
-        self.key_tx.send(Err(Error::Rc(rc)).context(ks_err!(
+        self.key_tx.send(Err(Error::Rc(rc)).context(source_location_msg!(
             "GetKeyCallback failed: {:?} {:?}",
             error,
             description
@@ -195,7 +194,7 @@
 
     registration
         .getKey(caller_uid.try_into().unwrap(), &cb)
-        .context(ks_err!("Trying to get key."))?;
+        .context(source_location_msg!("Trying to get key."))?;
 
     match timeout(RKPD_TIMEOUT, rx).await {
         Err(e) => {
@@ -204,7 +203,7 @@
                 log::error!("IRegistration::cancelGetKey failed: {:?}", e);
             }
             Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
-                .context(ks_err!("Waiting for RKPD key timed out: {:?}", e))
+                .context(source_location_msg!("Waiting for RKPD key timed out: {:?}", e))
         }
         Ok(v) => v.unwrap(),
     }
@@ -216,7 +215,7 @@
 ) -> Result<RemotelyProvisionedKey> {
     let registration = get_rkpd_registration(rpc_name)
         .await
-        .context(ks_err!("Trying to get to IRegistration service."))?;
+        .context(source_location_msg!("Trying to get to IRegistration service."))?;
     get_rkpd_attestation_key_from_registration_async(&registration, caller_uid).await
 }
 
@@ -247,7 +246,7 @@
         log::error!("IGetRegistrationCallback failed: {error}");
         self.completer.send(
             Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
-                .context(ks_err!("Failed to store upgraded key: {:?}", error)),
+                .context(source_location_msg!("Failed to store upgraded key: {:?}", error)),
         );
         Ok(())
     }
@@ -263,11 +262,11 @@
 
     registration
         .storeUpgradedKeyAsync(key_blob, upgraded_blob, &cb)
-        .context(ks_err!("Failed to store upgraded blob with RKPD."))?;
+        .context(source_location_msg!("Failed to store upgraded blob with RKPD."))?;
 
     match timeout(RKPD_TIMEOUT, rx).await {
         Err(e) => Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
-            .context(ks_err!("Waiting for RKPD to complete storing key: {:?}", e)),
+            .context(source_location_msg!("Waiting for RKPD to complete storing key: {:?}", e)),
         Ok(v) => v.unwrap(),
     }
 }
@@ -279,7 +278,7 @@
 ) -> Result<()> {
     let registration = get_rkpd_registration(rpc_name)
         .await
-        .context(ks_err!("Trying to get to IRegistration service."))?;
+        .context(source_location_msg!("Trying to get to IRegistration service."))?;
     store_rkpd_attestation_key_with_registration_async(&registration, key_blob, upgraded_blob).await
 }