Snap for 9430503 from 5abd0a5fb99f683ffbf98f3d0cd9ed015c5d4698 to t-keystone-qcom-release

Change-Id: I98969dbe20264ba51dbd7f6a17e3cced9cc52f95
diff --git a/apps/test/chqts/src/general_test/basic_wifi_test.cc b/apps/test/chqts/src/general_test/basic_wifi_test.cc
index af648c9..08e1be2 100644
--- a/apps/test/chqts/src/general_test/basic_wifi_test.cc
+++ b/apps/test/chqts/src/general_test/basic_wifi_test.cc
@@ -17,6 +17,7 @@
 #include <general_test/basic_wifi_test.h>
 
 #include <algorithm>
+#include <cinttypes>
 #include <cmath>
 
 #include <chre.h>
@@ -564,6 +565,14 @@
 
   for (uint8_t i = 0; i < eventData->resultCount; i++) {
     auto &result = eventData->results[i];
+
+    if (result.timestamp < mStartTimestampNs ||
+        result.timestamp > chreGetTime()) {
+      LOGE("Invalid Ranging result timestamp = %" PRIu64 " (%" PRIu64
+           ", %" PRIu64 "). Status = %" PRIu8,
+           result.timestamp, mStartTimestampNs, chreGetTime(), result.status);
+    }
+
     ASSERT_IN_RANGE(result.timestamp, mStartTimestampNs, chreGetTime(),
                     "Ranging result timestamp isn't between the ranging "
                     "request start time and the current time");
diff --git a/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc b/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc
index 5d8c628..dd32753 100644
--- a/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc
+++ b/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc
@@ -635,7 +635,7 @@
     LOGE("Could not get encoded size of proto message");
   } else {
     pb_byte_t *buffer = static_cast<pb_byte_t *>(chreHeapAlloc(encodedSize));
-    if (buffer == nullptr) {
+    if (encodedSize > 0 && buffer == nullptr) {
       LOG_OOM();
     } else {
       pb_ostream_t ostream = pb_ostream_from_buffer(buffer, encodedSize);
diff --git a/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc b/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc
index e4b35d4..86abfe7 100644
--- a/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc
+++ b/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc
@@ -299,7 +299,7 @@
     LOGE("Could not get encoded size of test result message");
   } else {
     pb_byte_t *buffer = static_cast<pb_byte_t *>(chreHeapAlloc(encodedSize));
-    if (buffer == nullptr) {
+    if (encodedSize > 0 && buffer == nullptr) {
       LOG_OOM();
     } else {
       pb_ostream_t ostream = pb_ostream_from_buffer(buffer, encodedSize);
diff --git a/apps/test/common/chre_settings_test/src/chre_settings_test_util.cc b/apps/test/common/chre_settings_test/src/chre_settings_test_util.cc
index 4f39b85..6f4639d 100644
--- a/apps/test/common/chre_settings_test/src/chre_settings_test_util.cc
+++ b/apps/test/common/chre_settings_test/src/chre_settings_test_util.cc
@@ -47,7 +47,7 @@
     LOGE("Failed to get message size");
   } else {
     pb_byte_t *bytes = static_cast<pb_byte_t *>(chreHeapAlloc(size));
-    if (bytes == nullptr) {
+    if (size > 0 && bytes == nullptr) {
       LOG_OOM();
     } else {
       pb_ostream_t stream = pb_ostream_from_buffer(bytes, size);
diff --git a/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h b/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h
index b6c8f91..b02acde 100644
--- a/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h
+++ b/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h
@@ -157,6 +157,11 @@
   void makeWwanCellInfoRequest();
 
   /**
+   * Send the capabilities to the host.
+   */
+  void sendCapabilitiesMessage();
+
+  /**
    * @param event The cell info event from CHRE.
    */
   void handleCellInfoResult(const chreWwanCellInfoResult *event);
diff --git a/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc b/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc
index 4be5765..2136f12 100644
--- a/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc
+++ b/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc
@@ -17,6 +17,7 @@
 #include "chre_stress_test_manager.h"
 
 #include <pb_decode.h>
+#include <pb_encode.h>
 
 #include "chre/util/macros.h"
 #include "chre/util/nanoapp/callbacks.h"
@@ -75,6 +76,9 @@
     // Do nothing and only update the host endpoint
     mHostEndpoint = hostData->hostEndpoint;
     success = true;
+  } else if (messageType == chre_stress_test_MessageType_GET_CAPABILITIES) {
+    sendCapabilitiesMessage();
+    success = true;
   } else if (messageType != chre_stress_test_MessageType_TEST_COMMAND) {
     LOGE("Invalid message type %" PRIu32, messageType);
   } else if (mHostEndpoint.has_value() &&
@@ -553,6 +557,40 @@
       false /* success */, errorMessage, false /* abortOnFailure */);
 }
 
+void Manager::sendCapabilitiesMessage() {
+  if (!mHostEndpoint.has_value()) {
+    LOGE("mHostEndpoint is not initialized");
+    return;
+  }
+
+  chre_stress_test_Capabilities capabilities =
+      chre_stress_test_Capabilities_init_default;
+  capabilities.wifi = chreWifiGetCapabilities();
+
+  size_t size;
+  if (!pb_get_encoded_size(&size, chre_stress_test_Capabilities_fields,
+                           &capabilities)) {
+    LOGE("Failed to get message size");
+    return;
+  }
+
+  pb_byte_t *bytes = static_cast<pb_byte_t *>(chreHeapAlloc(size));
+  if (size > 0 && bytes == nullptr) {
+    LOG_OOM();
+  } else {
+    pb_ostream_t stream = pb_ostream_from_buffer(bytes, size);
+    if (!pb_encode(&stream, chre_stress_test_Capabilities_fields,
+                   &capabilities)) {
+      LOGE("Failed to encode capabilities error %s", PB_GET_ERROR(&stream));
+      chreHeapFree(bytes);
+    } else {
+      chreSendMessageToHostEndpoint(
+          bytes, size, chre_stress_test_MessageType_CAPABILITIES,
+          mHostEndpoint.value(), heapFreeMessageCallback);
+    }
+  }
+}
+
 }  // namespace stress_test
 
 }  // namespace chre
diff --git a/apps/test/common/proto/chre_stress_test.proto b/apps/test/common/proto/chre_stress_test.proto
index 4b6c645..7075093 100644
--- a/apps/test/common/proto/chre_stress_test.proto
+++ b/apps/test/common/proto/chre_stress_test.proto
@@ -30,6 +30,13 @@
   // unicast messages.
   // No payload.
   TEST_HOST_RESTARTED = 4;
+
+  // H2C: Request Capabilities.
+  // No payload.
+  GET_CAPABILITIES = 5;
+
+  // C2H: Capabilities (response to a GET_CAPABILITIES request).
+  CAPABILITIES = 6;
 }
 
 // A message to start the test.
@@ -51,3 +58,12 @@
   // True to start the test, false to stop.
   optional bool start = 2;
 }
+
+/*
+ * CHRE capabilities
+ */
+message Capabilities {
+  // Wifi capabilities
+  // see //system/chre/chre_api/include/chre_api/chre/wifi.h
+  optional uint32 wifi = 1;
+}
diff --git a/apps/test/common/shared/src/send_message.cc b/apps/test/common/shared/src/send_message.cc
index 3a62753..0af68e2 100644
--- a/apps/test/common/shared/src/send_message.cc
+++ b/apps/test/common/shared/src/send_message.cc
@@ -69,7 +69,7 @@
     LOGE("Failed to get message size");
   } else {
     pb_byte_t *bytes = static_cast<pb_byte_t *>(chreHeapAlloc(size));
-    if (bytes == nullptr) {
+    if (size > 0 && bytes == nullptr) {
       LOG_OOM();
     } else {
       pb_ostream_t stream = pb_ostream_from_buffer(bytes, size);
diff --git a/external/tflm/tflm.mk b/external/tflm/tflm.mk
index fad1e6d..63c7360 100644
--- a/external/tflm/tflm.mk
+++ b/external/tflm/tflm.mk
@@ -14,11 +14,6 @@
          export TFLM_PATH=$$(CHRE_PREFIX)/external/tflm/latest")
 endif
 
-ifeq ($(HEXAGON_SDK_PREFIX),)
-$(error "You must set HEXAGON_SDK_PREFIX, e.g. export \
-         HEXAGON_SDK_PREFIX=~/chre-sdk/vendor/qcom/tools/Qualcomm/Hexagon_SDK/latest")
-endif
-
 # TFLM Source Files ############################################################
 
 TFLM_SRCS = $(shell find $(TFLM_PATH) \( -name '*.cc' -o -name '*.c' \))
@@ -38,9 +33,11 @@
 COMMON_CFLAGS += -I$(TFLM_PATH)/third_party/gemmlowp
 
 # TFLM uses <complex> which requires including several SDK headers
-COMMON_CFLAGS += -I$(HEXAGON_SDK_PREFIX)/libs/common/qurt/latest/include/posix
-COMMON_CFLAGS += -I$(HEXAGON_SDK_PREFIX)/libs/common/qurt/latest/include/qurt
+ifneq ($(HEXAGON_SDK_PREFIX),)
+HEXAGON_CFLAGS += -I$(HEXAGON_SDK_PREFIX)/libs/qurt/latest/include/posix
+HEXAGON_CFLAGS += -I$(HEXAGON_SDK_PREFIX)/libs/qurt/latest/include/qurt
+endif
 
 COMMON_CFLAGS += -DTF_LITE_STATIC_MEMORY
 
-endif
\ No newline at end of file
+endif
diff --git a/host/common/daemon_base.cc b/host/common/daemon_base.cc
index 7b4915e..99e0426 100644
--- a/host/common/daemon_base.cc
+++ b/host/common/daemon_base.cc
@@ -357,13 +357,15 @@
       break;
     }
     default: {
+#ifdef CHRE_LOG_ATOM_EXTENSION_ENABLED
+      handleVendorMetricLog(metricMsg);
+#else
       LOGW("Unknown metric ID %" PRIu32, metricMsg->id);
+#endif  // CHRE_LOG_ATOM_EXTENSION_ENABLED
     }
   }
 }
