Merge "Fix visibility rules now that Make supports visibility checks"
diff --git a/adb/Android.bp b/adb/Android.bp
index 8747182..2fc205f 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -25,7 +25,6 @@
         "-Wthread-safety",
         "-Wvla",
         "-DADB_HOST=1",         // overridden by adbd_defaults
-        "-DALLOW_ADBD_ROOT=0",  // overridden by adbd_defaults
         "-DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION=1",
     ],
     cpp_std: "experimental",
@@ -81,16 +80,6 @@
     defaults: ["adb_defaults"],
 
     cflags: ["-UADB_HOST", "-DADB_HOST=0"],
-    product_variables: {
-        debuggable: {
-            cflags: [
-                "-UALLOW_ADBD_ROOT",
-                "-DALLOW_ADBD_ROOT=1",
-                "-DALLOW_ADBD_DISABLE_VERITY",
-                "-DALLOW_ADBD_NO_AUTH",
-            ],
-        },
-    },
 }
 
 cc_defaults {
@@ -640,16 +629,14 @@
             ],
         }
     },
-
-    required: [
-        "libadbd_auth",
-        "libadbd_fs",
-    ],
 }
 
 phony {
-    name: "adbd_system_binaries",
+    // Interface between adbd in a module and the system.
+    name: "adbd_system_api",
     required: [
+        "libadbd_auth",
+        "libadbd_fs",
         "abb",
         "reboot",
         "set-verity-state",
@@ -657,8 +644,10 @@
 }
 
 phony {
-    name: "adbd_system_binaries_recovery",
+    name: "adbd_system_api_recovery",
     required: [
+        "libadbd_auth",
+        "libadbd_fs",
         "reboot.recovery",
     ],
 }
diff --git a/adb/daemon/main.cpp b/adb/daemon/main.cpp
index db8f07b..eb28668 100644
--- a/adb/daemon/main.cpp
+++ b/adb/daemon/main.cpp
@@ -62,23 +62,7 @@
 #if defined(__ANDROID__)
 static const char* root_seclabel = nullptr;
 
-static inline bool is_device_unlocked() {
-    return "orange" == android::base::GetProperty("ro.boot.verifiedbootstate", "");
-}
-
-static bool should_drop_capabilities_bounding_set() {
-    if (ALLOW_ADBD_ROOT || is_device_unlocked()) {
-        if (__android_log_is_debuggable()) {
-            return false;
-        }
-    }
-    return true;
-}
-
 static bool should_drop_privileges() {
-    // "adb root" not allowed, always drop privileges.
-    if (!ALLOW_ADBD_ROOT && !is_device_unlocked()) return true;
-
     // The properties that affect `adb root` and `adb unroot` are ro.secure and
     // ro.debuggable. In this context the names don't make the expected behavior
     // particularly obvious.
@@ -132,7 +116,7 @@
     // Don't listen on a port (default 5037) if running in secure mode.
     // Don't run as root if running in secure mode.
     if (should_drop_privileges()) {
-        const bool should_drop_caps = should_drop_capabilities_bounding_set();
+        const bool should_drop_caps = !__android_log_is_debuggable();
 
         if (should_drop_caps) {
             minijail_use_caps(jail.get(), CAP_TO_MASK(CAP_SETUID) | CAP_TO_MASK(CAP_SETGID));
@@ -218,15 +202,10 @@
     // descriptor will always be open.
     adbd_cloexec_auth_socket();
 
-#if defined(__ANDROID_RECOVERY__)
-    if (is_device_unlocked() || __android_log_is_debuggable()) {
-        auth_required = false;
-    }
-#elif defined(ALLOW_ADBD_NO_AUTH)
-    // If ro.adb.secure is unset, default to no authentication required.
-    auth_required = android::base::GetBoolProperty("ro.adb.secure", false);
-#elif defined(__ANDROID__)
-    if (is_device_unlocked()) {  // allows no authentication when the device is unlocked.
+#if defined(__ANDROID__)
+    // If we're on userdebug/eng or the device is unlocked, permit no-authentication.
+    bool device_unlocked = "orange" == android::base::GetProperty("ro.boot.verifiedbootstate", "");
+    if (__android_log_is_debuggable() || device_unlocked) {
         auth_required = android::base::GetBoolProperty("ro.adb.secure", false);
     }
 #endif
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 7abc936..46d1d36 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -1229,7 +1229,7 @@
 static void CancelSnapshotIfNeeded() {
     std::string merge_status = "none";
     if (fb->GetVar(FB_VAR_SNAPSHOT_UPDATE_STATUS, &merge_status) == fastboot::SUCCESS &&
-        merge_status != "none") {
+        !merge_status.empty() && merge_status != "none") {
         fb->SnapshotUpdateCommand("cancel");
     }
 }
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 8c2e001..b2c7a27 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -1099,8 +1099,28 @@
                 }
 
                 android::dm::DmTable table;
-                if (!table.AddTarget(std::make_unique<android::dm::DmTargetBow>(
-                            0, size, entry->blk_device))) {
+                auto bowTarget =
+                        std::make_unique<android::dm::DmTargetBow>(0, size, entry->blk_device);
+
+                // dm-bow uses the first block as a log record, and relocates the real first block
+                // elsewhere. For metadata encrypted devices, dm-bow sits below dm-default-key, and
+                // for post Android Q devices dm-default-key uses a block size of 4096 always.
+                // So if dm-bow's block size, which by default is the block size of the underlying
+                // hardware, is less than dm-default-key's, blocks will get broken up and I/O will
+                // fail as it won't be data_unit_size aligned.
+                // However, since it is possible there is an already shipping non
+                // metadata-encrypted device with smaller blocks, we must not change this for
+                // devices shipped with Q or earlier unless they explicitly selected dm-default-key
+                // v2
+                constexpr unsigned int pre_gki_level = __ANDROID_API_Q__;
+                unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
+                        "ro.crypto.dm_default_key.options_format.version",
+                        (android::fscrypt::GetFirstApiLevel() <= pre_gki_level ? 1 : 2));
+                if (options_format_version > 1) {
+                    bowTarget->SetBlockSize(4096);
+                }
+
+                if (!table.AddTarget(std::move(bowTarget))) {
                     LERROR << "Failed to add bow target";
                     return false;
                 }
@@ -1736,6 +1756,11 @@
 // wrapper to __mount() and expects a fully prepared fstab_rec,
 // unlike fs_mgr_do_mount which does more things with avb / verity etc.
 int fs_mgr_do_mount_one(const FstabEntry& entry, const std::string& mount_point) {
+    // First check the filesystem if requested.
+    if (entry.fs_mgr_flags.wait && !WaitForFile(entry.blk_device, 20s)) {
+        LERROR << "Skipping mounting '" << entry.blk_device << "'";
+    }
+
     // Run fsck if needed
     prepare_fs_for_mount(entry.blk_device, entry);
 
diff --git a/fs_mgr/libdm/dm_target.cpp b/fs_mgr/libdm/dm_target.cpp
index a594198..250cb82 100644
--- a/fs_mgr/libdm/dm_target.cpp
+++ b/fs_mgr/libdm/dm_target.cpp
@@ -120,6 +120,11 @@
     return keyid_ + " " + block_device_;
 }
 
+std::string DmTargetBow::GetParameterString() const {
+    if (!block_size_) return target_string_;
+    return target_string_ + " 1 block_size:" + std::to_string(block_size_);
+}
+
 std::string DmTargetSnapshot::name() const {
     if (mode_ == SnapshotStorageMode::Merge) {
         return "snapshot-merge";
diff --git a/fs_mgr/libdm/include/libdm/dm_target.h b/fs_mgr/libdm/include/libdm/dm_target.h
index 57096ce..f986cfe 100644
--- a/fs_mgr/libdm/include/libdm/dm_target.h
+++ b/fs_mgr/libdm/include/libdm/dm_target.h
@@ -175,11 +175,14 @@
     DmTargetBow(uint64_t start, uint64_t length, const std::string& target_string)
         : DmTarget(start, length), target_string_(target_string) {}
 
+    void SetBlockSize(uint32_t block_size) { block_size_ = block_size; }
+
     std::string name() const override { return "bow"; }
-    std::string GetParameterString() const override { return target_string_; }
+    std::string GetParameterString() const override;
 
   private:
     std::string target_string_;
+    uint32_t block_size_ = 0;
 };
 
 enum class SnapshotStorageMode {
diff --git a/init/README.md b/init/README.md
index 0dd1490..2d06971 100644
--- a/init/README.md
+++ b/init/README.md
@@ -564,9 +564,11 @@
   _options_ include "barrier=1", "noauto\_da\_alloc", "discard", ... as
   a comma separated string, e.g. barrier=1,noauto\_da\_alloc
 
-`parse_apex_configs`
-> Parses config file(s) from the mounted APEXes. Intended to be used only once
-  when apexd notifies the mount event by setting apexd.status to ready.
+`perform_apex_config`
+> Performs tasks after APEXes are mounted. For example, creates data directories
+  for the mounted APEXes, parses config file(s) from them, and updates linker
+  configurations. Intended to be used only once when apexd notifies the mount
+  event by setting `apexd.status` to ready.
 
 `restart <service>`
 > Stops and restarts a running service, does nothing if the service is currently
@@ -623,8 +625,11 @@
 `stop <service>`
 > Stop a service from running if it is currently running.
 
-`swapon_all <fstab>`
+`swapon_all [ <fstab> ]`
 > Calls fs\_mgr\_swapon\_all on the given fstab file.
+  If the fstab parameter is not specified, fstab.${ro.boot.fstab_suffix},
+  fstab.${ro.hardware} or fstab.${ro.hardware.platform} will be scanned for
+  under /odm/etc, /vendor/etc, or / at runtime, in that order.
 
 `symlink <target> <path>`
 > Create a symbolic link at _path_ with the value _target_
@@ -639,6 +644,12 @@
 `umount <path>`
 > Unmount the filesystem mounted at that path.
 
+`umount_all [ <fstab> ]`
+> Calls fs\_mgr\_umount\_all on the given fstab file.
+  If the fstab parameter is not specified, fstab.${ro.boot.fstab_suffix},
+  fstab.${ro.hardware} or fstab.${ro.hardware.platform} will be scanned for
+  under /odm/etc, /vendor/etc, or / at runtime, in that order.
+
 `verity_update_state <mount-point>`
 > Internal implementation detail used to update dm-verity state and
   set the partition._mount-point_.verified properties used by adb remount
diff --git a/init/builtins.cpp b/init/builtins.cpp
index e918e12..0ac66f2 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -708,10 +708,20 @@
     return {};
 }
 
+/* swapon_all [ <fstab> ] */
 static Result<void> do_swapon_all(const BuiltinArguments& args) {
+    auto swapon_all = ParseSwaponAll(args.args);
+    if (!swapon_all.ok()) return swapon_all.error();
+
     Fstab fstab;
-    if (!ReadFstabFromFile(args[1], &fstab)) {
-        return Error() << "Could not read fstab '" << args[1] << "'";
+    if (swapon_all->empty()) {
+        if (!ReadDefaultFstab(&fstab)) {
+            return Error() << "Could not read default fstab";
+        }
+    } else {
+        if (!ReadFstabFromFile(*swapon_all, &fstab)) {
+            return Error() << "Could not read fstab '" << *swapon_all << "'";
+        }
     }
 
     if (!fs_mgr_swapon_all(fstab)) {
@@ -1371,7 +1381,7 @@
         {"setrlimit",               {3,     3,    {false,  do_setrlimit}}},
         {"start",                   {1,     1,    {false,  do_start}}},
         {"stop",                    {1,     1,    {false,  do_stop}}},
-        {"swapon_all",              {1,     1,    {false,  do_swapon_all}}},
+        {"swapon_all",              {0,     1,    {false,  do_swapon_all}}},
         {"enter_default_mount_ns",  {0,     0,    {false,  do_enter_default_mount_ns}}},
         {"symlink",                 {2,     2,    {true,   do_symlink}}},
         {"sysclktz",                {1,     1,    {false,  do_sysclktz}}},
diff --git a/init/check_builtins.cpp b/init/check_builtins.cpp
index 450c079..481fa31 100644
--- a/init/check_builtins.cpp
+++ b/init/check_builtins.cpp
@@ -202,6 +202,14 @@
     return {};
 }
 
+Result<void> check_swapon_all(const BuiltinArguments& args) {
+    auto options = ParseSwaponAll(args.args);
+    if (!options.ok()) {
+        return options.error();
+    }
+    return {};
+}
+
 Result<void> check_sysclktz(const BuiltinArguments& args) {
     ReturnIfAnyArgsEmpty();
 
diff --git a/init/check_builtins.h b/init/check_builtins.h
index 725a6fd..dc1b752 100644
--- a/init/check_builtins.h
+++ b/init/check_builtins.h
@@ -37,6 +37,7 @@
 Result<void> check_restorecon_recursive(const BuiltinArguments& args);
 Result<void> check_setprop(const BuiltinArguments& args);
 Result<void> check_setrlimit(const BuiltinArguments& args);
+Result<void> check_swapon_all(const BuiltinArguments& args);
 Result<void> check_sysclktz(const BuiltinArguments& args);
 Result<void> check_umount_all(const BuiltinArguments& args);
 Result<void> check_wait(const BuiltinArguments& args);
diff --git a/init/util.cpp b/init/util.cpp
index 40f24b1..aec3173 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -654,11 +654,22 @@
     return std::pair(flag, paths);
 }
 
+Result<std::string> ParseSwaponAll(const std::vector<std::string>& args) {
+    if (args.size() <= 1) {
+        if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
+            return Error() << "swapon_all requires at least 1 argument";
+        }
+        return {};
+    }
+    return args[1];
+}
+
 Result<std::string> ParseUmountAll(const std::vector<std::string>& args) {
-    if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
-        if (args.size() <= 1) {
+    if (args.size() <= 1) {
+        if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
             return Error() << "umount_all requires at least 1 argument";
         }
+        return {};
     }
     return args[1];
 }
diff --git a/init/util.h b/init/util.h
index 28f6b18..8a6aa60 100644
--- a/init/util.h
+++ b/init/util.h
@@ -92,6 +92,8 @@
 Result<std::pair<int, std::vector<std::string>>> ParseRestorecon(
         const std::vector<std::string>& args);
 
+Result<std::string> ParseSwaponAll(const std::vector<std::string>& args);
+
 Result<std::string> ParseUmountAll(const std::vector<std::string>& args);
 
 void SetStdioToDevNull(char** argv);
diff --git a/libkeyutils/keyutils.cpp b/libkeyutils/keyutils.cpp
index 8f63f70..1c5acc9 100644
--- a/libkeyutils/keyutils.cpp
+++ b/libkeyutils/keyutils.cpp
@@ -32,17 +32,7 @@
 #include <sys/syscall.h>
 #include <unistd.h>
 
-// Deliberately not exposed. Callers should use the typed APIs instead.
-static long keyctl(int cmd, ...) {
-  va_list va;
-  va_start(va, cmd);
-  unsigned long arg2 = va_arg(va, unsigned long);
-  unsigned long arg3 = va_arg(va, unsigned long);
-  unsigned long arg4 = va_arg(va, unsigned long);
-  unsigned long arg5 = va_arg(va, unsigned long);
-  va_end(va);
-  return syscall(__NR_keyctl, cmd, arg2, arg3, arg4, arg5);
-}
+// keyctl(2) is deliberately not exposed. Callers should use the typed APIs instead.
 
 key_serial_t add_key(const char* type, const char* description, const void* payload,
                      size_t payload_length, key_serial_t ring_id) {
@@ -50,30 +40,30 @@
 }
 
 key_serial_t keyctl_get_keyring_ID(key_serial_t id, int create) {
-  return keyctl(KEYCTL_GET_KEYRING_ID, id, create);
+  return syscall(__NR_keyctl, KEYCTL_GET_KEYRING_ID, id, create);
 }
 
 long keyctl_revoke(key_serial_t id) {
-  return keyctl(KEYCTL_REVOKE, id);
+  return syscall(__NR_keyctl, KEYCTL_REVOKE, id);
 }
 
 long keyctl_search(key_serial_t ring_id, const char* type, const char* description,
                    key_serial_t dest_ring_id) {
-  return keyctl(KEYCTL_SEARCH, ring_id, type, description, dest_ring_id);
+  return syscall(__NR_keyctl, KEYCTL_SEARCH, ring_id, type, description, dest_ring_id);
 }
 
 long keyctl_setperm(key_serial_t id, int permissions) {
-  return keyctl(KEYCTL_SETPERM, id, permissions);
+  return syscall(__NR_keyctl, KEYCTL_SETPERM, id, permissions);
 }
 
 long keyctl_unlink(key_serial_t key, key_serial_t keyring) {
-  return keyctl(KEYCTL_UNLINK, key, keyring);
+  return syscall(__NR_keyctl, KEYCTL_UNLINK, key, keyring);
 }
 
 long keyctl_restrict_keyring(key_serial_t keyring, const char* type, const char* restriction) {
-  return keyctl(KEYCTL_RESTRICT_KEYRING, keyring, type, restriction);
+  return syscall(__NR_keyctl, KEYCTL_RESTRICT_KEYRING, keyring, type, restriction);
 }
 
 long keyctl_get_security(key_serial_t id, char* buffer, size_t buflen) {
-  return keyctl(KEYCTL_GET_SECURITY, id, buffer, buflen);
+  return syscall(__NR_keyctl, KEYCTL_GET_SECURITY, id, buffer, buflen);
 }
diff --git a/libsync/Android.bp b/libsync/Android.bp
index c996e1b..bad6230 100644
--- a/libsync/Android.bp
+++ b/libsync/Android.bp
@@ -25,6 +25,12 @@
     recovery_available: true,
     native_bridge_supported: true,
     defaults: ["libsync_defaults"],
+    stubs: {
+        symbol_file: "libsync.map.txt",
+        versions: [
+            "26",
+        ],
+    },
 }
 
 llndk_library {
diff --git a/libsync/libsync.map.txt b/libsync/libsync.map.txt
index 91c3528..aac6b57 100644
--- a/libsync/libsync.map.txt
+++ b/libsync/libsync.map.txt
@@ -19,7 +19,7 @@
     sync_merge; # introduced=26
     sync_file_info; # introduced=26
     sync_file_info_free; # introduced=26
-    sync_wait; # llndk
+    sync_wait; # llndk apex
     sync_fence_info; # llndk
     sync_pt_info; # llndk
     sync_fence_info_free; # llndk
diff --git a/logcat/event.logtags b/logcat/event.logtags
index 56a670a..93c3d6d 100644
--- a/logcat/event.logtags
+++ b/logcat/event.logtags
@@ -116,6 +116,9 @@
 # audio
 # 61000 - 61199 reserved for audioserver
 
+# input
+# 62000 - 62199 reserved for inputflinger
+
 # com.android.server.policy
 # 70000 - 70199 reserved for PhoneWindowManager and other policies
 
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 13023f2..0056c80 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -36,6 +36,7 @@
 
 #include <memory>
 #include <regex>
+#include <set>
 #include <string>
 #include <utility>
 #include <vector>
@@ -358,6 +359,10 @@
   -T '<time>'                 Print the lines since specified time (not imply -d).
                               count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'
                               'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format.
+  --uid=<uids>                Only display log messages from UIDs present in the comma separate list
+                              <uids>. No name look-up is performed, so UIDs must be provided as
+                              numeric values. This option is only useful for the 'root', 'log', and
+                              'system' users since only those users can view logs from other users.
 )init");
 
     fprintf(stderr, "\nfilterspecs are a series of \n"
@@ -535,6 +540,7 @@
     size_t pid = 0;
     bool got_t = false;
     unsigned id_mask = 0;
+    std::set<uid_t> uids;
 
     if (argc == 2 && !strcmp(argv[1], "--help")) {
         show_help();
@@ -554,6 +560,7 @@
         static const char id_str[] = "id";
         static const char wrap_str[] = "wrap";
         static const char print_str[] = "print";
+        static const char uid_str[] = "uid";
         // clang-format off
         static const struct option long_options[] = {
           { "binary",        no_argument,       nullptr, 'B' },
@@ -581,6 +588,7 @@
           { "statistics",    no_argument,       nullptr, 'S' },
           // hidden and undocumented reserved alias for -t
           { "tail",          required_argument, nullptr, 't' },
+          { uid_str,         required_argument, nullptr, 0 },
           // support, but ignore and do not document, the optional argument
           { wrap_str,        optional_argument, nullptr, 0 },
           { nullptr,         0,                 nullptr, 0 }
@@ -631,6 +639,17 @@
                 if (long_options[option_index].name == id_str) {
                     setId = (optarg && optarg[0]) ? optarg : nullptr;
                 }
+                if (long_options[option_index].name == uid_str) {
+                    auto uid_strings = Split(optarg, delimiters);
+                    for (const auto& uid_string : uid_strings) {
+                        uid_t uid;
+                        if (!ParseUint(uid_string, &uid)) {
+                            error(EXIT_FAILURE, 0, "Unable to parse UID '%s'", uid_string.c_str());
+                        }
+                        uids.emplace(uid);
+                    }
+                    break;
+                }
                 break;
 
             case 's':
@@ -1164,6 +1183,10 @@
                   LOG_ID_MAX);
         }
 
+        if (!uids.empty() && uids.count(log_msg.entry.uid) == 0) {
+            continue;
+        }
+
         PrintDividers(log_msg.id(), printDividers);
 
         if (print_binary_) {
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index f3fdfd7..a2daeb0 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -16,6 +16,7 @@
 
 #include <ctype.h>
 #include <dirent.h>
+#include <pwd.h>
 #include <signal.h>
 #include <stdint.h>
 #include <stdio.h>
@@ -28,10 +29,12 @@
 #include <unistd.h>
 
 #include <memory>
+#include <regex>
 #include <string>
 
 #include <android-base/file.h>
 #include <android-base/macros.h>
+#include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <gtest/gtest.h>
@@ -1748,3 +1751,83 @@
 
   ASSERT_TRUE(android::base::StartsWith(output, "unknown buffer foo\n"));
 }
+
+static void SniffUid(const std::string& line, uid_t& uid) {
+    auto uid_regex = std::regex{"\\S+\\s+\\S+\\s+(\\S+).*"};
+
+    auto trimmed_line = android::base::Trim(line);
+
+    std::smatch match_results;
+    ASSERT_TRUE(std::regex_match(trimmed_line, match_results, uid_regex))
+            << "Unable to find UID in line '" << trimmed_line << "'";
+    auto uid_string = match_results[1];
+    if (!android::base::ParseUint(uid_string, &uid)) {
+        auto pwd = getpwnam(uid_string.str().c_str());
+        ASSERT_NE(nullptr, pwd) << "uid '" << uid_string << "' in line '" << trimmed_line << "'";
+        uid = pwd->pw_uid;
+    }
+}
+
+static void UidsInLog(std::optional<std::vector<uid_t>> filter_uid, std::map<uid_t, size_t>& uids) {
+    std::string command;
+    if (filter_uid) {
+        std::vector<std::string> uid_strings;
+        for (const auto& uid : *filter_uid) {
+            uid_strings.emplace_back(std::to_string(uid));
+        }
+        command = android::base::StringPrintf(logcat_executable
+                                              " -v uid -b all -d 2>/dev/null --uid=%s",
+                                              android::base::Join(uid_strings, ",").c_str());
+    } else {
+        command = logcat_executable " -v uid -b all -d 2>/dev/null";
+    }
+    auto fp = std::unique_ptr<FILE, decltype(&pclose)>(popen(command.c_str(), "r"), pclose);
+    ASSERT_NE(nullptr, fp);
+
+    char buffer[BIG_BUFFER];
+    while (fgets(buffer, sizeof(buffer), fp.get())) {
+        // Ignore dividers, e.g. '--------- beginning of radio'
+        if (android::base::StartsWith(buffer, "---------")) {
+            continue;
+        }
+        uid_t uid;
+        SniffUid(buffer, uid);
+        uids[uid]++;
+    }
+}
+
+static std::vector<uid_t> TopTwoInMap(const std::map<uid_t, size_t>& uids) {
+    std::pair<uid_t, size_t> top = {0, 0};
+    std::pair<uid_t, size_t> second = {0, 0};
+    for (const auto& [uid, count] : uids) {
+        if (count > top.second) {
+            top = second;
+            top = {uid, count};
+        } else if (count > second.second) {
+            second = {uid, count};
+        }
+    }
+    return {top.first, second.first};
+}
+
+TEST(logcat, uid_filter) {
+    std::map<uid_t, size_t> uids;
+    UidsInLog({}, uids);
+
+    ASSERT_GT(uids.size(), 2U);
+    auto top_uids = TopTwoInMap(uids);
+
+    // Test filtering with --uid=<top uid>
+    std::map<uid_t, size_t> uids_only_top;
+    std::vector<uid_t> top_uid = {top_uids[0]};
+    UidsInLog(top_uid, uids_only_top);
+
+    EXPECT_EQ(1U, uids_only_top.size());
+
+    // Test filtering with --uid=<top uid>,<2nd top uid>
+    std::map<uid_t, size_t> uids_only_top2;
+    std::vector<uid_t> top2_uids = {top_uids[0], top_uids[1]};
+    UidsInLog(top2_uids, uids_only_top2);
+
+    EXPECT_EQ(2U, uids_only_top2.size());
+}
diff --git a/logd/ChattyLogBuffer.cpp b/logd/ChattyLogBuffer.cpp
index 62c8629..f92fe65 100644
--- a/logd/ChattyLogBuffer.cpp
+++ b/logd/ChattyLogBuffer.cpp
@@ -217,12 +217,12 @@
     log_id_for_each(i) {
         for (auto b : mLastWorst[i]) {
             if (bad == b.second) {
-                android::prdebug("stale mLastWorst[%d] key=%d mykey=%d\n", i, b.first, key);
+                LOG(ERROR) << StringPrintf("stale mLastWorst[%d] key=%d mykey=%d", i, b.first, key);
             }
         }
         for (auto b : mLastWorstPidOfSystem[i]) {
             if (bad == b.second) {
-                android::prdebug("stale mLastWorstPidOfSystem[%d] pid=%d\n", i, b.first);
+                LOG(ERROR) << StringPrintf("stale mLastWorstPidOfSystem[%d] pid=%d", i, b.first);
             }
         }
     }
diff --git a/logd/CommandListener.cpp b/logd/CommandListener.cpp
index c6ab22d..9764c44 100644
--- a/logd/CommandListener.cpp
+++ b/logd/CommandListener.cpp
@@ -31,6 +31,7 @@
 
 #include <string>
 
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <cutils/sockets.h>
 #include <log/log_properties.h>
@@ -298,7 +299,7 @@
                                            char** /*argv*/) {
     setname();
 
-    android::prdebug("logd reinit");
+    LOG(INFO) << "logd reinit";
     buf()->Init();
     prune()->init(nullptr);
 
diff --git a/logd/LogBufferTest.cpp b/logd/LogBufferTest.cpp
index ced4a21..e651b4f 100644
--- a/logd/LogBufferTest.cpp
+++ b/logd/LogBufferTest.cpp
@@ -43,14 +43,6 @@
 }
 #endif
 
-void android::prdebug(const char* fmt, ...) {
-    va_list ap;
-    va_start(ap, fmt);
-    vfprintf(stderr, fmt, ap);
-    fprintf(stderr, "\n");
-    va_end(ap);
-}
-
 char* android::uidToName(uid_t) {
     return nullptr;
 }
diff --git a/logd/LogReader.cpp b/logd/LogReader.cpp
index 42d4574..f71133d 100644
--- a/logd/LogReader.cpp
+++ b/logd/LogReader.cpp
@@ -23,6 +23,7 @@
 
 #include <chrono>
 
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <cutils/sockets.h>
 #include <private/android_filesystem_config.h>
@@ -201,9 +202,9 @@
         }
     }
 
-    android::prdebug(
+    LOG(INFO) << android::base::StringPrintf(
             "logdr: UID=%d GID=%d PID=%d %c tail=%lu logMask=%x pid=%d "
-            "start=%" PRIu64 "ns deadline=%" PRIi64 "ns\n",
+            "start=%" PRIu64 "ns deadline=%" PRIi64 "ns",
             cli->getUid(), cli->getGid(), cli->getPid(), nonBlock ? 'n' : 'b', tail, logMask,
             (int)pid, start.nsec(), static_cast<int64_t>(deadline.time_since_epoch().count()));
 
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index 04fd59d..d49982a 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -36,6 +36,30 @@
 
 std::atomic<size_t> LogStatistics::SizesTotal;
 
+static std::string TagNameKey(const LogStatisticsElement& element) {
+    if (IsBinary(element.log_id)) {
+        uint32_t tag = element.tag;
+        if (tag) {
+            const char* cp = android::tagToName(tag);
+            if (cp) {
+                return std::string(cp);
+            }
+        }
+        return android::base::StringPrintf("[%" PRIu32 "]", tag);
+    }
+    const char* msg = element.msg;
+    if (!msg) {
+        return "chatty";
+    }
+    ++msg;
+    uint16_t len = element.msg_len;
+    len = (len <= 1) ? 0 : strnlen(msg, len - 1);
+    if (!len) {
+        return "<NULL>";
+    }
+    return std::string(msg, len);
+}
+
 LogStatistics::LogStatistics(bool enable_statistics) : enable(enable_statistics) {
     log_time now(CLOCK_REALTIME);
     log_id_for_each(id) {
@@ -308,8 +332,9 @@
 void LogStatistics::WorstTwoWithThreshold(const LogHashtable<TKey, TEntry>& table, size_t threshold,
                                           int* worst, size_t* worst_sizes,
                                           size_t* second_worst_sizes) const {
+    std::array<const TKey*, 2> max_keys;
     std::array<const TEntry*, 2> max_entries;
-    table.MaxEntries(AID_ROOT, 0, &max_entries);
+    table.MaxEntries(AID_ROOT, 0, max_keys, max_entries);
     if (max_entries[0] == nullptr || max_entries[1] == nullptr) {
         return;
     }
@@ -317,7 +342,7 @@
     // b/24782000: Allow time horizon to extend roughly tenfold, assume average entry length is
     // 100 characters.
     if (*worst_sizes > threshold && *worst_sizes > (10 * max_entries[0]->dropped_count())) {
-        *worst = max_entries[0]->key();
+        *worst = *max_keys[0];
         *second_worst_sizes = max_entries[1]->getSizes();
         if (*second_worst_sizes < threshold) {
             *second_worst_sizes = threshold;
@@ -340,13 +365,14 @@
 void LogStatistics::WorstTwoSystemPids(log_id id, size_t worst_uid_sizes, int* worst,
                                        size_t* second_worst_sizes) const {
     auto lock = std::lock_guard{lock_};
+    std::array<const pid_t*, 2> max_keys;
     std::array<const PidEntry*, 2> max_entries;
-    pidSystemTable[id].MaxEntries(AID_SYSTEM, 0, &max_entries);
+    pidSystemTable[id].MaxEntries(AID_SYSTEM, 0, max_keys, max_entries);
     if (max_entries[0] == nullptr || max_entries[1] == nullptr) {
         return;
     }
 
-    *worst = max_entries[0]->key();
+    *worst = *max_keys[0];
     *second_worst_sizes = worst_uid_sizes - max_entries[0]->getSizes() + max_entries[1]->getSizes();
 }
 
@@ -412,11 +438,12 @@
     }
 }
 
-std::string UidEntry::format(const LogStatistics& stat, log_id_t id) const REQUIRES(stat.lock_) {
-    std::string name = android::base::StringPrintf("%u", uid_);
+std::string UidEntry::format(const LogStatistics& stat, log_id_t id, uid_t uid) const
+        REQUIRES(stat.lock_) {
+    std::string name = android::base::StringPrintf("%u", uid);
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
-    stat.FormatTmp(nullptr, uid_, name, size, 6);
+    stat.FormatTmp(nullptr, uid, name, size, 6);
 
     std::string pruned = "";
     if (worstUidEnabledForLogid(id)) {
@@ -474,19 +501,20 @@
 
     std::string output = formatLine(name, size, pruned);
 
-    if (uid_ != AID_SYSTEM) {
+    if (uid != AID_SYSTEM) {
         return output;
     }
 
     static const size_t maximum_sorted_entries = 32;
-    std::array<const PidEntry*, maximum_sorted_entries> sorted;
-    stat.pidSystemTable[id].MaxEntries(uid_, 0, &sorted);
+    std::array<const pid_t*, maximum_sorted_entries> sorted_pids;
+    std::array<const PidEntry*, maximum_sorted_entries> sorted_entries;
+    stat.pidSystemTable[id].MaxEntries(uid, 0, sorted_pids, sorted_entries);
 
     std::string byPid;
     size_t index;
     bool hasDropped = false;
     for (index = 0; index < maximum_sorted_entries; ++index) {
-        const PidEntry* entry = sorted[index];
+        const PidEntry* entry = sorted_entries[index];
         if (!entry) {
             break;
         }
@@ -496,7 +524,7 @@
         if (entry->dropped_count()) {
             hasDropped = true;
         }
-        byPid += entry->format(stat, id);
+        byPid += entry->format(stat, id, *sorted_pids[index]);
     }
     if (index > 1) {  // print this only if interesting
         std::string ditto("\" ");
@@ -515,9 +543,9 @@
                       std::string("BYTES"), std::string("NUM"));
 }
 
-std::string PidEntry::format(const LogStatistics& stat, log_id_t /* id */) const
+std::string PidEntry::format(const LogStatistics& stat, log_id_t, pid_t pid) const
         REQUIRES(stat.lock_) {
-    std::string name = android::base::StringPrintf("%5u/%u", pid_, uid_);
+    std::string name = android::base::StringPrintf("%5u/%u", pid, uid_);
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
     stat.FormatTmp(name_, uid_, name, size, 12);
@@ -538,9 +566,9 @@
                       std::string("NUM"));
 }
 
-std::string TidEntry::format(const LogStatistics& stat, log_id_t /* id */) const
+std::string TidEntry::format(const LogStatistics& stat, log_id_t, pid_t tid) const
         REQUIRES(stat.lock_) {
-    std::string name = android::base::StringPrintf("%5u/%u", tid(), uid_);
+    std::string name = android::base::StringPrintf("%5u/%u", tid, uid_);
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
     stat.FormatTmp(name_, uid_, name, size, 12);
@@ -562,8 +590,7 @@
                       std::string("BYTES"), std::string(isprune ? "NUM" : ""));
 }
 
-std::string TagEntry::format(const LogStatistics& /* stat */,
-                             log_id_t /* id */) const {
+std::string TagEntry::format(const LogStatistics&, log_id_t, uint32_t) const {
     std::string name;
     if (uid_ == (uid_t)-1) {
         name = android::base::StringPrintf("%7u", key());
@@ -594,8 +621,8 @@
                       std::string("BYTES"), std::string(""));
 }
 
-std::string TagNameEntry::format(const LogStatistics& /* stat */,
-                                 log_id_t /* id */) const {
+std::string TagNameEntry::format(const LogStatistics&, log_id_t,
+                                 const std::string& key_name) const {
     std::string name;
     std::string pidstr;
     if (pid_ != (pid_t)-1) {
@@ -616,7 +643,7 @@
 
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
-    const char* nameTmp = this->name();
+    const char* nameTmp = key_name.data();
     if (nameTmp) {
         size_t lenSpace = std::max(16 - name.length(), (size_t)1);
         size_t len = EntryBase::TOTAL_LEN - EntryBase::PRUNED_LEN - size.length() - name.length() -
@@ -684,15 +711,16 @@
         REQUIRES(lock_) {
     static const size_t maximum_sorted_entries = 32;
     std::string output;
-    std::array<const TEntry*, maximum_sorted_entries> sorted;
-    table.MaxEntries(uid, pid, &sorted);
+    std::array<const TKey*, maximum_sorted_entries> sorted_keys;
+    std::array<const TEntry*, maximum_sorted_entries> sorted_entries;
+    table.MaxEntries(uid, pid, sorted_keys, sorted_entries);
     bool header_printed = false;
     for (size_t index = 0; index < maximum_sorted_entries; ++index) {
-        const TEntry* entry = sorted[index];
+        const TEntry* entry = sorted_entries[index];
         if (!entry) {
             break;
         }
-        if (entry->getSizes() <= (sorted[0]->getSizes() / 100)) {
+        if (entry->getSizes() <= (sorted_entries[0]->getSizes() / 100)) {
             break;
         }
         if (!header_printed) {
@@ -700,7 +728,7 @@
             output += entry->formatHeader(name, id);
             header_printed = true;
         }
-        output += entry->format(*this, id);
+        output += entry->format(*this, id, *sorted_keys[index]);
     }
     return output;
 }
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 33a4d63..200c228 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -44,6 +44,8 @@
     for (log_id_t i = LOG_ID_MIN; (i) < LOG_ID_MAX; (i) = (log_id_t)((i) + 1))
 
 class LogStatistics;
+class UidEntry;
+class PidEntry;
 
 struct LogStatisticsElement {
     uid_t uid;
@@ -95,31 +97,43 @@
     // Returns a sorted array of up to len highest entries sorted by size.  If fewer than len
     // entries are found, their positions are set to nullptr.
     template <size_t len>
-    void MaxEntries(uid_t uid, pid_t pid, std::array<const TEntry*, len>* out) const {
-        auto& retval = *out;
-        retval.fill(nullptr);
-        for (const_iterator it = map.begin(); it != map.end(); ++it) {
-            const TEntry& entry = it->second;
-
-            if (uid != AID_ROOT && uid != entry.uid()) {
+    void MaxEntries(uid_t uid, pid_t pid, std::array<const TKey*, len>& out_keys,
+                    std::array<const TEntry*, len>& out_entries) const {
+        out_keys.fill(nullptr);
+        out_entries.fill(nullptr);
+        for (const auto& [key, entry] : map) {
+            uid_t entry_uid = 0;
+            if constexpr (std::is_same_v<TEntry, UidEntry>) {
+                entry_uid = key;
+            } else {
+                entry_uid = entry.uid();
+            }
+            if (uid != AID_ROOT && uid != entry_uid) {
                 continue;
             }
-            if (pid && entry.pid() && pid != entry.pid()) {
+            pid_t entry_pid = 0;
+            if constexpr (std::is_same_v<TEntry, PidEntry>) {
+                entry_pid = key;
+            } else {
+                entry_pid = entry.pid();
+            }
+            if (pid && entry_pid && pid != entry_pid) {
                 continue;
             }
 
             size_t sizes = entry.getSizes();
             ssize_t index = len - 1;
-            while ((!retval[index] || (sizes > retval[index]->getSizes())) &&
-                   (--index >= 0))
+            while ((!out_entries[index] || sizes > out_entries[index]->getSizes()) && --index >= 0)
                 ;
             if (++index < (ssize_t)len) {
                 size_t num = len - index - 1;
                 if (num) {
-                    memmove(&retval[index + 1], &retval[index],
-                            num * sizeof(retval[0]));
+                    memmove(&out_keys[index + 1], &out_keys[index], num * sizeof(out_keys[0]));
+                    memmove(&out_entries[index + 1], &out_entries[index],
+                            num * sizeof(out_entries[0]));
                 }
-                retval[index] = &entry;
+                out_keys[index] = &key;
+                out_entries[index] = &entry;
             }
         }
     }
@@ -229,10 +243,8 @@
 class UidEntry : public EntryBaseDropped {
   public:
     explicit UidEntry(const LogStatisticsElement& element)
-        : EntryBaseDropped(element), uid_(element.uid), pid_(element.pid) {}
+        : EntryBaseDropped(element), pid_(element.pid) {}
 
-    uid_t key() const { return uid_; }
-    uid_t uid() const { return key(); }
     pid_t pid() const { return pid_; }
 
     void Add(const LogStatisticsElement& element) {
@@ -243,10 +255,9 @@
     }
 
     std::string formatHeader(const std::string& name, log_id_t id) const;
-    std::string format(const LogStatistics& stat, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id, uid_t uid) const;
 
   private:
-    const uid_t uid_;
     pid_t pid_;
 };
 
@@ -258,23 +269,16 @@
   public:
     explicit PidEntry(pid_t pid)
         : EntryBaseDropped(),
-          pid_(pid),
           uid_(android::pidToUid(pid)),
           name_(android::pidToName(pid)) {}
     explicit PidEntry(const LogStatisticsElement& element)
-        : EntryBaseDropped(element),
-          pid_(element.pid),
-          uid_(element.uid),
-          name_(android::pidToName(pid_)) {}
+        : EntryBaseDropped(element), uid_(element.uid), name_(android::pidToName(element.pid)) {}
     PidEntry(const PidEntry& element)
         : EntryBaseDropped(element),
-          pid_(element.pid_),
           uid_(element.uid_),
           name_(element.name_ ? strdup(element.name_) : nullptr) {}
     ~PidEntry() { free(name_); }
 
-    pid_t key() const { return pid_; }
-    pid_t pid() const { return key(); }
     uid_t uid() const { return uid_; }
     const char* name() const { return name_; }
 
@@ -301,10 +305,9 @@
     }
 
     std::string formatHeader(const std::string& name, log_id_t id) const;
-    std::string format(const LogStatistics& stat, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id, pid_t pid) const;
 
   private:
-    const pid_t pid_;
     uid_t uid_;
     char* name_;
 };
@@ -313,26 +316,21 @@
   public:
     TidEntry(pid_t tid, pid_t pid)
         : EntryBaseDropped(),
-          tid_(tid),
           pid_(pid),
           uid_(android::pidToUid(tid)),
           name_(android::tidToName(tid)) {}
     explicit TidEntry(const LogStatisticsElement& element)
         : EntryBaseDropped(element),
-          tid_(element.tid),
           pid_(element.pid),
           uid_(element.uid),
-          name_(android::tidToName(tid_)) {}
+          name_(android::tidToName(element.tid)) {}
     TidEntry(const TidEntry& element)
         : EntryBaseDropped(element),
-          tid_(element.tid_),
           pid_(element.pid_),
           uid_(element.uid_),
           name_(element.name_ ? strdup(element.name_) : nullptr) {}
     ~TidEntry() { free(name_); }
 
-    pid_t key() const { return tid_; }
-    pid_t tid() const { return key(); }
     pid_t pid() const { return pid_; }
     uid_t uid() const { return uid_; }
     const char* name() const { return name_; }
@@ -362,10 +360,9 @@
     }
 
     std::string formatHeader(const std::string& name, log_id_t id) const;
-    std::string format(const LogStatistics& stat, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id, pid_t pid) const;
 
   private:
-    const pid_t tid_;
     pid_t pid_;
     uid_t uid_;
     char* name_;
@@ -392,7 +389,7 @@
     }
 
     std::string formatHeader(const std::string& name, log_id_t id) const;
-    std::string format(const LogStatistics& stat, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id, uint32_t) const;
 
   private:
     const uint32_t tag_;
@@ -400,108 +397,14 @@
     uid_t uid_;
 };
 
-struct TagNameKey {
-    std::string* alloc;
-    std::string_view name;  // Saves space if const char*
-
-    explicit TagNameKey(const LogStatisticsElement& element)
-        : alloc(nullptr), name("", strlen("")) {
-        if (IsBinary(element.log_id)) {
-            uint32_t tag = element.tag;
-            if (tag) {
-                const char* cp = android::tagToName(tag);
-                if (cp) {
-                    name = std::string_view(cp, strlen(cp));
-                    return;
-                }
-            }
-            alloc = new std::string(
-                android::base::StringPrintf("[%" PRIu32 "]", tag));
-            if (!alloc) return;
-            name = std::string_view(alloc->c_str(), alloc->size());
-            return;
-        }
-        const char* msg = element.msg;
-        if (!msg) {
-            name = std::string_view("chatty", strlen("chatty"));
-            return;
-        }
-        ++msg;
-        uint16_t len = element.msg_len;
-        len = (len <= 1) ? 0 : strnlen(msg, len - 1);
-        if (!len) {
-            name = std::string_view("<NULL>", strlen("<NULL>"));
-            return;
-        }
-        alloc = new std::string(msg, len);
-        if (!alloc) return;
-        name = std::string_view(alloc->c_str(), alloc->size());
-    }
-
-    explicit TagNameKey(TagNameKey&& rval) noexcept
-        : alloc(rval.alloc), name(rval.name.data(), rval.name.length()) {
-        rval.alloc = nullptr;
-    }
-
-    explicit TagNameKey(const TagNameKey& rval)
-        : alloc(rval.alloc ? new std::string(*rval.alloc) : nullptr),
-          name(alloc ? alloc->data() : rval.name.data(), rval.name.length()) {
-    }
-
-    ~TagNameKey() {
-        if (alloc) delete alloc;
-    }
-
-    operator const std::string_view() const {
-        return name;
-    }
-
-    const char* data() const {
-        return name.data();
-    }
-    size_t length() const {
-        return name.length();
-    }
-
-    bool operator==(const TagNameKey& rval) const {
-        if (length() != rval.length()) return false;
-        if (length() == 0) return true;
-        return fastcmp<strncmp>(data(), rval.data(), length()) == 0;
-    }
-    bool operator!=(const TagNameKey& rval) const {
-        return !(*this == rval);
-    }
-
-    size_t getAllocLength() const {
-        return alloc ? alloc->length() + 1 + sizeof(std::string) : 0;
-    }
-};
-
-// Hash for TagNameKey
-template <>
-struct std::hash<TagNameKey>
-    : public std::unary_function<const TagNameKey&, size_t> {
-    size_t operator()(const TagNameKey& __t) const noexcept {
-        if (!__t.length()) return 0;
-        return std::hash<std::string_view>()(std::string_view(__t));
-    }
-};
-
 class TagNameEntry : public EntryBase {
   public:
     explicit TagNameEntry(const LogStatisticsElement& element)
-        : EntryBase(element),
-          tid_(element.tid),
-          pid_(element.pid),
-          uid_(element.uid),
-          name_(element) {}
+        : EntryBase(element), tid_(element.tid), pid_(element.pid), uid_(element.uid) {}
 
-    const TagNameKey& key() const { return name_; }
     pid_t tid() const { return tid_; }
     pid_t pid() const { return pid_; }
     uid_t uid() const { return uid_; }
-    const char* name() const { return name_.data(); }
-    size_t getNameAllocLength() const { return name_.getAllocLength(); }
 
     void Add(const LogStatisticsElement& element) {
         if (uid_ != element.uid) {
@@ -517,16 +420,14 @@
     }
 
     std::string formatHeader(const std::string& name, log_id_t id) const;
-    std::string format(const LogStatistics& stat, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id, const std::string& key_name) const;
 
   private:
     pid_t tid_;
     pid_t pid_;
     uid_t uid_;
-    TagNameKey name_;
 };
 
-// Log Statistics
 class LogStatistics {
     friend UidEntry;
     friend PidEntry;
@@ -567,7 +468,7 @@
     tagTable_t securityTagTable GUARDED_BY(lock_);
 
     // global tag list
-    typedef LogHashtable<TagNameKey, TagNameEntry> tagNameTable_t;
+    typedef LogHashtable<std::string, TagNameEntry> tagNameTable_t;
     tagNameTable_t tagNameTable;
 
     size_t sizeOf() const REQUIRES(lock_) {
@@ -584,13 +485,21 @@
             const char* name = it.second.name();
             if (name) size += strlen(name) + 1;
         }
-        for (auto it : tagNameTable) size += it.second.getNameAllocLength();
+        for (auto it : tagNameTable) {
+            size += sizeof(std::string);
+            size_t len = it.first.size();
+            // Account for short string optimization: if the string's length is <= 22 bytes for 64
+            // bit or <= 10 bytes for 32 bit, then there is no additional allocation.
+            if ((sizeof(std::string) == 24 && len > 22) ||
+                (sizeof(std::string) != 24 && len > 10)) {
+                size += len;
+            }
+        }
         log_id_for_each(id) {
             size += uidTable[id].sizeOf();
             size += uidTable[id].size() * sizeof(uidTable_t::iterator);
             size += pidSystemTable[id].sizeOf();
-            size +=
-                pidSystemTable[id].size() * sizeof(pidSystemTable_t::iterator);
+            size += pidSystemTable[id].size() * sizeof(pidSystemTable_t::iterator);
         }
         return size;
     }
diff --git a/logd/LogTags.cpp b/logd/LogTags.cpp
index 3afe3ee..8e18f9d 100644
--- a/logd/LogTags.cpp
+++ b/logd/LogTags.cpp
@@ -29,6 +29,7 @@
 #include <string>
 
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/macros.h>
 #include <android-base/scopeguard.h>
 #include <android-base/stringprintf.h>
@@ -115,10 +116,11 @@
     }
 
     if (warn) {
-        android::prdebug(
-            ((fd < 0) ? "%s failed to rebuild"
-                      : "%s missing, damaged or truncated; rebuilt"),
-            filename);
+        if (fd < 0) {
+            LOG(ERROR) << filename << " failed to rebuild";
+        } else {
+            LOG(ERROR) << filename << " missing, damaged or truncated; rebuilt";
+        }
     }
 
     if (fd >= 0) {
@@ -182,8 +184,7 @@
         WritePersistEventLogTags(tag, uid, source);
     } else if (warn && !newOne && source) {
         // For the files, we want to report dupes.
-        android::prdebug("Multiple tag %" PRIu32 " %s %s %s", tag, Name.c_str(),
-                         Format.c_str(), source);
+        LOG(DEBUG) << "Multiple tag " << tag << " " << Name << " " << Format << " " << source;
     }
 }
 
@@ -216,7 +217,7 @@
                 } else if (isdigit(*cp)) {
                     unsigned long Tag = strtoul(cp, &cp, 10);
                     if (warn && (Tag > emptyTag)) {
-                        android::prdebug("tag too large %lu", Tag);
+                        LOG(WARNING) << "tag too large " << Tag;
                     }
                     while ((cp < endp) && (*cp != '\n') && isspace(*cp)) ++cp;
                     if (cp >= endp) break;
@@ -231,9 +232,8 @@
                     std::string Name(name, cp - name);
 #ifdef ALLOW_NOISY_LOGGING_OF_PROBLEM_WITH_LOTS_OF_TECHNICAL_DEBT
                     static const size_t maximum_official_tag_name_size = 24;
-                    if (warn &&
-                        (Name.length() > maximum_official_tag_name_size)) {
-                        android::prdebug("tag name too long %s", Name.c_str());
+                    if (warn && (Name.length() > maximum_official_tag_name_size)) {
+                        LOG(WARNING) << "tag name too long " << Name;
                     }
 #endif
                     if (hasAlpha &&
@@ -264,8 +264,8 @@
                                         filename, warn);
                     } else {
                         if (warn) {
-                            android::prdebug("tag name invalid %.*s",
-                                             (int)(cp - name + 1), name);
+                            LOG(ERROR) << android::base::StringPrintf("tag name invalid %.*s",
+                                                                      (int)(cp - name + 1), name);
                         }
                         lineStart = nullptr;
                     }
@@ -276,7 +276,7 @@
             cp++;
         }
     } else if (warn) {
-        android::prdebug("Cannot read %s", filename);
+        LOG(ERROR) << "Cannot read " << filename;
     }
 }
 
@@ -479,8 +479,8 @@
 
 static int openFile(const char* name, int mode, bool warning) {
     int fd = TEMP_FAILURE_RETRY(open(name, mode));
-    if ((fd < 0) && warning) {
-        android::prdebug("Failed open %s (%d)", name, errno);
+    if (fd < 0 && warning) {
+        PLOG(ERROR) << "Failed to open " << name;
     }
     return fd;
 }
diff --git a/logd/LogUtils.h b/logd/LogUtils.h
index 96aa1d3..df78a50 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -30,7 +30,6 @@
 
 // Furnished in main.cpp. Caller must own and free returned value
 char* uidToName(uid_t uid);
-void prdebug(const char* fmt, ...) __attribute__((__format__(printf, 1, 2)));
 
 // Caller must own and free returned value
 char* pidToName(pid_t pid);
diff --git a/logd/SimpleLogBuffer.cpp b/logd/SimpleLogBuffer.cpp
index b4b3546..292a7e4 100644
--- a/logd/SimpleLogBuffer.cpp
+++ b/logd/SimpleLogBuffer.cpp
@@ -16,6 +16,8 @@
 
 #include "SimpleLogBuffer.h"
 
+#include <android-base/logging.h>
+
 #include "LogBufferElement.h"
 
 SimpleLogBuffer::SimpleLogBuffer(LogReaderList* reader_list, LogTags* tags, LogStatistics* stats)
@@ -232,8 +234,8 @@
                 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
                 for (const auto& reader_thread : reader_list_->reader_threads()) {
                     if (reader_thread->IsWatching(id)) {
-                        android::prdebug("Kicking blocked reader, %s, from LogBuffer::clear()\n",
-                                         reader_thread->name().c_str());
+                        LOG(WARNING) << "Kicking blocked reader, " << reader_thread->name()
+                                     << ", from LogBuffer::clear()";
                         reader_thread->release_Locked();
                     }
                 }
@@ -350,16 +352,16 @@
     if (stats_->Sizes(id) > (2 * max_size_[id])) {  // +100%
         // A misbehaving or slow reader has its connection
         // dropped if we hit too much memory pressure.
-        android::prdebug("Kicking blocked reader, %s, from LogBuffer::kickMe()\n",
-                         reader->name().c_str());
+        LOG(WARNING) << "Kicking blocked reader, " << reader->name()
+                     << ", from LogBuffer::kickMe()";
         reader->release_Locked();
     } else if (reader->deadline().time_since_epoch().count() != 0) {
         // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
         reader->triggerReader_Locked();
     } else {
         // tell slow reader to skip entries to catch up
-        android::prdebug("Skipping %lu entries from slow reader, %s, from LogBuffer::kickMe()\n",
-                         prune_rows, reader->name().c_str());
+        LOG(WARNING) << "Skipping " << prune_rows << " entries from slow reader, " << reader->name()
+                     << ", from LogBuffer::kickMe()";
         reader->triggerSkip_Locked(id, prune_rows);
     }
 }
diff --git a/logd/fuzz/log_buffer_log_fuzzer.cpp b/logd/fuzz/log_buffer_log_fuzzer.cpp
index 8f90f50..b576ddf 100644
--- a/logd/fuzz/log_buffer_log_fuzzer.cpp
+++ b/logd/fuzz/log_buffer_log_fuzzer.cpp
@@ -79,13 +79,6 @@
     return 1;
 }
 
-// Because system/core/logd/main.cpp redefines these.
-void prdebug(char const* fmt, ...) {
-    va_list ap;
-    va_start(ap, fmt);
-    vfprintf(stderr, fmt, ap);
-    va_end(ap);
-}
 char* uidToName(uid_t) {
     return strdup("fake");
 }
diff --git a/logd/main.cpp b/logd/main.cpp
index c2b5a1d..773ffb8 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -36,7 +36,9 @@
 
 #include <memory>
 
+#include <android-base/logging.h>
 #include <android-base/macros.h>
+#include <android-base/stringprintf.h>
 #include <cutils/android_get_control_file.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
@@ -70,19 +72,18 @@
     sched_param param = {};
 
     if (set_sched_policy(0, SP_BACKGROUND) < 0) {
-        android::prdebug("failed to set background scheduling policy");
+        PLOG(ERROR) << "failed to set background scheduling policy";
         return -1;
     }
 
     if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
-        android::prdebug("failed to set batch scheduler");
+        PLOG(ERROR) << "failed to set batch scheduler";
         return -1;
     }
 
-    if (!__android_logger_property_get_bool("ro.debuggable",
-                                            BOOL_DEFAULT_FALSE) &&
+    if (!__android_logger_property_get_bool("ro.debuggable", BOOL_DEFAULT_FALSE) &&
         prctl(PR_SET_DUMPABLE, 0) == -1) {
-        android::prdebug("failed to clear PR_SET_DUMPABLE");
+        PLOG(ERROR) << "failed to clear PR_SET_DUMPABLE";
         return -1;
     }
 
@@ -105,40 +106,13 @@
         return -1;
     }
     if (cap_set_proc(caps.get()) < 0) {
-        android::prdebug("failed to set CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)", errno);
+        PLOG(ERROR) << "failed to set CAP_SYSLOG or CAP_AUDIT_CONTROL";
         return -1;
     }
 
     return 0;
 }
 
-static int fdDmesg = -1;
-void android::prdebug(const char* fmt, ...) {
-    if (fdDmesg < 0) {
-        return;
-    }
-
-    static const char message[] = {
-        KMSG_PRIORITY(LOG_DEBUG), 'l', 'o', 'g', 'd', ':', ' '
-    };
-    char buffer[256];
-    memcpy(buffer, message, sizeof(message));
-
-    va_list ap;
-    va_start(ap, fmt);
-    int n = vsnprintf(buffer + sizeof(message),
-                      sizeof(buffer) - sizeof(message), fmt, ap);
-    va_end(ap);
-    if (n > 0) {
-        buffer[sizeof(buffer) - 1] = '\0';
-        if (!strchr(buffer, '\n')) {
-            buffer[sizeof(buffer) - 2] = '\0';
-            strlcat(buffer, "\n", sizeof(buffer));
-        }
-        write(fdDmesg, buffer, strlen(buffer));
-    }
-}
-
 char* android::uidToName(uid_t u) {
     struct Userdata {
         uid_t uid;
@@ -246,8 +220,20 @@
         return issueReinit();
     }
 
+    android::base::InitLogging(
+            argv, [](android::base::LogId log_id, android::base::LogSeverity severity,
+                     const char* tag, const char* file, unsigned int line, const char* message) {
+                if (tag && strcmp(tag, "logd") != 0) {
+                    auto prefixed_message = android::base::StringPrintf("%s: %s", tag, message);
+                    android::base::KernelLogger(log_id, severity, "logd", file, line,
+                                                prefixed_message.c_str());
+                } else {
+                    android::base::KernelLogger(log_id, severity, "logd", file, line, message);
+                }
+            });
+
     static const char dev_kmsg[] = "/dev/kmsg";
-    fdDmesg = android_get_control_file(dev_kmsg);
+    int fdDmesg = android_get_control_file(dev_kmsg);
     if (fdDmesg < 0) {
         fdDmesg = TEMP_FAILURE_RETRY(open(dev_kmsg, O_WRONLY | O_CLOEXEC));
     }
@@ -263,7 +249,7 @@
             fdPmesg = TEMP_FAILURE_RETRY(
                 open(proc_kmsg, O_RDONLY | O_NDELAY | O_CLOEXEC));
         }
-        if (fdPmesg < 0) android::prdebug("Failed to open %s\n", proc_kmsg);
+        if (fdPmesg < 0) PLOG(ERROR) << "Failed to open " << proc_kmsg;
     }
 
     bool auditd = __android_logger_property_get_bool("ro.logd.auditd", BOOL_DEFAULT_TRUE);
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 00a58bf..427ac4b 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -162,7 +162,7 @@
     chmod 0664 /dev/blkio/tasks
     chmod 0664 /dev/blkio/background/tasks
     write /dev/blkio/blkio.weight 1000
-    write /dev/blkio/background/blkio.weight 500
+    write /dev/blkio/background/blkio.weight 200
     write /dev/blkio/blkio.group_idle 0
     write /dev/blkio/background/blkio.group_idle 0