Guard btsnooz ringbuffer access from multiple threads

Since moving to HIDL, the btsnooz packet ringbuffer can be accessed from
two separate threads. Thus it should be guarded from concurrent access
to avoid pointer corruption.

Bug: 35182804
Test: manual
Change-Id: I3e6e1a869887a7ad5d87d8bb09ed78a22b3383ae
(cherry picked from commit 29bc0b99aa31f1f748ce4281704bf4838c523da3)
diff --git a/btif/src/btif_debug_btsnoop.cc b/btif/src/btif_debug_btsnoop.cc
index 4b71a33..b20cdc8 100644
--- a/btif/src/btif_debug_btsnoop.cc
+++ b/btif/src/btif_debug_btsnoop.cc
@@ -16,6 +16,8 @@
  *
  ******************************************************************************/
 
+#include <mutex>
+
 #include <base/logging.h>
 #include <resolv.h>
 #include <zlib.h>
@@ -39,6 +41,7 @@
 // Maximum line length in bugreport (should be multiple of 4 for base64 output)
 static const uint8_t MAX_LINE_LENGTH = 128;
 
+static std::mutex buffer_mutex;
 static ringbuffer_t* buffer = NULL;
 static uint64_t last_timestamp_ms = 0;
 
@@ -53,6 +56,8 @@
   size_t included_length = btsnoop_calculate_packet_length(type, data, length);
   if (included_length == 0) return;
 
+  std::lock_guard<std::mutex> lock(buffer_mutex);
+
   // Make room in the ring buffer
 
   while (ringbuffer_available(buffer) <
@@ -174,9 +179,6 @@
 }
 
 void btif_debug_btsnoop_dump(int fd) {
-  dprintf(fd, "--- BEGIN:BTSNOOP_LOG_SUMMARY (%zu bytes in) ---\n",
-          ringbuffer_size(buffer));
-
   ringbuffer_t* ringbuffer = ringbuffer_init(BTSNOOP_MEM_BUFFER_SIZE);
   if (ringbuffer == NULL) {
     dprintf(fd, "%s Unable to allocate memory for compression", __func__);
@@ -198,7 +200,14 @@
 
   size_t line_length = 0;
 
-  bool rc = btsnoop_compress(ringbuffer, buffer);
+  bool rc;
+  {
+    std::lock_guard<std::mutex> lock(buffer_mutex);
+    dprintf(fd, "--- BEGIN:BTSNOOP_LOG_SUMMARY (%zu bytes in) ---\n",
+            ringbuffer_size(buffer));
+    rc = btsnoop_compress(ringbuffer, buffer);
+  }
+
   if (rc == false) {
     dprintf(fd, "%s Log compression failed", __func__);
     goto error;