Make native metrics logger write to statsd socket

Previous submission of this change, aosp/790068, caused a failure in
sdk_mac for CLOCK_REALTIME and <endian.h> not being available.

Bug: 110537511
Test: compiles without failures and verified the correct metric
Change-Id: Iba1dc920ad82e88a4bcdd2feaee9a06202a440c2
diff --git a/libstats/Android.bp b/libstats/Android.bp
index d58f294..f5ee1da 100644
--- a/libstats/Android.bp
+++ b/libstats/Android.bp
@@ -17,12 +17,13 @@
 // ==========================================================
 // Native library to write stats log to statsd socket
 // ==========================================================
-cc_library_static {
+cc_library {
     name: "libstatssocket",
     srcs: [
         "stats_event_list.c",
         "statsd_writer.c",
     ],
+    host_supported: true,
     cflags: [
         "-Wall",
         "-Werror",
@@ -32,6 +33,7 @@
     ],
     export_include_dirs: ["include"],
     shared_libs: [
+        "libcutils",
         "liblog",
     ],
 }
diff --git a/libstats/stats_event_list.c b/libstats/stats_event_list.c
index 8eedc60..72770d4 100644
--- a/libstats/stats_event_list.c
+++ b/libstats/stats_event_list.c
@@ -17,6 +17,7 @@
 #include "include/stats_event_list.h"
 
 #include <string.h>
+#include <sys/time.h>
 #include "statsd_writer.h"
 
 #define MAX_EVENT_PAYLOAD (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(int32_t))
@@ -156,7 +157,14 @@
     }
 
     save_errno = errno;
+#if defined(__ANDROID__)
     clock_gettime(CLOCK_REALTIME, &ts);
+#else
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    ts.tv_sec = tv.tv_sec;
+    ts.tv_nsec = tv.tv_usec * 1000;
+#endif
 
     int ret = (int)(*statsdLoggerWrite.write)(&ts, vec, nr);
     errno = save_errno;
diff --git a/libstats/statsd_writer.c b/libstats/statsd_writer.c
index afe401f..88f7d44 100644
--- a/libstats/statsd_writer.c
+++ b/libstats/statsd_writer.c
@@ -15,8 +15,9 @@
  */
 #include "statsd_writer.h"
 
+#include <cutils/fs.h>
 #include <cutils/sockets.h>
-#include <endian.h>
+#include <cutils/threads.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
@@ -37,6 +38,14 @@
 /* branchless on many architectures. */
 #define min(x, y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
 
+#ifndef htole32
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define htole32(x) (x)
+#else
+#define htole32(x) __bswap_32(x)
+#endif
+#endif
+
 static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
 static atomic_int dropped = 0;
 
@@ -78,7 +87,14 @@
 
     i = atomic_load(&statsdLoggerWrite.sock);
     if (i < 0) {
-        int sock = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
+        int flags = SOCK_DGRAM;
+#ifdef SOCK_CLOEXEC
+        flags |= SOCK_CLOEXEC;
+#endif
+#ifdef SOCK_NONBLOCK
+        flags |= SOCK_NONBLOCK;
+#endif
+        int sock = TEMP_FAILURE_RETRY(socket(PF_UNIX, flags, 0));
         if (sock < 0) {
             ret = -errno;
         } else {