-#endif  // CHRE_DAEMON_METRIC_ENABLED
 
-#ifdef CHRE_DAEMON_METRIC_ENABLED
 void ChreDaemonBase::reportMetric(const VendorAtom &atom) {
   const std::string statsServiceName =
       std::string(IStats::descriptor).append("/default");
@@ -374,6 +376,10 @@
 
   std::shared_ptr<IStats> stats_client = IStats::fromBinder(ndk::SpAIBinder(
       AServiceManager_waitForService(statsServiceName.c_str())));
+  if (stats_client == nullptr) {
+    LOGE("Failed to get IStats service");
+    return;
+  }
 
   const ndk::ScopedAStatus ret = stats_client->reportVendorAtom(atom);
   if (!ret.isOk()) {
diff --git a/host/common/include/chre_host/daemon_base.h b/host/common/include/chre_host/daemon_base.h
index 66ca4e0..b3e57a1 100644
--- a/host/common/include/chre_host/daemon_base.h
+++ b/host/common/include/chre_host/daemon_base.h
@@ -217,9 +217,15 @@
    * Handles a metric log message sent from CHRE
    */
   virtual void handleMetricLog(const ::chre::fbs::MetricLogT *metric_msg);
-#endif  // CHRE_DAEMON_METRIC_ENABLED
 
-#ifdef CHRE_DAEMON_METRIC_ENABLED
+#ifdef CHRE_LOG_ATOM_EXTENSION_ENABLED
+  /**
+   * Handles additional metrics that aren't logged by the common CHRE code.
+   */
+  virtual void handleVendorMetricLog(
+      const ::chre::fbs::MetricLogT *metric_msg) = 0;
+#endif  // CHRE_LOG_ATOM_EXTENSION_ENABLED
+
   /**
    * Create and report CHRE vendor atom and send it to stats_client
    *
diff --git a/host/common/log_message_parser.cc b/host/common/log_message_parser.cc
index 8afccab..952f1fd 100644
--- a/host/common/log_message_parser.cc
+++ b/host/common/log_message_parser.cc
@@ -39,6 +39,7 @@
     : mVerboseLoggingEnabled(kVerboseLoggingEnabled) {}
 
 std::unique_ptr<Detokenizer> LogMessageParser::logDetokenizerInit() {
+#ifdef CHRE_TOKENIZED_LOGGING_ENABLED
   constexpr const char kLogDatabaseFilePath[] =
       "/vendor/etc/chre/libchre_log_database.bin";
   std::vector<uint8_t> tokenData;
@@ -54,6 +55,7 @@
   } else {
     LOGE("Failed to read CHRE Token database file");
   }
+#endif
   return std::unique_ptr<Detokenizer>(nullptr);
 }
 
diff --git a/host/hal_generic/common/hal_chre_socket_connection.cc b/host/hal_generic/common/hal_chre_socket_connection.cc
index 2070508..648f28e 100644
--- a/host/hal_generic/common/hal_chre_socket_connection.cc
+++ b/host/hal_generic/common/hal_chre_socket_connection.cc
@@ -363,7 +363,6 @@
 
 #ifdef CHRE_HAL_SOCKET_METRICS_ENABLED
 void HalChreSocketConnection::reportMetric(const VendorAtom atom) {
-  // check service availability
   const std::string statsServiceName =
       std::string(IStats::descriptor).append("/default");
   if (!AServiceManager_isDeclared(statsServiceName.c_str())) {
@@ -371,9 +370,12 @@
     return;
   }
 
-  // obtain the service
   std::shared_ptr<IStats> stats_client = IStats::fromBinder(ndk::SpAIBinder(
       AServiceManager_waitForService(statsServiceName.c_str())));
+  if (stats_client == nullptr) {
+    ALOGE("Failed to get IStats service");
+    return;
+  }
 
   const ndk::ScopedAStatus ret = stats_client->reportVendorAtom(atom);
   if (!ret.isOk()) {
diff --git a/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java b/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java
index c3ddfb7..9ce2da3 100644
--- a/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java
+++ b/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java
@@ -48,6 +48,12 @@
 public class ContextHubStressTestExecutor extends ContextHubClientCallback {
     private static final String TAG = "ContextHubStressTestExecutor";
 
+    /**
+     * Wifi capabilities flags listed in
+     * //system/chre/chre_api/include/chre_api/chre/wifi.h
+     */
+    private static final int WIFI_CAPABILITIES_SCAN_MONITORING = 1;
+
     private final NanoAppBinary mNanoAppBinary;
 
     private final long mNanoAppId;
@@ -65,6 +71,8 @@
 
     private CountDownLatch mCountDownLatch;
 
+    private ChreStressTest.Capabilities mCapabilities;
+
     // Set to true to have the test suite only load the nanoapp and start the test.
     // This can be useful for long-running stress tests, where we do not want to wait a fixed
     // time to wait for successful completion.
@@ -103,6 +111,16 @@
                     valid = true;
                     break;
                 }
+                case ChreStressTest.MessageType.CAPABILITIES_VALUE: {
+                    try {
+                        mCapabilities =
+                                ChreStressTest.Capabilities.parseFrom(message.getMessageBody());
+                        valid = true;
+                    } catch (InvalidProtocolBufferException e) {
+                        Log.e(TAG, "Failed to parse message: " + e.getMessage());
+                    }
+                    break;
+                }
                 default: {
                     Log.e(TAG, "Unknown message type " + message.getMessageType());
                 }
@@ -220,21 +238,36 @@
                 new byte[0]);
         sendMessageToNanoApp(message);
 
