Log keystore2 crash events.

Ignore-AOSP-First: Merge conflict resolution of a CL in the topic.
Bug: 188590587
Test: statsd TestDrive script.
Merged-In: I0ad7c94187060dca28469ba262e1e4d93fe3df83

Change-Id: I0ad7c94187060dca28469ba262e1e4d93fe3df83
diff --git a/keystore2/system_property/Android.bp b/keystore2/system_property/Android.bp
index 9e7b056..773804d 100644
--- a/keystore2/system_property/Android.bp
+++ b/keystore2/system_property/Android.bp
@@ -31,6 +31,7 @@
         "--size_t-is-usize",
         "--allowlist-function=__system_property_find",
         "--allowlist-function=__system_property_read_callback",
+        "--allowlist-function=__system_property_set",
         "--allowlist-function=__system_property_wait",
     ],
 }
diff --git a/keystore2/system_property/lib.rs b/keystore2/system_property/lib.rs
index be13c88..b993c87 100644
--- a/keystore2/system_property/lib.rs
+++ b/keystore2/system_property/lib.rs
@@ -15,6 +15,7 @@
 //! This crate provides the PropertyWatcher type, which watches for changes
 //! in Android system properties.
 
+use anyhow::{anyhow, Context, Result as AnyhowResult};
 use keystore2_system_property_bindgen::prop_info as PropInfo;
 use std::os::raw::c_char;
 use std::ptr::null;
@@ -48,6 +49,9 @@
     /// read callback returned an error
     #[error("Callback failed")]
     CallbackError(#[from] anyhow::Error),
+    /// Failure in setting the system property
+    #[error("__system_property_set failed.")]
+    SetPropertyFailed,
 }
 
 /// Result type specific for this crate.
@@ -189,3 +193,25 @@
         Ok(())
     }
 }
+
+/// Writes a system property.
+pub fn write(name: &str, value: &str) -> AnyhowResult<()> {
+    if
+    // Unsafe required for FFI call. Input and output are both const and valid strings.
+    unsafe {
+        // If successful, __system_property_set returns 0, otherwise, returns -1.
+        keystore2_system_property_bindgen::__system_property_set(
+            CString::new(name)
+                .context("In keystore2::system_property::write: Construction CString from name.")?
+                .as_ptr(),
+            CString::new(value)
+                .context("In keystore2::system_property::write: Constructing CString from value.")?
+                .as_ptr(),
+        )
+    } == 0
+    {
+        Ok(())
+    } else {
+        Err(anyhow!(PropertyWatcherError::SetPropertyFailed))
+    }
+}