From 501c373916e292764400dbae735f44b33378400f Mon Sep 17 00:00:00 2001 From: Mark Salyzyn Date: Fri, 10 Mar 2017 14:31:54 -0800 Subject: [PATCH] logd: specify clang format Switch _all_ file's coding style to match to ease all future changes. SideEffects: None Test: compile Bug: 35373582 Change-Id: I470cb17f64fa48f14aafc02f574e296bffe3a3f3 --- logd/.clang-format | 11 + logd/CommandListener.cpp | 137 +++++------ logd/CommandListener.h | 79 ++++--- logd/FlushCommand.cpp | 40 ++-- logd/FlushCommand.h | 21 +- logd/LogAudit.cpp | 144 ++++++------ logd/LogAudit.h | 26 ++- logd/LogBuffer.cpp | 304 ++++++++++++------------- logd/LogBuffer.h | 80 ++++--- logd/LogBufferElement.cpp | 112 +++++---- logd/LogBufferElement.h | 82 ++++--- logd/LogCommand.cpp | 41 ++-- logd/LogCommand.h | 9 +- logd/LogKlog.cpp | 364 ++++++++++++++--------------- logd/LogKlog.h | 40 ++-- logd/LogListener.cpp | 54 ++--- logd/LogListener.h | 14 +- logd/LogReader.cpp | 62 ++--- logd/LogReader.h | 19 +- logd/LogStatistics.cpp | 225 +++++++++--------- logd/LogStatistics.h | 394 ++++++++++++++++++-------------- logd/LogTags.cpp | 147 ++++++------ logd/LogTags.h | 49 ++-- logd/LogTimes.cpp | 88 +++---- logd/LogTimes.h | 62 +++-- logd/LogUtils.h | 19 +- logd/LogWhiteBlackList.cpp | 20 +- logd/LogWhiteBlackList.h | 46 ++-- logd/libaudit.c | 31 +-- logd/libaudit.h | 15 +- logd/main.cpp | 161 +++++++------ logd/tests/logd_test.cpp | 455 ++++++++++++++++++------------------- 32 files changed, 1735 insertions(+), 1616 deletions(-) create mode 100644 logd/.clang-format diff --git a/logd/.clang-format b/logd/.clang-format new file mode 100644 index 000000000..393c3094b --- /dev/null +++ b/logd/.clang-format @@ -0,0 +1,11 @@ +BasedOnStyle: Google +AllowShortFunctionsOnASingleLine: false + +CommentPragmas: NOLINT:.* +DerivePointerAlignment: false +IndentWidth: 4 +PointerAlignment: Left +TabWidth: 4 +PenaltyExcessCharacter: 32 + +Cpp11BracedListStyle: false diff --git a/logd/CommandListener.cpp b/logd/CommandListener.cpp index 6ad735152..06c0ab5fe 100644 --- a/logd/CommandListener.cpp +++ b/logd/CommandListener.cpp @@ -20,8 +20,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -37,9 +37,9 @@ #include "LogCommand.h" #include "LogUtils.h" -CommandListener::CommandListener(LogBuffer *buf, LogReader * /*reader*/, - LogListener * /*swl*/) : - FrameworkListener(getLogSocket()) { +CommandListener::CommandListener(LogBuffer* buf, LogReader* /*reader*/, + LogListener* /*swl*/) + : FrameworkListener(getLogSocket()) { // registerCmd(new ShutdownCmd(buf, writer, swl)); registerCmd(new ClearCmd(buf)); registerCmd(new GetBufSizeCmd(buf)); @@ -53,24 +53,19 @@ CommandListener::CommandListener(LogBuffer *buf, LogReader * /*reader*/, registerCmd(new ExitCmd(this)); } -CommandListener::ShutdownCmd::ShutdownCmd(LogReader *reader, - LogListener *swl) : - LogCommand("shutdown"), - mReader(*reader), - mSwl(*swl) { +CommandListener::ShutdownCmd::ShutdownCmd(LogReader* reader, LogListener* swl) + : LogCommand("shutdown"), mReader(*reader), mSwl(*swl) { } -int CommandListener::ShutdownCmd::runCommand(SocketClient * /*cli*/, - int /*argc*/, - char ** /*argv*/) { +int CommandListener::ShutdownCmd::runCommand(SocketClient* /*cli*/, + int /*argc*/, char** /*argv*/) { mSwl.stopListener(); mReader.stopListener(); exit(0); } -CommandListener::ClearCmd::ClearCmd(LogBuffer *buf) : - LogCommand("clear"), - mBuf(*buf) { +CommandListener::ClearCmd::ClearCmd(LogBuffer* buf) + : LogCommand("clear"), mBuf(*buf) { } static void setname() { @@ -81,8 +76,8 @@ static void setname() { } } -int CommandListener::ClearCmd::runCommand(SocketClient *cli, - int argc, char **argv) { +int CommandListener::ClearCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); uid_t uid = cli->getUid(); if (clientHasLogCredentials(cli)) { @@ -100,17 +95,16 @@ int CommandListener::ClearCmd::runCommand(SocketClient *cli, return 0; } - cli->sendMsg(mBuf.clear((log_id_t) id, uid) ? "busy" : "success"); + cli->sendMsg(mBuf.clear((log_id_t)id, uid) ? "busy" : "success"); return 0; } -CommandListener::GetBufSizeCmd::GetBufSizeCmd(LogBuffer *buf) : - LogCommand("getLogSize"), - mBuf(*buf) { +CommandListener::GetBufSizeCmd::GetBufSizeCmd(LogBuffer* buf) + : LogCommand("getLogSize"), mBuf(*buf) { } -int CommandListener::GetBufSizeCmd::runCommand(SocketClient *cli, - int argc, char **argv) { +int CommandListener::GetBufSizeCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); if (argc < 2) { cli->sendMsg("Missing Argument"); @@ -123,20 +117,19 @@ int CommandListener::GetBufSizeCmd::runCommand(SocketClient *cli, return 0; } - unsigned long size = mBuf.getSize((log_id_t) id); + unsigned long size = mBuf.getSize((log_id_t)id); char buf[512]; snprintf(buf, sizeof(buf), "%lu", size); cli->sendMsg(buf); return 0; } -CommandListener::SetBufSizeCmd::SetBufSizeCmd(LogBuffer *buf) : - LogCommand("setLogSize"), - mBuf(*buf) { +CommandListener::SetBufSizeCmd::SetBufSizeCmd(LogBuffer* buf) + : LogCommand("setLogSize"), mBuf(*buf) { } -int CommandListener::SetBufSizeCmd::runCommand(SocketClient *cli, - int argc, char **argv) { +int CommandListener::SetBufSizeCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); if (!clientHasLogCredentials(cli)) { cli->sendMsg("Permission Denied"); @@ -155,7 +148,7 @@ int CommandListener::SetBufSizeCmd::runCommand(SocketClient *cli, } unsigned long size = atol(argv[2]); - if (mBuf.setSize((log_id_t) id, size)) { + if (mBuf.setSize((log_id_t)id, size)) { cli->sendMsg("Range Error"); return 0; } @@ -164,13 +157,12 @@ int CommandListener::SetBufSizeCmd::runCommand(SocketClient *cli, return 0; } -CommandListener::GetBufSizeUsedCmd::GetBufSizeUsedCmd(LogBuffer *buf) : - LogCommand("getLogSizeUsed"), - mBuf(*buf) { +CommandListener::GetBufSizeUsedCmd::GetBufSizeUsedCmd(LogBuffer* buf) + : LogCommand("getLogSizeUsed"), mBuf(*buf) { } -int CommandListener::GetBufSizeUsedCmd::runCommand(SocketClient *cli, - int argc, char **argv) { +int CommandListener::GetBufSizeUsedCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); if (argc < 2) { cli->sendMsg("Missing Argument"); @@ -183,29 +175,29 @@ int CommandListener::GetBufSizeUsedCmd::runCommand(SocketClient *cli, return 0; } - unsigned long size = mBuf.getSizeUsed((log_id_t) id); + unsigned long size = mBuf.getSizeUsed((log_id_t)id); char buf[512]; snprintf(buf, sizeof(buf), "%lu", size); cli->sendMsg(buf); return 0; } -CommandListener::GetStatisticsCmd::GetStatisticsCmd(LogBuffer *buf) : - LogCommand("getStatistics"), - mBuf(*buf) { +CommandListener::GetStatisticsCmd::GetStatisticsCmd(LogBuffer* buf) + : LogCommand("getStatistics"), mBuf(*buf) { } -static std::string package_string(const std::string &str) { +static std::string package_string(const std::string& str) { // Calculate total buffer size prefix, count is the string length w/o nul char fmt[32]; - for(size_t l = str.length(), y = 0, x = 6; y != x; y = x, x = strlen(fmt) - 2) { + for (size_t l = str.length(), y = 0, x = 6; y != x; + y = x, x = strlen(fmt) - 2) { snprintf(fmt, sizeof(fmt), "%zu\n%%s\n\f", l + x); } return android::base::StringPrintf(fmt, str.c_str()); } -int CommandListener::GetStatisticsCmd::runCommand(SocketClient *cli, - int argc, char **argv) { +int CommandListener::GetStatisticsCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); uid_t uid = cli->getUid(); if (clientHasLogCredentials(cli)) { @@ -236,30 +228,28 @@ int CommandListener::GetStatisticsCmd::runCommand(SocketClient *cli, } } - cli->sendMsg(package_string(mBuf.formatStatistics(uid, pid, - logMask)).c_str()); + cli->sendMsg( + package_string(mBuf.formatStatistics(uid, pid, logMask)).c_str()); return 0; } -CommandListener::GetPruneListCmd::GetPruneListCmd(LogBuffer *buf) : - LogCommand("getPruneList"), - mBuf(*buf) { +CommandListener::GetPruneListCmd::GetPruneListCmd(LogBuffer* buf) + : LogCommand("getPruneList"), mBuf(*buf) { } -int CommandListener::GetPruneListCmd::runCommand(SocketClient *cli, - int /*argc*/, char ** /*argv*/) { +int CommandListener::GetPruneListCmd::runCommand(SocketClient* cli, + int /*argc*/, char** /*argv*/) { setname(); cli->sendMsg(package_string(mBuf.formatPrune()).c_str()); return 0; } -CommandListener::SetPruneListCmd::SetPruneListCmd(LogBuffer *buf) : - LogCommand("setPruneList"), - mBuf(*buf) { +CommandListener::SetPruneListCmd::SetPruneListCmd(LogBuffer* buf) + : LogCommand("setPruneList"), mBuf(*buf) { } -int CommandListener::SetPruneListCmd::runCommand(SocketClient *cli, - int argc, char **argv) { +int CommandListener::SetPruneListCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); if (!clientHasLogCredentials(cli)) { cli->sendMsg("Permission Denied"); @@ -286,22 +276,21 @@ int CommandListener::SetPruneListCmd::runCommand(SocketClient *cli, return 0; } -CommandListener::GetEventTagCmd::GetEventTagCmd(LogBuffer *buf) : - LogCommand("getEventTag"), - mBuf(*buf) { +CommandListener::GetEventTagCmd::GetEventTagCmd(LogBuffer* buf) + : LogCommand("getEventTag"), mBuf(*buf) { } -int CommandListener::GetEventTagCmd::runCommand(SocketClient *cli, - int argc, char ** argv) { +int CommandListener::GetEventTagCmd::runCommand(SocketClient* cli, int argc, + char** argv) { setname(); uid_t uid = cli->getUid(); if (clientHasLogCredentials(cli)) { uid = AID_ROOT; } - const char *name = NULL; - const char *format = NULL; - const char *id = NULL; + const char* name = NULL; + const char* format = NULL; + const char* id = NULL; for (int i = 1; i < argc; ++i) { static const char _name[] = "name="; if (!strncmp(argv[i], _name, strlen(_name))) { @@ -331,8 +320,8 @@ int CommandListener::GetEventTagCmd::runCommand(SocketClient *cli, return 0; } - cli->sendMsg(package_string(mBuf.formatGetEventTag(uid, - name, format)).c_str()); + cli->sendMsg( + package_string(mBuf.formatGetEventTag(uid, name, format)).c_str()); return 0; } @@ -340,8 +329,8 @@ int CommandListener::GetEventTagCmd::runCommand(SocketClient *cli, CommandListener::ReinitCmd::ReinitCmd() : LogCommand("reinit") { } -int CommandListener::ReinitCmd::runCommand(SocketClient *cli, - int /*argc*/, char ** /*argv*/) { +int CommandListener::ReinitCmd::runCommand(SocketClient* cli, int /*argc*/, + char** /*argv*/) { setname(); reinit_signal_handler(SIGHUP); @@ -351,13 +340,12 @@ int CommandListener::ReinitCmd::runCommand(SocketClient *cli, return 0; } -CommandListener::ExitCmd::ExitCmd(CommandListener *parent) : - LogCommand("EXIT"), - mParent(*parent) { +CommandListener::ExitCmd::ExitCmd(CommandListener* parent) + : LogCommand("EXIT"), mParent(*parent) { } -int CommandListener::ExitCmd::runCommand(SocketClient * cli, - int /*argc*/, char ** /*argv*/) { +int CommandListener::ExitCmd::runCommand(SocketClient* cli, int /*argc*/, + char** /*argv*/) { setname(); cli->sendMsg("success"); @@ -371,9 +359,8 @@ int CommandListener::getLogSocket() { int sock = android_get_control_socket(socketName); if (sock < 0) { - sock = socket_local_server(socketName, - ANDROID_SOCKET_NAMESPACE_RESERVED, - SOCK_STREAM); + sock = socket_local_server( + socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM); } return sock; diff --git a/logd/CommandListener.h b/logd/CommandListener.h index 39de03b5a..ed9941938 100644 --- a/logd/CommandListener.h +++ b/logd/CommandListener.h @@ -18,40 +18,43 @@ #define _COMMANDLISTENER_H__ #include -#include "LogCommand.h" #include "LogBuffer.h" -#include "LogReader.h" +#include "LogCommand.h" #include "LogListener.h" +#include "LogReader.h" // See main.cpp for implementation void reinit_signal_handler(int /*signal*/); class CommandListener : public FrameworkListener { + public: + CommandListener(LogBuffer* buf, LogReader* reader, LogListener* swl); + virtual ~CommandListener() { + } -public: - CommandListener(LogBuffer *buf, LogReader *reader, LogListener *swl); - virtual ~CommandListener() {} - -private: + private: static int getLogSocket(); class ShutdownCmd : public LogCommand { - LogReader &mReader; - LogListener &mSwl; + LogReader& mReader; + LogListener& mSwl; - public: - ShutdownCmd(LogReader *reader, LogListener *swl); - virtual ~ShutdownCmd() {} - int runCommand(SocketClient *c, int argc, char ** argv); + public: + ShutdownCmd(LogReader* reader, LogListener* swl); + virtual ~ShutdownCmd() { + } + int runCommand(SocketClient* c, int argc, char** argv); }; -#define LogBufferCmd(name) \ - class name##Cmd : public LogCommand { \ - LogBuffer &mBuf; \ - public: \ - explicit name##Cmd(LogBuffer *buf); \ - virtual ~name##Cmd() {} \ - int runCommand(SocketClient *c, int argc, char ** argv); \ +#define LogBufferCmd(name) \ + class name##Cmd : public LogCommand { \ + LogBuffer& mBuf; \ + \ + public: \ + explicit name##Cmd(LogBuffer* buf); \ + virtual ~name##Cmd() { \ + } \ + int runCommand(SocketClient* c, int argc, char** argv); \ } LogBufferCmd(Clear); @@ -63,29 +66,33 @@ private: LogBufferCmd(SetPruneList); LogBufferCmd(GetEventTag); -#define LogCmd(name) \ - class name##Cmd : public LogCommand { \ - public: \ - name##Cmd(); \ - virtual ~name##Cmd() {} \ - int runCommand(SocketClient *c, int argc, char ** argv); \ +#define LogCmd(name) \ + class name##Cmd : public LogCommand { \ + public: \ + name##Cmd(); \ + virtual ~name##Cmd() { \ + } \ + int runCommand(SocketClient* c, int argc, char** argv); \ } LogCmd(Reinit); -#define LogParentCmd(name) \ - class name##Cmd : public LogCommand { \ - CommandListener &mParent; \ - public: \ - name##Cmd(); \ - explicit name##Cmd(CommandListener *parent); \ - virtual ~name##Cmd() {} \ - int runCommand(SocketClient *c, int argc, char ** argv); \ - void release(SocketClient *c) { mParent.release(c); } \ +#define LogParentCmd(name) \ + class name##Cmd : public LogCommand { \ + CommandListener& mParent; \ + \ + public: \ + name##Cmd(); \ + explicit name##Cmd(CommandListener* parent); \ + virtual ~name##Cmd() { \ + } \ + int runCommand(SocketClient* c, int argc, char** argv); \ + void release(SocketClient* c) { \ + mParent.release(c); \ + } \ } LogParentCmd(Exit); - }; #endif diff --git a/logd/FlushCommand.cpp b/logd/FlushCommand.cpp index 6a26d00f3..5a5c0d981 100644 --- a/logd/FlushCommand.cpp +++ b/logd/FlushCommand.cpp @@ -26,20 +26,16 @@ #include "LogTimes.h" #include "LogUtils.h" -FlushCommand::FlushCommand(LogReader &reader, - bool nonBlock, - unsigned long tail, - unsigned int logMask, - pid_t pid, - uint64_t start, - uint64_t timeout) : - mReader(reader), - mNonBlock(nonBlock), - mTail(tail), - mLogMask(logMask), - mPid(pid), - mStart(start), - mTimeout((start > 1) ? timeout : 0) { +FlushCommand::FlushCommand(LogReader& reader, bool nonBlock, unsigned long tail, + unsigned int logMask, pid_t pid, uint64_t start, + uint64_t timeout) + : mReader(reader), + mNonBlock(nonBlock), + mTail(tail), + mLogMask(logMask), + mPid(pid), + mStart(start), + mTimeout((start > 1) ? timeout : 0) { } // runSocketCommand is called once for every open client on the @@ -51,13 +47,13 @@ FlushCommand::FlushCommand(LogReader &reader, // global LogTimeEntry::lock() is used to protect access, // reference counts are used to ensure that individual // LogTimeEntry lifetime is managed when not protected. -void FlushCommand::runSocketCommand(SocketClient *client) { - LogTimeEntry *entry = NULL; - LastLogTimes × = mReader.logbuf().mTimes; +void FlushCommand::runSocketCommand(SocketClient* client) { + LogTimeEntry* entry = NULL; + LastLogTimes& times = mReader.logbuf().mTimes; LogTimeEntry::lock(); LastLogTimes::iterator it = times.begin(); - while(it != times.end()) { + while (it != times.end()) { entry = (*it); if (entry->mClient == client) { if (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec) { @@ -77,7 +73,7 @@ void FlushCommand::runSocketCommand(SocketClient *client) { if (it == times.end()) { // Create LogTimeEntry in notifyNewLog() ? - if (mTail == (unsigned long) -1) { + if (mTail == (unsigned long)-1) { LogTimeEntry::unlock(); return; } @@ -93,14 +89,14 @@ void FlushCommand::runSocketCommand(SocketClient *client) { LogTimeEntry::unlock(); } -bool FlushCommand::hasReadLogs(SocketClient *client) { +bool FlushCommand::hasReadLogs(SocketClient* client) { return clientHasLogCredentials(client); } -static bool clientHasSecurityCredentials(SocketClient *client) { +static bool clientHasSecurityCredentials(SocketClient* client) { return (client->getUid() == AID_SYSTEM) || (client->getGid() == AID_SYSTEM); } -bool FlushCommand::hasSecurityLogs(SocketClient *client) { +bool FlushCommand::hasSecurityLogs(SocketClient* client) { return clientHasSecurityCredentials(client); } diff --git a/logd/FlushCommand.h b/logd/FlushCommand.h index 1e7818a97..45cb9c509 100644 --- a/logd/FlushCommand.h +++ b/logd/FlushCommand.h @@ -26,7 +26,7 @@ class LogBufferElement; class LogReader; class FlushCommand : public SocketClientCommand { - LogReader &mReader; + LogReader& mReader; bool mNonBlock; unsigned long mTail; unsigned int mLogMask; @@ -34,18 +34,15 @@ class FlushCommand : public SocketClientCommand { uint64_t mStart; uint64_t mTimeout; -public: - explicit FlushCommand(LogReader &mReader, - bool nonBlock = false, - unsigned long tail = -1, - unsigned int logMask = -1, - pid_t pid = 0, - uint64_t start = 1, - uint64_t timeout = 0); - virtual void runSocketCommand(SocketClient *client); + public: + explicit FlushCommand(LogReader& mReader, bool nonBlock = false, + unsigned long tail = -1, unsigned int logMask = -1, + pid_t pid = 0, uint64_t start = 1, + uint64_t timeout = 0); + virtual void runSocketCommand(SocketClient* client); - static bool hasReadLogs(SocketClient *client); - static bool hasSecurityLogs(SocketClient *client); + static bool hasReadLogs(SocketClient* client); + static bool hasSecurityLogs(SocketClient* client); }; #endif diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp index 92d957fb1..2d9024ac5 100644 --- a/logd/LogAudit.cpp +++ b/logd/LogAudit.cpp @@ -29,38 +29,52 @@ #include #include -#include "libaudit.h" #include "LogAudit.h" #include "LogBuffer.h" #include "LogKlog.h" #include "LogReader.h" #include "LogUtils.h" +#include "libaudit.h" -#define KMSG_PRIORITY(PRI) \ - '<', \ - '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) / 10, \ - '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) % 10, \ - '>' +#define KMSG_PRIORITY(PRI) \ + '<', '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) / 10, \ + '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) % 10, '>' -LogAudit::LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg) : - SocketListener(mSock = getLogSocket(), false), - logbuf(buf), - reader(reader), - fdDmesg(fdDmesg), - main(__android_logger_property_get_bool("ro.logd.auditd.main", +LogAudit::LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg) + : SocketListener(mSock = getLogSocket(), false), + logbuf(buf), + reader(reader), + fdDmesg(fdDmesg), + main(__android_logger_property_get_bool("ro.logd.auditd.main", + BOOL_DEFAULT_TRUE)), + events(__android_logger_property_get_bool("ro.logd.auditd.events", BOOL_DEFAULT_TRUE)), - events(__android_logger_property_get_bool("ro.logd.auditd.events", - BOOL_DEFAULT_TRUE)), - initialized(false), - tooFast(false) { + initialized(false), + tooFast(false) { static const char auditd_message[] = { KMSG_PRIORITY(LOG_INFO), - 'l', 'o', 'g', 'd', '.', 'a', 'u', 'd', 'i', 't', 'd', ':', - ' ', 's', 't', 'a', 'r', 't', '\n' }; + 'l', + 'o', + 'g', + 'd', + '.', + 'a', + 'u', + 'd', + 'i', + 't', + 'd', + ':', + ' ', + 's', + 't', + 'a', + 'r', + 't', + '\n' }; write(fdDmesg, auditd_message, sizeof(auditd_message)); } void LogAudit::checkRateLimit() { - // trim list for AUDIT_RATE_LIMIT_BURST_DURATION of history log_time oldest(AUDIT_RATE_LIMIT_BURST_DURATION, 0); bucket.emplace(android_log_clockid()); @@ -69,8 +83,9 @@ void LogAudit::checkRateLimit() { static const size_t upperThreshold = ((AUDIT_RATE_LIMIT_BURST_DURATION * - (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) + 1) / - 2; + (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) + + 1) / + 2; if (bucket.size() >= upperThreshold) { // Hit peak, slow down source if (!tooFast) { @@ -89,8 +104,8 @@ void LogAudit::checkRateLimit() { if (!tooFast) return; - static const size_t lowerThreshold = AUDIT_RATE_LIMIT_BURST_DURATION * - AUDIT_RATE_LIMIT_MAX; + static const size_t lowerThreshold = + AUDIT_RATE_LIMIT_BURST_DURATION * AUDIT_RATE_LIMIT_MAX; if (bucket.size() >= lowerThreshold) return; @@ -99,7 +114,7 @@ void LogAudit::checkRateLimit() { audit_rate_limit(mSock, AUDIT_RATE_LIMIT_DEFAULT); } -bool LogAudit::onDataAvailable(SocketClient *cli) { +bool LogAudit::onDataAvailable(SocketClient* cli) { if (!initialized) { prctl(PR_SET_NAME, "logd.auditd"); initialized = true; @@ -123,14 +138,14 @@ bool LogAudit::onDataAvailable(SocketClient *cli) { return true; } -int LogAudit::logPrint(const char *fmt, ...) { +int LogAudit::logPrint(const char* fmt, ...) { if (fmt == NULL) { return -EINVAL; } va_list args; - char *str = NULL; + char* str = NULL; va_start(args, fmt); int rc = vasprintf(&str, fmt, args); va_end(args); @@ -139,7 +154,7 @@ int LogAudit::logPrint(const char *fmt, ...) { return rc; } - char *cp; + char* cp; // Work around kernels missing // https://github.com/torvalds/linux/commit/b8f89caafeb55fba75b74bea25adc4e4cd91be67 // Such kernels improperly add newlines inside audit messages. @@ -160,19 +175,19 @@ int LogAudit::logPrint(const char *fmt, ...) { // Dedupe messages, checking for identical messages starting with avc: static unsigned count; - static char *last_str; + static char* last_str; static bool last_info; if (last_str != NULL) { static const char avc[] = "): avc: "; - char *avcl = strstr(last_str, avc); + char* avcl = strstr(last_str, avc); bool skip = false; if (avcl) { - char *avcr = strstr(str, avc); + char* avcr = strstr(str, avc); - skip = avcr && !fastcmp(avcl + strlen(avc), - avcr + strlen(avc)); + skip = avcr && + !fastcmp(avcl + strlen(avc), avcr + strlen(avc)); if (skip) { ++count; free(last_str); @@ -183,19 +198,17 @@ int LogAudit::logPrint(const char *fmt, ...) { if (!skip) { static const char resume[] = " duplicate messages suppressed\n"; - iov[0].iov_base = last_info ? - const_cast(log_info) : - const_cast(log_warning); - iov[0].iov_len = last_info ? - sizeof(log_info) : - sizeof(log_warning); + iov[0].iov_base = last_info ? const_cast(log_info) + : const_cast(log_warning); + iov[0].iov_len = + last_info ? sizeof(log_info) : sizeof(log_warning); iov[1].iov_base = last_str; iov[1].iov_len = strlen(last_str); if (count > 1) { - iov[2].iov_base = const_cast(resume); + iov[2].iov_base = const_cast(resume); iov[2].iov_len = strlen(resume); } else { - iov[2].iov_base = const_cast(newline); + iov[2].iov_base = const_cast(newline); iov[2].iov_len = strlen(newline); } @@ -210,15 +223,12 @@ int LogAudit::logPrint(const char *fmt, ...) { last_info = info; } if (count == 0) { - iov[0].iov_base = info ? - const_cast(log_info) : - const_cast(log_warning); - iov[0].iov_len = info ? - sizeof(log_info) : - sizeof(log_warning); + iov[0].iov_base = info ? const_cast(log_info) + : const_cast(log_warning); + iov[0].iov_len = info ? sizeof(log_info) : sizeof(log_warning); iov[1].iov_base = str; iov[1].iov_len = strlen(str); - iov[2].iov_base = const_cast(newline); + iov[2].iov_base = const_cast(newline); iov[2].iov_len = strlen(newline); writev(fdDmesg, iov, arraysize(iov)); @@ -236,10 +246,10 @@ int LogAudit::logPrint(const char *fmt, ...) { log_time now; static const char audit_str[] = " audit("; - char *timeptr = strstr(str, audit_str); - if (timeptr - && ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q"))) - && (*cp == ':')) { + char* timeptr = strstr(str, audit_str); + if (timeptr && + ((cp = now.strptime(timeptr + sizeof(audit_str) - 1, "%s.%q"))) && + (*cp == ':')) { memcpy(timeptr + sizeof(audit_str) - 1, "0.0", 3); memmove(timeptr + sizeof(audit_str) - 1 + 3, cp, strlen(cp) + 1); if (!isMonotonic()) { @@ -258,7 +268,7 @@ int LogAudit::logPrint(const char *fmt, ...) { } static const char pid_str[] = " pid="; - char *pidptr = strstr(str, pid_str); + char* pidptr = strstr(str, pid_str); if (pidptr && isdigit(pidptr[sizeof(pid_str) - 1])) { cp = pidptr + sizeof(pid_str) - 1; pid = 0; @@ -280,19 +290,19 @@ int LogAudit::logPrint(const char *fmt, ...) { bool notify = false; - if (events) { // begin scope for event buffer + if (events) { // begin scope for event buffer uint32_t buffer[(n + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; - android_log_event_string_t *event - = reinterpret_cast(buffer); + android_log_event_string_t* event = + reinterpret_cast(buffer); event->header.tag = htole32(AUDITD_LOG_TAG); event->type = EVENT_TYPE_STRING; event->length = htole32(l); memcpy(event->data, str, l); rc = logbuf->log(LOG_ID_EVENTS, now, uid, pid, tid, - reinterpret_cast(event), - (n <= USHRT_MAX) ? (unsigned short) n : USHRT_MAX); + reinterpret_cast(event), + (n <= USHRT_MAX) ? (unsigned short)n : USHRT_MAX); if (rc >= 0) { notify = true; } @@ -302,9 +312,9 @@ int LogAudit::logPrint(const char *fmt, ...) { // log to main static const char comm_str[] = " comm=\""; - const char *comm = strstr(str, comm_str); - const char *estr = str + strlen(str); - const char *commfree = NULL; + const char* comm = strstr(str, comm_str); + const char* estr = str + strlen(str); + const char* commfree = NULL; if (comm) { estr = comm; comm += sizeof(comm_str) - 1; @@ -320,7 +330,7 @@ int LogAudit::logPrint(const char *fmt, ...) { } } - const char *ecomm = strchr(comm, '"'); + const char* ecomm = strchr(comm, '"'); if (ecomm) { ++ecomm; l = ecomm - comm; @@ -335,7 +345,7 @@ int LogAudit::logPrint(const char *fmt, ...) { size_t e = strnlen(ecomm, LOGGER_ENTRY_MAX_PAYLOAD - b); n = b + e + l + 2; - if (main) { // begin scope for main buffer + if (main) { // begin scope for main buffer char newstr[n]; *newstr = info ? ANDROID_LOG_INFO : ANDROID_LOG_WARN; @@ -344,7 +354,7 @@ int LogAudit::logPrint(const char *fmt, ...) { strncpy(newstr + 1 + l + b, ecomm, e); rc = logbuf->log(LOG_ID_MAIN, now, uid, pid, tid, newstr, - (n <= USHRT_MAX) ? (unsigned short) n : USHRT_MAX); + (n <= USHRT_MAX) ? (unsigned short)n : USHRT_MAX); if (rc >= 0) { notify = true; @@ -352,7 +362,7 @@ int LogAudit::logPrint(const char *fmt, ...) { // end scope for main buffer } - free(const_cast(commfree)); + free(const_cast(commfree)); free(str); if (notify) { @@ -365,8 +375,8 @@ int LogAudit::logPrint(const char *fmt, ...) { return rc; } -int LogAudit::log(char *buf, size_t len) { - char *audit = strstr(buf, " audit("); +int LogAudit::log(char* buf, size_t len) { + char* audit = strstr(buf, " audit("); if (!audit || (audit >= &buf[len])) { return 0; } @@ -374,7 +384,7 @@ int LogAudit::log(char *buf, size_t len) { *audit = '\0'; int rc; - char *type = strstr(buf, "type="); + char* type = strstr(buf, "type="); if (type && (type < &buf[len])) { rc = logPrint("%s %s", type, audit + 1); } else { diff --git a/logd/LogAudit.h b/logd/LogAudit.h index 045d6314f..594781910 100644 --- a/logd/LogAudit.h +++ b/logd/LogAudit.h @@ -26,9 +26,9 @@ class LogReader; class LogAudit : public SocketListener { - LogBuffer *logbuf; - LogReader *reader; - int fdDmesg; // fdDmesg >= 0 is functionally bool dmesg + LogBuffer* logbuf; + LogReader* reader; + int fdDmesg; // fdDmesg >= 0 is functionally bool dmesg bool main; bool events; bool initialized; @@ -38,18 +38,20 @@ class LogAudit : public SocketListener { std::queue bucket; void checkRateLimit(); -public: - LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg); - int log(char *buf, size_t len); - bool isMonotonic() { return logbuf->isMonotonic(); } + public: + LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg); + int log(char* buf, size_t len); + bool isMonotonic() { + return logbuf->isMonotonic(); + } -protected: - virtual bool onDataAvailable(SocketClient *cli); + protected: + virtual bool onDataAvailable(SocketClient* cli); -private: + private: static int getLogSocket(); - int logPrint(const char *fmt, ...) - __attribute__ ((__format__ (__printf__, 2, 3))); + int logPrint(const char* fmt, ...) + __attribute__((__format__(__printf__, 2, 3))); }; #endif diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp index 7613c1e98..9c634f680 100644 --- a/logd/LogBuffer.cpp +++ b/logd/LogBuffer.cpp @@ -72,8 +72,8 @@ void LogBuffer::init() { // pthread_mutex_lock(&mLogElementsLock); LogBufferElementCollection::iterator it = mLogElements.begin(); - while((it != mLogElements.end())) { - LogBufferElement *e = *it; + while ((it != mLogElements.end())) { + LogBufferElement* e = *it; if (monotonic) { if (!android::isMonotonic(e->mRealTime)) { LogKlog::convertRealToMonotonic(e->mRealTime); @@ -96,8 +96,8 @@ void LogBuffer::init() { LogTimeEntry::lock(); LastLogTimes::iterator times = mTimes.begin(); - while(times != mTimes.end()) { - LogTimeEntry *entry = (*times); + while (times != mTimes.end()) { + LogTimeEntry* entry = (*times); if (entry->owned_Locked()) { entry->triggerReader_Locked(); } @@ -107,9 +107,8 @@ void LogBuffer::init() { LogTimeEntry::unlock(); } -LogBuffer::LogBuffer(LastLogTimes *times): - monotonic(android_log_clockid() == CLOCK_MONOTONIC), - mTimes(*times) { +LogBuffer::LogBuffer(LastLogTimes* times) + : monotonic(android_log_clockid() == CLOCK_MONOTONIC), mTimes(*times) { pthread_mutex_init(&mLogElementsLock, NULL); log_id_for_each(i) { @@ -127,28 +126,26 @@ LogBuffer::~LogBuffer() { } } -enum match_type { - DIFFERENT, - SAME, - SAME_LIBLOG -}; +enum match_type { DIFFERENT, SAME, SAME_LIBLOG }; -static enum match_type identical(LogBufferElement* elem, LogBufferElement* last) { +static enum match_type identical(LogBufferElement* elem, + LogBufferElement* last) { // is it mostly identical? -// if (!elem) return DIFFERENT; + // if (!elem) return DIFFERENT; unsigned short lenl = elem->getMsgLen(); if (!lenl) return DIFFERENT; -// if (!last) return DIFFERENT; + // if (!last) return DIFFERENT; unsigned short lenr = last->getMsgLen(); if (!lenr) return DIFFERENT; -// if (elem->getLogId() != last->getLogId()) return DIFFERENT; + // if (elem->getLogId() != last->getLogId()) return DIFFERENT; if (elem->getUid() != last->getUid()) return DIFFERENT; if (elem->getPid() != last->getPid()) return DIFFERENT; if (elem->getTid() != last->getTid()) return DIFFERENT; // last is more than a minute old, stop squashing identical messages if (elem->getRealTime().nsec() > - (last->getRealTime().nsec() + 60 * NS_PER_SEC)) return DIFFERENT; + (last->getRealTime().nsec() + 60 * NS_PER_SEC)) + return DIFFERENT; // Identical message const char* msgl = elem->getMsg(); @@ -158,47 +155,47 @@ static enum match_type identical(LogBufferElement* elem, LogBufferElement* last) // liblog tagged messages (content gets summed) if ((elem->getLogId() == LOG_ID_EVENTS) && (lenl == sizeof(android_log_event_int_t)) && - !fastcmp(msgl, msgr, - sizeof(android_log_event_int_t) - sizeof(int32_t)) && - (elem->getTag() == LIBLOG_LOG_TAG)) return SAME_LIBLOG; + !fastcmp(msgl, msgr, sizeof(android_log_event_int_t) - + sizeof(int32_t)) && + (elem->getTag() == LIBLOG_LOG_TAG)) + return SAME_LIBLOG; } // audit message (except sequence number) identical? static const char avc[] = "): avc: "; if (last->isBinary()) { - if (fastcmp(msgl, msgr, - sizeof(android_log_event_string_t) - - sizeof(int32_t))) return DIFFERENT; + if (fastcmp(msgl, msgr, sizeof(android_log_event_string_t) - + sizeof(int32_t))) + return DIFFERENT; msgl += sizeof(android_log_event_string_t); lenl -= sizeof(android_log_event_string_t); msgr += sizeof(android_log_event_string_t); lenr -= sizeof(android_log_event_string_t); } - const char *avcl = android::strnstr(msgl, lenl, avc); + const char* avcl = android::strnstr(msgl, lenl, avc); if (!avcl) return DIFFERENT; lenl -= avcl - msgl; - const char *avcr = android::strnstr(msgr, lenr, avc); + const char* avcr = android::strnstr(msgr, lenr, avc); if (!avcr) return DIFFERENT; lenr -= avcr - msgr; if (lenl != lenr) return DIFFERENT; - if (fastcmp(avcl + strlen(avc), - avcr + strlen(avc), lenl)) return DIFFERENT; + if (fastcmp(avcl + strlen(avc), avcr + strlen(avc), lenl)) + return DIFFERENT; return SAME; } -int LogBuffer::log(log_id_t log_id, log_time realtime, - uid_t uid, pid_t pid, pid_t tid, - const char *msg, unsigned short len) { +int LogBuffer::log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, + pid_t tid, const char* msg, unsigned short len) { if ((log_id >= LOG_ID_MAX) || (log_id < 0)) { return -EINVAL; } - LogBufferElement *elem = new LogBufferElement(log_id, realtime, - uid, pid, tid, msg, len); + LogBufferElement* elem = + new LogBufferElement(log_id, realtime, uid, pid, tid, msg, len); if (log_id != LOG_ID_SECURITY) { int prio = ANDROID_LOG_INFO; - const char *tag = NULL; + const char* tag = NULL; if (log_id == LOG_ID_EVENTS) { tag = tagToName(elem->getTag()); } else { @@ -219,7 +216,7 @@ int LogBuffer::log(log_id_t log_id, log_time realtime, pthread_mutex_lock(&mLogElementsLock); LogBufferElement* currentLast = lastLoggedElements[log_id]; if (currentLast) { - LogBufferElement *dropped = droppedElements[log_id]; + LogBufferElement* dropped = droppedElements[log_id]; unsigned short count = dropped ? dropped->getDropped() : 0; // // State Init @@ -309,7 +306,7 @@ int LogBuffer::log(log_id_t log_id, log_time realtime, uint32_t swab = event->payload.data; unsigned long long total = htole32(swab); event = reinterpret_cast( - const_cast(elem->getMsg())); + const_cast(elem->getMsg())); swab = event->payload.data; lastLoggedElements[LOG_ID_EVENTS] = elem; @@ -346,15 +343,15 @@ int LogBuffer::log(log_id_t log_id, log_time realtime, pthread_mutex_unlock(&mLogElementsLock); return len; } - if (dropped) { // State 1 or 2 - if (count) { // State 2 - log(dropped); // report chatty - } else { // State 1 - delete dropped; + if (dropped) { // State 1 or 2 + if (count) { // State 2 + log(dropped); // report chatty + } else { // State 1 + delete dropped; } droppedElements[log_id] = NULL; - log(currentLast); // report last message in the series - } else { // State 0 + log(currentLast); // report last message in the series + } else { // State 0 delete currentLast; } } @@ -390,7 +387,7 @@ void LogBuffer::log(LogBufferElement* elem) { LogTimeEntry::lock(); LastLogTimes::iterator times = mTimes.begin(); - while(times != mTimes.end()) { + while (times != mTimes.end()) { LogTimeEntry* entry = (*times); if (entry->owned_Locked()) { if (!entry->mNonBlock) { @@ -405,8 +402,7 @@ void LogBuffer::log(LogBufferElement* elem) { times++; } - if (end_always - || (end_set && (end >= (*last)->getSequence()))) { + if (end_always || (end_set && (end >= (*last)->getSequence()))) { mLogElements.push_back(elem); } else { mLogElements.insert(last, elem); @@ -444,30 +440,31 @@ void LogBuffer::maybePrune(log_id_t id) { } LogBufferElementCollection::iterator LogBuffer::erase( - LogBufferElementCollection::iterator it, bool coalesce) { - LogBufferElement *element = *it; + LogBufferElementCollection::iterator it, bool coalesce) { + LogBufferElement* element = *it; log_id_t id = element->getLogId(); // Remove iterator references in the various lists that will become stale // after the element is erased from the main logging list. - { // start of scope for found iterator - int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) ? - element->getTag() : element->getUid(); + { // start of scope for found iterator + int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) + ? element->getTag() + : element->getUid(); LogBufferIteratorMap::iterator found = mLastWorst[id].find(key); if ((found != mLastWorst[id].end()) && (it == found->second)) { mLastWorst[id].erase(found); } } - { // start of scope for pid found iterator + { // start of scope for pid found iterator // element->getUid() may not be AID_SYSTEM for next-best-watermark. // will not assume id != LOG_ID_EVENTS or LOG_ID_SECURITY for KISS and // long term code stability, find() check should be fast for those ids. LogBufferPidIteratorMap::iterator found = mLastWorstPidOfSystem[id].find(element->getPid()); - if ((found != mLastWorstPidOfSystem[id].end()) - && (it == found->second)) { + if ((found != mLastWorstPidOfSystem[id].end()) && + (it == found->second)) { mLastWorstPidOfSystem[id].erase(found); } } @@ -479,34 +476,35 @@ LogBufferElementCollection::iterator LogBuffer::erase( } #ifdef DEBUG_CHECK_FOR_STALE_ENTRIES LogBufferElementCollection::iterator bad = it; - int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) ? - element->getTag() : element->getUid(); + int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) + ? element->getTag() + : element->getUid(); #endif it = mLogElements.erase(it); if (doSetLast) { log_id_for_each(i) { if (setLast[i]) { - if (__predict_false(it == mLogElements.end())) { // impossible + if (__predict_false(it == mLogElements.end())) { // impossible mLastSet[i] = false; mLast[i] = mLogElements.begin(); } else { - mLast[i] = it; // push down the road as next-best-watermark + mLast[i] = it; // push down the road as next-best-watermark } } } } #ifdef DEBUG_CHECK_FOR_STALE_ENTRIES log_id_for_each(i) { - for(auto b : mLastWorst[i]) { + for (auto b : mLastWorst[i]) { if (bad == b.second) { - android::prdebug("stale mLastWorst[%d] key=%d mykey=%d\n", - i, b.first, key); + android::prdebug("stale mLastWorst[%d] key=%d mykey=%d\n", i, + b.first, key); } } - for(auto b : mLastWorstPidOfSystem[i]) { + for (auto b : mLastWorstPidOfSystem[i]) { if (bad == b.second) { - android::prdebug("stale mLastWorstPidOfSystem[%d] pid=%d\n", - i, b.first); + android::prdebug("stale mLastWorstPidOfSystem[%d] pid=%d\n", i, + b.first); } } if (mLastSet[i] && (bad == mLast[i])) { @@ -539,32 +537,29 @@ class LogBufferElementKey { uint64_t value; } __packed; -public: - LogBufferElementKey(uid_t uid, pid_t pid, pid_t tid): - uid(uid), - pid(pid), - tid(tid) - { + public: + LogBufferElementKey(uid_t uid, pid_t pid, pid_t tid) + : uid(uid), pid(pid), tid(tid) { + } + explicit LogBufferElementKey(uint64_t key) : value(key) { } - explicit LogBufferElementKey(uint64_t key):value(key) { } - uint64_t getKey() { return value; } + uint64_t getKey() { + return value; + } }; class LogBufferElementLast { - - typedef std::unordered_map LogBufferElementMap; + typedef std::unordered_map LogBufferElementMap; LogBufferElementMap map; -public: - - bool coalesce(LogBufferElement *element, unsigned short dropped) { - LogBufferElementKey key(element->getUid(), - element->getPid(), + public: + bool coalesce(LogBufferElement* element, unsigned short dropped) { + LogBufferElementKey key(element->getUid(), element->getPid(), element->getTid()); LogBufferElementMap::iterator it = map.find(key.getKey()); if (it != map.end()) { - LogBufferElement *found = it->second; + LogBufferElement* found = it->second; unsigned short moreDropped = found->getDropped(); if ((dropped + moreDropped) > USHRT_MAX) { map.erase(it); @@ -576,9 +571,8 @@ public: return false; } - void add(LogBufferElement *element) { - LogBufferElementKey key(element->getUid(), - element->getPid(), + void add(LogBufferElement* element) { + LogBufferElementKey key(element->getUid(), element->getPid(), element->getTid()); map[key.getKey()] = element; } @@ -587,20 +581,19 @@ public: map.clear(); } - void clear(LogBufferElement *element) { - uint64_t current = element->getRealTime().nsec() - - (EXPIRE_RATELIMIT * NS_PER_SEC); - for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) { - LogBufferElement *mapElement = it->second; - if ((mapElement->getDropped() >= EXPIRE_THRESHOLD) - && (current > mapElement->getRealTime().nsec())) { + void clear(LogBufferElement* element) { + uint64_t current = + element->getRealTime().nsec() - (EXPIRE_RATELIMIT * NS_PER_SEC); + for (LogBufferElementMap::iterator it = map.begin(); it != map.end();) { + LogBufferElement* mapElement = it->second; + if ((mapElement->getDropped() >= EXPIRE_THRESHOLD) && + (current > mapElement->getRealTime().nsec())) { it = map.erase(it); } else { ++it; } } } - }; // prune "pruneRows" of type "id" from the buffer. @@ -651,7 +644,7 @@ public: // mLogElementsLock must be held when this function is called. // bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { - LogTimeEntry *oldest = NULL; + LogTimeEntry* oldest = NULL; bool busy = false; bool clearAll = pruneRows == ULONG_MAX; @@ -659,13 +652,12 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { // Region locked? LastLogTimes::iterator times = mTimes.begin(); - while(times != mTimes.end()) { - LogTimeEntry *entry = (*times); - if (entry->owned_Locked() && entry->isWatching(id) - && (!oldest || - (oldest->mStart > entry->mStart) || - ((oldest->mStart == entry->mStart) && - (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) { + while (times != mTimes.end()) { + LogTimeEntry* entry = (*times); + if (entry->owned_Locked() && entry->isWatching(id) && + (!oldest || (oldest->mStart > entry->mStart) || + ((oldest->mStart == entry->mStart) && + (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) { oldest = entry; } times++; @@ -673,14 +665,15 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { LogBufferElementCollection::iterator it; - if (__predict_false(caller_uid != AID_ROOT)) { // unlikely + if (__predict_false(caller_uid != AID_ROOT)) { // unlikely // Only here if clear all request from non system source, so chatty // filter logistics is not required. it = mLastSet[id] ? mLast[id] : mLogElements.begin(); while (it != mLogElements.end()) { - LogBufferElement *element = *it; + LogBufferElement* element = *it; - if ((element->getLogId() != id) || (element->getUid() != caller_uid)) { + if ((element->getLogId() != id) || + (element->getUid() != caller_uid)) { ++it; continue; } @@ -713,26 +706,28 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { bool hasBlacklist = (id != LOG_ID_SECURITY) && mPrune.naughty(); while (!clearAll && (pruneRows > 0)) { // recalculate the worst offender on every batched pass - int worst = -1; // not valid for getUid() or getKey() + int worst = -1; // not valid for getUid() or getKey() size_t worst_sizes = 0; size_t second_worst_sizes = 0; - pid_t worstPid = 0; // POSIX guarantees PID != 0 + pid_t worstPid = 0; // POSIX guarantees PID != 0 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) { // Calculate threshold as 12.5% of available storage size_t threshold = log_buffer_size(id) / 8; if ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) { - stats.sortTags(AID_ROOT, (pid_t)0, 2, id).findWorst( - worst, worst_sizes, second_worst_sizes, threshold); + stats.sortTags(AID_ROOT, (pid_t)0, 2, id) + .findWorst(worst, worst_sizes, second_worst_sizes, + threshold); // per-pid filter for AID_SYSTEM sources is too complex } else { - stats.sort(AID_ROOT, (pid_t)0, 2, id).findWorst( - worst, worst_sizes, second_worst_sizes, threshold); + stats.sort(AID_ROOT, (pid_t)0, 2, id) + .findWorst(worst, worst_sizes, second_worst_sizes, + threshold); if ((worst == AID_SYSTEM) && mPrune.worstPidOfSystemEnabled()) { - stats.sortPids(worst, (pid_t)0, 2, id).findWorst( - worstPid, worst_sizes, second_worst_sizes); + stats.sortPids(worst, (pid_t)0, 2, id) + .findWorst(worstPid, worst_sizes, second_worst_sizes); } } } @@ -751,35 +746,34 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { // - check age-out of preserved logs bool gc = pruneRows <= 1; if (!gc && (worst != -1)) { - { // begin scope for worst found iterator - LogBufferIteratorMap::iterator found = mLastWorst[id].find(worst); - if ((found != mLastWorst[id].end()) - && (found->second != mLogElements.end())) { + { // begin scope for worst found iterator + LogBufferIteratorMap::iterator found = + mLastWorst[id].find(worst); + if ((found != mLastWorst[id].end()) && + (found->second != mLogElements.end())) { leading = false; it = found->second; } } - if (worstPid) { // begin scope for pid worst found iterator + if (worstPid) { // begin scope for pid worst found iterator // FYI: worstPid only set if !LOG_ID_EVENTS and // !LOG_ID_SECURITY, not going to make that assumption ... - LogBufferPidIteratorMap::iterator found - = mLastWorstPidOfSystem[id].find(worstPid); - if ((found != mLastWorstPidOfSystem[id].end()) - && (found->second != mLogElements.end())) { + LogBufferPidIteratorMap::iterator found = + mLastWorstPidOfSystem[id].find(worstPid); + if ((found != mLastWorstPidOfSystem[id].end()) && + (found->second != mLogElements.end())) { leading = false; it = found->second; } } } - static const timespec too_old = { - EXPIRE_HOUR_THRESHOLD * 60 * 60, 0 - }; + static const timespec too_old = { EXPIRE_HOUR_THRESHOLD * 60 * 60, 0 }; LogBufferElementCollection::iterator lastt; lastt = mLogElements.end(); --lastt; LogBufferElementLast last; while (it != mLogElements.end()) { - LogBufferElement *element = *it; + LogBufferElement* element = *it; if (oldest && (oldest->mStart <= element->getSequence())) { busy = true; @@ -813,9 +807,9 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { continue; } - int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) ? - element->getTag() : - element->getUid(); + int key = ((id == LOG_ID_EVENTS) || (id == LOG_ID_SECURITY)) + ? element->getTag() + : element->getUid(); if (hasBlacklist && mPrune.naughty(element)) { last.clear(element); @@ -839,32 +833,32 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { continue; } - if ((element->getRealTime() < ((*lastt)->getRealTime() - too_old)) - || (element->getRealTime() > (*lastt)->getRealTime())) { + if ((element->getRealTime() < ((*lastt)->getRealTime() - too_old)) || + (element->getRealTime() > (*lastt)->getRealTime())) { break; } if (dropped) { last.add(element); - if (worstPid - && ((!gc && (element->getPid() == worstPid)) - || (mLastWorstPidOfSystem[id].find(element->getPid()) - == mLastWorstPidOfSystem[id].end()))) { + if (worstPid && + ((!gc && (element->getPid() == worstPid)) || + (mLastWorstPidOfSystem[id].find(element->getPid()) == + mLastWorstPidOfSystem[id].end()))) { // element->getUid() may not be AID_SYSTEM, next best // watermark if current one empty. id is not LOG_ID_EVENTS // or LOG_ID_SECURITY because of worstPid check. mLastWorstPidOfSystem[id][element->getPid()] = it; } - if ((!gc && !worstPid && (key == worst)) - || (mLastWorst[id].find(key) == mLastWorst[id].end())) { + if ((!gc && !worstPid && (key == worst)) || + (mLastWorst[id].find(key) == mLastWorst[id].end())) { mLastWorst[id][key] = it; } ++it; continue; } - if ((key != worst) - || (worstPid && (element->getPid() != worstPid))) { + if ((key != worst) || + (worstPid && (element->getPid() != worstPid))) { leading = false; last.clear(element); ++it; @@ -892,16 +886,16 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { it = erase(it, true); } else { last.add(element); - if (worstPid && (!gc - || (mLastWorstPidOfSystem[id].find(worstPid) - == mLastWorstPidOfSystem[id].end()))) { + if (worstPid && + (!gc || (mLastWorstPidOfSystem[id].find(worstPid) == + mLastWorstPidOfSystem[id].end()))) { // element->getUid() may not be AID_SYSTEM, next best // watermark if current one empty. id is not // LOG_ID_EVENTS or LOG_ID_SECURITY because of worstPid. mLastWorstPidOfSystem[id][worstPid] = it; } if ((!gc && !worstPid) || - (mLastWorst[id].find(worst) == mLastWorst[id].end())) { + (mLastWorst[id].find(worst) == mLastWorst[id].end())) { mLastWorst[id][worst] = it; } ++it; @@ -915,15 +909,15 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { last.clear(); if (!kick || !mPrune.worstUidEnabled()) { - break; // the following loop will ask bad clients to skip/drop + break; // the following loop will ask bad clients to skip/drop } } bool whitelist = false; bool hasWhitelist = (id != LOG_ID_SECURITY) && mPrune.nice() && !clearAll; it = mLastSet[id] ? mLast[id] : mLogElements.begin(); - while((pruneRows > 0) && (it != mLogElements.end())) { - LogBufferElement *element = *it; + while ((pruneRows > 0) && (it != mLogElements.end())) { + LogBufferElement* element = *it; if (element->getLogId() != id) { it++; @@ -966,8 +960,8 @@ bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) { // Do not save the whitelist if we are reader range limited if (whitelist && (pruneRows > 0)) { it = mLastSet[id] ? mLast[id] : mLogElements.begin(); - while((it != mLogElements.end()) && (pruneRows > 0)) { - LogBufferElement *element = *it; + while ((it != mLogElements.end()) && (pruneRows > 0)) { + LogBufferElement* element = *it; if (element->getLogId() != id) { ++it; @@ -1007,7 +1001,7 @@ bool LogBuffer::clear(log_id_t id, uid_t uid) { bool busy = true; // If it takes more than 4 tries (seconds) to clear, then kill reader(s) for (int retry = 4;;) { - if (retry == 1) { // last pass + if (retry == 1) { // last pass // Check if it is still busy after the sleep, we say prune // one entry, not another clear run, so we are looking for // the quick side effect of the return value to tell us if @@ -1023,7 +1017,7 @@ bool LogBuffer::clear(log_id_t id, uid_t uid) { LogTimeEntry::lock(); LastLogTimes::iterator times = mTimes.begin(); while (times != mTimes.end()) { - LogTimeEntry *entry = (*times); + LogTimeEntry* entry = (*times); // Killer punch if (entry->owned_Locked() && entry->isWatching(id)) { entry->release_Locked(); @@ -1039,7 +1033,7 @@ bool LogBuffer::clear(log_id_t id, uid_t uid) { if (!busy || !--retry) { break; } - sleep (1); // Let reader(s) catch up after notification + sleep(1); // Let reader(s) catch up after notification } return busy; } @@ -1073,9 +1067,8 @@ unsigned long LogBuffer::getSize(log_id_t id) { } uint64_t LogBuffer::flushTo( - SocketClient *reader, const uint64_t start, - bool privileged, bool security, - int (*filter)(const LogBufferElement *element, void *arg), void *arg) { + SocketClient* reader, const uint64_t start, bool privileged, bool security, + int (*filter)(const LogBufferElement* element, void* arg), void* arg) { LogBufferElementCollection::iterator it; uint64_t max = start; uid_t uid = reader->getUid(); @@ -1088,9 +1081,10 @@ uint64_t LogBuffer::flushTo( } else { // Client wants to start from some specified time. Chances are // we are better off starting from the end of the time sorted list. - for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) { + for (it = mLogElements.end(); it != mLogElements.begin(); + /* do nothing */) { --it; - LogBufferElement *element = *it; + LogBufferElement* element = *it; if (element->getSequence() <= start) { it++; break; @@ -1103,7 +1097,7 @@ uint64_t LogBuffer::flushTo( pid_t lastTid[LOG_ID_MAX] = { 0 }; for (; it != mLogElements.end(); ++it) { - LogBufferElement *element = *it; + LogBufferElement* element = *it; if (!privileged && (element->getUid() != uid)) { continue; @@ -1134,8 +1128,8 @@ uint64_t LogBuffer::flushTo( // multiple identical squash. chatty that differs source // is due to spam filter. chatty to chatty of different // source is also due to spam filter. - lastTid[element->getLogId()] = (element->getDropped() && !sameTid) ? - 0 : element->getTid(); + lastTid[element->getLogId()] = + (element->getDropped() && !sameTid) ? 0 : element->getTid(); pthread_mutex_unlock(&mLogElementsLock); diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h index 9feef32e7..92b0297e2 100644 --- a/logd/LogBuffer.h +++ b/logd/LogBuffer.h @@ -27,9 +27,9 @@ #include #include "LogBufferElement.h" +#include "LogStatistics.h" #include "LogTags.h" #include "LogTimes.h" -#include "LogStatistics.h" #include "LogWhiteBlackList.h" // @@ -41,7 +41,7 @@ // namespace android { -static bool isMonotonic(const log_time &mono) { +static bool isMonotonic(const log_time& mono) { static const uint32_t EPOCH_PLUS_2_YEARS = 2 * 24 * 60 * 60 * 1461 / 4; static const uint32_t EPOCH_PLUS_MINUTE = 60; @@ -70,10 +70,9 @@ static bool isMonotonic(const log_time &mono) { /* dividing line half way between monotonic and realtime */ return mono.tv_sec < ((cpu.tv_sec + now.tv_sec) / 2); } - } -typedef std::list LogBufferElementCollection; +typedef std::list LogBufferElementCollection; class LogBuffer { LogBufferElementCollection mLogElements; @@ -86,14 +85,12 @@ class LogBuffer { LogBufferElementCollection::iterator mLast[LOG_ID_MAX]; bool mLastSet[LOG_ID_MAX]; // watermark of any worst/chatty uid processing - typedef std::unordered_map - LogBufferIteratorMap; + typedef std::unordered_map + LogBufferIteratorMap; LogBufferIteratorMap mLastWorst[LOG_ID_MAX]; // watermark of any worst/chatty pid of system processing - typedef std::unordered_map - LogBufferPidIteratorMap; + typedef std::unordered_map + LogBufferPidIteratorMap; LogBufferPidIteratorMap mLastWorstPidOfSystem[LOG_ID_MAX]; unsigned long mMaxSize[LOG_ID_MAX]; @@ -106,21 +103,23 @@ class LogBuffer { LogBufferElement* droppedElements[LOG_ID_MAX]; void log(LogBufferElement* elem); -public: - LastLogTimes &mTimes; + public: + LastLogTimes& mTimes; - explicit LogBuffer(LastLogTimes *times); + explicit LogBuffer(LastLogTimes* times); ~LogBuffer(); void init(); - bool isMonotonic() { return monotonic; } + bool isMonotonic() { + return monotonic; + } - int log(log_id_t log_id, log_time realtime, - uid_t uid, pid_t pid, pid_t tid, - const char *msg, unsigned short len); - uint64_t flushTo(SocketClient *writer, const uint64_t start, + int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid, + const char* msg, unsigned short len); + uint64_t flushTo(SocketClient* writer, const uint64_t start, bool privileged, bool security, - int (*filter)(const LogBufferElement *element, void *arg) = NULL, - void *arg = NULL); + int (*filter)(const LogBufferElement* element, + void* arg) = NULL, + void* arg = NULL); bool clear(log_id_t id, uid_t uid = AID_ROOT); unsigned long getSize(log_id_t id); @@ -133,27 +132,42 @@ public: stats.enableStatistics(); } - int initPrune(const char *cp) { return mPrune.init(cp); } - std::string formatPrune() { return mPrune.format(); } + int initPrune(const char* cp) { + return mPrune.init(cp); + } + std::string formatPrune() { + return mPrune.format(); + } - std::string formatGetEventTag(uid_t uid, - const char *name, const char *format) { + std::string formatGetEventTag(uid_t uid, const char* name, + const char* format) { return tags.formatGetEventTag(uid, name, format); } std::string formatEntry(uint32_t tag, uid_t uid) { return tags.formatEntry(tag, uid); } - const char *tagToName(uint32_t tag) { return tags.tagToName(tag); } + const char* tagToName(uint32_t tag) { + return tags.tagToName(tag); + } // helper must be protected directly or implicitly by lock()/unlock() - const char *pidToName(pid_t pid) { return stats.pidToName(pid); } - uid_t pidToUid(pid_t pid) { return stats.pidToUid(pid); } - const char *uidToName(uid_t uid) { return stats.uidToName(uid); } - void lock() { pthread_mutex_lock(&mLogElementsLock); } - void unlock() { pthread_mutex_unlock(&mLogElementsLock); } - -private: + const char* pidToName(pid_t pid) { + return stats.pidToName(pid); + } + uid_t pidToUid(pid_t pid) { + return stats.pidToUid(pid); + } + const char* uidToName(uid_t uid) { + return stats.uidToName(uid); + } + void lock() { + pthread_mutex_lock(&mLogElementsLock); + } + void unlock() { + pthread_mutex_unlock(&mLogElementsLock); + } + private: static constexpr size_t minPrune = 4; static constexpr size_t maxPrune = 256; @@ -163,4 +177,4 @@ private: LogBufferElementCollection::iterator it, bool coalesce = false); }; -#endif // _LOGD_LOG_BUFFER_H__ +#endif // _LOGD_LOG_BUFFER_H__ diff --git a/logd/LogBufferElement.cpp b/logd/LogBufferElement.cpp index a651fd4be..5ba3a1514 100644 --- a/logd/LogBufferElement.cpp +++ b/logd/LogBufferElement.cpp @@ -35,41 +35,41 @@ atomic_int_fast64_t LogBufferElement::sequence(1); LogBufferElement::LogBufferElement(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid, - const char *msg, unsigned short len) : - mUid(uid), - mPid(pid), - mTid(tid), - mSequence(sequence.fetch_add(1, memory_order_relaxed)), - mRealTime(realtime), - mMsgLen(len), - mLogId(log_id) { + const char* msg, unsigned short len) + : mUid(uid), + mPid(pid), + mTid(tid), + mSequence(sequence.fetch_add(1, memory_order_relaxed)), + mRealTime(realtime), + mMsgLen(len), + mLogId(log_id) { mMsg = new char[len]; memcpy(mMsg, msg, len); - mTag = (isBinary() && (mMsgLen >= sizeof(uint32_t))) ? - le32toh(reinterpret_cast(mMsg)->tag) : - 0; + mTag = (isBinary() && (mMsgLen >= sizeof(uint32_t))) + ? le32toh(reinterpret_cast(mMsg)->tag) + : 0; } -LogBufferElement::LogBufferElement(const LogBufferElement &elem) : - mTag(elem.mTag), - mUid(elem.mUid), - mPid(elem.mPid), - mTid(elem.mTid), - mSequence(elem.mSequence), - mRealTime(elem.mRealTime), - mMsgLen(elem.mMsgLen), - mLogId(elem.mLogId) { +LogBufferElement::LogBufferElement(const LogBufferElement& elem) + : mTag(elem.mTag), + mUid(elem.mUid), + mPid(elem.mPid), + mTid(elem.mTid), + mSequence(elem.mSequence), + mRealTime(elem.mRealTime), + mMsgLen(elem.mMsgLen), + mLogId(elem.mLogId) { mMsg = new char[mMsgLen]; memcpy(mMsg, elem.mMsg, mMsgLen); } LogBufferElement::~LogBufferElement() { - delete [] mMsg; + delete[] mMsg; } // caller must own and free character string -char *android::tidToName(pid_t tid) { - char *retval = NULL; +char* android::tidToName(pid_t tid) { + char* retval = NULL; char buffer[256]; snprintf(buffer, sizeof(buffer), "/proc/%u/comm", tid); int fd = open(buffer, O_RDONLY); @@ -89,7 +89,7 @@ char *android::tidToName(pid_t tid) { } // if nothing for comm, check out cmdline - char *name = android::pidToName(tid); + char* name = android::pidToName(tid); if (!retval) { retval = name; name = NULL; @@ -101,8 +101,8 @@ char *android::tidToName(pid_t tid) { size_t retval_len = strlen(retval); size_t name_len = strlen(name); // KISS: ToDo: Only checks prefix truncated, not suffix, or both - if ((retval_len < name_len) - && !fastcmp(retval, name + name_len - retval_len)) { + if ((retval_len < name_len) && + !fastcmp(retval, name + name_len - retval_len)) { free(retval); retval = name; } else { @@ -113,21 +113,20 @@ char *android::tidToName(pid_t tid) { } // assumption: mMsg == NULL -size_t LogBufferElement::populateDroppedMessage(char*& buffer, - LogBuffer* parent, bool lastSame) { +size_t LogBufferElement::populateDroppedMessage(char*& buffer, LogBuffer* parent, + bool lastSame) { static const char tag[] = "chatty"; - if (!__android_log_is_loggable_len(ANDROID_LOG_INFO, - tag, strlen(tag), + if (!__android_log_is_loggable_len(ANDROID_LOG_INFO, tag, strlen(tag), ANDROID_LOG_VERBOSE)) { return 0; } static const char format_uid[] = "uid=%u%s%s %s %u line%s"; parent->lock(); - const char *name = parent->uidToName(mUid); + const char* name = parent->uidToName(mUid); parent->unlock(); - const char *commName = android::tidToName(mTid); + const char* commName = android::tidToName(mTid); if (!commName && (mTid != mPid)) { commName = android::tidToName(mPid); } @@ -140,35 +139,35 @@ size_t LogBufferElement::populateDroppedMessage(char*& buffer, size_t len = strlen(name + 1); if (!strncmp(name + 1, commName + 1, len)) { if (commName[len + 1] == '\0') { - free(const_cast(commName)); + free(const_cast(commName)); commName = NULL; } else { - free(const_cast(name)); + free(const_cast(name)); name = NULL; } } } if (name) { - char *buf = NULL; + char* buf = NULL; asprintf(&buf, "(%s)", name); if (buf) { - free(const_cast(name)); + free(const_cast(name)); name = buf; } } if (commName) { - char *buf = NULL; + char* buf = NULL; asprintf(&buf, " %s", commName); if (buf) { - free(const_cast(commName)); + free(const_cast(commName)); commName = buf; } } // identical to below to calculate the buffer size required const char* type = lastSame ? "identical" : "expire"; size_t len = snprintf(NULL, 0, format_uid, mUid, name ? name : "", - commName ? commName : "", type, - mDropped, (mDropped > 1) ? "s" : ""); + commName ? commName : "", type, mDropped, + (mDropped > 1) ? "s" : ""); size_t hdrLen; if (isBinary()) { @@ -177,17 +176,17 @@ size_t LogBufferElement::populateDroppedMessage(char*& buffer, hdrLen = 1 + sizeof(tag); } - buffer = static_cast(calloc(1, hdrLen + len + 1)); + buffer = static_cast(calloc(1, hdrLen + len + 1)); if (!buffer) { - free(const_cast(name)); - free(const_cast(commName)); + free(const_cast(name)); + free(const_cast(commName)); return 0; } size_t retval = hdrLen + len; if (isBinary()) { - android_log_event_string_t *event = - reinterpret_cast(buffer); + android_log_event_string_t* event = + reinterpret_cast(buffer); event->header.tag = htole32(CHATTY_LOG_TAG); event->type = EVENT_TYPE_STRING; @@ -199,10 +198,10 @@ size_t LogBufferElement::populateDroppedMessage(char*& buffer, } snprintf(buffer + hdrLen, len + 1, format_uid, mUid, name ? name : "", - commName ? commName : "", type, - mDropped, (mDropped > 1) ? "s" : ""); - free(const_cast(name)); - free(const_cast(commName)); + commName ? commName : "", type, mDropped, + (mDropped > 1) ? "s" : ""); + free(const_cast(name)); + free(const_cast(commName)); return retval; } @@ -213,9 +212,8 @@ uint64_t LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent, memset(&entry, 0, sizeof(struct logger_entry_v4)); - entry.hdr_size = privileged ? - sizeof(struct logger_entry_v4) : - sizeof(struct logger_entry_v3); + entry.hdr_size = privileged ? sizeof(struct logger_entry_v4) + : sizeof(struct logger_entry_v3); entry.lid = mLogId; entry.pid = mPid; entry.tid = mTid; @@ -227,13 +225,11 @@ uint64_t LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent, iovec[0].iov_base = &entry; iovec[0].iov_len = entry.hdr_size; - char *buffer = NULL; + char* buffer = NULL; if (!mMsg) { entry.len = populateDroppedMessage(buffer, parent, lastSame); - if (!entry.len) { - return mSequence; - } + if (!entry.len) return mSequence; iovec[1].iov_base = buffer; } else { entry.len = mMsgLen; @@ -243,9 +239,7 @@ uint64_t LogBufferElement::flushTo(SocketClient* reader, LogBuffer* parent, uint64_t retval = reader->sendDatav(iovec, 2) ? FLUSH_ERROR : mSequence; - if (buffer) { - free(buffer); - } + if (buffer) free(buffer); return retval; } diff --git a/logd/LogBufferElement.h b/logd/LogBufferElement.h index bd98b9c4b..43990e835 100644 --- a/logd/LogBufferElement.h +++ b/logd/LogBufferElement.h @@ -26,69 +26,89 @@ class LogBuffer; -#define EXPIRE_HOUR_THRESHOLD 24 // Only expire chatty UID logs to preserve - // non-chatty UIDs less than this age in hours -#define EXPIRE_THRESHOLD 10 // A smaller expire count is considered too - // chatty for the temporal expire messages -#define EXPIRE_RATELIMIT 10 // maximum rate in seconds to report expiration +#define EXPIRE_HOUR_THRESHOLD 24 // Only expire chatty UID logs to preserve + // non-chatty UIDs less than this age in hours +#define EXPIRE_THRESHOLD 10 // A smaller expire count is considered too + // chatty for the temporal expire messages +#define EXPIRE_RATELIMIT 10 // maximum rate in seconds to report expiration class LogBufferElement { - friend LogBuffer; // sized to match reality of incoming log packets - uint32_t mTag; // only valid for isBinary() + uint32_t mTag; // only valid for isBinary() const uint32_t mUid; const uint32_t mPid; const uint32_t mTid; const uint64_t mSequence; log_time mRealTime; - char *mMsg; + char* mMsg; union { - const uint16_t mMsgLen; // mMSg != NULL - uint16_t mDropped; // mMsg == NULL + const uint16_t mMsgLen; // mMSg != NULL + uint16_t mDropped; // mMsg == NULL }; const uint8_t mLogId; static atomic_int_fast64_t sequence; // assumption: mMsg == NULL - size_t populateDroppedMessage(char*& buffer, - LogBuffer* parent, + size_t populateDroppedMessage(char*& buffer, LogBuffer* parent, bool lastSame); -public: - LogBufferElement(log_id_t log_id, log_time realtime, - uid_t uid, pid_t pid, pid_t tid, - const char *msg, unsigned short len); - LogBufferElement(const LogBufferElement &elem); + + public: + LogBufferElement(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, + pid_t tid, const char* msg, unsigned short len); + LogBufferElement(const LogBufferElement& elem); virtual ~LogBufferElement(); bool isBinary(void) const { return (mLogId == LOG_ID_EVENTS) || (mLogId == LOG_ID_SECURITY); } - log_id_t getLogId() const { return static_cast(mLogId); } - uid_t getUid(void) const { return mUid; } - pid_t getPid(void) const { return mPid; } - pid_t getTid(void) const { return mTid; } - uint32_t getTag() const { return mTag; } - unsigned short getDropped(void) const { return mMsg ? 0 : mDropped; } + log_id_t getLogId() const { + return static_cast(mLogId); + } + uid_t getUid(void) const { + return mUid; + } + pid_t getPid(void) const { + return mPid; + } + pid_t getTid(void) const { + return mTid; + } + uint32_t getTag() const { + return mTag; + } + unsigned short getDropped(void) const { + return mMsg ? 0 : mDropped; + } unsigned short setDropped(unsigned short value) { if (mMsg) { - delete [] mMsg; + delete[] mMsg; mMsg = NULL; } return mDropped = value; } - unsigned short getMsgLen() const { return mMsg ? mMsgLen : 0; } - const char* getMsg() const { return mMsg; } - uint64_t getSequence(void) const { return mSequence; } - static uint64_t getCurrentSequence(void) { return sequence.load(memory_order_relaxed); } - log_time getRealTime(void) const { return mRealTime; } + unsigned short getMsgLen() const { + return mMsg ? mMsgLen : 0; + } + const char* getMsg() const { + return mMsg; + } + uint64_t getSequence(void) const { + return mSequence; + } + static uint64_t getCurrentSequence(void) { + return sequence.load(memory_order_relaxed); + } + log_time getRealTime(void) const { + return mRealTime; + } static const uint64_t FLUSH_ERROR; - uint64_t flushTo(SocketClient* writer, LogBuffer* parent, - bool privileged, bool lastSame); + uint64_t flushTo(SocketClient* writer, LogBuffer* parent, bool privileged, + bool lastSame); }; #endif diff --git a/logd/LogCommand.cpp b/logd/LogCommand.cpp index 3b1757656..6d7c0a5dc 100644 --- a/logd/LogCommand.cpp +++ b/logd/LogCommand.cpp @@ -24,7 +24,7 @@ #include "LogCommand.h" #include "LogUtils.h" -LogCommand::LogCommand(const char *cmd) : FrameworkCommand(cmd) { +LogCommand::LogCommand(const char* cmd) : FrameworkCommand(cmd) { } // gets a list of supplementary group IDs associated with @@ -40,8 +40,8 @@ LogCommand::LogCommand(const char *cmd) : FrameworkCommand(cmd) { // has open permissions, and one that has restricted // permissions. -static bool groupIsLog(char *buf) { - char *ptr; +static bool groupIsLog(char* buf) { + char* ptr; static const char ws[] = " \n"; for (buf = strtok_r(buf, ws, &ptr); buf; buf = strtok_r(NULL, ws, &ptr)) { @@ -91,15 +91,14 @@ bool clientHasLogCredentials(uid_t uid, gid_t gid, pid_t pid) { // doubt, but we expect the falses should be reduced significantly as // three times is a charm. // - for (int retry = 3; - !(ret = foundGid && foundUid && foundLog) && retry; - --retry) { - FILE *file = fopen(filename, "r"); + for (int retry = 3; !(ret = foundGid && foundUid && foundLog) && retry; + --retry) { + FILE* file = fopen(filename, "r"); if (!file) { continue; } - char *line = NULL; + char* line = NULL; size_t len = 0; while (getline(&line, &len, file) > 0) { static const char groups_string[] = "Groups:\t"; @@ -111,29 +110,25 @@ bool clientHasLogCredentials(uid_t uid, gid_t gid, pid_t pid) { foundLog = true; } } else if (strncmp(uid_string, line, sizeof(uid_string) - 1) == 0) { - uid_t u[4] = { (uid_t) -1, (uid_t) -1, (uid_t) -1, (uid_t) -1}; + uid_t u[4] = { (uid_t)-1, (uid_t)-1, (uid_t)-1, (uid_t)-1 }; - sscanf(line + sizeof(uid_string) - 1, "%u\t%u\t%u\t%u", - &u[0], &u[1], &u[2], &u[3]); + sscanf(line + sizeof(uid_string) - 1, "%u\t%u\t%u\t%u", &u[0], + &u[1], &u[2], &u[3]); // Protect against PID reuse by checking that UID is the same - if ((uid == u[0]) - && (uid == u[1]) - && (uid == u[2]) - && (uid == u[3])) { + if ((uid == u[0]) && (uid == u[1]) && (uid == u[2]) && + (uid == u[3])) { foundUid = true; } } else if (strncmp(gid_string, line, sizeof(gid_string) - 1) == 0) { - gid_t g[4] = { (gid_t) -1, (gid_t) -1, (gid_t) -1, (gid_t) -1}; + gid_t g[4] = { (gid_t)-1, (gid_t)-1, (gid_t)-1, (gid_t)-1 }; - sscanf(line + sizeof(gid_string) - 1, "%u\t%u\t%u\t%u", - &g[0], &g[1], &g[2], &g[3]); + sscanf(line + sizeof(gid_string) - 1, "%u\t%u\t%u\t%u", &g[0], + &g[1], &g[2], &g[3]); // Protect against PID reuse by checking that GID is the same - if ((gid == g[0]) - && (gid == g[1]) - && (gid == g[2]) - && (gid == g[3])) { + if ((gid == g[0]) && (gid == g[1]) && (gid == g[2]) && + (gid == g[3])) { foundGid = true; } } @@ -145,6 +140,6 @@ bool clientHasLogCredentials(uid_t uid, gid_t gid, pid_t pid) { return ret; } -bool clientHasLogCredentials(SocketClient *cli) { +bool clientHasLogCredentials(SocketClient* cli) { return clientHasLogCredentials(cli->getUid(), cli->getGid(), cli->getPid()); } diff --git a/logd/LogCommand.h b/logd/LogCommand.h index 0adc2a1d7..e10ffa0e6 100644 --- a/logd/LogCommand.h +++ b/logd/LogCommand.h @@ -17,13 +17,14 @@ #ifndef _LOGD_COMMAND_H #define _LOGD_COMMAND_H -#include #include +#include class LogCommand : public FrameworkCommand { -public: - explicit LogCommand(const char *cmd); - virtual ~LogCommand() {} + public: + explicit LogCommand(const char* cmd); + virtual ~LogCommand() { + } }; #endif diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp index f22407929..9ae95f996 100644 --- a/logd/LogKlog.cpp +++ b/logd/LogKlog.cpp @@ -25,25 +25,22 @@ #include #include -#include #include +#include #include "LogBuffer.h" #include "LogKlog.h" #include "LogReader.h" -#define KMSG_PRIORITY(PRI) \ - '<', \ - '0' + (LOG_SYSLOG | (PRI)) / 10, \ - '0' + (LOG_SYSLOG | (PRI)) % 10, \ - '>' +#define KMSG_PRIORITY(PRI) \ + '<', '0' + (LOG_SYSLOG | (PRI)) / 10, '0' + (LOG_SYSLOG | (PRI)) % 10, '>' static const char priority_message[] = { KMSG_PRIORITY(LOG_INFO), '\0' }; // Parsing is hard // called if we see a '<', s is the next character, returns pointer after '>' -static char *is_prio(char *s, size_t len) { +static char* is_prio(char* s, size_t len) { if (!len || !isdigit(*s++)) { return NULL; } @@ -60,7 +57,7 @@ static char *is_prio(char *s, size_t len) { } // called if we see a '[', s is the next character, returns pointer after ']' -static char *is_timestamp(char *s, size_t len) { +static char* is_timestamp(char* s, size_t len) { while (len && (*s == ' ')) { ++s; --len; @@ -83,19 +80,20 @@ static char *is_timestamp(char *s, size_t len) { } // Like strtok_r with "\r\n" except that we look for log signatures (regex) -// \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[] *[0-9]+[.][0-9]+[]] \) +// \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[] +// *[0-9]+[.][0-9]+[]] \) // and split if we see a second one without a newline. // We allow nuls in content, monitoring the overall length and sub-length of // the discovered tokens. -#define SIGNATURE_MASK 0xF0 +#define SIGNATURE_MASK 0xF0 // following ('0' to '9' masked with ~SIGNATURE_MASK) added to signature -#define LESS_THAN_SIG SIGNATURE_MASK -#define OPEN_BRACKET_SIG ((SIGNATURE_MASK << 1) & SIGNATURE_MASK) +#define LESS_THAN_SIG SIGNATURE_MASK +#define OPEN_BRACKET_SIG ((SIGNATURE_MASK << 1) & SIGNATURE_MASK) // space is one more than of 9 #define OPEN_BRACKET_SPACE ((char)(OPEN_BRACKET_SIG | 10)) -char *log_strntok_r(char *s, size_t *len, char **last, size_t *sublen) { +char* log_strntok_r(char* s, size_t* len, char** last, size_t* sublen) { *sublen = 0; if (!*len) { return NULL; @@ -144,32 +142,24 @@ char *log_strntok_r(char *s, size_t *len, char **last, size_t *sublen) { --*len; size_t adjust; switch (c) { - case '\r': - case '\n': - s[-1] = '\0'; - *last = s; - return tok; - - case '<': - peek = is_prio(s, *len); - if (!peek) { - break; - } - if (s != (tok + 1)) { // not first? + case '\r': + case '\n': s[-1] = '\0'; - *s &= ~SIGNATURE_MASK; - *s |= LESS_THAN_SIG; // signature for '<' *last = s; return tok; - } - adjust = peek - s; - if (adjust > *len) { - adjust = *len; - } - *sublen += adjust; - *len -= adjust; - s = peek; - if ((*s == '[') && ((peek = is_timestamp(s + 1, *len - 1)))) { + + case '<': + peek = is_prio(s, *len); + if (!peek) { + break; + } + if (s != (tok + 1)) { // not first? + s[-1] = '\0'; + *s &= ~SIGNATURE_MASK; + *s |= LESS_THAN_SIG; // signature for '<' + *last = s; + return tok; + } adjust = peek - s; if (adjust > *len) { adjust = *len; @@ -177,33 +167,41 @@ char *log_strntok_r(char *s, size_t *len, char **last, size_t *sublen) { *sublen += adjust; *len -= adjust; s = peek; - } - break; - - case '[': - peek = is_timestamp(s, *len); - if (!peek) { - break; - } - if (s != (tok + 1)) { // not first? - s[-1] = '\0'; - if (*s == ' ') { - *s = OPEN_BRACKET_SPACE; - } else { - *s &= ~SIGNATURE_MASK; - *s |= OPEN_BRACKET_SIG; // signature for '[' + if ((*s == '[') && ((peek = is_timestamp(s + 1, *len - 1)))) { + adjust = peek - s; + if (adjust > *len) { + adjust = *len; + } + *sublen += adjust; + *len -= adjust; + s = peek; } - *last = s; - return tok; - } - adjust = peek - s; - if (adjust > *len) { - adjust = *len; - } - *sublen += adjust; - *len -= adjust; - s = peek; - break; + break; + + case '[': + peek = is_timestamp(s, *len); + if (!peek) { + break; + } + if (s != (tok + 1)) { // not first? + s[-1] = '\0'; + if (*s == ' ') { + *s = OPEN_BRACKET_SPACE; + } else { + *s &= ~SIGNATURE_MASK; + *s |= OPEN_BRACKET_SIG; // signature for '[' + } + *last = s; + return tok; + } + adjust = peek - s; + if (adjust > *len) { + adjust = *len; + } + *sublen += adjust; + *len -= adjust; + s = peek; + break; } ++*sublen; } @@ -215,22 +213,23 @@ log_time LogKlog::correction = ? log_time::EPOCH : (log_time(CLOCK_REALTIME) - log_time(CLOCK_MONOTONIC)); -LogKlog::LogKlog(LogBuffer *buf, LogReader *reader, int fdWrite, int fdRead, bool auditd) : - SocketListener(fdRead, false), - logbuf(buf), - reader(reader), - signature(CLOCK_MONOTONIC), - initialized(false), - enableLogging(true), - auditd(auditd) { +LogKlog::LogKlog(LogBuffer* buf, LogReader* reader, int fdWrite, int fdRead, + bool auditd) + : SocketListener(fdRead, false), + logbuf(buf), + reader(reader), + signature(CLOCK_MONOTONIC), + initialized(false), + enableLogging(true), + auditd(auditd) { static const char klogd_message[] = "%slogd.klogd: %" PRIu64 "\n"; char buffer[sizeof(priority_message) + sizeof(klogd_message) + 20 - 4]; snprintf(buffer, sizeof(buffer), klogd_message, priority_message, - signature.nsec()); + signature.nsec()); write(fdWrite, buffer, strlen(buffer)); } -bool LogKlog::onDataAvailable(SocketClient *cli) { +bool LogKlog::onDataAvailable(SocketClient* cli) { if (!initialized) { prctl(PR_SET_NAME, "logd.klogd"); initialized = true; @@ -240,10 +239,11 @@ bool LogKlog::onDataAvailable(SocketClient *cli) { char buffer[LOGGER_ENTRY_MAX_PAYLOAD]; size_t len = 0; - for(;;) { + for (;;) { ssize_t retval = 0; if ((sizeof(buffer) - 1 - len) > 0) { - retval = read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len); + retval = + read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len); } if ((retval == 0) && (len == 0)) { break; @@ -253,12 +253,11 @@ bool LogKlog::onDataAvailable(SocketClient *cli) { } len += retval; bool full = len == (sizeof(buffer) - 1); - char *ep = buffer + len; + char* ep = buffer + len; *ep = '\0'; size_t sublen; - for(char *ptr = NULL, *tok = buffer; - ((tok = log_strntok_r(tok, &len, &ptr, &sublen))); - tok = NULL) { + for (char *ptr = NULL, *tok = buffer; + ((tok = log_strntok_r(tok, &len, &ptr, &sublen))); tok = NULL) { if (((tok + sublen) >= ep) && (retval != 0) && full) { memmove(buffer, tok, sublen); len = sublen; @@ -273,12 +272,10 @@ bool LogKlog::onDataAvailable(SocketClient *cli) { return true; } - -void LogKlog::calculateCorrection(const log_time &monotonic, - const char *real_string, - size_t len) { +void LogKlog::calculateCorrection(const log_time& monotonic, + const char* real_string, size_t len) { log_time real; - const char *ep = real.strptime(real_string, "%Y-%m-%d %H:%M:%S.%09q UTC"); + const char* ep = real.strptime(real_string, "%Y-%m-%d %H:%M:%S.%09q UTC"); if (!ep || (ep > &real_string[len]) || (real > log_time(CLOCK_REALTIME))) { return; } @@ -323,10 +320,9 @@ const char* android::strnstr(const char* s, size_t len, const char* needle) { return s; } -void LogKlog::sniffTime(log_time &now, - const char **buf, size_t len, +void LogKlog::sniffTime(log_time& now, const char** buf, size_t len, bool reverse) { - const char *cp = now.strptime(*buf, "[ %s.%q]"); + const char* cp = now.strptime(*buf, "[ %s.%q]"); if (cp && (cp >= &(*buf)[len])) { cp = NULL; } @@ -346,28 +342,28 @@ void LogKlog::sniffTime(log_time &now, } const char* b; - if (((b = android::strnstr(cp, len, suspendStr))) - && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) { + if (((b = android::strnstr(cp, len, suspendStr))) && + ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) { len -= b - cp; calculateCorrection(now, b, len); - } else if (((b = android::strnstr(cp, len, resumeStr))) - && ((size_t)((b += sizeof(resumeStr) - 1) - cp) < len)) { + } else if (((b = android::strnstr(cp, len, resumeStr))) && + ((size_t)((b += sizeof(resumeStr) - 1) - cp) < len)) { len -= b - cp; calculateCorrection(now, b, len); - } else if (((b = android::strnstr(cp, len, healthd))) - && ((size_t)((b += sizeof(healthd) - 1) - cp) < len) - && ((b = android::strnstr(b, len -= b - cp, battery))) - && ((size_t)((b += sizeof(battery) - 1) - cp) < len)) { + } else if (((b = android::strnstr(cp, len, healthd))) && + ((size_t)((b += sizeof(healthd) - 1) - cp) < len) && + ((b = android::strnstr(b, len -= b - cp, battery))) && + ((size_t)((b += sizeof(battery) - 1) - cp) < len)) { // NB: healthd is roughly 150us late, so we use it instead to // trigger a check for ntp-induced or hardware clock drift. log_time real(CLOCK_REALTIME); log_time mono(CLOCK_MONOTONIC); correction = (real < mono) ? log_time::EPOCH : (real - mono); - } else if (((b = android::strnstr(cp, len, suspendedStr))) - && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) { + } else if (((b = android::strnstr(cp, len, suspendedStr))) && + ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) { len -= b - cp; log_time real; - char *endp; + char* endp; real.tv_sec = strtol(b, &endp, 10); if ((*endp == '.') && ((size_t)(endp - b) < len)) { unsigned long multiplier = NS_PER_SEC; @@ -398,14 +394,11 @@ void LogKlog::sniffTime(log_time &now, } } -pid_t LogKlog::sniffPid(const char **buf, size_t len) { - const char *cp = *buf; +pid_t LogKlog::sniffPid(const char** buf, size_t len) { + const char* cp = *buf; // HTC kernels with modified printk "c0 1648 " - if ((len > 9) && - (cp[0] == 'c') && - isdigit(cp[1]) && - (isdigit(cp[2]) || (cp[2] == ' ')) && - (cp[3] == ' ')) { + if ((len > 9) && (cp[0] == 'c') && isdigit(cp[1]) && + (isdigit(cp[2]) || (cp[2] == ' ')) && (cp[3] == ' ')) { bool gotDigit = false; int i; for (i = 4; i < 9; ++i) { @@ -419,7 +412,7 @@ pid_t LogKlog::sniffPid(const char **buf, size_t len) { int pid = 0; char dummy; if (sscanf(cp + 4, "%d%c", &pid, &dummy) == 2) { - *buf = cp + 10; // skip-it-all + *buf = cp + 10; // skip-it-all return pid; } } @@ -432,7 +425,7 @@ pid_t LogKlog::sniffPid(const char **buf, size_t len) { if (sscanf(cp, "[%d:%*[a-z_./0-9:A-Z]]%c", &pid, &dummy) == 2) { return pid; } - break; // Only the first one + break; // Only the first one } ++cp; --len; @@ -441,12 +434,12 @@ pid_t LogKlog::sniffPid(const char **buf, size_t len) { } // kernel log prefix, convert to a kernel log priority number -static int parseKernelPrio(const char **buf, size_t len) { +static int parseKernelPrio(const char** buf, size_t len) { int pri = LOG_USER | LOG_INFO; - const char *cp = *buf; + const char* cp = *buf; if (len && (*cp == '<')) { pri = 0; - while(--len && isdigit(*++cp)) { + while (--len && isdigit(*++cp)) { pri = (pri * 10) + *cp - '0'; } if (len && (*cp == '>')) { @@ -502,42 +495,42 @@ void LogKlog::synchronize(const char* buf, size_t len) { // Convert kernel log priority number into an Android Logger priority number static int convertKernelPrioToAndroidPrio(int pri) { - switch(pri & LOG_PRIMASK) { - case LOG_EMERG: + switch (pri & LOG_PRIMASK) { + case LOG_EMERG: // FALLTHRU - case LOG_ALERT: + case LOG_ALERT: // FALLTHRU - case LOG_CRIT: - return ANDROID_LOG_FATAL; + case LOG_CRIT: + return ANDROID_LOG_FATAL; - case LOG_ERR: - return ANDROID_LOG_ERROR; + case LOG_ERR: + return ANDROID_LOG_ERROR; - case LOG_WARNING: - return ANDROID_LOG_WARN; + case LOG_WARNING: + return ANDROID_LOG_WARN; - default: + default: // FALLTHRU - case LOG_NOTICE: + case LOG_NOTICE: // FALLTHRU - case LOG_INFO: - break; + case LOG_INFO: + break; - case LOG_DEBUG: - return ANDROID_LOG_DEBUG; + case LOG_DEBUG: + return ANDROID_LOG_DEBUG; } return ANDROID_LOG_INFO; } -static const char *strnrchr(const char *s, size_t len, char c) { - const char *save = NULL; - for (;len; ++s, len--) { - if (*s == c) { - save = s; +static const char* strnrchr(const char* s, size_t len, char c) { + const char* save = NULL; + for (; len; ++s, len--) { + if (*s == c) { + save = s; + } } - } - return save; + return save; } // @@ -621,38 +614,41 @@ int LogKlog::log(const char* buf, size_t len) { while ((p < &buf[len]) && (isspace(*p) || !*p)) { ++p; } - if (p >= &buf[len]) { // timestamp, no content + if (p >= &buf[len]) { // timestamp, no content return 0; } start = p; - const char *tag = ""; - const char *etag = tag; + const char* tag = ""; + const char* etag = tag; size_t taglen = len - (p - buf); - const char *bt = p; + const char* bt = p; static const char infoBrace[] = "[INFO]"; static const size_t infoBraceLen = strlen(infoBrace); - if ((taglen >= infoBraceLen) && !fastcmp(p, infoBrace, infoBraceLen)) { + if ((taglen >= infoBraceLen) && + !fastcmp(p, infoBrace, infoBraceLen)) { // [