-        WifiManager manager = (WifiManager) mInstrumentation.getContext().getSystemService(
-                Context.WIFI_SERVICE);
-        Assert.assertNotNull(manager);
-
-        mWifiScanMonitorTriggered.set(false);
         mCountDownLatch = new CountDownLatch(1);
-        Assert.assertTrue(manager.startScan());
+        message = NanoAppMessage.createMessageToNanoApp(
+                mNanoAppId, ChreStressTest.MessageType.GET_CAPABILITIES_VALUE,
+                new byte[0]);
+        sendMessageToNanoApp(message);
 
         try {
             mCountDownLatch.await(30, TimeUnit.SECONDS);
         } catch (InterruptedException e) {
             Assert.fail(e.getMessage());
         }
-        Assert.assertTrue(mWifiScanMonitorTriggered.get());
-        checkTestFailure();
+
+        if ((mCapabilities.getWifi() & WIFI_CAPABILITIES_SCAN_MONITORING) != 0) {
+            WifiManager manager =
+                    (WifiManager)
+                            mInstrumentation.getContext().getSystemService(Context.WIFI_SERVICE);
+            Assert.assertNotNull(manager);
+
+            mWifiScanMonitorTriggered.set(false);
+            mCountDownLatch = new CountDownLatch(1);
+            Assert.assertTrue(manager.startScan());
+
+            try {
+                mCountDownLatch.await(30, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                Assert.fail(e.getMessage());
+            }
+            Assert.assertTrue(mWifiScanMonitorTriggered.get());
+            checkTestFailure();
+        }
 
         sendTestMessage(ChreStressTest.TestCommand.Feature.WIFI_SCAN_MONITOR, false /* start */);
 
diff --git a/platform/shared/nanoapp_loader.cc b/platform/shared/nanoapp_loader.cc
index 3dd32a7..df6019d 100644
--- a/platform/shared/nanoapp_loader.cc
+++ b/platform/shared/nanoapp_loader.cc
@@ -32,6 +32,14 @@
 #include "chre/util/dynamic_vector.h"
 #include "chre/util/macros.h"
 
+#ifdef CHRE_LOG_ATOM_EXTENSION_ENABLED
+#include "chrex_log_atom.h"
+#endif
+
+#ifdef CHREX_VOTE_ENABLED
+#include "chrex_vote.h"
+#endif
+
 #ifndef CHRE_LOADER_ARCH
 #define CHRE_LOADER_ARCH EM_ARM
 #endif  // CHRE_LOADER_ARCH
@@ -142,6 +150,7 @@
 // TODO(karthikmb/stange): While this array was hand-coded for simple
 // "hello-world" prototyping, the list of exported symbols must be
 // generated to minimize runtime errors and build breaks.
+// TODO(b/226455808): Allow extensions to this list via an external file
 // clang-format off
 // Disable deprecation warning so that deprecated symbols in the array
 // can be exported for older nanoapps and tests.
@@ -267,6 +276,12 @@
     ADD_EXPORTED_C_SYMBOL(chreConfigureHostEndpointNotifications),
     ADD_EXPORTED_C_SYMBOL(chrePublishRpcServices),
     ADD_EXPORTED_C_SYMBOL(chreGetHostEndpointInfo),
+#ifdef CHRE_LOG_ATOM_EXTENSION_ENABLED
+    ADD_EXPORTED_C_SYMBOL(chrexLogAtom),
+#endif
+#ifdef CHREX_VOTE_ENABLED
+    ADD_EXPORTED_C_SYMBOL(chrexClockRateChangeRequest),
+#endif
 };
 CHRE_DEPRECATED_EPILOGUE
 // clang-format on