Move the logging line interleave lock from libbase to ART

libbase will now print up to 4k chunks of data to logd at once and
it will print the full log message to stderr at once, so there is no
need for a majority of users to hold a lock during logging to prevent
other threads from interleaving log messages between lines of an
individual log message.

ART is historically the only user of libbase that strongly cared to
have this lock to prevent the interleaving in all cases, thus this
lock is moved to ART only.

Bug: 65062446
Bug: 153824050
Test: logging unit tests
Change-Id: I4b9e13fcc8996c419cb7472f545589f860a3e510
(cherry picked from commit 0240d2ba620e42d68fa9b6a6ca4ff01a0c79b8e3)
diff --git a/libartbase/base/logging.cc b/libartbase/base/logging.cc
index a66a7e3..e9bffaf 100644
--- a/libartbase/base/logging.cc
+++ b/libartbase/base/logging.cc
@@ -18,6 +18,7 @@
 
 #include <iostream>
 #include <limits>
+#include <mutex>
 #include <sstream>
 
 #include "aborting.h"
@@ -79,7 +80,31 @@
   }
 
 #ifdef ART_TARGET_ANDROID
-#define INIT_LOGGING_DEFAULT_LOGGER android::base::LogdLogger()
+  // android::base::LogdLogger breaks messages up into line delimited 4K chunks, since that is the
+  // most that logd can handle per message.  To prevent other threads from interleaving their
+  // messages, LogdLoggerLocked uses a mutex to ensure that only one ART thread is logging at a
+  // time.
+  // Note that this lock makes logging after fork() unsafe in multi-threaded programs, which is part
+  // of the motivation that this lock is not a part of libbase logging.  Zygote guarantees that no
+  // threads are running before calling fork() via ZygoteHooks.waitUntilAllThreadsStopped().
+  class LogdLoggerLocked {
+   public:
+    LogdLoggerLocked() {}
+    void operator()(android::base::LogId id,
+                    android::base::LogSeverity severity,
+                    const char* tag,
+                    const char* file,
+                    unsigned int line,
+                    const char* message) {
+      static std::mutex* logging_lock_ = new std::mutex();
+      std::lock_guard<std::mutex> guard(*logging_lock_);
+      logd_logger_(id, severity, tag, file, line, message);
+    }
+
+   private:
+    android::base::LogdLogger logd_logger_;
+  };
+#define INIT_LOGGING_DEFAULT_LOGGER LogdLoggerLocked()
 #else
 #define INIT_LOGGING_DEFAULT_LOGGER android::base::StderrLogger
 #endif