diff --git a/.clang-format b/.clang-format index 039559d63..95efed137 100644 --- a/.clang-format +++ b/.clang-format @@ -84,7 +84,7 @@ IncludeIsMainRegex: '([-_](test|unittest))?$' IncludeIsMainSourceRegex: '' IndentCaseLabels: true IndentGotoLabels: true -IndentPPDirectives: None +IndentPPDirectives: AfterHash IndentWidth: 2 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave diff --git a/src/base/commandlineflags.h b/src/base/commandlineflags.h index e6ffd48e3..3d31a861f 100644 --- a/src/base/commandlineflags.h +++ b/src/base/commandlineflags.h @@ -48,63 +48,64 @@ #ifndef BASE_COMMANDLINEFLAGS_H__ #define BASE_COMMANDLINEFLAGS_H__ -#include "config.h" -#include // for getenv -#include // for memchr +#include // for getenv +#include // for memchr #include +#include "config.h" + #ifdef GLOG_USE_GFLAGS -#include +# include #else -#include "glog/logging.h" +# include "glog/logging.h" -#define DECLARE_VARIABLE(type, shorttype, name, tn) \ - namespace fL##shorttype { \ - extern GLOG_EXPORT type FLAGS_##name; \ - } \ - using fL##shorttype::FLAGS_##name -#define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \ - namespace fL##shorttype { \ - GLOG_EXPORT type FLAGS_##name(value); \ - char FLAGS_no##name; \ - } \ - using fL##shorttype::FLAGS_##name +# define DECLARE_VARIABLE(type, shorttype, name, tn) \ + namespace fL##shorttype { \ + extern GLOG_EXPORT type FLAGS_##name; \ + } \ + using fL##shorttype::FLAGS_##name +# define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \ + namespace fL##shorttype { \ + GLOG_EXPORT type FLAGS_##name(value); \ + char FLAGS_no##name; \ + } \ + using fL##shorttype::FLAGS_##name // bool specialization -#define DECLARE_bool(name) \ - DECLARE_VARIABLE(bool, B, name, bool) -#define DEFINE_bool(name, value, meaning) \ - DEFINE_VARIABLE(bool, B, name, value, meaning, bool) +# define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name, bool) +# define DEFINE_bool(name, value, meaning) \ + DEFINE_VARIABLE(bool, B, name, value, meaning, bool) // int32 specialization -#define DECLARE_int32(name) DECLARE_VARIABLE(google::int32, I, name, int32) -#define DEFINE_int32(name, value, meaning) \ - DEFINE_VARIABLE(google::int32, I, name, value, meaning, int32) +# define DECLARE_int32(name) DECLARE_VARIABLE(google::int32, I, name, int32) +# define DEFINE_int32(name, value, meaning) \ + DEFINE_VARIABLE(google::int32, I, name, value, meaning, int32) // uint32 specialization -#ifndef DECLARE_uint32 -#define DECLARE_uint32(name) DECLARE_VARIABLE(google::uint32, U, name, uint32) -#endif // DECLARE_uint64 -#define DEFINE_uint32(name, value, meaning) \ - DEFINE_VARIABLE(google::uint32, U, name, value, meaning, uint32) +# ifndef DECLARE_uint32 +# define DECLARE_uint32(name) \ + DECLARE_VARIABLE(google::uint32, U, name, uint32) +# endif // DECLARE_uint64 +# define DEFINE_uint32(name, value, meaning) \ + DEFINE_VARIABLE(google::uint32, U, name, value, meaning, uint32) // Special case for string, because we have to specify the namespace // std::string, which doesn't play nicely with our FLAG__namespace hackery. -#define DECLARE_string(name) \ - namespace fLS { \ - extern GLOG_EXPORT std::string& FLAGS_##name; \ - } \ - using fLS::FLAGS_##name -#define DEFINE_string(name, value, meaning) \ - namespace fLS { \ - std::string FLAGS_##name##_buf(value); \ - GLOG_EXPORT std::string& FLAGS_##name = FLAGS_##name##_buf; \ - char FLAGS_no##name; \ - } \ - using fLS::FLAGS_##name +# define DECLARE_string(name) \ + namespace fLS { \ + extern GLOG_EXPORT std::string& FLAGS_##name; \ + } \ + using fLS::FLAGS_##name +# define DEFINE_string(name, value, meaning) \ + namespace fLS { \ + std::string FLAGS_##name##_buf(value); \ + GLOG_EXPORT std::string& FLAGS_##name = FLAGS_##name##_buf; \ + char FLAGS_no##name; \ + } \ + using fLS::FLAGS_##name #endif // GLOG_USE_GFLAGS @@ -130,8 +131,7 @@ // These macros (could be functions, but I don't want to bother with a .cc // file), make it easier to initialize flags from the environment. -#define EnvToString(envname, dflt) \ - (!getenv(envname) ? (dflt) : getenv(envname)) +#define EnvToString(envname, dflt) (!getenv(envname) ? (dflt) : getenv(envname)) #define EnvToBool(envname, dflt) \ (!getenv(envname) ? (dflt) \ diff --git a/src/base/googleinit.h b/src/base/googleinit.h index b5f4436a5..bf569b804 100644 --- a/src/base/googleinit.h +++ b/src/base/googleinit.h @@ -1,10 +1,10 @@ // Copyright (c) 2008, Google Inc. // All rights reserved. -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: -// +// // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above @@ -14,7 +14,7 @@ // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -36,16 +36,14 @@ class GoogleInitializer { public: using void_function = void (*)(); - GoogleInitializer(const char*, void_function f) { - f(); - } + GoogleInitializer(const char*, void_function f) { f(); } }; -#define REGISTER_MODULE_INITIALIZER(name, body) \ - namespace { \ - static void google_init_module_##name () { body; } \ - GoogleInitializer google_initializer_module_##name(#name, \ - google_init_module_##name); \ +#define REGISTER_MODULE_INITIALIZER(name, body) \ + namespace { \ + static void google_init_module_##name() { body; } \ + GoogleInitializer google_initializer_module_##name( \ + #name, google_init_module_##name); \ } #endif /* _GOOGLEINIT_H */ diff --git a/src/base/mutex.h b/src/base/mutex.h index 6d10df1f4..0eadca088 100644 --- a/src/base/mutex.h +++ b/src/base/mutex.h @@ -102,55 +102,56 @@ #ifndef GOOGLE_MUTEX_H_ #define GOOGLE_MUTEX_H_ -#include "config.h" // to figure out pthreads support +#include "config.h" // to figure out pthreads support #if defined(NO_THREADS) - typedef int MutexType; // to keep a lock-count +typedef int MutexType; // to keep a lock-count #elif defined(_WIN32) || defined(__CYGWIN__) -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN // We only need minimal includes -# endif -# ifdef GMUTEX_TRYLOCK - // We need Windows NT or later for TryEnterCriticalSection(). If you - // don't need that functionality, you can remove these _WIN32_WINNT - // lines, and change TryLock() to assert(0) or something. -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0400 -# endif -# endif +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN // We only need minimal includes +# endif +# ifdef GMUTEX_TRYLOCK +// We need Windows NT or later for TryEnterCriticalSection(). If you +// don't need that functionality, you can remove these _WIN32_WINNT +// lines, and change TryLock() to assert(0) or something. +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0400 +# endif +# endif // To avoid macro definition of ERROR. -# ifndef NOGDI -# define NOGDI -# endif +# ifndef NOGDI +# define NOGDI +# endif // To avoid macro definition of min/max. -# ifndef NOMINMAX -# define NOMINMAX -# endif -# include - typedef CRITICAL_SECTION MutexType; +# ifndef NOMINMAX +# define NOMINMAX +# endif +# include +typedef CRITICAL_SECTION MutexType; #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) - // Needed for pthread_rwlock_*. If it causes problems, you could take it - // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it - // *does* cause problems for FreeBSD, or MacOSX, but isn't needed - // for locking there.) -# ifdef __linux__ -# ifndef _XOPEN_SOURCE // Some other header might have already set it for us. -# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls -# endif -# endif -# include +// Needed for pthread_rwlock_*. If it causes problems, you could take it +// out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it +// *does* cause problems for FreeBSD, or MacOSX, but isn't needed +// for locking there.) +# ifdef __linux__ +# ifndef _XOPEN_SOURCE // Some other header might have already set it for + // us. +# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls +# endif +# endif +# include using MutexType = pthread_rwlock_t; #elif defined(HAVE_PTHREAD) -# include - typedef pthread_mutex_t MutexType; +# include +typedef pthread_mutex_t MutexType; #else -# error Need to implement mutex.h for your architecture, or #define NO_THREADS +# error Need to implement mutex.h for your architecture, or #define NO_THREADS #endif // We need to include these header files after defining _XOPEN_SOURCE // as they may define the _XOPEN_SOURCE macro. #include -#include // for abort() +#include // for abort() #define MUTEX_NAMESPACE glog_internal_namespace_ @@ -170,16 +171,16 @@ class Mutex { inline void Lock(); // Block if needed until free then acquire exclusively inline void Unlock(); // Release a lock acquired via Lock() #ifdef GMUTEX_TRYLOCK - inline bool TryLock(); // If free, Lock() and return true, else return false + inline bool TryLock(); // If free, Lock() and return true, else return false #endif // Note that on systems that don't support read-write locks, these may // be implemented as synonyms to Lock() and Unlock(). So you can use // these for efficiency, but don't use them anyplace where being able // to do shared reads is necessary to avoid deadlock. - inline void ReaderLock(); // Block until free or shared then acquire a share - inline void ReaderUnlock(); // Release a read share of this Mutex - inline void WriterLock() { Lock(); } // Acquire an exclusive lock - inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() + inline void ReaderLock(); // Block until free or shared then acquire a share + inline void ReaderUnlock(); // Release a read share of this Mutex + inline void WriterLock() { Lock(); } // Acquire an exclusive lock + inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() // TODO(hamaji): Do nothing, implement correctly. inline void AssertHeld() {} @@ -213,71 +214,86 @@ class Mutex { // we do nothing, for efficiency. That's why everything is in an // assert. -Mutex::Mutex() : mutex_(0) { } -Mutex::~Mutex() { assert(mutex_ == 0); } -void Mutex::Lock() { assert(--mutex_ == -1); } -void Mutex::Unlock() { assert(mutex_++ == -1); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } -#endif -void Mutex::ReaderLock() { assert(++mutex_ > 0); } +Mutex::Mutex() : mutex_(0) {} +Mutex::~Mutex() { assert(mutex_ == 0); } +void Mutex::Lock() { assert(--mutex_ == -1); } +void Mutex::Unlock() { assert(mutex_++ == -1); } +# ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { + if (mutex_) return false; + Lock(); + return true; +} +# endif +void Mutex::ReaderLock() { assert(++mutex_ > 0); } void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } #elif defined(_WIN32) || defined(__CYGWIN__) -Mutex::Mutex() { InitializeCriticalSection(&mutex_); SetIsSafe(); } -Mutex::~Mutex() { DeleteCriticalSection(&mutex_); } -void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); } -void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { return is_safe_ ? - TryEnterCriticalSection(&mutex_) != 0 : true; } -#endif -void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks +Mutex::Mutex() { + InitializeCriticalSection(&mutex_); + SetIsSafe(); +} +Mutex::~Mutex() { DeleteCriticalSection(&mutex_); } +void Mutex::Lock() { + if (is_safe_) EnterCriticalSection(&mutex_); +} +void Mutex::Unlock() { + if (is_safe_) LeaveCriticalSection(&mutex_); +} +# ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { + return is_safe_ ? TryEnterCriticalSection(&mutex_) != 0 : true; +} +# endif +void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks void Mutex::ReaderUnlock() { Unlock(); } #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) -#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ - if (is_safe_ && fncall(&mutex_) != 0) abort(); \ -} while (0) +# define SAFE_PTHREAD(fncall) \ + do { /* run fncall if is_safe_ is true */ \ + if (is_safe_ && fncall(&mutex_) != 0) abort(); \ + } while (0) Mutex::Mutex() { SetIsSafe(); if (is_safe_ && pthread_rwlock_init(&mutex_, nullptr) != 0) abort(); } -Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); } -void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } -void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { return is_safe_ ? - pthread_rwlock_trywrlock(&mutex_) == 0 : - true; } -#endif -void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } +Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); } +void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } +void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } +# ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { + return is_safe_ ? pthread_rwlock_trywrlock(&mutex_) == 0 : true; +} +# endif +void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } -#undef SAFE_PTHREAD +# undef SAFE_PTHREAD #elif defined(HAVE_PTHREAD) -#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ - if (is_safe_ && fncall(&mutex_) != 0) abort(); \ -} while (0) +# define SAFE_PTHREAD(fncall) \ + do { /* run fncall if is_safe_ is true */ \ + if (is_safe_ && fncall(&mutex_) != 0) abort(); \ + } while (0) -Mutex::Mutex() { +Mutex::Mutex() { SetIsSafe(); if (is_safe_ && pthread_mutex_init(&mutex_, nullptr) != 0) abort(); } -Mutex::~Mutex() { SAFE_PTHREAD(pthread_mutex_destroy); } -void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } -void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { return is_safe_ ? - pthread_mutex_trylock(&mutex_) == 0 : true; } -#endif -void Mutex::ReaderLock() { Lock(); } +Mutex::~Mutex() { SAFE_PTHREAD(pthread_mutex_destroy); } +void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } +void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } +# ifdef GMUTEX_TRYLOCK +bool Mutex::TryLock() { + return is_safe_ ? pthread_mutex_trylock(&mutex_) == 0 : true; +} +# endif +void Mutex::ReaderLock() { Lock(); } void Mutex::ReaderUnlock() { Unlock(); } -#undef SAFE_PTHREAD +# undef SAFE_PTHREAD #endif @@ -289,8 +305,9 @@ class MutexLock { public: explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } ~MutexLock() { mu_->Unlock(); } + private: - Mutex * const mu_; + Mutex *const mu_; // Disallow "evil" constructors MutexLock(const MutexLock &) = delete; void operator=(const MutexLock &) = delete; @@ -301,8 +318,9 @@ class ReaderMutexLock { public: explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } ~ReaderMutexLock() { mu_->ReaderUnlock(); } + private: - Mutex * const mu_; + Mutex *const mu_; // Disallow "evil" constructors ReaderMutexLock(const ReaderMutexLock &) = delete; void operator=(const ReaderMutexLock &) = delete; @@ -312,8 +330,9 @@ class WriterMutexLock { public: explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } ~WriterMutexLock() { mu_->WriterUnlock(); } + private: - Mutex * const mu_; + Mutex *const mu_; // Disallow "evil" constructors WriterMutexLock(const WriterMutexLock &) = delete; void operator=(const WriterMutexLock &) = delete; @@ -330,4 +349,4 @@ using namespace MUTEX_NAMESPACE; #undef MUTEX_NAMESPACE -#endif /* #define GOOGLE_MUTEX_H__ */ +#endif /* #define GOOGLE_MUTEX_H__ */ diff --git a/src/cleanup_immediately_unittest.cc b/src/cleanup_immediately_unittest.cc index 9d2823db9..83b765b23 100644 --- a/src/cleanup_immediately_unittest.cc +++ b/src/cleanup_immediately_unittest.cc @@ -33,14 +33,14 @@ #include "googletest.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif #ifdef HAVE_LIB_GMOCK -#include +# include -#include "mock-log.h" +# include "mock-log.h" // Introduce several symbols from gmock. using google::glog_testing::ScopedMockLog; using testing::_; diff --git a/src/cleanup_with_absolute_prefix_unittest.cc b/src/cleanup_with_absolute_prefix_unittest.cc index 69b62d8f4..e262579b1 100644 --- a/src/cleanup_with_absolute_prefix_unittest.cc +++ b/src/cleanup_with_absolute_prefix_unittest.cc @@ -33,14 +33,14 @@ #include "googletest.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif #ifdef HAVE_LIB_GMOCK -#include +# include -#include "mock-log.h" +# include "mock-log.h" // Introduce several symbols from gmock. using google::glog_testing::ScopedMockLog; using testing::_; diff --git a/src/cleanup_with_relative_prefix_unittest.cc b/src/cleanup_with_relative_prefix_unittest.cc index 70c3b537d..3195f85b3 100644 --- a/src/cleanup_with_relative_prefix_unittest.cc +++ b/src/cleanup_with_relative_prefix_unittest.cc @@ -33,14 +33,14 @@ #include "googletest.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif #ifdef HAVE_LIB_GMOCK -#include +# include -#include "mock-log.h" +# include "mock-log.h" // Introduce several symbols from gmock. using google::glog_testing::ScopedMockLog; using testing::_; diff --git a/src/demangle.cc b/src/demangle.cc index 1c619344d..bcac5de85 100644 --- a/src/demangle.cc +++ b/src/demangle.cc @@ -43,7 +43,7 @@ #include "utilities.h" #if defined(GLOG_OS_WINDOWS) -#include +# include #endif namespace google { @@ -140,15 +140,14 @@ static bool AtLeastNumCharsRemaining(const char *str, ssize_t n) { // Returns true if "str" has "prefix" as a prefix. static bool StrPrefix(const char *str, const char *prefix) { size_t i = 0; - while (str[i] != '\0' && prefix[i] != '\0' && - str[i] == prefix[i]) { + while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) { ++i; } return prefix[i] == '\0'; // Consumed everything in "prefix". } -static void InitState(State *state, const char *mangled, - char *out, size_t out_size) { +static void InitState(State *state, const char *mangled, char *out, + size_t out_size) { state->mangled_cur = mangled; state->out_cur = out; state->out_begin = out; @@ -200,9 +199,7 @@ static bool ParseCharClass(State *state, const char *char_class) { } // This function is used for handling an optional non-terminal. -static bool Optional(bool) { - return true; -} +static bool Optional(bool) { return true; } // This function is used for handling + syntax. using ParseFunc = bool (*)(State *); @@ -228,7 +225,7 @@ static bool ZeroOrMore(ParseFunc parse_func, State *state) { // Append "str" at "out_cur". If there is an overflow, "overflowed" // is set to true for later use. The output string is ensured to // always terminate with '\0' as long as there is no overflow. -static void Append(State *state, const char * const str, ssize_t length) { +static void Append(State *state, const char *const str, ssize_t length) { if (state->out_cur == nullptr) { state->overflowed = true; return; @@ -248,17 +245,13 @@ static void Append(State *state, const char * const str, ssize_t length) { } // We don't use equivalents in libc to avoid locale issues. -static bool IsLower(char c) { - return c >= 'a' && c <= 'z'; -} +static bool IsLower(char c) { return c >= 'a' && c <= 'z'; } static bool IsAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } -static bool IsDigit(char c) { - return c >= '0' && c <= '9'; -} +static bool IsDigit(char c) { return c >= '0' && c <= '9'; } // Returns true if "str" is a function clone suffix. These suffixes are used // by GCC 4.5.x and later versions to indicate functions which have been @@ -288,12 +281,12 @@ static bool IsFunctionCloneSuffix(const char *str) { // Append "str" with some tweaks, iff "append" state is true. // Returns true so that it can be placed in "if" conditions. -static void MaybeAppendWithLength(State *state, const char * const str, +static void MaybeAppendWithLength(State *state, const char *const str, ssize_t length) { if (state->append && length > 0) { // Append a space if the output buffer ends with '<' and "str" // starts with '<' to avoid <<<. - if (str[0] == '<' && state->out_begin < state->out_cur && + if (str[0] == '<' && state->out_begin < state->out_cur && state->out_cur[-1] == '<') { Append(state, " ", 1); } @@ -307,7 +300,7 @@ static void MaybeAppendWithLength(State *state, const char * const str, } // A convenient wrapper around MaybeAppendWithLength(). -static bool MaybeAppend(State *state, const char * const str) { +static bool MaybeAppend(State *state, const char *const str) { if (state->append) { size_t length = StrLen(str); MaybeAppendWithLength(state, str, static_cast(length)); @@ -473,8 +466,7 @@ static bool ParseName(State *state) { } State copy = *state; - if (ParseUnscopedTemplateName(state) && - ParseTemplateArgs(state)) { + if (ParseUnscopedTemplateName(state) && ParseTemplateArgs(state)) { return true; } *state = copy; @@ -494,8 +486,7 @@ static bool ParseUnscopedName(State *state) { } State copy = *state; - if (ParseTwoCharToken(state, "St") && - MaybeAppend(state, "std::") && + if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") && ParseUnqualifiedName(state)) { return true; } @@ -513,10 +504,8 @@ static bool ParseUnscopedTemplateName(State *state) { // ::= N [] E static bool ParseNestedName(State *state) { State copy = *state; - if (ParseOneCharToken(state, 'N') && - EnterNestedName(state) && - Optional(ParseCVQualifiers(state)) && - ParsePrefix(state) && + if (ParseOneCharToken(state, 'N') && EnterNestedName(state) && + Optional(ParseCVQualifiers(state)) && ParsePrefix(state) && LeaveNestedName(state, copy.nest_level) && ParseOneCharToken(state, 'E')) { return true; @@ -540,8 +529,7 @@ static bool ParsePrefix(State *state) { bool has_something = false; while (true) { MaybeAppendSeparator(state); - if (ParseTemplateParam(state) || - ParseSubstitution(state) || + if (ParseTemplateParam(state) || ParseSubstitution(state) || ParseUnscopedName(state)) { has_something = true; MaybeIncreaseNestLevel(state); @@ -562,8 +550,7 @@ static bool ParsePrefix(State *state) { // ::= [] // ::= [] static bool ParseUnqualifiedName(State *state) { - return (ParseOperatorName(state) || - ParseCtorDtorName(state) || + return (ParseOperatorName(state) || ParseCtorDtorName(state) || (ParseSourceName(state) && Optional(ParseAbiTags(state))) || (ParseLocalSourceName(state) && Optional(ParseAbiTags(state)))); } @@ -605,7 +592,7 @@ static bool ParseNumber(State *state, int *number_out) { const char *p = state->mangled_cur; int number = 0; constexpr int int_max_by_10 = std::numeric_limits::max() / 10; - for (;*p != '\0'; ++p) { + for (; *p != '\0'; ++p) { if (IsDigit(*p)) { // Prevent signed integer overflow when multiplying if (number > int_max_by_10) { @@ -639,7 +626,7 @@ static bool ParseNumber(State *state, int *number_out) { // hexadecimal string. static bool ParseFloatNumber(State *state) { const char *p = state->mangled_cur; - for (;*p != '\0'; ++p) { + for (; *p != '\0'; ++p) { if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) { break; } @@ -655,7 +642,7 @@ static bool ParseFloatNumber(State *state) { // using digits and upper case letters static bool ParseSeqId(State *state) { const char *p = state->mangled_cur; - for (;*p != '\0'; ++p) { + for (; *p != '\0'; ++p) { if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) { break; } @@ -669,8 +656,7 @@ static bool ParseSeqId(State *state) { // ::= (of given length) static bool ParseIdentifier(State *state, ssize_t length) { - if (length == -1 || - !AtLeastNumCharsRemaining(state->mangled_cur, length)) { + if (length == -1 || !AtLeastNumCharsRemaining(state->mangled_cur, length)) { return false; } if (IdentifierIsAnonymousNamespace(state, length)) { @@ -712,10 +698,8 @@ static bool ParseOperatorName(State *state) { } // First check with "cv" (cast) case. State copy = *state; - if (ParseTwoCharToken(state, "cv") && - MaybeAppend(state, "operator ") && - EnterNestedName(state) && - ParseType(state) && + if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") && + EnterNestedName(state) && ParseType(state) && LeaveNestedName(state, copy.nest_level)) { return true; } @@ -730,8 +714,7 @@ static bool ParseOperatorName(State *state) { // Other operator names should start with a lower alphabet followed // by a lower/upper alphabet. - if (!(IsLower(state->mangled_cur[0]) && - IsAlpha(state->mangled_cur[1]))) { + if (!(IsLower(state->mangled_cur[0]) && IsAlpha(state->mangled_cur[1]))) { return false; } // We may want to perform a binary search if we really need speed. @@ -771,8 +754,7 @@ static bool ParseOperatorName(State *state) { // stack traces. The are special data. static bool ParseSpecialName(State *state) { State copy = *state; - if (ParseOneCharToken(state, 'T') && - ParseCharClass(state, "VTIS") && + if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTIS") && ParseType(state)) { return true; } @@ -784,8 +766,7 @@ static bool ParseSpecialName(State *state) { } *state = copy; - if (ParseTwoCharToken(state, "GV") && - ParseName(state)) { + if (ParseTwoCharToken(state, "GV") && ParseName(state)) { return true; } *state = copy; @@ -833,14 +814,14 @@ static bool ParseSpecialName(State *state) { // ::= v _ static bool ParseCallOffset(State *state) { State copy = *state; - if (ParseOneCharToken(state, 'h') && - ParseNVOffset(state) && ParseOneCharToken(state, '_')) { + if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) && + ParseOneCharToken(state, '_')) { return true; } *state = copy; - if (ParseOneCharToken(state, 'v') && - ParseVOffset(state) && ParseOneCharToken(state, '_')) { + if (ParseOneCharToken(state, 'v') && ParseVOffset(state) && + ParseOneCharToken(state, '_')) { return true; } *state = copy; @@ -866,18 +847,16 @@ static bool ParseVOffset(State *state) { // ::= D0 | D1 | D2 static bool ParseCtorDtorName(State *state) { State copy = *state; - if (ParseOneCharToken(state, 'C') && - ParseCharClass(state, "123")) { - const char * const prev_name = state->prev_name; + if (ParseOneCharToken(state, 'C') && ParseCharClass(state, "123")) { + const char *const prev_name = state->prev_name; const ssize_t prev_name_length = state->prev_name_length; MaybeAppendWithLength(state, prev_name, prev_name_length); return true; } *state = copy; - if (ParseOneCharToken(state, 'D') && - ParseCharClass(state, "012")) { - const char * const prev_name = state->prev_name; + if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "012")) { + const char *const prev_name = state->prev_name; const ssize_t prev_name_length = state->prev_name_length; MaybeAppend(state, "~"); MaybeAppendWithLength(state, prev_name, prev_name_length); @@ -937,17 +916,13 @@ static bool ParseType(State *state) { } *state = copy; - if (ParseBuiltinType(state) || - ParseFunctionType(state) || - ParseClassEnumType(state) || - ParseArrayType(state) || - ParsePointerToMemberType(state) || - ParseSubstitution(state)) { + if (ParseBuiltinType(state) || ParseFunctionType(state) || + ParseClassEnumType(state) || ParseArrayType(state) || + ParsePointerToMemberType(state) || ParseSubstitution(state)) { return true; } - if (ParseTemplateTemplateParam(state) && - ParseTemplateArgs(state)) { + if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) { return true; } *state = copy; @@ -995,8 +970,8 @@ static bool ParseBuiltinType(State *state) { static bool ParseFunctionType(State *state) { State copy = *state; if (ParseOneCharToken(state, 'F') && - Optional(ParseOneCharToken(state, 'Y')) && - ParseBareFunctionType(state) && ParseOneCharToken(state, 'E')) { + Optional(ParseOneCharToken(state, 'Y')) && ParseBareFunctionType(state) && + ParseOneCharToken(state, 'E')) { return true; } *state = copy; @@ -1017,9 +992,7 @@ static bool ParseBareFunctionType(State *state) { } // ::= -static bool ParseClassEnumType(State *state) { - return ParseName(state); -} +static bool ParseClassEnumType(State *state) { return ParseName(state); } // ::= A <(positive dimension) number> _ <(element) type> // ::= A [<(dimension) expression>] _ <(element) type> @@ -1042,8 +1015,7 @@ static bool ParseArrayType(State *state) { // ::= M <(class) type> <(member) type> static bool ParsePointerToMemberType(State *state) { State copy = *state; - if (ParseOneCharToken(state, 'M') && ParseType(state) && - ParseType(state)) { + if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) { return true; } *state = copy; @@ -1068,20 +1040,17 @@ static bool ParseTemplateParam(State *state) { return false; } - // ::= // ::= static bool ParseTemplateTemplateParam(State *state) { - return (ParseTemplateParam(state) || - ParseSubstitution(state)); + return (ParseTemplateParam(state) || ParseSubstitution(state)); } // ::= I + E static bool ParseTemplateArgs(State *state) { State copy = *state; DisableAppend(state); - if (ParseOneCharToken(state, 'I') && - OneOrMore(ParseTemplateArg, state) && + if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) { RestoreAppend(state, copy.append); MaybeAppend(state, "<>"); @@ -1107,15 +1076,13 @@ static bool ParseTemplateArg(State *state) { State copy = *state; if ((ParseOneCharToken(state, 'I') || ParseOneCharToken(state, 'J')) && - ZeroOrMore(ParseTemplateArg, state) && - ParseOneCharToken(state, 'E')) { + ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) { --state->arg_level; return true; } *state = copy; - if (ParseType(state) || - ParseExprPrimary(state)) { + if (ParseType(state) || ParseExprPrimary(state)) { --state->arg_level; return true; } @@ -1153,25 +1120,21 @@ static bool ParseExpression(State *state) { ++state->expr_level; State copy = *state; - if (ParseOperatorName(state) && - ParseExpression(state) && - ParseExpression(state) && - ParseExpression(state)) { + if (ParseOperatorName(state) && ParseExpression(state) && + ParseExpression(state) && ParseExpression(state)) { --state->expr_level; return true; } *state = copy; - if (ParseOperatorName(state) && - ParseExpression(state) && + if (ParseOperatorName(state) && ParseExpression(state) && ParseExpression(state)) { --state->expr_level; return true; } *state = copy; - if (ParseOperatorName(state) && - ParseExpression(state)) { + if (ParseOperatorName(state) && ParseExpression(state)) { --state->expr_level; return true; } @@ -1184,8 +1147,7 @@ static bool ParseExpression(State *state) { *state = copy; if (ParseTwoCharToken(state, "sr") && ParseType(state) && - ParseUnqualifiedName(state) && - ParseTemplateArgs(state)) { + ParseUnqualifiedName(state) && ParseTemplateArgs(state)) { --state->expr_level; return true; } @@ -1214,8 +1176,7 @@ static bool ParseExprPrimary(State *state) { *state = copy; if (ParseOneCharToken(state, 'L') && ParseType(state) && - ParseFloatNumber(state) && - ParseOneCharToken(state, 'E')) { + ParseFloatNumber(state) && ParseOneCharToken(state, 'E')) { return true; } *state = copy; @@ -1336,7 +1297,7 @@ static bool ParseTopLevelMangledName(State *state) { // The demangler entry point. bool Demangle(const char *mangled, char *out, size_t out_size) { #if defined(GLOG_OS_WINDOWS) -#if defined(HAVE_DBGHELP) +# if defined(HAVE_DBGHELP) // When built with incremental linking, the Windows debugger // library provides a more complicated `Symbol->Name` with the // Incremental Linking Table offset, which looks like @@ -1355,15 +1316,15 @@ bool Demangle(const char *mangled, char *out, size_t out_size) { strncpy(buffer, lparen + 1, length); buffer[length] = '\0'; mangled = buffer; - } // Else the symbol wasn't inside a set of parentheses + } // Else the symbol wasn't inside a set of parentheses // We use the ANSI version to ensure the string type is always `char *`. return UnDecorateSymbolName(mangled, out, out_size, UNDNAME_COMPLETE); -#else +# else (void)mangled; (void)out; (void)out_size; return false; -#endif +# endif #else State state; InitState(&state, mangled, out, out_size); diff --git a/src/demangle_unittest.cc b/src/demangle_unittest.cc index 869454fc0..d56191d9b 100644 --- a/src/demangle_unittest.cc +++ b/src/demangle_unittest.cc @@ -43,7 +43,7 @@ #include "utilities.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif @@ -54,7 +54,7 @@ using namespace std; using namespace google; // A wrapper function for Demangle() to make the unit test simple. -static const char *DemangleIt(const char * const mangled) { +static const char *DemangleIt(const char *const mangled) { static char demangled[4096]; if (Demangle(mangled, demangled, sizeof(demangled))) { return demangled; @@ -65,26 +65,23 @@ static const char *DemangleIt(const char * const mangled) { #if defined(GLOG_OS_WINDOWS) -#if defined(HAVE_DBGHELP) && !defined(NDEBUG) +# if defined(HAVE_DBGHELP) && !defined(NDEBUG) TEST(Demangle, Windows) { - EXPECT_STREQ( - "public: static void __cdecl Foo::func(int)", - DemangleIt("?func@Foo@@SAXH@Z")); - EXPECT_STREQ( - "public: static void __cdecl Foo::func(int)", - DemangleIt("@ILT+1105(?func@Foo@@SAXH@Z)")); - EXPECT_STREQ( - "int __cdecl foobarArray(int * const)", - DemangleIt("?foobarArray@@YAHQAH@Z")); + EXPECT_STREQ("public: static void __cdecl Foo::func(int)", + DemangleIt("?func@Foo@@SAXH@Z")); + EXPECT_STREQ("public: static void __cdecl Foo::func(int)", + DemangleIt("@ILT+1105(?func@Foo@@SAXH@Z)")); + EXPECT_STREQ("int __cdecl foobarArray(int * const)", + DemangleIt("?foobarArray@@YAHQAH@Z")); } -#endif +# endif #else // Test corner cases of boundary conditions. TEST(Demangle, CornerCases) { const size_t size = 10; - char tmp[size] = { 0 }; + char tmp[size] = {0}; const char *demangled = "foobar()"; const char *mangled = "_Z6foobarv"; EXPECT_TRUE(Demangle(mangled, tmp, sizeof(tmp))); diff --git a/src/glog/log_severity.h b/src/glog/log_severity.h index d52989d72..99f4b522b 100644 --- a/src/glog/log_severity.h +++ b/src/glog/log_severity.h @@ -51,20 +51,20 @@ using LogSeverity = int; const int GLOG_INFO = 0, GLOG_WARNING = 1, GLOG_ERROR = 2, GLOG_FATAL = 3, - NUM_SEVERITIES = 4; + NUM_SEVERITIES = 4; #ifndef GLOG_NO_ABBREVIATED_SEVERITIES -# ifdef ERROR +# ifdef ERROR # error ERROR macro is defined. Define GLOG_NO_ABBREVIATED_SEVERITIES before including logging.h. See the document for detail. -# endif -const int INFO = GLOG_INFO, WARNING = GLOG_WARNING, - ERROR = GLOG_ERROR, FATAL = GLOG_FATAL; +# endif +const int INFO = GLOG_INFO, WARNING = GLOG_WARNING, ERROR = GLOG_ERROR, + FATAL = GLOG_FATAL; #endif // DFATAL is FATAL in debug mode, ERROR in normal mode #ifdef NDEBUG -#define DFATAL_LEVEL ERROR +# define DFATAL_LEVEL ERROR #else -#define DFATAL_LEVEL FATAL +# define DFATAL_LEVEL FATAL #endif extern GLOG_EXPORT const char* const LogSeverityNames[NUM_SEVERITIES]; @@ -89,10 +89,10 @@ extern GLOG_EXPORT const char* const LogSeverityNames[NUM_SEVERITIES]; // #ifdef NDEBUG enum { DEBUG_MODE = 0 }; -#define IF_DEBUG_MODE(x) +# define IF_DEBUG_MODE(x) #else enum { DEBUG_MODE = 1 }; -#define IF_DEBUG_MODE(x) x +# define IF_DEBUG_MODE(x) x #endif #endif // BASE_LOG_SEVERITY_H__ diff --git a/src/glog/logging.h b/src/glog/logging.h index 326b77075..b69fc506e 100644 --- a/src/glog/logging.h +++ b/src/glog/logging.h @@ -50,28 +50,28 @@ #include #if defined(_MSC_VER) -#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) \ - __pragma(warning(push)) __pragma(warning(disable : n)) -#define GLOG_MSVC_POP_WARNING() __pragma(warning(pop)) +# define GLOG_MSVC_PUSH_DISABLE_WARNING(n) \ + __pragma(warning(push)) __pragma(warning(disable : n)) +# define GLOG_MSVC_POP_WARNING() __pragma(warning(pop)) #else -#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) -#define GLOG_MSVC_POP_WARNING() +# define GLOG_MSVC_PUSH_DISABLE_WARNING(n) +# define GLOG_MSVC_POP_WARNING() #endif #include "glog/platform.h" #if defined(__has_attribute) -#if __has_attribute(used) -#define GLOG_USED __attribute__((used)) -#endif // __has_attribute(used) -#endif // defined(__has_attribute) +# if __has_attribute(used) +# define GLOG_USED __attribute__((used)) +# endif // __has_attribute(used) +#endif // defined(__has_attribute) #if !defined(GLOG_USED) -#define GLOG_USED +# define GLOG_USED #endif // !defined(GLOG_USED) #if defined(GLOG_USE_GLOG_EXPORT) -#include "glog/export.h" +# include "glog/export.h" #endif // We care a lot about number of bits things take up. Unfortunately, @@ -83,7 +83,7 @@ #include // the normal place uint16_t is defined #if defined(GLOG_USE_GFLAGS) -#include +# include #endif #include @@ -158,7 +158,7 @@ typedef void (*CustomPrefixCallback)(std::ostream& s, const LogMessageInfo& l, // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including // base/logging.h #ifndef GOOGLE_STRIP_LOG -#define GOOGLE_STRIP_LOG 0 +# define GOOGLE_STRIP_LOG 0 #endif // GCC can be told that a certain branch is not likely to be taken (for @@ -167,43 +167,43 @@ typedef void (*CustomPrefixCallback)(std::ostream& s, const LogMessageInfo& l, // the absence of better information (ie. -fprofile-arcs). // #if defined(__has_builtin) -#if __has_builtin(__builtin_expect) -#define GLOG_BUILTIN_EXPECT_PRESENT -#endif +# if __has_builtin(__builtin_expect) +# define GLOG_BUILTIN_EXPECT_PRESENT +# endif #endif #if !defined(GLOG_BUILTIN_EXPECT_PRESENT) && defined(__GNUG__) // __has_builtin is not available prior to GCC 10 -#define GLOG_BUILTIN_EXPECT_PRESENT +# define GLOG_BUILTIN_EXPECT_PRESENT #endif #if defined(GLOG_BUILTIN_EXPECT_PRESENT) -#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN -#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0)) -#endif +# ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN +# define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0)) +# endif -#ifndef GOOGLE_PREDICT_FALSE -#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) -#endif +# ifndef GOOGLE_PREDICT_FALSE +# define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) +# endif -#ifndef GOOGLE_PREDICT_TRUE -#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) -#endif +# ifndef GOOGLE_PREDICT_TRUE +# define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) +# endif #else -#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN -#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x -#endif +# ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN +# define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x +# endif -#ifndef GOOGLE_PREDICT_TRUE -#define GOOGLE_PREDICT_FALSE(x) x -#endif +# ifndef GOOGLE_PREDICT_TRUE +# define GOOGLE_PREDICT_FALSE(x) x +# endif -#ifndef GOOGLE_PREDICT_TRUE -#define GOOGLE_PREDICT_TRUE(x) x -#endif +# ifndef GOOGLE_PREDICT_TRUE +# define GOOGLE_PREDICT_TRUE(x) x +# endif #endif @@ -370,50 +370,51 @@ typedef void (*CustomPrefixCallback)(std::ostream& s, const LogMessageInfo& l, #pragma push_macro("DECLARE_uint32") #ifdef DECLARE_VARIABLE -#undef DECLARE_VARIABLE +# undef DECLARE_VARIABLE #endif #ifdef DECLARE_bool -#undef DECLARE_bool +# undef DECLARE_bool #endif #ifdef DECLARE_string -#undef DECLARE_string +# undef DECLARE_string #endif #ifdef DECLARE_int32 -#undef DECLARE_int32 +# undef DECLARE_int32 #endif #ifdef DECLARE_uint32 -#undef DECLARE_uint32 +# undef DECLARE_uint32 #endif #ifndef DECLARE_VARIABLE -#define DECLARE_VARIABLE(type, shorttype, name, tn) \ - namespace fL##shorttype { \ - extern GLOG_EXPORT type FLAGS_##name; \ - } \ - using fL##shorttype::FLAGS_##name +# define DECLARE_VARIABLE(type, shorttype, name, tn) \ + namespace fL##shorttype { \ + extern GLOG_EXPORT type FLAGS_##name; \ + } \ + using fL##shorttype::FLAGS_##name // bool specialization -#define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name, bool) +# define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name, bool) // int32 specialization -#define DECLARE_int32(name) DECLARE_VARIABLE(google::int32, I, name, int32) +# define DECLARE_int32(name) DECLARE_VARIABLE(google::int32, I, name, int32) -#if !defined(DECLARE_uint32) +# if !defined(DECLARE_uint32) // uint32 specialization -#define DECLARE_uint32(name) DECLARE_VARIABLE(google::uint32, U, name, uint32) -#endif // !defined(DECLARE_uint32) && !defined(GLOG_USE_GFLAGS) +# define DECLARE_uint32(name) \ + DECLARE_VARIABLE(google::uint32, U, name, uint32) +# endif // !defined(DECLARE_uint32) && !defined(GLOG_USE_GFLAGS) // Special case for string, because we have to specify the namespace // std::string, which doesn't play nicely with our FLAG__namespace hackery. -#define DECLARE_string(name) \ - namespace fLS { \ - extern GLOG_EXPORT std::string& FLAGS_##name; \ - } \ - using fLS::FLAGS_##name +# define DECLARE_string(name) \ + namespace fLS { \ + extern GLOG_EXPORT std::string& FLAGS_##name; \ + } \ + using fLS::FLAGS_##name #endif // Set whether appending a timestamp to the log file name @@ -493,58 +494,58 @@ DECLARE_string(logmailer); // better to have compact code for these operations. #if GOOGLE_STRIP_LOG == 0 -#define COMPACT_GOOGLE_LOG_INFO google::LogMessage(__FILE__, __LINE__) -#define LOG_TO_STRING_INFO(message) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, message) +# define COMPACT_GOOGLE_LOG_INFO google::LogMessage(__FILE__, __LINE__) +# define LOG_TO_STRING_INFO(message) \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, message) #else -#define COMPACT_GOOGLE_LOG_INFO google::NullStream() -#define LOG_TO_STRING_INFO(message) google::NullStream() +# define COMPACT_GOOGLE_LOG_INFO google::NullStream() +# define LOG_TO_STRING_INFO(message) google::NullStream() #endif #if GOOGLE_STRIP_LOG <= 1 -#define COMPACT_GOOGLE_LOG_WARNING \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING) -#define LOG_TO_STRING_WARNING(message) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, message) +# define COMPACT_GOOGLE_LOG_WARNING \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING) +# define LOG_TO_STRING_WARNING(message) \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, message) #else -#define COMPACT_GOOGLE_LOG_WARNING google::NullStream() -#define LOG_TO_STRING_WARNING(message) google::NullStream() +# define COMPACT_GOOGLE_LOG_WARNING google::NullStream() +# define LOG_TO_STRING_WARNING(message) google::NullStream() #endif #if GOOGLE_STRIP_LOG <= 2 -#define COMPACT_GOOGLE_LOG_ERROR \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR) -#define LOG_TO_STRING_ERROR(message) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, message) +# define COMPACT_GOOGLE_LOG_ERROR \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR) +# define LOG_TO_STRING_ERROR(message) \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, message) #else -#define COMPACT_GOOGLE_LOG_ERROR google::NullStream() -#define LOG_TO_STRING_ERROR(message) google::NullStream() +# define COMPACT_GOOGLE_LOG_ERROR google::NullStream() +# define LOG_TO_STRING_ERROR(message) google::NullStream() #endif #if GOOGLE_STRIP_LOG <= 3 -#define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal(__FILE__, __LINE__) -#define LOG_TO_STRING_FATAL(message) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, message) +# define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal(__FILE__, __LINE__) +# define LOG_TO_STRING_FATAL(message) \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, message) #else -#define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal() -#define LOG_TO_STRING_FATAL(message) google::NullStreamFatal() +# define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal() +# define LOG_TO_STRING_FATAL(message) google::NullStreamFatal() #endif #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) -#define DCHECK_IS_ON() 0 +# define DCHECK_IS_ON() 0 #else -#define DCHECK_IS_ON() 1 +# define DCHECK_IS_ON() 1 #endif // For DFATAL, we want to use LogMessage (as opposed to // LogMessageFatal), to be consistent with the original behavior. #if !DCHECK_IS_ON() -#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR +# define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR #elif GOOGLE_STRIP_LOG <= 3 -#define COMPACT_GOOGLE_LOG_DFATAL \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL) +# define COMPACT_GOOGLE_LOG_DFATAL \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL) #else -#define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal() +# define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal() #endif #define GOOGLE_LOG_INFO(counter) \ @@ -581,22 +582,22 @@ DECLARE_string(logmailer); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \ defined(__CYGWIN__) || defined(__CYGWIN32__) // A very useful logging macro to log windows errors: -#define LOG_SYSRESULT(result) \ - if (FAILED(HRESULT_FROM_WIN32(result))) { \ - LPSTR message = nullptr; \ - LPSTR msg = reinterpret_cast(&message); \ - DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ - FORMAT_MESSAGE_FROM_SYSTEM | \ - FORMAT_MESSAGE_IGNORE_INSERTS, \ - 0, result, 0, msg, 100, nullptr); \ - if (message_length > 0) { \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, 0, \ - &google::LogMessage::SendToLog) \ - .stream() \ - << reinterpret_cast(message); \ - LocalFree(message); \ - } \ - } +# define LOG_SYSRESULT(result) \ + if (FAILED(HRESULT_FROM_WIN32(result))) { \ + LPSTR message = nullptr; \ + LPSTR msg = reinterpret_cast(&message); \ + DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ + FORMAT_MESSAGE_FROM_SYSTEM | \ + FORMAT_MESSAGE_IGNORE_INSERTS, \ + 0, result, 0, msg, 100, nullptr); \ + if (message_length > 0) { \ + google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, 0, \ + &google::LogMessage::SendToLog) \ + .stream() \ + << reinterpret_cast(message); \ + LocalFree(message); \ + } \ + } #endif // We use the preprocessor's merging operator, "##", so that, e.g., @@ -781,9 +782,9 @@ GLOG_EXPORT void MakeCheckOpValueString(std::ostream* os, template std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) #if defined(__has_attribute) -#if __has_attribute(used) +# if __has_attribute(used) __attribute__((noinline)) -#endif +# endif #endif ; @@ -866,7 +867,7 @@ DEFINE_CHECK_OP_IMPL(Check_GT, >) #if defined(STATIC_ANALYSIS) // Only for static analysis tool to know that it is equivalent to assert -#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1)op(val2)) +# define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1)op(val2)) #elif DCHECK_IS_ON() // In debug mode, avoid constructing CheckOpStrings if possible, // to reduce the overhead of CHECK statements by 2x. @@ -878,27 +879,27 @@ DEFINE_CHECK_OP_IMPL(Check_GT, >) // file is included). Save the current meaning now and use it // in the macro. typedef std::string _Check_string; -#define CHECK_OP_LOG(name, op, val1, val2, log) \ - while (google::_Check_string* _result = google::Check##name##Impl( \ - google::GetReferenceableValue(val1), \ - google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \ - log(__FILE__, __LINE__, google::CheckOpString(_result)).stream() +# define CHECK_OP_LOG(name, op, val1, val2, log) \ + while (google::_Check_string* _result = google::Check##name##Impl( \ + google::GetReferenceableValue(val1), \ + google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \ + log(__FILE__, __LINE__, google::CheckOpString(_result)).stream() #else // In optimized mode, use CheckOpString to hint to compiler that // the while condition is unlikely. -#define CHECK_OP_LOG(name, op, val1, val2, log) \ - while (google::CheckOpString _result = google::Check##name##Impl( \ - google::GetReferenceableValue(val1), \ - google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \ - log(__FILE__, __LINE__, _result).stream() +# define CHECK_OP_LOG(name, op, val1, val2, log) \ + while (google::CheckOpString _result = google::Check##name##Impl( \ + google::GetReferenceableValue(val1), \ + google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \ + log(__FILE__, __LINE__, _result).stream() #endif // STATIC_ANALYSIS, DCHECK_IS_ON() #if GOOGLE_STRIP_LOG <= 3 -#define CHECK_OP(name, op, val1, val2) \ - CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal) +# define CHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal) #else -#define CHECK_OP(name, op, val1, val2) \ - CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal) +# define CHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal) #endif // STRIP_LOG <= 3 // Equality/Inequality checks - compare two values, and log a FATAL message @@ -1028,20 +1029,20 @@ DECLARE_CHECK_STROP_IMPL(strcasecmp, false) #define LOG_PREVIOUS_TIME LOG_EVERY_N_VARNAME(previousTime_, __LINE__) #if defined(__has_feature) -#if __has_feature(thread_sanitizer) -#define GLOG_SANITIZE_THREAD 1 -#endif +# if __has_feature(thread_sanitizer) +# define GLOG_SANITIZE_THREAD 1 +# endif #endif #if !defined(GLOG_SANITIZE_THREAD) && defined(__SANITIZE_THREAD__) && \ __SANITIZE_THREAD__ -#define GLOG_SANITIZE_THREAD 1 +# define GLOG_SANITIZE_THREAD 1 #endif #if defined(GLOG_SANITIZE_THREAD) -#define GLOG_IFDEF_THREAD_SANITIZER(X) X +# define GLOG_IFDEF_THREAD_SANITIZER(X) X #else -#define GLOG_IFDEF_THREAD_SANITIZER(X) +# define GLOG_IFDEF_THREAD_SANITIZER(X) #endif #if defined(GLOG_SANITIZE_THREAD) @@ -1166,9 +1167,9 @@ enum PRIVATE_Counter { COUNTER }; // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us // to keep using this syntax, we define this macro to do the same thing // as COMPACT_GOOGLE_LOG_ERROR. -#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR -#define SYSLOG_0 SYSLOG_ERROR -#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR +# define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR +# define SYSLOG_0 SYSLOG_ERROR +# define LOG_TO_STRING_0 LOG_TO_STRING_ERROR // Needed for LOG_IS_ON(ERROR). const LogSeverity GLOG_0 = GLOG_ERROR; #else @@ -1176,126 +1177,126 @@ const LogSeverity GLOG_0 = GLOG_ERROR; // GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN. // For this case, we cannot detect if ERROR is defined before users // actually use ERROR. Let's make an undefined symbol to warn users. -#define GLOG_ERROR_MSG \ - ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail -#define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG -#define SYSLOG_0 GLOG_ERROR_MSG -#define LOG_TO_STRING_0 GLOG_ERROR_MSG -#define GLOG_0 GLOG_ERROR_MSG +# define GLOG_ERROR_MSG \ + ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail +# define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG +# define SYSLOG_0 GLOG_ERROR_MSG +# define LOG_TO_STRING_0 GLOG_ERROR_MSG +# define GLOG_0 GLOG_ERROR_MSG #endif // Plus some debug-logging macros that get compiled to nothing for production #if DCHECK_IS_ON() -#define DLOG(severity) LOG(severity) -#define DVLOG(verboselevel) VLOG(verboselevel) -#define DLOG_IF(severity, condition) LOG_IF(severity, condition) -#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n) -#define DLOG_IF_EVERY_N(severity, condition, n) \ - LOG_IF_EVERY_N(severity, condition, n) -#define DLOG_FIRST_N(severity, n) LOG_FIRST_N(severity, n) -#define DLOG_EVERY_T(severity, T) LOG_EVERY_T(severity, T) -#define DLOG_ASSERT(condition) LOG_ASSERT(condition) +# define DLOG(severity) LOG(severity) +# define DVLOG(verboselevel) VLOG(verboselevel) +# define DLOG_IF(severity, condition) LOG_IF(severity, condition) +# define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n) +# define DLOG_IF_EVERY_N(severity, condition, n) \ + LOG_IF_EVERY_N(severity, condition, n) +# define DLOG_FIRST_N(severity, n) LOG_FIRST_N(severity, n) +# define DLOG_EVERY_T(severity, T) LOG_EVERY_T(severity, T) +# define DLOG_ASSERT(condition) LOG_ASSERT(condition) // debug-only checking. executed if DCHECK_IS_ON(). -#define DCHECK(condition) CHECK(condition) -#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) -#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) -#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) -#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) -#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) -#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) -#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val) -#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2) -#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2) -#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2) -#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2) +# define DCHECK(condition) CHECK(condition) +# define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) +# define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) +# define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) +# define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) +# define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) +# define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) +# define DCHECK_NOTNULL(val) CHECK_NOTNULL(val) +# define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2) +# define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2) +# define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2) +# define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2) #else // !DCHECK_IS_ON() -#define DLOG(severity) \ - static_cast(0), \ - true ? (void)0 : google::LogMessageVoidify() & LOG(severity) +# define DLOG(severity) \ + static_cast(0), \ + true ? (void)0 : google::LogMessageVoidify() & LOG(severity) -#define DVLOG(verboselevel) \ - static_cast(0), (true || !VLOG_IS_ON(verboselevel)) \ - ? (void)0 \ - : google::LogMessageVoidify() & LOG(INFO) +# define DVLOG(verboselevel) \ + static_cast(0), (true || !VLOG_IS_ON(verboselevel)) \ + ? (void)0 \ + : google::LogMessageVoidify() & LOG(INFO) -#define DLOG_IF(severity, condition) \ - static_cast(0), (true || !(condition)) \ - ? (void)0 \ - : google::LogMessageVoidify() & LOG(severity) +# define DLOG_IF(severity, condition) \ + static_cast(0), (true || !(condition)) \ + ? (void)0 \ + : google::LogMessageVoidify() & LOG(severity) -#define DLOG_EVERY_N(severity, n) \ - static_cast(0), \ - true ? (void)0 : google::LogMessageVoidify() & LOG(severity) +# define DLOG_EVERY_N(severity, n) \ + static_cast(0), \ + true ? (void)0 : google::LogMessageVoidify() & LOG(severity) -#define DLOG_IF_EVERY_N(severity, condition, n) \ - static_cast(0), (true || !(condition)) \ - ? (void)0 \ - : google::LogMessageVoidify() & LOG(severity) +# define DLOG_IF_EVERY_N(severity, condition, n) \ + static_cast(0), (true || !(condition)) \ + ? (void)0 \ + : google::LogMessageVoidify() & LOG(severity) -#define DLOG_FIRST_N(severity, n) \ - static_cast(0), \ - true ? (void)0 : google::LogMessageVoidify() & LOG(severity) +# define DLOG_FIRST_N(severity, n) \ + static_cast(0), \ + true ? (void)0 : google::LogMessageVoidify() & LOG(severity) -#define DLOG_EVERY_T(severity, T) \ - static_cast(0), \ - true ? (void)0 : google::LogMessageVoidify() & LOG(severity) +# define DLOG_EVERY_T(severity, T) \ + static_cast(0), \ + true ? (void)0 : google::LogMessageVoidify() & LOG(severity) -#define DLOG_ASSERT(condition) \ - static_cast(0), true ? (void)0 : LOG_ASSERT(condition) +# define DLOG_ASSERT(condition) \ + static_cast(0), true ? (void)0 : LOG_ASSERT(condition) // MSVC warning C4127: conditional expression is constant -#define DCHECK(condition) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK(condition) +# define DCHECK(condition) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK(condition) -#define DCHECK_EQ(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2) +# define DCHECK_EQ(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2) -#define DCHECK_NE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2) +# define DCHECK_NE(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2) -#define DCHECK_LE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2) +# define DCHECK_LE(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2) -#define DCHECK_LT(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2) +# define DCHECK_LT(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2) -#define DCHECK_GE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2) +# define DCHECK_GE(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2) -#define DCHECK_GT(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2) +# define DCHECK_GT(val1, val2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2) // You may see warnings in release mode if you don't use the return // value of DCHECK_NOTNULL. Please just use DCHECK for such cases. -#define DCHECK_NOTNULL(val) (val) +# define DCHECK_NOTNULL(val) (val) -#define DCHECK_STREQ(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2) +# define DCHECK_STREQ(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2) -#define DCHECK_STRCASEEQ(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2) +# define DCHECK_STRCASEEQ(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2) -#define DCHECK_STRNE(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2) +# define DCHECK_STRNE(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2) -#define DCHECK_STRCASENE(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2) +# define DCHECK_STRCASENE(str1, str2) \ + GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ + while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2) #endif // DCHECK_IS_ON() diff --git a/src/glog/platform.h b/src/glog/platform.h index 7893c45d1..f9478e48a 100644 --- a/src/glog/platform.h +++ b/src/glog/platform.h @@ -35,26 +35,26 @@ #define GLOG_PLATFORM_H #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) -#define GLOG_OS_WINDOWS +# define GLOG_OS_WINDOWS #elif defined(__CYGWIN__) || defined(__CYGWIN32__) -#define GLOG_OS_CYGWIN +# define GLOG_OS_CYGWIN #elif defined(linux) || defined(__linux) || defined(__linux__) -#ifndef GLOG_OS_LINUX -#define GLOG_OS_LINUX -#endif +# ifndef GLOG_OS_LINUX +# define GLOG_OS_LINUX +# endif #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) -#define GLOG_OS_MACOSX +# define GLOG_OS_MACOSX #elif defined(__FreeBSD__) -#define GLOG_OS_FREEBSD +# define GLOG_OS_FREEBSD #elif defined(__NetBSD__) -#define GLOG_OS_NETBSD +# define GLOG_OS_NETBSD #elif defined(__OpenBSD__) -#define GLOG_OS_OPENBSD +# define GLOG_OS_OPENBSD #elif defined(__EMSCRIPTEN__) -#define GLOG_OS_EMSCRIPTEN +# define GLOG_OS_EMSCRIPTEN #else // TODO(hamaji): Add other platforms. #error Platform not supported by glog. Please consider to contribute platform information by submitting a pull request on Github. #endif -#endif // GLOG_PLATFORM_H +#endif // GLOG_PLATFORM_H diff --git a/src/glog/raw_logging.h b/src/glog/raw_logging.h index 0a9b52262..b30e54019 100644 --- a/src/glog/raw_logging.h +++ b/src/glog/raw_logging.h @@ -44,8 +44,8 @@ namespace google { #include "glog/vlog_is_on.h" #if defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wvariadic-macros" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wvariadic-macros" #endif // This is similar to LOG(severity) << format... and VLOG(level) << format.., @@ -85,46 +85,46 @@ namespace google { // The following STRIP_LOG testing is performed in the header file so that it's // possible to completely compile out the logging code and the log messages. #if !defined(STRIP_LOG) || STRIP_LOG == 0 -#define RAW_VLOG(verboselevel, ...) \ - do { \ - if (VLOG_IS_ON(verboselevel)) { \ - RAW_LOG_INFO(__VA_ARGS__); \ - } \ - } while (0) +# define RAW_VLOG(verboselevel, ...) \ + do { \ + if (VLOG_IS_ON(verboselevel)) { \ + RAW_LOG_INFO(__VA_ARGS__); \ + } \ + } while (0) #else -#define RAW_VLOG(verboselevel, ...) RawLogStub__(0, __VA_ARGS__) +# define RAW_VLOG(verboselevel, ...) RawLogStub__(0, __VA_ARGS__) #endif // STRIP_LOG == 0 #if !defined(STRIP_LOG) || STRIP_LOG == 0 -#define RAW_LOG_INFO(...) \ - google::RawLog__(google::GLOG_INFO, __FILE__, __LINE__, __VA_ARGS__) +# define RAW_LOG_INFO(...) \ + google::RawLog__(google::GLOG_INFO, __FILE__, __LINE__, __VA_ARGS__) #else -#define RAW_LOG_INFO(...) google::RawLogStub__(0, __VA_ARGS__) +# define RAW_LOG_INFO(...) google::RawLogStub__(0, __VA_ARGS__) #endif // STRIP_LOG == 0 #if !defined(STRIP_LOG) || STRIP_LOG <= 1 -#define RAW_LOG_WARNING(...) \ - google::RawLog__(google::GLOG_WARNING, __FILE__, __LINE__, __VA_ARGS__) +# define RAW_LOG_WARNING(...) \ + google::RawLog__(google::GLOG_WARNING, __FILE__, __LINE__, __VA_ARGS__) #else -#define RAW_LOG_WARNING(...) google::RawLogStub__(0, __VA_ARGS__) +# define RAW_LOG_WARNING(...) google::RawLogStub__(0, __VA_ARGS__) #endif // STRIP_LOG <= 1 #if !defined(STRIP_LOG) || STRIP_LOG <= 2 -#define RAW_LOG_ERROR(...) \ - google::RawLog__(google::GLOG_ERROR, __FILE__, __LINE__, __VA_ARGS__) +# define RAW_LOG_ERROR(...) \ + google::RawLog__(google::GLOG_ERROR, __FILE__, __LINE__, __VA_ARGS__) #else -#define RAW_LOG_ERROR(...) google::RawLogStub__(0, __VA_ARGS__) +# define RAW_LOG_ERROR(...) google::RawLogStub__(0, __VA_ARGS__) #endif // STRIP_LOG <= 2 #if !defined(STRIP_LOG) || STRIP_LOG <= 3 -#define RAW_LOG_FATAL(...) \ - google::RawLog__(google::GLOG_FATAL, __FILE__, __LINE__, __VA_ARGS__) +# define RAW_LOG_FATAL(...) \ + google::RawLog__(google::GLOG_FATAL, __FILE__, __LINE__, __VA_ARGS__) #else -#define RAW_LOG_FATAL(...) \ - do { \ - google::RawLogStub__(0, __VA_ARGS__); \ - exit(EXIT_FAILURE); \ - } while (0) +# define RAW_LOG_FATAL(...) \ + do { \ + google::RawLogStub__(0, __VA_ARGS__); \ + exit(EXIT_FAILURE); \ + } while (0) #endif // STRIP_LOG <= 3 // Similar to CHECK(condition) << message, @@ -142,20 +142,20 @@ namespace google { // Debug versions of RAW_LOG and RAW_CHECK #ifndef NDEBUG -#define RAW_DLOG(severity, ...) RAW_LOG(severity, __VA_ARGS__) -#define RAW_DCHECK(condition, message) RAW_CHECK(condition, message) +# define RAW_DLOG(severity, ...) RAW_LOG(severity, __VA_ARGS__) +# define RAW_DCHECK(condition, message) RAW_CHECK(condition, message) #else // NDEBUG -#define RAW_DLOG(severity, ...) \ - while (false) RAW_LOG(severity, __VA_ARGS__) -#define RAW_DCHECK(condition, message) \ - while (false) RAW_CHECK(condition, message) +# define RAW_DLOG(severity, ...) \ + while (false) RAW_LOG(severity, __VA_ARGS__) +# define RAW_DCHECK(condition, message) \ + while (false) RAW_CHECK(condition, message) #endif // NDEBUG #if defined(__GNUC__) -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif // Stub log function used to work around for unused variable warnings when @@ -169,9 +169,9 @@ static inline void RawLogStub__(int /* ignored */, ...) {} GLOG_EXPORT void RawLog__(LogSeverity severity, const char* file, int line, const char* format, ...) #if defined(__has_attribute) -#if __has_attribute(used) +# if __has_attribute(used) __attribute__((__format__(__printf__, 4, 5))) -#endif +# endif #endif ; } // namespace google diff --git a/src/glog/vlog_is_on.h b/src/glog/vlog_is_on.h index 78d16d772..914a57d13 100644 --- a/src/glog/vlog_is_on.h +++ b/src/glog/vlog_is_on.h @@ -72,20 +72,21 @@ // it's either FLAGS_v or an appropriate internal variable // matching the current source file that represents results of // parsing of --vmodule flag and/or SetVLOGLevel calls. -#define VLOG_IS_ON(verboselevel) \ - __extension__({ \ - static google::SiteFlag vlocal__ = {nullptr, nullptr, 0, nullptr}; \ - GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ - __FILE__, __LINE__, &vlocal__, sizeof(google::SiteFlag), "")); \ - google::int32 verbose_level__ = (verboselevel); \ - (vlocal__.level == nullptr \ - ? google::InitVLOG3__(&vlocal__, &FLAGS_v, __FILE__, verbose_level__) \ - : *vlocal__.level >= verbose_level__); \ - }) +# define VLOG_IS_ON(verboselevel) \ + __extension__({ \ + static google::SiteFlag vlocal__ = {nullptr, nullptr, 0, nullptr}; \ + GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ + __FILE__, __LINE__, &vlocal__, sizeof(google::SiteFlag), "")); \ + google::int32 verbose_level__ = (verboselevel); \ + (vlocal__.level == nullptr \ + ? google::InitVLOG3__(&vlocal__, &FLAGS_v, __FILE__, \ + verbose_level__) \ + : *vlocal__.level >= verbose_level__); \ + }) #else // GNU extensions not available, so we do not support --vmodule. // Dynamic value of FLAGS_v always controls the logging level. -#define VLOG_IS_ON(verboselevel) (FLAGS_v >= (verboselevel)) +# define VLOG_IS_ON(verboselevel) (FLAGS_v >= (verboselevel)) #endif // Set VLOG(_IS_ON) level for module_pattern to log_level. diff --git a/src/googletest.h b/src/googletest.h index 62b5b0b7b..8a6e3eb96 100644 --- a/src/googletest.h +++ b/src/googletest.h @@ -31,7 +31,7 @@ // (based on googletest: http://code.google.com/p/googletest/) #ifdef GOOGLETEST_H__ -#error You must not include this file twice. +# error You must not include this file twice. #endif #define GOOGLETEST_H__ @@ -53,15 +53,15 @@ #include "utilities.h" #ifdef HAVE_UNISTD_H -# include +# include #endif #include "base/commandlineflags.h" #if __cplusplus < 201103L && !defined(_MSC_VER) -#define GOOGLE_GLOG_THROW_BAD_ALLOC throw (std::bad_alloc) +# define GOOGLE_GLOG_THROW_BAD_ALLOC throw(std::bad_alloc) #else -#define GOOGLE_GLOG_THROW_BAD_ALLOC +# define GOOGLE_GLOG_THROW_BAD_ALLOC #endif using std::map; @@ -95,7 +95,7 @@ static inline string GetTempDir() { // (e.g., glog/vsproject/logging_unittest). static const char TEST_SRC_DIR[] = "../.."; #elif !defined(TEST_SRC_DIR) -# warning TEST_SRC_DIR should be defined in config.h +# warning TEST_SRC_DIR should be defined in config.h static const char TEST_SRC_DIR[] = "."; #endif @@ -112,10 +112,10 @@ DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark"); #endif #ifdef HAVE_LIB_GTEST -# include +# include // Use our ASSERT_DEATH implementation. -# undef ASSERT_DEATH -# undef ASSERT_DEBUG_DEATH +# undef ASSERT_DEATH +# undef ASSERT_DEBUG_DEATH using testing::InitGoogleTest; #else @@ -127,81 +127,83 @@ void InitGoogleTest(int*, char**) {} // The following is some bare-bones testing infrastructure -#define EXPECT_NEAR(val1, val2, abs_error) \ - do { \ - if (abs(val1 - val2) > abs_error) { \ - fprintf(stderr, "Check failed: %s within %s of %s\n", #val1, #abs_error, \ - #val2); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) - -#define EXPECT_TRUE(cond) \ - do { \ - if (!(cond)) { \ - fprintf(stderr, "Check failed: %s\n", #cond); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) - -#define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond)) - -#define EXPECT_OP(op, val1, val2) \ - do { \ - if (!((val1) op (val2))) { \ - fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) - -#define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2) -#define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2) -#define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2) -#define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2) - -#define EXPECT_NAN(arg) \ - do { \ - if (!isnan(arg)) { \ - fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) - -#define EXPECT_INF(arg) \ - do { \ - if (!isinf(arg)) { \ - fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) - -#define EXPECT_DOUBLE_EQ(val1, val2) \ - do { \ - if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \ - fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) - -#define EXPECT_STREQ(val1, val2) \ - do { \ - if (strcmp((val1), (val2)) != 0) { \ - fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) +# define EXPECT_NEAR(val1, val2, abs_error) \ + do { \ + if (abs(val1 - val2) > abs_error) { \ + fprintf(stderr, "Check failed: %s within %s of %s\n", #val1, \ + #abs_error, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +# define EXPECT_TRUE(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "Check failed: %s\n", #cond); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +# define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond)) + +# define EXPECT_OP(op, val1, val2) \ + do { \ + if (!((val1)op(val2))) { \ + fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +# define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2) +# define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2) +# define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2) +# define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2) + +# define EXPECT_NAN(arg) \ + do { \ + if (!isnan(arg)) { \ + fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +# define EXPECT_INF(arg) \ + do { \ + if (!isinf(arg)) { \ + fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +# define EXPECT_DOUBLE_EQ(val1, val2) \ + do { \ + if (((val1) < (val2)-0.001 || (val1) > (val2) + 0.001)) { \ + fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +# define EXPECT_STREQ(val1, val2) \ + do { \ + if (strcmp((val1), (val2)) != 0) { \ + fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) vector g_testlist; // the tests to run -#define TEST(a, b) \ - struct Test_##a##_##b { \ - Test_##a##_##b() { g_testlist.push_back(&Run); } \ - static void Run() { FlagSaver fs; RunTest(); } \ - static void RunTest(); \ - }; \ - static Test_##a##_##b g_test_##a##_##b; \ - void Test_##a##_##b::RunTest() - +# define TEST(a, b) \ + struct Test_##a##_##b { \ + Test_##a##_##b() { g_testlist.push_back(&Run); } \ + static void Run() { \ + FlagSaver fs; \ + RunTest(); \ + } \ + static void RunTest(); \ + }; \ + static Test_##a##_##b g_test_##a##_##b; \ + void Test_##a##_##b::RunTest() static inline int RUN_ALL_TESTS() { vector::const_iterator it; @@ -228,33 +230,33 @@ static inline void CalledAbort() { #ifdef GLOG_OS_WINDOWS // TODO(hamaji): Death test somehow doesn't work in Windows. -#define ASSERT_DEATH(fn, msg) +# define ASSERT_DEATH(fn, msg) #else -#define ASSERT_DEATH(fn, msg) \ - do { \ - g_called_abort = false; \ - /* in logging.cc */ \ - void (*original_logging_fail_func)() = g_logging_fail_func; \ - g_logging_fail_func = &CalledAbort; \ - if (!setjmp(g_jmp_buf)) fn; \ - /* set back to their default */ \ - g_logging_fail_func = original_logging_fail_func; \ - if (!g_called_abort) { \ - fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \ - exit(EXIT_FAILURE); \ - } \ - } while (0) +# define ASSERT_DEATH(fn, msg) \ + do { \ + g_called_abort = false; \ + /* in logging.cc */ \ + void (*original_logging_fail_func)() = g_logging_fail_func; \ + g_logging_fail_func = &CalledAbort; \ + if (!setjmp(g_jmp_buf)) fn; \ + /* set back to their default */ \ + g_logging_fail_func = original_logging_fail_func; \ + if (!g_called_abort) { \ + fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) #endif #ifdef NDEBUG -#define ASSERT_DEBUG_DEATH(fn, msg) +# define ASSERT_DEBUG_DEATH(fn, msg) #else -#define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg) +# define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg) #endif // NDEBUG // Benchmark tools. -#define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n); +#define BENCHMARK(n) static BenchmarkRegisterer __benchmark_##n(#n, &n); map g_benchlist; // the benchmarks to run @@ -278,13 +280,13 @@ static inline void RunSpecifiedBenchmarks() { double elapsed_ns = (static_cast(clock()) - start) / CLOCKS_PER_SEC * 1000 * 1000 * 1000; #if defined(__GNUC__) && !defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wformat=" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wformat=" #endif printf("%s\t%8.2lf\t%10d\n", iter.first.c_str(), elapsed_ns / iter_cnt, iter_cnt); #if defined(__GNUC__) && !defined(__clang__) -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif } puts(""); @@ -317,8 +319,7 @@ class CapturedStream { CHECK(uncaptured_fd_ != -1); // Open file to save stream to - int cap_fd = open(filename_.c_str(), - O_CREAT | O_TRUNC | O_WRONLY, + int cap_fd = open(filename_.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); CHECK(cap_fd != -1); @@ -337,18 +338,18 @@ class CapturedStream { } } - const string & filename() const { return filename_; } + const string& filename() const { return filename_; } private: - int fd_; // file descriptor being captured + int fd_; // file descriptor being captured int uncaptured_fd_{-1}; // where the stream was originally being sent to - string filename_; // file where stream is being saved + string filename_; // file where stream is being saved }; -static CapturedStream * s_captured_streams[STDERR_FILENO+1]; +static CapturedStream* s_captured_streams[STDERR_FILENO + 1]; // Redirect a file descriptor to a file. // fd - Should be STDOUT_FILENO or STDERR_FILENO // filename - File where output should be stored -static inline void CaptureTestOutput(int fd, const string & filename) { +static inline void CaptureTestOutput(int fd, const string& filename) { CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO)); CHECK(s_captured_streams[fd] == nullptr); s_captured_streams[fd] = new CapturedStream(fd, filename); @@ -360,14 +361,14 @@ static inline void CaptureTestStderr() { CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err"); } // Return the size (in bytes) of a file -static inline size_t GetFileSize(FILE * file) { +static inline size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast(ftell(file)); } // Read the entire content of a file as a string -static inline string ReadEntireFile(FILE * file) { +static inline string ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); - char * const buffer = new char[file_size]; + char* const buffer = new char[file_size]; size_t bytes_last_read = 0; // # of bytes read in the last fread() size_t bytes_read = 0; // # of bytes read so far @@ -377,11 +378,12 @@ static inline string ReadEntireFile(FILE * file) { // Keep reading the file until we cannot read further or the // pre-determined file size is reached. do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_last_read = + fread(buffer + bytes_read, 1, file_size - bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); - const string content = string(buffer, buffer+bytes_read); + const string content = string(buffer, buffer + bytes_read); delete[] buffer; return content; @@ -390,15 +392,14 @@ static inline string ReadEntireFile(FILE * file) { // fd is STDERR_FILENO) as a string static inline string GetCapturedTestOutput(int fd) { CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO); - CapturedStream * const cap = s_captured_streams[fd]; - CHECK(cap) - << ": did you forget CaptureTestStdout() or CaptureTestStderr()?"; + CapturedStream* const cap = s_captured_streams[fd]; + CHECK(cap) << ": did you forget CaptureTestStdout() or CaptureTestStderr()?"; // Make sure everything is flushed. cap->StopCapture(); // Read the captured file. - FILE * const file = fopen(cap->filename().c_str(), "r"); + FILE* const file = fopen(cap->filename().c_str(), "r"); const string content = ReadEntireFile(file); fclose(file); @@ -421,7 +422,7 @@ static inline bool IsLoggingPrefix(const string& s) { } if (!strchr("IWEF", s[0])) return false; for (size_t i = 1; i <= 8; ++i) { - if (!isdigit(s[i]) && s[i] != "YEARDATE"[i-1]) return false; + if (!isdigit(s[i]) && s[i] != "YEARDATE"[i - 1]) return false; } return true; } @@ -461,16 +462,15 @@ static inline string MungeLine(const string& line) { } size_t index = thread_lineinfo.find(':'); CHECK_NE(string::npos, index); - thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]"; + thread_lineinfo = thread_lineinfo.substr(0, index + 1) + "LINE]"; string rest; std::getline(iss, rest); return (before + logcode_date[0] + "YEARDATE TIME__ " + thread_lineinfo + MungeLine(rest)); } -static inline void StringReplace(string* str, - const string& oldsub, - const string& newsub) { +static inline void StringReplace(string* str, const string& oldsub, + const string& newsub) { size_t pos = str->find(oldsub); if (pos != string::npos) { str->replace(pos, oldsub.size(), newsub); @@ -589,9 +589,7 @@ class Thread { handle_ = CreateThread(nullptr, 0, &Thread::InvokeThreadW, this, 0, &th_); CHECK(handle_) << "CreateThread"; } - void Join() { - WaitForSingleObject(handle_, INFINITE); - } + void Join() { WaitForSingleObject(handle_, INFINITE); } #elif defined(HAVE_PTHREAD) void Start() { pthread_create(&th_, nullptr, &Thread::InvokeThread, this); } void Join() { pthread_join(th_, nullptr); } @@ -623,12 +621,12 @@ class Thread { static inline void SleepForMilliseconds(unsigned t) { #ifndef GLOG_OS_WINDOWS -# if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L +# if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L const struct timespec req = {0, t * 1000 * 1000}; nanosleep(&req, nullptr); -# else +# else usleep(t * 1000); -# endif +# endif #else Sleep(t); #endif diff --git a/src/logging.cc b/src/logging.cc index 1b7dae54d..4607402b2 100644 --- a/src/logging.cc +++ b/src/logging.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() +#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() #include "glog/logging.h" @@ -45,13 +45,13 @@ #include "utilities.h" #ifdef HAVE_STACKTRACE -#include "stacktrace.h" +# include "stacktrace.h" #endif #ifdef GLOG_OS_WINDOWS -#include "windows/dirent.h" +# include "windows/dirent.h" #else -#include // for automatic removal of old logs +# include // for automatic removal of old logs #endif #include @@ -69,49 +69,49 @@ #include #ifdef HAVE__CHSIZE_S -#include // for truncate log file +# include // for truncate log file #endif #ifdef HAVE_PWD_H -#include +# include #endif #ifdef HAVE_SYS_UTSNAME_H -#include // For uname. +# include // For uname. #endif #ifdef HAVE_SYSLOG_H -#include +# include #endif #ifdef __ANDROID__ -#include +# include #endif #ifdef HAVE_SYS_TYPES_H -#include +# include #endif #ifdef HAVE_UNISTD_H -#include +# include #endif #ifndef HAVE_MODE_T typedef int mode_t; #endif -using std::string; -using std::vector; -using std::setw; -using std::setfill; -using std::hex; using std::dec; +using std::hex; using std::min; using std::ostream; using std::ostringstream; +using std::setfill; +using std::setw; +using std::string; +using std::vector; -using std::FILE; -using std::fwrite; using std::fclose; using std::fflush; +using std::FILE; using std::fprintf; +using std::fwrite; using std::perror; #ifdef __QNX__ @@ -119,13 +119,13 @@ using std::fdopen; #endif #ifdef _WIN32 -#define fdopen _fdopen +# define fdopen _fdopen #endif // There is no thread annotation support. #define EXCLUSIVE_LOCKS_REQUIRED(mu) -static bool BoolFromEnv(const char *varname, bool defval) { +static bool BoolFromEnv(const char* varname, bool defval) { const char* const valstr = getenv(varname); if (!valstr) { return defval; @@ -147,10 +147,12 @@ GLOG_DEFINE_bool(colorlogtostdout, false, GLOG_DEFINE_bool(logtostdout, BoolFromEnv("GOOGLE_LOGTOSTDOUT", false), "log messages go to stdout instead of logfiles"); #ifdef GLOG_OS_LINUX -GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. " - "Logs can grow very quickly and they are rarely read before they " - "need to be evicted from memory. Instead, drop them from memory " - "as soon as they are flushed to disk."); +GLOG_DEFINE_bool( + drop_log_memory, true, + "Drop in-memory buffers of log contents. " + "Logs can grow very quickly and they are rarely read before they " + "need to be evicted from memory. Instead, drop them from memory " + "as soon as they are flushed to disk."); #endif // By default, errors (including fatal errors) get logged to stderr as @@ -171,7 +173,8 @@ GLOG_DEFINE_bool(log_prefix, true, "Prepend the log prefix to the start of each log line"); GLOG_DEFINE_bool(log_year_in_prefix, true, "Include the year in the log prefix"); -GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't " +GLOG_DEFINE_int32(minloglevel, 0, + "Messages logged at a lower level than this don't " "actually get logged anywhere"); GLOG_DEFINE_int32(logbuflevel, 0, "Buffer log messages logged at this level or lower" @@ -180,15 +183,14 @@ GLOG_DEFINE_int32(logbuflevel, 0, GLOG_DEFINE_int32(logbufsecs, 30, "Buffer log messages for at most this many seconds"); -GLOG_DEFINE_int32(logcleansecs, 60 * 5, // every 5 minutes +GLOG_DEFINE_int32(logcleansecs, 60 * 5, // every 5 minutes "Clean overdue logs every this many seconds"); GLOG_DEFINE_int32(logemaillevel, 999, "Email log messages logged at this level or higher" " (0 means email all; 3 means email FATAL only;" " ...)"); -GLOG_DEFINE_string(logmailer, "", - "Mailer used to send logging email"); +GLOG_DEFINE_string(logmailer, "", "Mailer used to send logging email"); // Compute the default value for --log_dir static const char* DefaultLogDir() { @@ -206,10 +208,12 @@ static const char* DefaultLogDir() { GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions."); -GLOG_DEFINE_string(log_dir, DefaultLogDir(), - "If specified, logfiles are written into this directory instead " - "of the default logging directory."); -GLOG_DEFINE_string(log_link, "", "Put additional links to the log " +GLOG_DEFINE_string( + log_dir, DefaultLogDir(), + "If specified, logfiles are written into this directory instead " + "of the default logging directory."); +GLOG_DEFINE_string(log_link, "", + "Put additional links to the log " "files in this directory"); GLOG_DEFINE_uint32(max_log_size, 1800, @@ -222,8 +226,7 @@ GLOG_DEFINE_bool(stop_logging_if_full_disk, false, GLOG_DEFINE_string(log_backtrace_at, "", "Emit a backtrace when logging at file:linenum."); -GLOG_DEFINE_bool(log_utc_time, false, - "Use UTC time for logging."); +GLOG_DEFINE_bool(log_utc_time, false, "Use UTC time for logging."); // TODO(hamaji): consider windows enum { PATH_SEPARATOR = '/' }; @@ -231,15 +234,11 @@ enum { PATH_SEPARATOR = '/' }; #ifndef HAVE_PREAD static ssize_t pread(int fd, void* buf, size_t count, off_t offset) { off_t orig_offset = lseek(fd, 0, SEEK_CUR); - if (orig_offset == (off_t)-1) - return -1; - if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) - return -1; + if (orig_offset == (off_t)-1) return -1; + if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) return -1; ssize_t len = read(fd, buf, count); - if (len < 0) - return len; - if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) - return -1; + if (len < 0) return len; + if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) return -1; return len; } #endif // !HAVE_PREAD @@ -247,15 +246,11 @@ static ssize_t pread(int fd, void* buf, size_t count, off_t offset) { #ifndef HAVE_PWRITE static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) { off_t orig_offset = lseek(fd, 0, SEEK_CUR); - if (orig_offset == (off_t)-1) - return -1; - if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) - return -1; + if (orig_offset == (off_t)-1) return -1; + if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) return -1; ssize_t len = write(fd, buf, count); - if (len < 0) - return len; - if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) - return -1; + if (len < 0) return len; + if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) return -1; return len; } #endif // !HAVE_PWRITE @@ -277,7 +272,7 @@ static void GetHostName(string* hostname) { hostname->clear(); } #else -# warning There is no way to retrieve the host name. +# warning There is no way to retrieve the host name. *hostname = "(unknown)"; #endif } @@ -294,16 +289,11 @@ static bool TerminalSupportsColor() { const char* const term = getenv("TERM"); if (term != nullptr && term[0] != '\0') { term_supports_color = - !strcmp(term, "xterm") || - !strcmp(term, "xterm-color") || - !strcmp(term, "xterm-256color") || - !strcmp(term, "screen-256color") || - !strcmp(term, "konsole") || - !strcmp(term, "konsole-16color") || - !strcmp(term, "konsole-256color") || - !strcmp(term, "screen") || - !strcmp(term, "linux") || - !strcmp(term, "cygwin"); + !strcmp(term, "xterm") || !strcmp(term, "xterm-color") || + !strcmp(term, "xterm-256color") || !strcmp(term, "screen-256color") || + !strcmp(term, "konsole") || !strcmp(term, "konsole-16color") || + !strcmp(term, "konsole-256color") || !strcmp(term, "screen") || + !strcmp(term, "linux") || !strcmp(term, "cygwin"); } #endif return term_supports_color; @@ -311,30 +301,25 @@ static bool TerminalSupportsColor() { namespace google { -enum GLogColor { - COLOR_DEFAULT, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW -}; +enum GLogColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; static GLogColor SeverityToColor(LogSeverity severity) { assert(severity >= 0 && severity < NUM_SEVERITIES); GLogColor color = COLOR_DEFAULT; switch (severity) { - case GLOG_INFO: - color = COLOR_DEFAULT; - break; - case GLOG_WARNING: - color = COLOR_YELLOW; - break; - case GLOG_ERROR: - case GLOG_FATAL: - color = COLOR_RED; - break; - default: - // should never get here. - assert(false); + case GLOG_INFO: + color = COLOR_DEFAULT; + break; + case GLOG_WARNING: + color = COLOR_YELLOW; + break; + case GLOG_ERROR: + case GLOG_FATAL: + color = COLOR_RED; + break; + default: + // should never get here. + assert(false); } return color; } @@ -344,10 +329,14 @@ static GLogColor SeverityToColor(LogSeverity severity) { // Returns the character attribute for the given color. static WORD GetColorAttribute(GLogColor color) { switch (color) { - case COLOR_RED: return FOREGROUND_RED; - case COLOR_GREEN: return FOREGROUND_GREEN; - case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; + case COLOR_RED: + return FOREGROUND_RED; + case COLOR_GREEN: + return FOREGROUND_GREEN; + case COLOR_YELLOW: + return FOREGROUND_RED | FOREGROUND_GREEN; + default: + return 0; } } @@ -356,10 +345,14 @@ static WORD GetColorAttribute(GLogColor color) { // Returns the ANSI color code for the given color. static const char* GetAnsiColorCode(GLogColor color) { switch (color) { - case COLOR_RED: return "1"; - case COLOR_GREEN: return "2"; - case COLOR_YELLOW: return "3"; - case COLOR_DEFAULT: return ""; + case COLOR_RED: + return "1"; + case COLOR_GREEN: + return "2"; + case COLOR_YELLOW: + return "3"; + case COLOR_DEFAULT: + return ""; }; return nullptr; // stop warning about return type. } @@ -377,15 +370,15 @@ static uint32 MaxLogSize() { // is so that streaming can be done more efficiently. const size_t LogMessage::kMaxLogMessageLen = 30000; -struct LogMessage::LogMessageData { +struct LogMessage::LogMessageData { LogMessageData(); - int preserved_errno_; // preserved errno + int preserved_errno_; // preserved errno // Buffer space; contains complete message text. - char message_text_[LogMessage::kMaxLogMessageLen+1]; + char message_text_[LogMessage::kMaxLogMessageLen + 1]; LogStream stream_; - char severity_; // What level is this LogMessage logged at? - int line_; // line number where logging call is. + char severity_; // What level is this LogMessage logged at? + int line_; // line number where logging call is. void (LogMessage::*send_method_)(); // Call this in destructor to send union { // At most one of these is used: union to keep the size low. LogSink* sink_; // nullptr or sink to send message to @@ -419,9 +412,8 @@ int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0}; // Globally disable log writing (if disk is full) static bool stop_writing = false; -const char*const LogSeverityNames[NUM_SEVERITIES] = { - "INFO", "WARNING", "ERROR", "FATAL" -}; +const char* const LogSeverityNames[NUM_SEVERITIES] = {"INFO", "WARNING", + "ERROR", "FATAL"}; // Has the user called SetExitOnDFatal(true)? static bool exit_on_dfatal = true; @@ -430,17 +422,17 @@ const char* GetLogSeverityName(LogSeverity severity) { return LogSeverityNames[severity]; } -static bool SendEmailInternal(const char*dest, const char *subject, - const char*body, bool use_logging); +static bool SendEmailInternal(const char* dest, const char* subject, + const char* body, bool use_logging); base::Logger::~Logger() = default; -namespace { - // Optional user-configured callback to print custom prefixes. +namespace { +// Optional user-configured callback to print custom prefixes. CustomPrefixCallback custom_prefix_callback = nullptr; // User-provided data to pass to the callback: void* custom_prefix_callback_data = nullptr; -} +} // namespace namespace { @@ -481,7 +473,7 @@ class LogFileObject : public base::Logger { bool base_filename_selected_; string base_filename_; string symlink_basename_; - string filename_extension_; // option users can specify (eg to add port#) + string filename_extension_; // option users can specify (eg to add port#) FILE* file_{nullptr}; LogSeverity severity_; uint32 bytes_since_flush_{0}; @@ -509,8 +501,7 @@ class LogCleaner { // update next_cleanup_time_ void UpdateCleanUpTime(); - void Run(bool base_filename_selected, - const string& base_filename, + void Run(bool base_filename_selected, const string& base_filename, const string& filename_extension); bool enabled() const { return enabled_; } @@ -544,11 +535,10 @@ class LogDestination { // These methods are just forwarded to by their global versions. static void SetLogDestination(LogSeverity severity, - const char* base_filename); - static void SetLogSymlink(LogSeverity severity, - const char* symlink_basename); - static void AddLogSink(LogSink *destination); - static void RemoveLogSink(LogSink *destination); + const char* base_filename); + static void SetLogSymlink(LogSeverity severity, const char* symlink_basename); + static void AddLogSink(LogSink* destination); + static void RemoveLogSink(LogSink* destination); static void SetLogFilenameExtension(const char* filename_extension); static void SetStderrLogging(LogSeverity min_severity); static void SetEmailLogging(LogSeverity min_severity, const char* addresses); @@ -576,22 +566,20 @@ class LogDestination { // Take a log message of a particular severity and log it to stderr // iff it's of a high enough severity to deserve it. static void MaybeLogToStderr(LogSeverity severity, const char* message, - size_t message_len, size_t prefix_len); + size_t message_len, size_t prefix_len); // Take a log message of a particular severity and log it to email // iff it's of a high enough severity to deserve it. static void MaybeLogToEmail(LogSeverity severity, const char* message, - size_t len); + size_t len); // Take a log message of a particular severity and log it to a file // iff the base filename is not "" (which means "don't log to me") - static void MaybeLogToLogfile(LogSeverity severity, - time_t timestamp, - const char* message, size_t len); + static void MaybeLogToLogfile(LogSeverity severity, time_t timestamp, + const char* message, size_t len); // Take a log message of a particular severity and log it to the file // for that severity and also for all files with severity less than // this severity. - static void LogToAllLogfiles(LogSeverity severity, - time_t timestamp, + static void LogToAllLogfiles(LogSeverity severity, time_t timestamp, const char* message, size_t len); // Send logging info to all registered sinks. @@ -611,7 +599,7 @@ class LogDestination { void ResetLoggerImpl() { SetLoggerImpl(&fileobject_); } LogFileObject fileobject_; - base::Logger* logger_; // Either &fileobject_, or wrapper around it + base::Logger* logger_; // Either &fileobject_, or wrapper around it static LogDestination* log_destinations_[NUM_SEVERITIES]; static LogSeverity email_logging_severity_; @@ -652,15 +640,10 @@ const string& LogDestination::hostname() { return hostname_; } -LogDestination::LogDestination(LogSeverity severity, - const char* base_filename) - : fileobject_(severity, base_filename), - logger_(&fileobject_) { -} +LogDestination::LogDestination(LogSeverity severity, const char* base_filename) + : fileobject_(severity, base_filename), logger_(&fileobject_) {} -LogDestination::~LogDestination() { - ResetLoggerImpl(); -} +LogDestination::~LogDestination() { ResetLoggerImpl(); } void LogDestination::SetLoggerImpl(base::Logger* logger) { if (logger_ == logger) { @@ -701,7 +684,7 @@ inline void LogDestination::FlushLogFiles(int min_severity) { } inline void LogDestination::SetLogDestination(LogSeverity severity, - const char* base_filename) { + const char* base_filename) { assert(severity >= 0 && severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. @@ -717,21 +700,22 @@ inline void LogDestination::SetLogSymlink(LogSeverity severity, log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename); } -inline void LogDestination::AddLogSink(LogSink *destination) { +inline void LogDestination::AddLogSink(LogSink* destination) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&sink_mutex_); - if (!sinks_) sinks_ = new vector; + if (!sinks_) sinks_ = new vector; sinks_->push_back(destination); } -inline void LogDestination::RemoveLogSink(LogSink *destination) { +inline void LogDestination::RemoveLogSink(LogSink* destination) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&sink_mutex_); // This doesn't keep the sinks in order, but who cares? if (sinks_) { - sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination), sinks_->end()); + sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination), + sinks_->end()); } } @@ -739,7 +723,7 @@ inline void LogDestination::SetLogFilenameExtension(const char* ext) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); - for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) { + for (int severity = 0; severity < NUM_SEVERITIES; ++severity) { log_destination(severity)->fileobject_.SetExtension(ext); } } @@ -755,14 +739,14 @@ inline void LogDestination::SetStderrLogging(LogSeverity min_severity) { inline void LogDestination::LogToStderr() { // *Don't* put this stuff in a mutex lock, since SetStderrLogging & // SetLogDestination already do the locking! - SetStderrLogging(0); // thus everything is "also" logged to stderr - for ( int i = 0; i < NUM_SEVERITIES; ++i ) { - SetLogDestination(i, ""); // "" turns off logging to a logfile + SetStderrLogging(0); // thus everything is "also" logged to stderr + for (int i = 0; i < NUM_SEVERITIES; ++i) { + SetLogDestination(i, ""); // "" turns off logging to a logfile } } inline void LogDestination::SetEmailLogging(LogSeverity min_severity, - const char* addresses) { + const char* addresses) { assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. @@ -835,35 +819,35 @@ static void WriteToStderr(const char* message, size_t len) { } inline void LogDestination::MaybeLogToStderr(LogSeverity severity, - const char* message, size_t message_len, size_t prefix_len) { + const char* message, + size_t message_len, + size_t prefix_len) { if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) { ColoredWriteToStderr(severity, message, message_len); #ifdef GLOG_OS_WINDOWS - (void) prefix_len; + (void)prefix_len; // On Windows, also output to the debugger ::OutputDebugStringA(message); #elif defined(__ANDROID__) // On Android, also output to logcat const int android_log_levels[NUM_SEVERITIES] = { - ANDROID_LOG_INFO, - ANDROID_LOG_WARN, - ANDROID_LOG_ERROR, - ANDROID_LOG_FATAL, + ANDROID_LOG_INFO, + ANDROID_LOG_WARN, + ANDROID_LOG_ERROR, + ANDROID_LOG_FATAL, }; __android_log_write(android_log_levels[severity], glog_internal_namespace_::ProgramInvocationShortName(), message + prefix_len); #else - (void) prefix_len; + (void)prefix_len; #endif } } - inline void LogDestination::MaybeLogToEmail(LogSeverity severity, - const char* message, size_t len) { - if (severity >= email_logging_severity_ || - severity >= FLAGS_logemaillevel) { + const char* message, size_t len) { + if (severity >= email_logging_severity_ || severity >= FLAGS_logemaillevel) { string to(FLAGS_alsologtoemail); if (!addresses_.empty()) { if (!to.empty()) { @@ -871,8 +855,9 @@ inline void LogDestination::MaybeLogToEmail(LogSeverity severity, } to += addresses_; } - const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " + - glog_internal_namespace_::ProgramInvocationShortName()); + const string subject( + string("[LOG] ") + LogSeverityNames[severity] + ": " + + glog_internal_namespace_::ProgramInvocationShortName()); string body(hostname()); body += "\n\n"; body.append(message, len); @@ -885,11 +870,9 @@ inline void LogDestination::MaybeLogToEmail(LogSeverity severity, } } - inline void LogDestination::MaybeLogToLogfile(LogSeverity severity, time_t timestamp, - const char* message, - size_t len) { + const char* message, size_t len) { const bool should_flush = severity > FLAGS_logbuflevel; LogDestination* destination = log_destination(severity); destination->logger_->Write(should_flush, timestamp, message, len); @@ -897,8 +880,7 @@ inline void LogDestination::MaybeLogToLogfile(LogSeverity severity, inline void LogDestination::LogToAllLogfiles(LogSeverity severity, time_t timestamp, - const char* message, - size_t len) { + const char* message, size_t len) { if (FLAGS_logtostdout) { // global flag: never log to file ColoredWriteToStdout(severity, message, len); } else if (FLAGS_logtostderr) { // global flag: never log to file @@ -918,9 +900,9 @@ inline void LogDestination::LogToSinks(LogSeverity severity, size_t message_len) { ReaderMutexLock l(&sink_mutex_); if (sinks_) { - for (size_t i = sinks_->size(); i-- > 0; ) { - (*sinks_)[i]->send(severity, full_filename, base_filename, - line, logmsgtime, message, message_len); + for (size_t i = sinks_->size(); i-- > 0;) { + (*sinks_)[i]->send(severity, full_filename, base_filename, line, + logmsgtime, message, message_len); } } } @@ -928,7 +910,7 @@ inline void LogDestination::LogToSinks(LogSeverity severity, inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { ReaderMutexLock l(&sink_mutex_); if (sinks_) { - for (size_t i = sinks_->size(); i-- > 0; ) { + for (size_t i = sinks_->size(); i-- > 0;) { (*sinks_)[i]->WaitTillSent(); } } @@ -943,7 +925,7 @@ inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES]; inline LogDestination* LogDestination::log_destination(LogSeverity severity) { - assert(severity >=0 && severity < NUM_SEVERITIES); + assert(severity >= 0 && severity < NUM_SEVERITIES); if (!log_destinations_[severity]) { log_destinations_[severity] = new LogDestination(severity, nullptr); } @@ -964,7 +946,7 @@ namespace { std::string g_application_fingerprint; -} // namespace +} // namespace void SetApplicationFingerprint(const std::string& fingerprint) { g_application_fingerprint = fingerprint; @@ -1021,7 +1003,7 @@ void LogFileObject::SetBasename(const char* basename) { if (file_ != nullptr) { fclose(file_); file_ = nullptr; - rollover_attempt_ = kRolloverAttemptFrequency-1; + rollover_attempt_ = kRolloverAttemptFrequency - 1; } base_filename_ = basename; } @@ -1034,7 +1016,7 @@ void LogFileObject::SetExtension(const char* ext) { if (file_ != nullptr) { fclose(file_); file_ = nullptr; - rollover_attempt_ = kRolloverAttemptFrequency-1; + rollover_attempt_ = kRolloverAttemptFrequency - 1; } filename_extension_ = ext; } @@ -1050,14 +1032,14 @@ void LogFileObject::Flush() { FlushUnlocked(); } -void LogFileObject::FlushUnlocked(){ +void LogFileObject::FlushUnlocked() { if (file_ != nullptr) { fflush(file_); bytes_since_flush_ = 0; } // Figure out when we are due for another flush. - const int64 next = (FLAGS_logbufsecs - * static_cast(1000000)); // in usec + const int64 next = + (FLAGS_logbufsecs * static_cast(1000000)); // in usec next_flush_time_ = CycleClock_Now() + UsecToCycles(next); } @@ -1068,10 +1050,10 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) { } string_filename += filename_extension_; const char* filename = string_filename.c_str(); - //only write to files, create if non-existant. + // only write to files, create if non-existant. int flags = O_WRONLY | O_CREAT; if (FLAGS_timestamp_in_logfile_name) { - //demand that the file is unique for our timestamp (fail if it exists). + // demand that the file is unique for our timestamp (fail if it exists). flags = flags | O_EXCL; } int fd = open(filename, flags, static_cast(FLAGS_logfile_mode)); @@ -1099,23 +1081,24 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) { int wlock_ret = fcntl(fd, F_SETLK, &w_lock); if (wlock_ret == -1) { - close(fd); //as we are failing already, do not check errors here - return false; + close(fd); // as we are failing already, do not check errors here + return false; } #endif - //fdopen in append mode so if the file exists it will fseek to the end + // fdopen in append mode so if the file exists it will fseek to the end file_ = fdopen(fd, "a"); // Make a FILE*. if (file_ == nullptr) { // Man, we're screwed! - close(fd); - if (FLAGS_timestamp_in_logfile_name) { - unlink(filename); // Erase the half-baked evidence: an unusable log file, only if we just created it. + close(fd); + if (FLAGS_timestamp_in_logfile_name) { + unlink(filename); // Erase the half-baked evidence: an unusable log file, + // only if we just created it. } return false; } #ifdef GLOG_OS_WINDOWS - // https://github.com/golang/go/issues/27638 - make sure we seek to the end to append - // empirically replicated with wine over mingw build + // https://github.com/golang/go/issues/27638 - make sure we seek to the end to + // append empirically replicated with wine over mingw build if (!FLAGS_timestamp_in_logfile_name) { if (fseek(file_, 0, SEEK_END) != 0) { return false; @@ -1131,11 +1114,13 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) { // take directory from filename const char* slash = strrchr(filename, PATH_SEPARATOR); const string linkname = - symlink_basename_ + '.' + LogSeverityNames[severity_]; + symlink_basename_ + '.' + LogSeverityNames[severity_]; string linkpath; - if ( slash ) linkpath = string(filename, static_cast(slash-filename+1)); // get dirname + if (slash) + linkpath = string( + filename, static_cast(slash - filename + 1)); // get dirname linkpath += linkname; - unlink(linkpath.c_str()); // delete old one if it exists + unlink(linkpath.c_str()); // delete old one if it exists #if defined(GLOG_OS_WINDOWS) // TODO(hamaji): Create lnk file on Windows? @@ -1143,7 +1128,7 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) { // We must have unistd.h. // Make the symlink be relative (in the same dir) so that if the // entire log directory gets relocated the link is still valid. - const char *linkdest = slash ? (slash + 1) : filename; + const char* linkdest = slash ? (slash + 1) : filename; if (symlink(linkdest, linkpath.c_str()) != 0) { // silently ignore failures } @@ -1152,7 +1137,7 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) { // FLAGS_log_link, if indicated if (!FLAGS_log_link.empty()) { linkpath = FLAGS_log_link + "/" + linkname; - unlink(linkpath.c_str()); // delete old one if it exists + unlink(linkpath.c_str()); // delete old one if it exists if (symlink(filename, linkpath.c_str()) != 0) { // silently ignore failures } @@ -1163,10 +1148,8 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) { return true; // Everything worked } -void LogFileObject::Write(bool force_flush, - time_t timestamp, - const char* message, - size_t message_len) { +void LogFileObject::Write(bool force_flush, time_t timestamp, + const char* message, size_t message_len) { MutexLock l(&lock_); // We don't log if the base_name_ is "" (which means "don't write") @@ -1199,15 +1182,10 @@ void LogFileObject::Write(bool force_flush, // The logfile's filename will have the date/time & pid in it ostringstream time_pid_stream; time_pid_stream.fill('0'); - time_pid_stream << 1900+tm_time.tm_year - << setw(2) << 1+tm_time.tm_mon - << setw(2) << tm_time.tm_mday - << '-' - << setw(2) << tm_time.tm_hour - << setw(2) << tm_time.tm_min - << setw(2) << tm_time.tm_sec - << '.' - << GetMainThreadPid(); + time_pid_stream << 1900 + tm_time.tm_year << setw(2) << 1 + tm_time.tm_mon + << setw(2) << tm_time.tm_mday << '-' << setw(2) + << tm_time.tm_hour << setw(2) << tm_time.tm_min << setw(2) + << tm_time.tm_sec << '.' << GetMainThreadPid(); const string& time_pid_string = time_pid_stream.str(); if (base_filename_selected_) { @@ -1241,24 +1219,23 @@ void LogFileObject::Write(bool force_flush, // deadlock. Simply use a name like invalid-user. if (uidname.empty()) uidname = "invalid-user"; - stripped_filename = stripped_filename+'.'+hostname+'.' - +uidname+".log." - +LogSeverityNames[severity_]+'.'; + stripped_filename = stripped_filename + '.' + hostname + '.' + uidname + + ".log." + LogSeverityNames[severity_] + '.'; // We're going to (potentially) try to put logs in several different dirs - const vector & log_dirs = GetLoggingDirectories(); + const vector& log_dirs = GetLoggingDirectories(); // Go through the list of dirs, and try to create the log file in each // until we succeed or run out of options bool success = false; for (const auto& log_dir : log_dirs) { base_filename_ = log_dir + "/" + stripped_filename; - if ( CreateLogfile(time_pid_string) ) { + if (CreateLogfile(time_pid_string)) { success = true; break; } } // If we never succeeded, we have to give up - if ( success == false ) { + if (success == false) { perror("Could not create logging file"); fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string.c_str()); @@ -1270,25 +1247,26 @@ void LogFileObject::Write(bool force_flush, if (FLAGS_log_file_header) { ostringstream file_header_stream; file_header_stream.fill('0'); - file_header_stream << "Log file created at: " - << 1900+tm_time.tm_year << '/' - << setw(2) << 1+tm_time.tm_mon << '/' - << setw(2) << tm_time.tm_mday - << ' ' - << setw(2) << tm_time.tm_hour << ':' - << setw(2) << tm_time.tm_min << ':' - << setw(2) << tm_time.tm_sec << (FLAGS_log_utc_time ? " UTC\n" : "\n") - << "Running on machine: " - << LogDestination::hostname() << '\n'; - - if(!g_application_fingerprint.empty()) { - file_header_stream << "Application fingerprint: " << g_application_fingerprint << '\n'; + file_header_stream << "Log file created at: " << 1900 + tm_time.tm_year + << '/' << setw(2) << 1 + tm_time.tm_mon << '/' + << setw(2) << tm_time.tm_mday << ' ' << setw(2) + << tm_time.tm_hour << ':' << setw(2) << tm_time.tm_min + << ':' << setw(2) << tm_time.tm_sec + << (FLAGS_log_utc_time ? " UTC\n" : "\n") + << "Running on machine: " << LogDestination::hostname() + << '\n'; + + if (!g_application_fingerprint.empty()) { + file_header_stream << "Application fingerprint: " + << g_application_fingerprint << '\n'; } const char* const date_time_format = FLAGS_log_year_in_prefix ? "yyyymmdd hh:mm:ss.uuuuuu" : "mmdd hh:mm:ss.uuuuuu"; file_header_stream << "Running duration (h:mm:ss): " - << PrettyDuration(static_cast(WallTime_Now() - start_time_)) << '\n' + << PrettyDuration( + static_cast(WallTime_Now() - start_time_)) + << '\n' << "Log line format: [IWEF]" << date_time_format << " " << "threadid file:line] msg" << '\n'; const string& file_header_string = file_header_stream.str(); @@ -1301,7 +1279,7 @@ void LogFileObject::Write(bool force_flush, } // Write to LOG file - if ( !stop_writing ) { + if (!stop_writing) { // fwrite() doesn't return an error when the disk is full, for // messages that are less than 4096 bytes. When the disk is full, // it returns the message length for messages that are less than @@ -1309,8 +1287,8 @@ void LogFileObject::Write(bool force_flush, // greater than 4096, thereby indicating an error. errno = 0; fwrite(message, 1, message_len, file_); - if ( FLAGS_stop_logging_if_full_disk && - errno == ENOSPC ) { // disk full, stop writing to disk + if (FLAGS_stop_logging_if_full_disk && + errno == ENOSPC) { // disk full, stop writing to disk stop_writing = true; // until the disk is return; } else { @@ -1326,9 +1304,8 @@ void LogFileObject::Write(bool force_flush, // See important msgs *now*. Also, flush logs at least every 10^6 chars, // or every "FLAGS_logbufsecs" seconds. - if ( force_flush || - (bytes_since_flush_ >= 1000000) || - (CycleClock_Now() >= next_flush_time_) ) { + if (force_flush || (bytes_since_flush_ >= 1000000) || + (CycleClock_Now() >= next_flush_time_)) { FlushUnlocked(); #ifdef GLOG_OS_LINUX // Only consider files >= 3MiB @@ -1340,14 +1317,14 @@ void LogFileObject::Write(bool force_flush, uint32 this_drop_length = total_drop_length - dropped_mem_length_; if (this_drop_length >= (2U << 20U)) { // Only advise when >= 2MiB to drop -# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) +# if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) // 'posix_fadvise' introduced in API 21: // * https://android.googlesource.com/platform/bionic/+/6880f936173081297be0dc12f687d341b86a4cfa/libc/libc.map.txt#732 -# else +# else posix_fadvise(fileno(file_), static_cast(dropped_mem_length_), static_cast(this_drop_length), POSIX_FADV_DONTNEED); -# endif +# endif dropped_mem_length_ = total_drop_length; } } @@ -1355,8 +1332,7 @@ void LogFileObject::Write(bool force_flush, // Remove old logs if (log_cleaner.enabled()) { - log_cleaner.Run(base_filename_selected_, - base_filename_, + log_cleaner.Run(base_filename_selected_, base_filename_, filename_extension_); } } @@ -1369,18 +1345,14 @@ void LogCleaner::Enable(unsigned int overdue_days) { overdue_days_ = overdue_days; } -void LogCleaner::Disable() { - enabled_ = false; -} +void LogCleaner::Disable() { enabled_ = false; } void LogCleaner::UpdateCleanUpTime() { - const int64 next = (FLAGS_logcleansecs - * 1000000); // in usec + const int64 next = (FLAGS_logcleansecs * 1000000); // in usec next_cleanup_time_ = CycleClock_Now() + UsecToCycles(next); } -void LogCleaner::Run(bool base_filename_selected, - const string& base_filename, +void LogCleaner::Run(bool base_filename_selected, const string& base_filename, const string& filename_extension) { assert(enabled_); assert(!base_filename_selected || !base_filename.empty()); @@ -1422,8 +1394,8 @@ vector LogCleaner::GetOverdueLogNames( vector overdue_log_names; // Try to get all files within log_directory. - DIR *dir; - struct dirent *ent; + DIR* dir; + struct dirent* ent; if ((dir = opendir(log_directory.c_str()))) { while ((ent = readdir(dir))) { @@ -1441,7 +1413,8 @@ vector LogCleaner::GetOverdueLogNames( filepath = log_directory + filepath; } - if (IsLogFromCurrentProject(filepath, base_filename, filename_extension) && + if (IsLogFromCurrentProject(filepath, base_filename, + filename_extension) && IsLogLastModifiedOver(filepath, days)) { overdue_log_names.push_back(filepath); } @@ -1452,9 +1425,9 @@ vector LogCleaner::GetOverdueLogNames( return overdue_log_names; } -bool LogCleaner::IsLogFromCurrentProject(const string& filepath, - const string& base_filename, - const string& filename_extension) const { +bool LogCleaner::IsLogFromCurrentProject( + const string& filepath, const string& base_filename, + const string& filename_extension) const { // We should remove duplicated delimiters from `base_filename`, e.g., // before: "/tmp//.." // after: "/tmp/.." @@ -1488,11 +1461,11 @@ bool LogCleaner::IsLogFromCurrentProject(const string& filepath, return false; } // for origin version, `filename_extension` is middle of the `filepath`. - string ext = filepath.substr(cleaned_base_filename.size(), filename_extension.size()); + string ext = filepath.substr(cleaned_base_filename.size(), + filename_extension.size()); if (ext == filename_extension) { cleaned_base_filename += filename_extension; - } - else { + } else { // for new version, `filename_extension` is right of the `filepath`. if (filename_extension.size() >= real_filepath_size) { return false; @@ -1509,20 +1482,30 @@ bool LogCleaner::IsLogFromCurrentProject(const string& filepath, for (size_t i = cleaned_base_filename.size(); i < real_filepath_size; i++) { const char& c = filepath[i]; - if (i <= cleaned_base_filename.size() + 7) { // 0 ~ 7 : YYYYMMDD - if (c < '0' || c > '9') { return false; } + if (i <= cleaned_base_filename.size() + 7) { // 0 ~ 7 : YYYYMMDD + if (c < '0' || c > '9') { + return false; + } - } else if (i == cleaned_base_filename.size() + 8) { // 8: - - if (c != '-') { return false; } + } else if (i == cleaned_base_filename.size() + 8) { // 8: - + if (c != '-') { + return false; + } - } else if (i <= cleaned_base_filename.size() + 14) { // 9 ~ 14: HHMMSS - if (c < '0' || c > '9') { return false; } + } else if (i <= cleaned_base_filename.size() + 14) { // 9 ~ 14: HHMMSS + if (c < '0' || c > '9') { + return false; + } - } else if (i == cleaned_base_filename.size() + 15) { // 15: . - if (c != '.') { return false; } + } else if (i == cleaned_base_filename.size() + 15) { // 15: . + if (c != '.') { + return false; + } - } else if (i >= cleaned_base_filename.size() + 16) { // 16+: pid - if (c < '0' || c > '9') { return false; } + } else if (i >= cleaned_base_filename.size() + 16) { // 16+: pid + if (c < '0' || c > '9') { + return false; + } } } @@ -1565,20 +1548,19 @@ static LogMessage::LogMessageData fatal_msg_data_shared; // allocations). static thread_local bool thread_data_available = true; -#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L +# if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L // std::aligned_storage is deprecated in C++23 alignas(LogMessage::LogMessageData) static thread_local std::byte thread_msg_data[sizeof(LogMessage::LogMessageData)]; -#else // !(defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L) +# else // !(defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L) static thread_local std::aligned_storage< sizeof(LogMessage::LogMessageData), alignof(LogMessage::LogMessageData)>::type thread_msg_data; -#endif // defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L -#endif // defined(GLOG_THREAD_LOCAL_STORAGE) +# endif // defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L +#endif // defined(GLOG_THREAD_LOCAL_STORAGE) LogMessage::LogMessageData::LogMessageData() - : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) { -} + : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) {} LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int64 ctr, void (LogMessage::*send_method)()) @@ -1605,8 +1587,9 @@ LogMessage::LogMessage(const char* file, int line, LogSeverity severity) LogMessage::LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, bool also_send_to_log) : allocated_(nullptr) { - Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog : - &LogMessage::SendToSink); + Init(file, line, severity, + also_send_to_log ? &LogMessage::SendToSinkAndLog + : &LogMessage::SendToSink); data_->sink_ = sink; // override Init()'s setting to nullptr } @@ -1624,9 +1607,7 @@ LogMessage::LogMessage(const char* file, int line, LogSeverity severity, data_->message_ = message; // override Init()'s setting to nullptr } -void LogMessage::Init(const char* file, - int line, - LogSeverity severity, +void LogMessage::Init(const char* file, int line, LogSeverity severity, void (LogMessage::*send_method)()) { allocated_ = nullptr; if (severity != GLOG_FATAL || !exit_on_dfatal) { @@ -1639,10 +1620,10 @@ void LogMessage::Init(const char* file, allocated_ = new LogMessageData(); data_ = allocated_; } -#else // !defined(GLOG_THREAD_LOCAL_STORAGE) +#else // !defined(GLOG_THREAD_LOCAL_STORAGE) allocated_ = new LogMessageData(); data_ = allocated_; -#endif // defined(GLOG_THREAD_LOCAL_STORAGE) +#endif // defined(GLOG_THREAD_LOCAL_STORAGE) data_->first_fatal_ = false; } else { MutexLock l(&fatal_msg_lock); @@ -1700,7 +1681,7 @@ void LogMessage::Init(const char* file, custom_prefix_callback_data); stream() << " "; } - stream().copyfmt(saved_fmt); + stream().copyfmt(saved_fmt); } data_->num_prefix_chars_ = data_->stream_.pcount(); @@ -1727,22 +1708,17 @@ LogMessage::~LogMessage() { if (data_ == static_cast(&thread_msg_data)) { data_->~LogMessageData(); thread_data_available = true; - } - else { + } else { delete allocated_; } -#else // !defined(GLOG_THREAD_LOCAL_STORAGE) +#else // !defined(GLOG_THREAD_LOCAL_STORAGE) delete allocated_; -#endif // defined(GLOG_THREAD_LOCAL_STORAGE) +#endif // defined(GLOG_THREAD_LOCAL_STORAGE) } -int LogMessage::preserved_errno() const { - return data_->preserved_errno_; -} +int LogMessage::preserved_errno() const { return data_->preserved_errno_; } -ostream& LogMessage::stream() { - return data_->stream_; -} +ostream& LogMessage::stream() { return data_->stream_; } // Flush buffered message, called by the destructor, or any other function // that needs to synchronize the log. @@ -1753,11 +1729,11 @@ void LogMessage::Flush() { data_->num_chars_to_log_ = data_->stream_.pcount(); data_->num_chars_to_syslog_ = - data_->num_chars_to_log_ - data_->num_prefix_chars_; + data_->num_chars_to_log_ - data_->num_prefix_chars_; // Do we need to add a \n to the end of this message? bool append_newline = - (data_->message_text_[data_->num_chars_to_log_-1] != '\n'); + (data_->message_text_[data_->num_chars_to_log_ - 1] != '\n'); char original_final_char = '\0'; // If we do need to add a \n, we'll do it by violating the memory of the @@ -1783,7 +1759,7 @@ void LogMessage::Flush() { if (append_newline) { // Fix the ostrstream back how it was before we screwed with it. // It's 99.44% certain that we don't need to worry about doing this. - data_->message_text_[data_->num_chars_to_log_-1] = original_final_char; + data_->message_text_[data_->num_chars_to_log_ - 1] = original_final_char; } // If errno was already set before we enter the logging call, we'll @@ -1824,13 +1800,15 @@ void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { log_mutex.AssertHeld(); RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + data_->message_text_[data_->num_chars_to_log_ - 1] == '\n', + ""); // Messages of a given severity get logged to lower severity logs, too if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) { - const char w[] = "WARNING: Logging before InitGoogleLogging() is " - "written to STDERR\n"; + const char w[] = + "WARNING: Logging before InitGoogleLogging() is " + "written to STDERR\n"; WriteToStderr(w, strlen(w)); already_warned_before_initgoogle = true; } @@ -1848,12 +1826,10 @@ void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { } // this could be protected by a flag if necessary. - LogDestination::LogToSinks(data_->severity_, - data_->fullname_, data_->basename_, - data_->line_, logmsgtime_, - data_->message_text_ + data_->num_prefix_chars_, - (data_->num_chars_to_log_ - - data_->num_prefix_chars_ - 1) ); + LogDestination::LogToSinks( + data_->severity_, data_->fullname_, data_->basename_, data_->line_, + logmsgtime_, data_->message_text_ + data_->num_prefix_chars_, + (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1)); } else { // log this message to all log files of severity <= severity_ LogDestination::LogToAllLogfiles(data_->severity_, logmsgtime_.timestamp(), @@ -1865,12 +1841,10 @@ void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { data_->num_prefix_chars_); LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_, data_->num_chars_to_log_); - LogDestination::LogToSinks(data_->severity_, - data_->fullname_, data_->basename_, - data_->line_, logmsgtime_, - data_->message_text_ + data_->num_prefix_chars_, - (data_->num_chars_to_log_ - - data_->num_prefix_chars_ - 1) ); + LogDestination::LogToSinks( + data_->severity_, data_->fullname_, data_->basename_, data_->line_, + logmsgtime_, data_->message_text_ + data_->num_prefix_chars_, + (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1)); // NOTE: -1 removes trailing \n } @@ -1885,8 +1859,8 @@ void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { SetCrashReason(&crash_reason); // Store shortened fatal message for other logs and GWQ status - const size_t copy = min(data_->num_chars_to_log_, - sizeof(fatal_message)-1); + const size_t copy = + min(data_->num_chars_to_log_, sizeof(fatal_message) - 1); memcpy(fatal_message, data_->message_text_, copy); fatal_message[copy] = '\0'; fatal_time = logmsgtime_.timestamp(); @@ -1955,20 +1929,18 @@ void InstallFailureFunction(logging_fail_func_t fail_func) { g_logging_fail_func = fail_func; } -void LogMessage::Fail() { - g_logging_fail_func(); -} +void LogMessage::Fail() { g_logging_fail_func(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->sink_ != nullptr) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); - data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_, - data_->line_, logmsgtime_, - data_->message_text_ + data_->num_prefix_chars_, - (data_->num_chars_to_log_ - - data_->num_prefix_chars_ - 1) ); + data_->message_text_[data_->num_chars_to_log_ - 1] == '\n', + ""); + data_->sink_->send( + data_->severity_, data_->fullname_, data_->basename_, data_->line_, + logmsgtime_, data_->message_text_ + data_->num_prefix_chars_, + (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1)); } } @@ -1982,9 +1954,10 @@ void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->outvec_ != nullptr) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + data_->message_text_[data_->num_chars_to_log_ - 1] == '\n', + ""); // Omit prefix of message and trailing newline when recording in outvec_. - const char *start = data_->message_text_ + data_->num_prefix_chars_; + const char* start = data_->message_text_ + data_->num_prefix_chars_; size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; data_->outvec_->push_back(string(start, len)); } else { @@ -1995,9 +1968,10 @@ void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->message_ != nullptr) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); + data_->message_text_[data_->num_chars_to_log_ - 1] == '\n', + ""); // Omit prefix of message and trailing newline when writing to message_. - const char *start = data_->message_text_ + data_->num_prefix_chars_; + const char* start = data_->message_text_ + data_->num_prefix_chars_; size_t len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; data_->message_->assign(start, len); } @@ -2011,13 +1985,12 @@ void LogMessage::SendToSyslogAndLog() { static bool openlog_already_called = false; if (!openlog_already_called) { openlog(glog_internal_namespace_::ProgramInvocationShortName(), - LOG_CONS | LOG_NDELAY | LOG_PID, - LOG_USER); + LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER); openlog_already_called = true; } // This array maps Google severity levels to syslog levels - const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG }; + const int SEVERITY_TO_LEVEL[] = {LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG}; syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast(data_->severity_)], "%.*s", static_cast(data_->num_chars_to_syslog_), data_->message_text_ + data_->num_prefix_chars_); @@ -2045,9 +2018,9 @@ int64 LogMessage::num_messages(int severity) { // Output the COUNTER value. This is only valid if ostream is a // LogStream. -ostream& operator<<(ostream &os, const PRIVATE_Counter&) { +ostream& operator<<(ostream& os, const PRIVATE_Counter&) { #ifdef DISABLE_RTTI - LogMessage::LogStream *log = static_cast(&os); + LogMessage::LogStream* log = static_cast(&os); #else auto* log = dynamic_cast(&os); #endif @@ -2065,8 +2038,8 @@ ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, ErrnoLogMessage::~ErrnoLogMessage() { // Don't access errno directly because it may have been altered // while streaming the message. - stream() << ": " << StrError(preserved_errno()) << " [" - << preserved_errno() << "]"; + stream() << ": " << StrError(preserved_errno()) << " [" << preserved_errno() + << "]"; } void FlushLogFiles(LogSeverity min_severity) { @@ -2092,18 +2065,18 @@ void LogSink::send(LogSeverity severity, const char* full_filename, const LogMessageTime& time, const char* message, size_t message_len) { #if defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #elif defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable : 4996) +# pragma warning(push) +# pragma warning(disable : 4996) #endif // __GNUC__ send(severity, full_filename, base_filename, line, &time.tm(), message, message_len); #if defined(__GNUC__) -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #elif defined(_MSC_VER) -#pragma warning(pop) +# pragma warning(pop) #endif // __GNUC__ } @@ -2133,17 +2106,11 @@ string LogSink::ToString(LogSeverity severity, const char* file, int line, if (FLAGS_log_year_in_prefix) { stream << setw(4) << 1900 + logmsgtime.year(); } - stream << setw(2) << 1 + logmsgtime.month() - << setw(2) << logmsgtime.day() - << ' ' - << setw(2) << logmsgtime.hour() << ':' - << setw(2) << logmsgtime.min() << ':' - << setw(2) << logmsgtime.sec() << '.' - << setw(6) << logmsgtime.usec() - << ' ' - << setfill(' ') << setw(5) << GetTID() << setfill('0') - << ' ' - << file << ':' << line << "] "; + stream << setw(2) << 1 + logmsgtime.month() << setw(2) << logmsgtime.day() + << ' ' << setw(2) << logmsgtime.hour() << ':' << setw(2) + << logmsgtime.min() << ':' << setw(2) << logmsgtime.sec() << '.' + << setw(6) << logmsgtime.usec() << ' ' << setfill(' ') << setw(5) + << GetTID() << setfill('0') << ' ' << file << ':' << line << "] "; // A call to `write' is enclosed in parenthneses to prevent possible macro // expansion. On Windows, `write' could be a macro defined for portability. @@ -2151,11 +2118,11 @@ string LogSink::ToString(LogSeverity severity, const char* file, int line, return stream.str(); } -void AddLogSink(LogSink *destination) { +void AddLogSink(LogSink* destination) { LogDestination::AddLogSink(destination); } -void RemoveLogSink(LogSink *destination) { +void RemoveLogSink(LogSink* destination) { LogDestination::RemoveLogSink(destination); } @@ -2171,9 +2138,7 @@ void SetEmailLogging(LogSeverity min_severity, const char* addresses) { LogDestination::SetEmailLogging(min_severity, addresses); } -void LogToStderr() { - LogDestination::LogToStderr(); -} +void LogToStderr() { LogDestination::LogToStderr(); } namespace base { namespace internal { @@ -2206,9 +2171,9 @@ void SetExitOnDFatal(bool value) { #ifndef GLOG_OS_EMSCRIPTEN // Shell-escaping as we need to shell out ot /bin/mail. static const char kDontNeedShellEscapeChars[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+-_.=/:,@"; + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+-_.=/:,@"; static string ShellEscape(const string& src) { string result; @@ -2240,7 +2205,7 @@ static string ShellEscape(const string& src) { } // Trim whitespace from both ends of the provided string. -static inline void trim(std::string &s) { +static inline void trim(std::string& s) { const auto toRemove = [](char ch) { return std::isspace(ch) == 0; }; s.erase(s.begin(), std::find_if(s.begin(), s.end(), toRemove)); s.erase(std::find_if(s.rbegin(), s.rend(), toRemove).base(), s.end()); @@ -2250,8 +2215,8 @@ static inline void trim(std::string &s) { // use_logging controls whether the logging functions LOG/VLOG are used // to log errors. It should be set to false when the caller holds the // log_mutex. -static bool SendEmailInternal(const char*dest, const char *subject, - const char*body, bool use_logging) { +static bool SendEmailInternal(const char* dest, const char* subject, + const char* body, bool use_logging) { #ifndef GLOG_OS_EMSCRIPTEN if (dest && *dest) { // Split the comma-separated list of email addresses, validate each one and @@ -2270,7 +2235,8 @@ static bool SendEmailInternal(const char*dest, const char *subject, // allow email addresses that start with a special character, such as a // pipe or dash, which could be misunderstood as a command-line flag by // certain versions of `mail` that are vulnerable to command injection.[2] - // [1] https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address + // [1] + // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address // [2] e.g. https://nvd.nist.gov/vuln/detail/CVE-2004-2771 if (!std::regex_match( s, @@ -2281,8 +2247,7 @@ static bool SendEmailInternal(const char*dest, const char *subject, if (use_logging) { VLOG(1) << "Invalid destination email address:" << s; } else { - fprintf(stderr, "Invalid destination email address: %s\n", - s.c_str()); + fprintf(stderr, "Invalid destination email address: %s\n", s.c_str()); } return false; } @@ -2295,12 +2260,12 @@ static bool SendEmailInternal(const char*dest, const char *subject, const std::string& tmp = sanitized_dests.str(); dest = tmp.c_str(); - if ( use_logging ) { - VLOG(1) << "Trying to send TITLE:" << subject - << " BODY:" << body << " to " << dest; + if (use_logging) { + VLOG(1) << "Trying to send TITLE:" << subject << " BODY:" << body + << " to " << dest; } else { - fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n", - subject, body, dest); + fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n", subject, + body, dest); } string logmailer; @@ -2315,7 +2280,7 @@ static bool SendEmailInternal(const char*dest, const char *subject, string cmd = logmailer + " -s" + ShellEscape(subject) + " " + ShellEscape(dest); if (use_logging) { - VLOG(4) << "Mailing command: " << cmd; + VLOG(4) << "Mailing command: " << cmd; } FILE* pipe = popen(cmd.c_str(), "w"); @@ -2325,18 +2290,18 @@ static bool SendEmailInternal(const char*dest, const char *subject, fwrite(body, sizeof(char), strlen(body), pipe); } bool ok = pclose(pipe) != -1; - if ( !ok ) { - if ( use_logging ) { + if (!ok) { + if (use_logging) { LOG(ERROR) << "Problems sending mail to " << dest << ": " << StrError(errno); } else { - fprintf(stderr, "Problems sending mail to %s: %s\n", - dest, StrError(errno).c_str()); + fprintf(stderr, "Problems sending mail to %s: %s\n", dest, + StrError(errno).c_str()); } } return ok; } else { - if ( use_logging ) { + if (use_logging) { LOG(ERROR) << "Unable to send mail to " << dest; } else { fprintf(stderr, "Unable to send mail to %s\n", dest); @@ -2353,7 +2318,7 @@ static bool SendEmailInternal(const char*dest, const char *subject, return false; } -bool SendEmail(const char*dest, const char *subject, const char*body){ +bool SendEmail(const char* dest, const char* subject, const char* body) { return SendEmailInternal(dest, subject, body, true); } @@ -2367,22 +2332,22 @@ static void GetTempDirectories(vector* list) { // C:/WINDOWS/ or C:/WINNT/ // . char tmp[MAX_PATH]; - if (GetTempPathA(MAX_PATH, tmp)) - list->push_back(tmp); + if (GetTempPathA(MAX_PATH, tmp)) list->push_back(tmp); list->push_back("C:\\tmp\\"); list->push_back("C:\\temp\\"); #else // Directories, in order of preference. If we find a dir that // exists, we stop adding other less-preferred dirs - const char * candidates[] = { - // Non-null only during unittest/regtest - getenv("TEST_TMPDIR"), + const char* candidates[] = { + // Non-null only during unittest/regtest + getenv("TEST_TMPDIR"), - // Explicitly-supplied temp dirs - getenv("TMPDIR"), getenv("TMP"), + // Explicitly-supplied temp dirs + getenv("TMPDIR"), + getenv("TMP"), - // If all else fails - "/tmp", + // If all else fails + "/tmp", }; for (auto d : candidates) { @@ -2412,10 +2377,11 @@ const vector& GetLoggingDirectories() { if (logging_directories_list == nullptr) { logging_directories_list = new vector; - if ( !FLAGS_log_dir.empty() ) { + if (!FLAGS_log_dir.empty()) { // Ensure the specified path ends with a directory delimiter. - if (std::find(std::begin(possible_dir_delim), std::end(possible_dir_delim), - FLAGS_log_dir.back()) == std::end(possible_dir_delim)) { + if (std::find(std::begin(possible_dir_delim), + std::end(possible_dir_delim), + FLAGS_log_dir.back()) == std::end(possible_dir_delim)) { logging_directories_list->push_back(FLAGS_log_dir + "/"); } else { logging_directories_list->push_back(FLAGS_log_dir); @@ -2436,7 +2402,8 @@ const vector& GetLoggingDirectories() { } void TestOnly_ClearLoggingDirectoriesList() { - fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be " + fprintf(stderr, + "TestOnly_ClearLoggingDirectoriesList should only be " "called from test code.\n"); delete logging_directories_list; logging_directories_list = nullptr; @@ -2445,10 +2412,10 @@ void TestOnly_ClearLoggingDirectoriesList() { void GetExistingTempDirectories(vector* list) { GetTempDirectories(list); auto i_dir = list->begin(); - while( i_dir != list->end() ) { + while (i_dir != list->end()) { // zero arg to access means test for existence; no constant // defined on windows - if ( access(i_dir->c_str(), 0) ) { + if (access(i_dir->c_str(), 0)) { i_dir = list->erase(i_dir); } else { ++i_dir; @@ -2456,7 +2423,7 @@ void GetExistingTempDirectories(vector* list) { } } -void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { +void TruncateLogFile(const char* path, uint64 limit, uint64 keep) { #if defined(HAVE_UNISTD_H) || defined(HAVE__CHSIZE_S) struct stat statbuf; const int kCopyBlockSize = 8 << 10; @@ -2465,10 +2432,10 @@ void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { // Don't follow symlinks unless they're our own fd symlinks in /proc int flags = O_RDWR; // TODO(hamaji): Support other environments. -#ifdef GLOG_OS_LINUX - const char *procfd_prefix = "/proc/self/fd/"; +# ifdef GLOG_OS_LINUX + const char* procfd_prefix = "/proc/self/fd/"; if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW; -#endif +# endif int fd = open(path, flags); if (fd == -1) { @@ -2478,11 +2445,11 @@ void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's // rather scary. // Instead just truncate the file to something we can manage -#ifdef HAVE__CHSIZE_S +# ifdef HAVE__CHSIZE_S if (_chsize_s(fd, 0) != 0) { -#else +# else if (truncate(path, 0) == -1) { -#endif +# endif PLOG(ERROR) << "Unable to truncate " << path; } else { LOG(ERROR) << "Truncated " << path << " due to EFBIG error"; @@ -2501,7 +2468,7 @@ void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { // See if the path refers to a regular file bigger than the // specified limit if (!S_ISREG(statbuf.st_mode)) goto out_close_fd; - if (statbuf.st_size <= static_cast(limit)) goto out_close_fd; + if (statbuf.st_size <= static_cast(limit)) goto out_close_fd; if (statbuf.st_size <= static_cast(keep)) goto out_close_fd; // This log file is too large - we need to truncate it @@ -2524,23 +2491,23 @@ void TruncateLogFile(const char *path, uint64 limit, uint64 keep) { } if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path; - // Truncate the remainder of the file. If someone else writes to the - // end of the file after our last read() above, we lose their latest - // data. Too bad ... -#ifdef HAVE__CHSIZE_S + // Truncate the remainder of the file. If someone else writes to the + // end of the file after our last read() above, we lose their latest + // data. Too bad ... +# ifdef HAVE__CHSIZE_S if (_chsize_s(fd, write_offset) != 0) { -#else +# else if (ftruncate(fd, write_offset) == -1) { -#endif +# endif PLOG(ERROR) << "Unable to truncate " << path; } - out_close_fd: +out_close_fd: close(fd); #else LOG(ERROR) << "No log truncation support."; #endif - } +} void TruncateStdoutStderr() { #ifdef HAVE_UNISTD_H @@ -2553,7 +2520,6 @@ void TruncateStdoutStderr() { #endif } - // Helper functions for string comparisons. #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \ string* Check##func##expected##Impl(const char* s1, const char* s2, \ @@ -2575,7 +2541,7 @@ DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true) DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false) #undef DEFINE_CHECK_STROP_IMPL -int posix_strerror_r(int err, char *buf, size_t len) { +int posix_strerror_r(int err, char* buf, size_t len) { // Sanity check input parameters if (buf == nullptr || len <= 0) { errno = EINVAL; @@ -2587,12 +2553,12 @@ int posix_strerror_r(int err, char *buf, size_t len) { buf[0] = '\000'; int old_errno = errno; errno = 0; - char *rc = reinterpret_cast(strerror_r(err, buf, len)); + char* rc = reinterpret_cast(strerror_r(err, buf, len)); // Both versions set errno on failure if (errno) { // Should already be there, but better safe than sorry - buf[0] = '\000'; + buf[0] = '\000'; return -1; } errno = old_errno; @@ -2601,7 +2567,7 @@ int posix_strerror_r(int err, char *buf, size_t len) { // is indirectly implies that typically ERANGE will be returned, instead // of truncating the string. This is different from the GNU implementation. // We play it safe by always terminating the string explicitly. - buf[len-1] = '\000'; + buf[len - 1] = '\000'; // If the function succeeded, we can use its exit code to determine the // semantics implemented by glibc @@ -2613,13 +2579,14 @@ int posix_strerror_r(int err, char *buf, size_t len) { return 0; } else { buf[0] = '\000'; -#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD) +#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || \ + defined(GLOG_OS_OPENBSD) if (reinterpret_cast(rc) < sys_nerr) { // This means an error on MacOSX or FreeBSD. return -1; } #endif - strncat(buf, rc, len-1); + strncat(buf, rc, len - 1); return 0; } } @@ -2634,28 +2601,26 @@ string StrError(int err) { return buf; } -LogMessageFatal::LogMessageFatal(const char* file, int line) : - LogMessage(file, line, GLOG_FATAL) {} +LogMessageFatal::LogMessageFatal(const char* file, int line) + : LogMessage(file, line, GLOG_FATAL) {} LogMessageFatal::LogMessageFatal(const char* file, int line, - const CheckOpString& result) : - LogMessage(file, line, result) {} + const CheckOpString& result) + : LogMessage(file, line, result) {} LogMessageFatal::~LogMessageFatal() { - Flush(); - LogMessage::Fail(); + Flush(); + LogMessage::Fail(); } namespace base { -CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext) +CheckOpMessageBuilder::CheckOpMessageBuilder(const char* exprtext) : stream_(new ostringstream) { *stream_ << exprtext << " ("; } -CheckOpMessageBuilder::~CheckOpMessageBuilder() { - delete stream_; -} +CheckOpMessageBuilder::~CheckOpMessageBuilder() { delete stream_; } ostream* CheckOpMessageBuilder::ForVar2() { *stream_ << " vs. "; @@ -2705,8 +2670,7 @@ void InitGoogleLogging(const char* argv0) { glog_internal_namespace_::InitGoogleLoggingUtilities(argv0); } -void InitGoogleLogging(const char* argv0, - CustomPrefixCallback prefix_callback, +void InitGoogleLogging(const char* argv0, CustomPrefixCallback prefix_callback, void* prefix_callback_data) { custom_prefix_callback = prefix_callback; custom_prefix_callback_data = prefix_callback_data; @@ -2724,9 +2688,7 @@ void EnableLogCleaner(unsigned int overdue_days) { log_cleaner.Enable(overdue_days); } -void DisableLogCleaner() { - log_cleaner.Disable(); -} +void DisableLogCleaner() { log_cleaner.Disable(); } LogMessageTime::LogMessageTime() : time_struct_(), timestamp_(0), usecs_(0), gmtoffset_(0) {} @@ -2758,7 +2720,7 @@ void LogMessageTime::init(const std::tm& t, std::time_t timestamp, void LogMessageTime::CalcGmtOffset() { std::tm gmt_struct; int isDst = 0; - if ( FLAGS_log_utc_time ) { + if (FLAGS_log_utc_time) { localtime_r(×tamp_, &gmt_struct); isDst = gmt_struct.tm_isdst; gmt_struct = time_struct_; @@ -2769,8 +2731,10 @@ void LogMessageTime::CalcGmtOffset() { time_t gmt_sec = mktime(&gmt_struct); const long hour_secs = 3600; - // If the Daylight Saving Time(isDst) is active subtract an hour from the current timestamp. - gmtoffset_ = static_cast(timestamp_ - gmt_sec + (isDst ? hour_secs : 0) ) ; + // If the Daylight Saving Time(isDst) is active subtract an hour from the + // current timestamp. + gmtoffset_ = + static_cast(timestamp_ - gmt_sec + (isDst ? hour_secs : 0)); } } // namespace google diff --git a/src/logging_unittest.cc b/src/logging_unittest.cc index e091cb4eb..6c254f1fe 100644 --- a/src/logging_unittest.cc +++ b/src/logging_unittest.cc @@ -29,19 +29,19 @@ // // Author: Ray Sidney +#include + #include "config.h" #include "utilities.h" - -#include #ifdef HAVE_GLOB_H -# include +# include #endif #include #ifdef HAVE_UNISTD_H -# include +# include #endif #ifdef HAVE_SYS_WAIT_H -# include +# include #endif #include @@ -63,13 +63,14 @@ DECLARE_string(log_backtrace_at); // logging.cc #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif #ifdef HAVE_LIB_GMOCK -#include -#include "mock-log.h" +# include + +# include "mock-log.h" // Introduce several symbols from gmock. using google::glog_testing::ScopedMockLog; using testing::_; @@ -132,7 +133,8 @@ static void BM_Check1(int n) { } BENCHMARK(BM_Check1) -static void CheckFailure(int a, int b, const char* file, int line, const char* msg); +static void CheckFailure(int a, int b, const char* file, int line, + const char* msg); static void BM_Check3(int n) { while (n-- > 0) { if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); @@ -165,8 +167,7 @@ static void BM_Check2(int n) { BENCHMARK(BM_Check2) static void CheckFailure(int, int, const char* /* file */, int /* line */, - const char* /* msg */) { -} + const char* /* msg */) {} static void BM_logspeed(int n) { while (n-- > 0) { @@ -182,31 +183,24 @@ static void BM_vlog(int n) { } BENCHMARK(BM_vlog) -// Dynamically generate a prefix using the default format and write it to the stream. -void PrefixAttacher(std::ostream &s, const LogMessageInfo &l, void* data) { +// Dynamically generate a prefix using the default format and write it to the +// stream. +void PrefixAttacher(std::ostream& s, const LogMessageInfo& l, void* data) { // Assert that `data` contains the expected contents before producing the // prefix (otherwise causing the tests to fail): if (data == nullptr || *static_cast(data) != "good data") { return; } - s << l.severity[0] - << setw(4) << 1900 + l.time.year() - << setw(2) << 1 + l.time.month() - << setw(2) << l.time.day() - << ' ' - << setw(2) << l.time.hour() << ':' - << setw(2) << l.time.min() << ':' - << setw(2) << l.time.sec() << "." - << setw(6) << l.time.usec() - << ' ' - << setfill(' ') << setw(5) - << l.thread_id << setfill('0') - << ' ' - << l.filename << ':' << l.line_number << "]"; + s << l.severity[0] << setw(4) << 1900 + l.time.year() << setw(2) + << 1 + l.time.month() << setw(2) << l.time.day() << ' ' << setw(2) + << l.time.hour() << ':' << setw(2) << l.time.min() << ':' << setw(2) + << l.time.sec() << "." << setw(6) << l.time.usec() << ' ' << setfill(' ') + << setw(5) << l.thread_id << setfill('0') << ' ' << l.filename << ':' + << l.line_number << "]"; } -int main(int argc, char **argv) { +int main(int argc, char** argv) { FLAGS_colorlogtostderr = false; FLAGS_timestamp_in_logfile_name = true; @@ -216,8 +210,8 @@ int main(int argc, char **argv) { // Test some basics before InitGoogleLogging: CaptureTestStderr(); - LogWithLevels(FLAGS_v, FLAGS_stderrthreshold, - FLAGS_logtostderr, FLAGS_alsologtostderr); + LogWithLevels(FLAGS_v, FLAGS_stderrthreshold, FLAGS_logtostderr, + FLAGS_alsologtostderr); LogWithLevels(0, 0, false, false); // simulate "before global c-tors" const string early_stderr = GetCapturedTestStderr(); @@ -226,7 +220,8 @@ int main(int argc, char **argv) { // Setting a custom prefix generator (it will use the default format so that // the golden outputs can be reused): string prefix_attacher_data = "good data"; - InitGoogleLogging(argv[0], &PrefixAttacher, static_cast(&prefix_attacher_data)); + InitGoogleLogging(argv[0], &PrefixAttacher, + static_cast(&prefix_attacher_data)); EXPECT_TRUE(IsGoogleLoggingInitialized()); @@ -249,7 +244,8 @@ int main(int argc, char **argv) { CaptureTestStderr(); // re-emit early_stderr - LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << early_stderr; + LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() + << early_stderr; TestLogging(true); TestRawLogging(); @@ -301,12 +297,12 @@ int main(int argc, char **argv) { } void TestLogging(bool check_counts) { - int64 base_num_infos = LogMessage::num_messages(GLOG_INFO); + int64 base_num_infos = LogMessage::num_messages(GLOG_INFO); int64 base_num_warning = LogMessage::num_messages(GLOG_WARNING); - int64 base_num_errors = LogMessage::num_messages(GLOG_ERROR); + int64 base_num_errors = LogMessage::num_messages(GLOG_ERROR); LOG(INFO) << string("foo ") << "bar " << 10 << ' ' << 3.4; - for ( int i = 0; i < 10; ++i ) { + for (int i = 0; i < 10; ++i) { int old_errno = errno; errno = i; PLOG_EVERY_N(ERROR, 2) << "Plog every 2, iteration " << COUNTER; @@ -330,7 +326,7 @@ void TestLogging(bool check_counts) { const char const_s[] = "const array"; LOG(INFO) << const_s; int j = 1000; - LOG(ERROR) << string("foo") << ' '<< j << ' ' << setw(10) << j << " " + LOG(ERROR) << string("foo") << ' ' << j << ' ' << setw(10) << j << " " << setw(1) << hex << j; LOG(INFO) << "foo " << std::setw(10) << 1.0; @@ -341,32 +337,27 @@ void TestLogging(bool check_counts) { LOG(ERROR) << "inner"; } - LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << "no prefix"; + LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() + << "no prefix"; if (check_counts) { - CHECK_EQ(base_num_infos + 15, LogMessage::num_messages(GLOG_INFO)); - CHECK_EQ(base_num_warning + 3, LogMessage::num_messages(GLOG_WARNING)); - CHECK_EQ(base_num_errors + 17, LogMessage::num_messages(GLOG_ERROR)); + CHECK_EQ(base_num_infos + 15, LogMessage::num_messages(GLOG_INFO)); + CHECK_EQ(base_num_warning + 3, LogMessage::num_messages(GLOG_WARNING)); + CHECK_EQ(base_num_errors + 17, LogMessage::num_messages(GLOG_ERROR)); } } -static void NoAllocNewHook() { - LOG(FATAL) << "unexpected new"; -} +static void NoAllocNewHook() { LOG(FATAL) << "unexpected new"; } struct NewHook { - NewHook() { - g_new_hook = &NoAllocNewHook; - } + NewHook() { g_new_hook = &NoAllocNewHook; } ~NewHook() { g_new_hook = nullptr; } }; TEST(DeathNoAllocNewHook, logging) { // tests that NewHook used below works NewHook new_hook; - ASSERT_DEATH({ - new int; - }, "unexpected new"); + ASSERT_DEATH({ new int; }, "unexpected new"); } void TestRawLogging() { @@ -425,8 +416,8 @@ void TestRawLogging() { void LogWithLevels(int v, int severity, bool err, bool alsoerr) { RAW_LOG(INFO, - "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d", - v, severity, err, alsoerr); + "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d", v, + severity, err, alsoerr); FlagSaver saver; @@ -463,28 +454,48 @@ void LogWithLevels(int v, int severity, bool err, bool alsoerr) { LOG_IF(ERROR, false) << "don't log_if error"; int c; - c = 1; VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; EXPECT_EQ(c, -1); - c = 1; VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1); - c = 1; LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1); - c = 1; LOG_IF(ERROR, c -= 2) << "log_if error expr"; EXPECT_EQ(c, -1); - c = 2; VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0); - c = 2; LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0); - - c = 3; LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr"; + c = 1; + VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; + EXPECT_EQ(c, -1); + c = 1; + VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1); - c = 3; LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr"; + c = 1; + LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1); - c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr"; + c = 1; + LOG_IF(ERROR, c -= 2) << "log_if error expr"; + EXPECT_EQ(c, -1); + c = 2; + VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0); - c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr"; + c = 2; + LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0); - c = 5; VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr"; + + c = 3; + LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr"; + EXPECT_EQ(c, -1); + c = 3; + LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr"; + EXPECT_EQ(c, -1); + c = 4; + LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr"; + EXPECT_EQ(c, 0); + c = 4; + LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr"; + EXPECT_EQ(c, 0); + c = 5; + VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr"; EXPECT_EQ(c, 1); - c = 5; VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr"; + c = 5; + VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr"; EXPECT_EQ(c, 1); - c = 6; VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr"; + c = 6; + VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr"; EXPECT_EQ(c, 0); - c = 6; VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr"; + c = 6; + VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr"; EXPECT_EQ(c, 0); } @@ -523,19 +534,24 @@ TEST(DeathRawCHECK, logging) { ASSERT_DEATH(RAW_CHECK(false, "failure 1"), "RAW: Check false failed: failure 1"); ASSERT_DEBUG_DEATH(RAW_DCHECK(1 == 2, "failure 2"), - "RAW: Check 1 == 2 failed: failure 2"); + "RAW: Check 1 == 2 failed: failure 2"); } void TestLogString() { vector errors; vector* no_errors = nullptr; - LOG_STRING(INFO, &errors) << "LOG_STRING: " << "collected info"; - LOG_STRING(WARNING, &errors) << "LOG_STRING: " << "collected warning"; - LOG_STRING(ERROR, &errors) << "LOG_STRING: " << "collected error"; - - LOG_STRING(INFO, no_errors) << "LOG_STRING: " << "reported info"; - LOG_STRING(WARNING, no_errors) << "LOG_STRING: " << "reported warning"; + LOG_STRING(INFO, &errors) << "LOG_STRING: " + << "collected info"; + LOG_STRING(WARNING, &errors) << "LOG_STRING: " + << "collected warning"; + LOG_STRING(ERROR, &errors) << "LOG_STRING: " + << "collected error"; + + LOG_STRING(INFO, no_errors) << "LOG_STRING: " + << "reported info"; + LOG_STRING(WARNING, no_errors) << "LOG_STRING: " + << "reported warning"; LOG_STRING(ERROR, nullptr) << "LOG_STRING: " << "reported error"; @@ -548,15 +564,20 @@ void TestLogToString() { string error; string* no_error = nullptr; - LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " << "collected info"; + LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " + << "collected info"; LOG(INFO) << "Captured by LOG_TO_STRING: " << error; - LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " << "collected warning"; + LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " + << "collected warning"; LOG(INFO) << "Captured by LOG_TO_STRING: " << error; - LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " << "collected error"; + LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " + << "collected error"; LOG(INFO) << "Captured by LOG_TO_STRING: " << error; - LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " << "reported info"; - LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " << "reported warning"; + LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " + << "reported info"; + LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " + << "reported warning"; LOG_TO_STRING(ERROR, nullptr) << "LOG_TO_STRING: " << "reported error"; } @@ -568,8 +589,8 @@ class TestLogSinkImpl : public LogSink { const char* base_filename, int line, const LogMessageTime& logmsgtime, const char* message, size_t message_len) override { - errors.push_back( - ToString(severity, base_filename, line, logmsgtime, message, message_len)); + errors.push_back(ToString(severity, base_filename, line, logmsgtime, + message, message_len)); } }; @@ -577,26 +598,36 @@ void TestLogSink() { TestLogSinkImpl sink; LogSink* no_sink = nullptr; - LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " << "collected info"; - LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " << "collected warning"; - LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " << "collected error"; - - LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " << "reported info"; - LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " << "reported warning"; + LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " + << "collected info"; + LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " + << "collected warning"; + LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " + << "collected error"; + + LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " + << "reported info"; + LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " + << "reported warning"; LOG_TO_SINK(nullptr, ERROR) << "LOG_TO_SINK: " << "reported error"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, INFO) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected info"; + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " + << "collected info"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, WARNING) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected warning"; + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " + << "collected warning"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, ERROR) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected error"; + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " + << "collected error"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, INFO) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed info"; + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " + << "thrashed info"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, WARNING) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed warning"; + << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " + << "thrashed warning"; LOG_TO_SINK_BUT_NOT_TO_LOGFILE(nullptr, ERROR) << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed error"; @@ -608,10 +639,7 @@ void TestLogSink() { } // For testing using CHECK*() on anonymous enums. -enum { - CASE_A, - CASE_B -}; +enum { CASE_A, CASE_B }; void TestCHECK() { // Tests using CHECK*() on int values. @@ -641,9 +669,9 @@ void TestCHECK() { void TestDCHECK() { #if defined(NDEBUG) - DCHECK( 1 == 2 ) << " DCHECK's shouldn't be compiled in normal mode"; + DCHECK(1 == 2) << " DCHECK's shouldn't be compiled in normal mode"; #endif - DCHECK( 1 == 1 ); + DCHECK(1 == 1); DCHECK_EQ(1, 1); DCHECK_NE(1, 2); DCHECK_GE(1, 1); @@ -668,9 +696,8 @@ void TestSTREQ() { CHECK_STRNE("this", nullptr); CHECK_STRCASENE("this", "that"); CHECK_STRCASENE(nullptr, "that"); - CHECK_STREQ((string("a")+"b").c_str(), "ab"); - CHECK_STREQ(string("test").c_str(), - (string("te") + string("st")).c_str()); + CHECK_STREQ((string("a") + "b").c_str(), "ab"); + CHECK_STREQ(string("test").c_str(), (string("te") + string("st")).c_str()); } TEST(DeathSTREQ, logging) { @@ -680,18 +707,18 @@ TEST(DeathSTREQ, logging) { ASSERT_DEATH(CHECK_STRCASEEQ("this", "siht"), ""); ASSERT_DEATH(CHECK_STRNE(nullptr, nullptr), ""); ASSERT_DEATH(CHECK_STRNE("this", "this"), ""); - ASSERT_DEATH(CHECK_STREQ((string("a")+"b").c_str(), "abc"), ""); + ASSERT_DEATH(CHECK_STREQ((string("a") + "b").c_str(), "abc"), ""); } TEST(CheckNOTNULL, Simple) { int64 t; - void *ptr = static_cast(&t); - void *ref = CHECK_NOTNULL(ptr); + void* ptr = static_cast(&t); + void* ref = CHECK_NOTNULL(ptr); EXPECT_EQ(ptr, ref); - CHECK_NOTNULL(reinterpret_cast(ptr)); - CHECK_NOTNULL(reinterpret_cast(ptr)); - CHECK_NOTNULL(reinterpret_cast(ptr)); - CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); + CHECK_NOTNULL(reinterpret_cast(ptr)); } TEST(DeathCheckNN, Simple) { @@ -728,7 +755,7 @@ static void GetFiles(const string& pattern, vector* files) { LOG_SYSRESULT(GetLastError()); } #else -# error There is no way to do glob. +# error There is no way to do glob. #endif } @@ -741,8 +768,9 @@ static void DeleteFiles(const string& pattern) { } } -//check string is in file (or is *NOT*, depending on optional checkInFileOrNot) -static void CheckFile(const string& name, const string& expected_string, const bool checkInFileOrNot = true) { +// check string is in file (or is *NOT*, depending on optional checkInFileOrNot) +static void CheckFile(const string& name, const string& expected_string, + const bool checkInFileOrNot = true) { vector files; GetFiles(name + "*", &files); CHECK_EQ(files.size(), 1UL); @@ -760,7 +788,8 @@ static void CheckFile(const string& name, const string& expected_string, const b } } fclose(file); - LOG(FATAL) << "Did " << (checkInFileOrNot? "not " : "") << "find " << expected_string << " in " << files[0]; + LOG(FATAL) << "Did " << (checkInFileOrNot ? "not " : "") << "find " + << expected_string << " in " << files[0]; } static void TestBasename() { @@ -780,8 +809,11 @@ static void TestBasename() { } static void TestBasenameAppendWhenNoTimestamp() { - fprintf(stderr, "==== Test setting log file basename without timestamp and appending properly\n"); - const string dest = FLAGS_test_tmpdir + "/logging_test_basename_append_when_no_timestamp"; + fprintf(stderr, + "==== Test setting log file basename without timestamp and appending " + "properly\n"); + const string dest = + FLAGS_test_tmpdir + "/logging_test_basename_append_when_no_timestamp"; DeleteFiles(dest + "*"); ofstream out(dest.c_str()); @@ -790,13 +822,13 @@ static void TestBasenameAppendWhenNoTimestamp() { CheckFile(dest, "test preexisting content"); - FLAGS_timestamp_in_logfile_name=false; + FLAGS_timestamp_in_logfile_name = false; SetLogDestination(GLOG_INFO, dest.c_str()); LOG(INFO) << "message to new base, appending to preexisting file"; FlushLogFiles(GLOG_INFO); - FLAGS_timestamp_in_logfile_name=true; + FLAGS_timestamp_in_logfile_name = true; - //if the logging overwrites the file instead of appending it will fail. + // if the logging overwrites the file instead of appending it will fail. CheckFile(dest, "test preexisting content"); CheckFile(dest, "message to new base, appending to preexisting file"); @@ -806,14 +838,18 @@ static void TestBasenameAppendWhenNoTimestamp() { } static void TestTwoProcessesWrite() { -// test only implemented for platforms with fork & wait; the actual implementation relies on flock +// test only implemented for platforms with fork & wait; the actual +// implementation relies on flock #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_UNISTD_H) && defined(HAVE_FCNTL) - fprintf(stderr, "==== Test setting log file basename and two processes writing - second should fail\n"); - const string dest = FLAGS_test_tmpdir + "/logging_test_basename_two_processes_writing"; + fprintf(stderr, + "==== Test setting log file basename and two processes writing - " + "second should fail\n"); + const string dest = + FLAGS_test_tmpdir + "/logging_test_basename_two_processes_writing"; DeleteFiles(dest + "*"); - //make both processes write into the same file (easier test) - FLAGS_timestamp_in_logfile_name=false; + // make both processes write into the same file (easier test) + FLAGS_timestamp_in_logfile_name = false; SetLogDestination(GLOG_INFO, dest.c_str()); LOG(INFO) << "message to new base, parent"; FlushLogFiles(GLOG_INFO); @@ -821,16 +857,20 @@ static void TestTwoProcessesWrite() { pid_t pid = fork(); CHECK_ERR(pid); if (pid == 0) { - LOG(INFO) << "message to new base, child - should only appear on STDERR not on the file"; - ShutdownGoogleLogging(); //for children proc + LOG(INFO) << "message to new base, child - should only appear on STDERR " + "not on the file"; + ShutdownGoogleLogging(); // for children proc exit(EXIT_SUCCESS); } else if (pid > 0) { wait(nullptr); } - FLAGS_timestamp_in_logfile_name=true; + FLAGS_timestamp_in_logfile_name = true; CheckFile(dest, "message to new base, parent"); - CheckFile(dest, "message to new base, child - should only appear on STDERR not on the file", false); + CheckFile(dest, + "message to new base, child - should only appear on STDERR not on " + "the file", + false); // Release LogToStderr(); @@ -924,7 +964,7 @@ static void TestErrno() { CHECK_EQ(errno, ENOENT); } -static void TestOneTruncate(const char *path, uint64 limit, uint64 keep, +static void TestOneTruncate(const char* path, uint64 limit, uint64 keep, size_t dsize, size_t ksize, size_t expect) { int fd; CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600)); @@ -992,33 +1032,31 @@ static void TestTruncate() { // MacOSX 10.4 doesn't fail in this case. // Windows doesn't have symlink. // Let's just ignore this test for these cases. -#if !defined(GLOG_OS_MACOSX) && !defined(GLOG_OS_WINDOWS) +# if !defined(GLOG_OS_MACOSX) && !defined(GLOG_OS_WINDOWS) // Through a symlink should fail to truncate string linkname = path + ".link"; unlink(linkname.c_str()); CHECK_ERR(symlink(path.c_str(), linkname.c_str())); TestOneTruncate(linkname.c_str(), 10, 10, 0, 30, 30); -#endif +# endif // The /proc/self path makes sense only for linux. -#if defined(GLOG_OS_LINUX) +# if defined(GLOG_OS_LINUX) // Through an open fd symlink should work int fd; CHECK_ERR(fd = open(path.c_str(), O_APPEND | O_WRONLY)); char fdpath[64]; std::snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd); TestOneTruncate(fdpath, 10, 10, 10, 10, 10); -#endif +# endif #endif } struct RecordDeletionLogger : public base::Logger { - RecordDeletionLogger(bool* set_on_destruction, - base::Logger* wrapped_logger) : - set_on_destruction_(set_on_destruction), - wrapped_logger_(wrapped_logger) - { + RecordDeletionLogger(bool* set_on_destruction, base::Logger* wrapped_logger) + : set_on_destruction_(set_on_destruction), + wrapped_logger_(wrapped_logger) { *set_on_destruction_ = false; } ~RecordDeletionLogger() override { *set_on_destruction_ = true; } @@ -1074,9 +1112,9 @@ std::ostream& operator<<(std::ostream& stream, LogTimeRecorder& t) { } // get elapsed time in nanoseconds int64 elapsedTime_ns(const std::chrono::steady_clock::time_point& begin, - const std::chrono::steady_clock::time_point& end) { + const std::chrono::steady_clock::time_point& end) { return std::chrono::duration_cast((end - begin)) - .count(); + .count(); } static void TestLogPeriodically() { @@ -1087,16 +1125,16 @@ static void TestLogPeriodically() { constexpr double LOG_PERIOD_SEC = LogTimes::LOG_PERIOD_NS * 1e-9; while (timeLogger.m_streamTimes < LogTimes::MAX_CALLS) { - LOG_EVERY_T(INFO, LOG_PERIOD_SEC) - << timeLogger << "Timed Message #" << timeLogger.m_streamTimes; + LOG_EVERY_T(INFO, LOG_PERIOD_SEC) + << timeLogger << "Timed Message #" << timeLogger.m_streamTimes; } // Calculate time between each call in nanoseconds for higher resolution to // minimize error. int64 nsBetweenCalls[LogTimes::MAX_CALLS - 1]; for (size_t i = 1; i < LogTimes::MAX_CALLS; ++i) { - nsBetweenCalls[i - 1] = elapsedTime_ns( - timeLogger.m_callTimes[i - 1], timeLogger.m_callTimes[i]); + nsBetweenCalls[i - 1] = elapsedTime_ns(timeLogger.m_callTimes[i - 1], + timeLogger.m_callTimes[i]); } for (long time_ns : nsBetweenCalls) { @@ -1107,17 +1145,18 @@ static void TestLogPeriodically() { namespace google { namespace glog_internal_namespace_ { extern // in logging.cc -bool SafeFNMatch_(const char* pattern, size_t patt_len, - const char* str, size_t str_len); -} // namespace glog_internal_namespace_ + bool + SafeFNMatch_(const char* pattern, size_t patt_len, const char* str, + size_t str_len); +} // namespace glog_internal_namespace_ using glog_internal_namespace_::SafeFNMatch_; } // namespace google static bool WrapSafeFNMatch(string pattern, string str) { pattern += "abc"; str += "defgh"; - return SafeFNMatch_(pattern.data(), pattern.size() - 3, - str.data(), str.size() - 5); + return SafeFNMatch_(pattern.data(), pattern.size() - 3, str.data(), + str.size() - 5); } TEST(SafeFNMatch, logging) { @@ -1184,7 +1223,6 @@ class TestLogSinkWriter : public Thread { } private: - // helpers --------------- // For creating a "Condition". @@ -1239,7 +1277,6 @@ class TestLogSinkWriter : public Thread { // (that other thread can than use LOG() itself), class TestWaitingLogSink : public LogSink { public: - TestWaitingLogSink() { tid_ = pthread_self(); // for thread-specific behavior AddLogSink(this); @@ -1260,18 +1297,17 @@ class TestWaitingLogSink : public LogSink { // Note: Something like ThreadLocalLogSink is a better choice // to do thread-specific LogSink logic for real. if (pthread_equal(tid_, pthread_self())) { - writer_.Buffer(ToString(severity, base_filename, line, - logmsgtime, message, message_len)); + writer_.Buffer(ToString(severity, base_filename, line, logmsgtime, + message, message_len)); } } void WaitTillSent() override { // Wait for Writer thread if we are the original logging thread. - if (pthread_equal(tid_, pthread_self())) writer_.Wait(); + if (pthread_equal(tid_, pthread_self())) writer_.Wait(); } private: - pthread_t tid_; TestLogSinkWriter writer_; }; @@ -1282,7 +1318,8 @@ static void TestLogSinkWaitTillSent() { // Clear global_messages here to make sure that this test case can be // reentered global_messages.clear(); - { TestWaitingLogSink sink; + { + TestWaitingLogSink sink; // Sleeps give the sink threads time to do all their work, // so that we get a reliable log capture to compare to the golden file. LOG(INFO) << "Message 1"; @@ -1300,15 +1337,16 @@ static void TestLogSinkWaitTillSent() { TEST(Strerror, logging) { int errcode = EINTR; - char *msg = strdup(strerror(errcode)); + char* msg = strdup(strerror(errcode)); const size_t buf_size = strlen(msg) + 1; - char *buf = new char[buf_size]; + char* buf = new char[buf_size]; CHECK_EQ(posix_strerror_r(errcode, nullptr, 0), -1); buf[0] = 'A'; CHECK_EQ(posix_strerror_r(errcode, buf, 0), -1); CHECK_EQ(buf[0], 'A'); CHECK_EQ(posix_strerror_r(errcode, nullptr, buf_size), -1); -#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || defined(GLOG_OS_OPENBSD) +#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || \ + defined(GLOG_OS_OPENBSD) // MacOSX or FreeBSD considers this case is an error since there is // no enough space. CHECK_EQ(posix_strerror_r(errcode, buf, 1), -1); @@ -1338,12 +1376,12 @@ static void MyCheck(bool a, bool b) { TEST(DVLog, Basic) { ScopedMockLog log; -#if defined(NDEBUG) +# if defined(NDEBUG) // We are expecting that nothing is logged. EXPECT_CALL(log, Log(_, _, _)).Times(0); -#else +# else EXPECT_CALL(log, Log(GLOG_INFO, __FILE__, "debug log")); -#endif +# endif FLAGS_v = 1; DVLOG(1) << "debug log"; @@ -1385,15 +1423,15 @@ TEST(TestExitOnDFatal, ToBeOrNotToBe) { // We don't die. { ScopedMockLog log; - //EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber()); - // LOG(DFATAL) has severity FATAL if debugging, but is - // downgraded to ERROR if not debugging. + // EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber()); + // LOG(DFATAL) has severity FATAL if debugging, but is + // downgraded to ERROR if not debugging. const LogSeverity severity = -#if defined(NDEBUG) +# if defined(NDEBUG) GLOG_ERROR; -#else +# else GLOG_FATAL; -#endif +# endif EXPECT_CALL(log, Log(severity, __FILE__, "This should not be fatal")); LOG(DFATAL) << "This should not be fatal"; } @@ -1402,20 +1440,19 @@ TEST(TestExitOnDFatal, ToBeOrNotToBe) { base::internal::SetExitOnDFatal(true); EXPECT_TRUE(base::internal::GetExitOnDFatal()); -#ifdef GTEST_HAS_DEATH_TEST +# ifdef GTEST_HAS_DEATH_TEST // Death comes on little cats' feet. - EXPECT_DEBUG_DEATH({ - LOG(DFATAL) << "This should be fatal in debug mode"; - }, "This should be fatal in debug mode"); -#endif + EXPECT_DEBUG_DEATH({ LOG(DFATAL) << "This should be fatal in debug mode"; }, + "This should be fatal in debug mode"); +# endif } -#ifdef HAVE_STACKTRACE +# ifdef HAVE_STACKTRACE static void BacktraceAtHelper() { LOG(INFO) << "Not me"; -// The vertical spacing of the next 3 lines is significant. + // The vertical spacing of the next 3 lines is significant. LOG(INFO) << "Backtrace me"; } static int kBacktraceAtLine = __LINE__ - 2; // The line of the LOG(INFO) above @@ -1443,19 +1480,19 @@ TEST(LogBacktraceAt, DoesBacktraceAtRightLineWhenEnabled) { // the name of the containing function, followed by the log message. // We use HasSubstr()s instead of ContainsRegex() for environments // which don't have regexp. - EXPECT_CALL(log, Log(_, _, AllOf(HasSubstr("stacktrace:"), - HasSubstr("BacktraceAtHelper"), - HasSubstr("main"), - HasSubstr("Backtrace me")))); + EXPECT_CALL( + log, Log(_, _, + AllOf(HasSubstr("stacktrace:"), HasSubstr("BacktraceAtHelper"), + HasSubstr("main"), HasSubstr("Backtrace me")))); // Other LOGs should not include a backtrace. EXPECT_CALL(log, Log(_, _, "Not me")); BacktraceAtHelper(); } -#endif // HAVE_STACKTRACE +# endif // HAVE_STACKTRACE -#endif // HAVE_LIB_GMOCK +#endif // HAVE_LIB_GMOCK struct UserDefinedClass { bool operator==(const UserDefinedClass&) const { return true; } @@ -1480,7 +1517,8 @@ TEST(UserDefinedClass, logging) { TEST(LogMsgTime, gmtoff) { /* * Unit test for GMT offset API - * TODO: To properly test this API, we need a platform independent way to set time-zone. + * TODO: To properly test this API, we need a platform independent way to set + * time-zone. * */ google::LogMessage log_obj(__FILE__, __LINE__); @@ -1488,21 +1526,23 @@ TEST(LogMsgTime, gmtoff) { // GMT offset ranges from UTC-12:00 to UTC+14:00 const long utc_min_offset = -43200; const long utc_max_offset = 50400; - EXPECT_TRUE( (nGmtOff >= utc_min_offset) && (nGmtOff <= utc_max_offset) ); + EXPECT_TRUE((nGmtOff >= utc_min_offset) && (nGmtOff <= utc_max_offset)); } TEST(EmailLogging, ValidAddress) { FlagSaver saver; FLAGS_logmailer = "/usr/bin/true"; - EXPECT_TRUE(SendEmail("example@example.com", "Example subject", "Example body")); + EXPECT_TRUE( + SendEmail("example@example.com", "Example subject", "Example body")); } TEST(EmailLogging, MultipleAddresses) { FlagSaver saver; FLAGS_logmailer = "/usr/bin/true"; - EXPECT_TRUE(SendEmail("example@example.com,foo@bar.com", "Example subject", "Example body")); + EXPECT_TRUE(SendEmail("example@example.com,foo@bar.com", "Example subject", + "Example body")); } TEST(EmailLogging, InvalidAddress) { @@ -1516,5 +1556,6 @@ TEST(EmailLogging, MaliciousAddress) { FlagSaver saver; FLAGS_logmailer = "/usr/bin/true"; - EXPECT_FALSE(SendEmail("!/bin/true@example.com", "Example subject", "Example body")); + EXPECT_FALSE( + SendEmail("!/bin/true@example.com", "Example subject", "Example body")); } diff --git a/src/mock-log_unittest.cc b/src/mock-log_unittest.cc index f5990d433..267e8333a 100644 --- a/src/mock-log_unittest.cc +++ b/src/mock-log_unittest.cc @@ -33,11 +33,11 @@ #include "mock-log.h" -#include - #include #include +#include + namespace { using google::GLOG_ERROR; @@ -57,8 +57,7 @@ TEST(ScopedMockLogTest, InterceptsLog) { InSequence s; EXPECT_CALL(log, Log(GLOG_WARNING, EndsWith("mock-log_unittest.cc"), "Fishy.")); - EXPECT_CALL(log, Log(GLOG_INFO, _, "Working...")) - .Times(2); + EXPECT_CALL(log, Log(GLOG_INFO, _, "Working...")).Times(2); EXPECT_CALL(log, Log(GLOG_ERROR, _, "Bad!!")); LOG(WARNING) << "Fishy."; @@ -67,13 +66,9 @@ TEST(ScopedMockLogTest, InterceptsLog) { LOG(ERROR) << "Bad!!"; } -void LogBranch() { - LOG(INFO) << "Logging a branch..."; -} +void LogBranch() { LOG(INFO) << "Logging a branch..."; } -void LogTree() { - LOG(INFO) << "Logging the whole tree..."; -} +void LogTree() { LOG(INFO) << "Logging the whole tree..."; } void LogForest() { LOG(INFO) << "Logging the entire forest."; diff --git a/src/package_config_unittest/working_config/glog_package_config.cc b/src/package_config_unittest/working_config/glog_package_config.cc index cfbbe7792..463aa9be2 100644 --- a/src/package_config_unittest/working_config/glog_package_config.cc +++ b/src/package_config_unittest/working_config/glog_package_config.cc @@ -1,6 +1,3 @@ #include "glog/logging.h" -int main(int /*argc*/, char** argv) -{ - google::InitGoogleLogging(argv[0]); -} +int main(int /*argc*/, char** argv) { google::InitGoogleLogging(argv[0]); } diff --git a/src/raw_logging.cc b/src/raw_logging.cc index d2d78781a..b27e2010a 100644 --- a/src/raw_logging.cc +++ b/src/raw_logging.cc @@ -37,7 +37,7 @@ #include "utilities.h" #ifdef HAVE_UNISTD_H -# include // for close() and write() +# include // for close() and write() #endif #include // for open() @@ -49,37 +49,37 @@ #include "glog/raw_logging.h" #ifdef HAVE_STACKTRACE -# include "stacktrace.h" +# include "stacktrace.h" #endif #if defined(HAVE_SYSCALL_H) -#include // for syscall() +# include // for syscall() #elif defined(HAVE_SYS_SYSCALL_H) -#include // for syscall() +# include // for syscall() #endif #ifdef HAVE_UNISTD_H -# include +# include #endif -#if (defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)) && \ +#if (defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)) && \ (!(defined(GLOG_OS_MACOSX)) && !(defined(GLOG_OS_OPENBSD))) && \ !defined(GLOG_OS_EMSCRIPTEN) -#define safe_write(fd, s, len) syscall(SYS_write, fd, s, len) +# define safe_write(fd, s, len) syscall(SYS_write, fd, s, len) #else // Not so safe, but what can you do? -#define safe_write(fd, s, len) write(fd, s, len) +# define safe_write(fd, s, len) write(fd, s, len) #endif namespace google { #if defined(__GNUC__) -#define GLOG_ATTRIBUTE_FORMAT(archetype, stringIndex, firstToCheck) \ - __attribute__((format(archetype, stringIndex, firstToCheck))) -#define GLOG_ATTRIBUTE_FORMAT_ARG(stringIndex) \ - __attribute__((format_arg(stringIndex))) +# define GLOG_ATTRIBUTE_FORMAT(archetype, stringIndex, firstToCheck) \ + __attribute__((format(archetype, stringIndex, firstToCheck))) +# define GLOG_ATTRIBUTE_FORMAT_ARG(stringIndex) \ + __attribute__((format_arg(stringIndex))) #else -#define GLOG_ATTRIBUTE_FORMAT(archetype, stringIndex, firstToCheck) -#define GLOG_ATTRIBUTE_FORMAT_ARG(stringIndex) +# define GLOG_ATTRIBUTE_FORMAT(archetype, stringIndex, firstToCheck) +# define GLOG_ATTRIBUTE_FORMAT_ARG(stringIndex) #endif // CAVEAT: std::vsnprintf called from *DoRawLog below has some (exotic) code @@ -103,15 +103,15 @@ static bool DoRawLog(char** buf, size_t* size, const char* format, ...) { } // Helper for RawLog__ below. -inline static bool VADoRawLog(char** buf, size_t* size, - const char* format, va_list ap) { +inline static bool VADoRawLog(char** buf, size_t* size, const char* format, + va_list ap) { #if defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wformat-nonliteral" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif int n = std::vsnprintf(*buf, *size, format, ap); #if defined(__GNUC__) -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif if (n < 0 || static_cast(n) > *size) return false; *size -= static_cast(n); @@ -122,7 +122,7 @@ inline static bool VADoRawLog(char** buf, size_t* size, static const int kLogBufSize = 3000; static bool crashed = false; static CrashReason crash_reason; -static char crash_buf[kLogBufSize + 1] = { 0 }; // Will end in '\0' +static char crash_buf[kLogBufSize + 1] = {0}; // Will end in '\0' GLOG_ATTRIBUTE_FORMAT(printf, 4, 5) void RawLog__(LogSeverity severity, const char* file, int line, @@ -139,9 +139,8 @@ void RawLog__(LogSeverity severity, const char* file, int line, // NOTE: this format should match the specification in base/logging.h DoRawLog(&buf, &size, "%c00000000 00:00:00.000000 %5u %s:%d] RAW: ", - LogSeverityNames[severity][0], - static_cast(GetTID()), - const_basename(const_cast(file)), line); + LogSeverityNames[severity][0], static_cast(GetTID()), + const_basename(const_cast(file)), line); // Record the position and size of the buffer after the prefix const char* msg_start = buf; @@ -161,7 +160,7 @@ void RawLog__(LogSeverity severity, const char* file, int line, // libc (to side-step any libc interception). // We write just once to avoid races with other invocations of RawLog__. safe_write(STDERR_FILENO, buffer, strlen(buffer)); - if (severity == GLOG_FATAL) { + if (severity == GLOG_FATAL) { if (!sync_val_compare_and_swap(&crashed, false, true)) { crash_reason.filename = file; crash_reason.line_number = line; diff --git a/src/signalhandler.cc b/src/signalhandler.cc index 1788ce94f..2c3ec6d5c 100644 --- a/src/signalhandler.cc +++ b/src/signalhandler.cc @@ -41,13 +41,13 @@ #include "utilities.h" #ifdef HAVE_UCONTEXT_H -# include +# include #endif #ifdef HAVE_SYS_UCONTEXT_H -# include +# include #endif #ifdef HAVE_UNISTD_H -#include +# include #endif namespace google { @@ -61,16 +61,14 @@ namespace { // The list should be synced with the comment in signalhandler.h. const struct { int number; - const char *name; + const char* name; } kFailureSignals[] = { - { SIGSEGV, "SIGSEGV" }, - { SIGILL, "SIGILL" }, - { SIGFPE, "SIGFPE" }, - { SIGABRT, "SIGABRT" }, + {SIGSEGV, "SIGSEGV"}, {SIGILL, "SIGILL"}, + {SIGFPE, "SIGFPE"}, {SIGABRT, "SIGABRT"}, #if !defined(GLOG_OS_WINDOWS) - { SIGBUS, "SIGBUS" }, + {SIGBUS, "SIGBUS"}, #endif - { SIGTERM, "SIGTERM" }, + {SIGTERM, "SIGTERM"}, }; static bool kFailureSignalHandlerInstalled = false; @@ -78,14 +76,15 @@ static bool kFailureSignalHandlerInstalled = false; #if !defined(GLOG_OS_WINDOWS) // Returns the program counter from signal context, nullptr if unknown. void* GetPC(void* ucontext_in_void) { -#if (defined(HAVE_UCONTEXT_H) || defined(HAVE_SYS_UCONTEXT_H)) && defined(PC_FROM_UCONTEXT) +# if (defined(HAVE_UCONTEXT_H) || defined(HAVE_SYS_UCONTEXT_H)) && \ + defined(PC_FROM_UCONTEXT) if (ucontext_in_void != nullptr) { - ucontext_t *context = reinterpret_cast(ucontext_in_void); + ucontext_t* context = reinterpret_cast(ucontext_in_void); return (void*)context->PC_FROM_UCONTEXT; } -#else +# else (void)ucontext_in_void; -#endif +# endif return nullptr; } #endif @@ -94,14 +93,13 @@ void* GetPC(void* ucontext_in_void) { // as it's not async signal safe. class MinimalFormatter { public: - MinimalFormatter(char *buffer, size_t size) - : buffer_(buffer), - cursor_(buffer), - end_(buffer + size) { - } + MinimalFormatter(char* buffer, size_t size) + : buffer_(buffer), cursor_(buffer), end_(buffer + size) {} // Returns the number of bytes written in the buffer. - std::size_t num_bytes_written() const { return static_cast(cursor_ - buffer_); } + std::size_t num_bytes_written() const { + return static_cast(cursor_ - buffer_); + } // Appends string from "str" and updates the internal cursor. void AppendString(const char* str) { @@ -147,9 +145,9 @@ class MinimalFormatter { } private: - char *buffer_; - char *cursor_; - const char * const end_; + char* buffer_; + char* cursor_; + const char* const end_; }; // Writes the given data with the size to the standard error. @@ -181,7 +179,7 @@ void DumpTimeInfo() { #if defined(HAVE_STACKTRACE) && defined(HAVE_SIGACTION) // Dumps information about the signal to STDERR. -void DumpSignalInfo(int signal_number, siginfo_t *siginfo) { +void DumpSignalInfo(int signal_number, siginfo_t* siginfo) { // Get the signal name. const char* signal_name = nullptr; for (auto kFailureSignal : kFailureSignals) { @@ -217,11 +215,11 @@ void DumpSignalInfo(int signal_number, siginfo_t *siginfo) { reinterpret_cast(reinterpret_cast(id)), 16); formatter.AppendString(") "); // Only linux has the PID of the signal sender in si_pid. -#ifdef GLOG_OS_LINUX +# ifdef GLOG_OS_LINUX formatter.AppendString("from PID "); formatter.AppendUint64(static_cast(siginfo->si_pid), 10); formatter.AppendString("; "); -#endif +# endif formatter.AppendString("stack trace: ***\n"); g_failure_writer(buf, formatter.num_bytes_written()); } @@ -231,12 +229,12 @@ void DumpSignalInfo(int signal_number, siginfo_t *siginfo) { // Dumps information about the stack frame to STDERR. void DumpStackFrameInfo(const char* prefix, void* pc) { // Get the symbol name. - const char *symbol = "(unknown)"; + const char* symbol = "(unknown)"; char symbolized[1024]; // Big enough for a sane symbol. // Symbolizes the previous address of pc because pc may be in the // next function. - if (Symbolize(reinterpret_cast(pc) - 1, - symbolized, sizeof(symbolized))) { + if (Symbolize(reinterpret_cast(pc) - 1, symbolized, + sizeof(symbolized))) { symbol = symbolized; } @@ -279,9 +277,8 @@ static pthread_t* g_entered_thread_id_pointer = nullptr; #if defined(GLOG_OS_WINDOWS) void FailureSignalHandler(int signal_number) #else -void FailureSignalHandler(int signal_number, - siginfo_t *signal_info, - void *ucontext) +void FailureSignalHandler(int signal_number, siginfo_t* signal_info, + void* ucontext) #endif { // First check if we've already entered the function. We use an atomic @@ -324,20 +321,20 @@ void FailureSignalHandler(int signal_number, #if !defined(GLOG_OS_WINDOWS) // Get the program counter from ucontext. - void *pc = GetPC(ucontext); + void* pc = GetPC(ucontext); DumpStackFrameInfo("PC: ", pc); #endif #ifdef HAVE_STACKTRACE // Get the stack traces. - void *stack[32]; + void* stack[32]; // +1 to exclude this function. const int depth = GetStackTrace(stack, ARRAYSIZE(stack), 1); -# ifdef HAVE_SIGACTION +# ifdef HAVE_SIGACTION DumpSignalInfo(signal_number, signal_info); -#elif !defined(GLOG_OS_WINDOWS) +# elif !defined(GLOG_OS_WINDOWS) (void)signal_info; -# endif +# endif // Dump the stack traces. for (int i = 0; i < depth; ++i) { DumpStackFrameInfo(" ", stack[i]); @@ -400,8 +397,7 @@ void InstallFailureSignalHandler() { kFailureSignalHandlerInstalled = true; #elif defined(GLOG_OS_WINDOWS) for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { - CHECK_NE(signal(kFailureSignals[i].number, &FailureSignalHandler), - SIG_ERR); + CHECK_NE(signal(kFailureSignals[i].number, &FailureSignalHandler), SIG_ERR); } kFailureSignalHandlerInstalled = true; #endif // HAVE_SIGACTION diff --git a/src/signalhandler_unittest.cc b/src/signalhandler_unittest.cc index 1ffa52f78..06c169e8f 100644 --- a/src/signalhandler_unittest.cc +++ b/src/signalhandler_unittest.cc @@ -35,7 +35,7 @@ #include "utilities.h" #if defined(HAVE_PTHREAD) -# include +# include #endif #include #include @@ -45,7 +45,7 @@ #include "glog/logging.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif @@ -72,12 +72,12 @@ static void WriteToStdout(const char* data, size_t size) { } } -int main(int argc, char **argv) { +int main(int argc, char** argv) { #if defined(HAVE_STACKTRACE) && defined(HAVE_SYMBOLIZE) InitGoogleLogging(argv[0]); -#ifdef GLOG_USE_GFLAGS +# ifdef GLOG_USE_GFLAGS ParseCommandLineFlags(&argc, &argv, true); -#endif +# endif InstallFailureSignalHandler(); const std::string command = argc > 1 ? argv[1] : "none"; if (command == "segv") { @@ -85,26 +85,27 @@ int main(int argc, char **argv) { LOG(INFO) << "create the log file"; LOG(INFO) << "a message before segv"; // We assume 0xDEAD is not writable. - int *a = (int*)0xDEAD; + int* a = (int*)0xDEAD; *a = 0; } else if (command == "loop") { fprintf(stderr, "looping\n"); - while (true); + while (true) + ; } else if (command == "die_in_thread") { -#if defined(HAVE_PTHREAD) +# if defined(HAVE_PTHREAD) pthread_t thread; pthread_create(&thread, nullptr, &DieInThread, nullptr); pthread_join(thread, nullptr); -#else +# else fprintf(stderr, "no pthread\n"); return 1; -#endif +# endif } else if (command == "dump_to_stdout") { InstallFailureWriter(WriteToStdout); abort(); } else if (command == "installed") { fprintf(stderr, "signal handler installed: %s\n", - IsFailureSignalHandlerInstalled() ? "true" : "false"); + IsFailureSignalHandlerInstalled() ? "true" : "false"); } else { // Tell the shell script puts("OK"); diff --git a/src/stacktrace_generic-inl.h b/src/stacktrace_generic-inl.h index c07072331..bdfadfa0c 100644 --- a/src/stacktrace_generic-inl.h +++ b/src/stacktrace_generic-inl.h @@ -42,7 +42,7 @@ namespace google { // If you change this function, also change GetStackFrames below. int GetStackTrace(void** result, int max_depth, int skip_count) { static const int kStackLength = 64; - void * stack[kStackLength]; + void* stack[kStackLength]; int size; size = backtrace(stack, kStackLength); diff --git a/src/stacktrace_libunwind-inl.h b/src/stacktrace_libunwind-inl.h index b01e37dd0..07b89ffda 100644 --- a/src/stacktrace_libunwind-inl.h +++ b/src/stacktrace_libunwind-inl.h @@ -51,10 +51,10 @@ namespace google { // cases, we return 0 to indicate the situation. // We can use the GCC __thread syntax here since libunwind is not supported on // Windows. -static __thread bool g_tl_entered; // Initialized to false. +static __thread bool g_tl_entered; // Initialized to false. // If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { +int GetStackTrace(void **result, int max_depth, int skip_count) { void *ip; int n = 0; unw_cursor_t cursor; @@ -67,7 +67,7 @@ int GetStackTrace(void** result, int max_depth, int skip_count) { unw_getcontext(&uc); RAW_CHECK(unw_init_local(&cursor, &uc) >= 0, "unw_init_local failed"); - skip_count++; // Do not include the "GetStackTrace" frame + skip_count++; // Do not include the "GetStackTrace" frame while (n < max_depth) { int ret = diff --git a/src/stacktrace_powerpc-inl.h b/src/stacktrace_powerpc-inl.h index 656189368..94b13226c 100644 --- a/src/stacktrace_powerpc-inl.h +++ b/src/stacktrace_powerpc-inl.h @@ -46,7 +46,7 @@ namespace google { // stackframe, or return nullptr if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. -template +template static void **NextStackFrame(void **old_sp) { void **new_sp = static_cast(*old_sp); @@ -77,16 +77,16 @@ void StacktracePowerPCDummyFunction() __attribute__((noinline)); void StacktracePowerPCDummyFunction() { __asm__ volatile(""); } // If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { +int GetStackTrace(void **result, int max_depth, int skip_count) { void **sp; // Apple OS X uses an old version of gnu as -- both Darwin 7.9.0 (Panther) // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a // different asm syntax. I don't know quite the best way to discriminate // systems using the old as from the new one; I've gone with __APPLE__. #ifdef __APPLE__ - __asm__ volatile ("mr %0,r1" : "=r" (sp)); + __asm__ volatile("mr %0,r1" : "=r"(sp)); #else - __asm__ volatile ("mr %0,1" : "=r" (sp)); + __asm__ volatile("mr %0,1" : "=r"(sp)); #endif // On PowerPC, the "Link Register" or "Link Record" (LR), is a stack @@ -111,17 +111,18 @@ int GetStackTrace(void** result, int max_depth, int skip_count) { // linux ppc64), it's in sp[2]. For SYSV (used by linux ppc), // it's in sp[1]. #if defined(_CALL_AIX) || defined(_CALL_DARWIN) - result[n++] = *(sp+2); + result[n++] = *(sp + 2); #elif defined(_CALL_SYSV) - result[n++] = *(sp+1); -#elif defined(__APPLE__) || ((defined(__linux) || defined(__linux__)) && defined(__PPC64__)) + result[n++] = *(sp + 1); +#elif defined(__APPLE__) || \ + ((defined(__linux) || defined(__linux__)) && defined(__PPC64__)) // This check is in case the compiler doesn't define _CALL_AIX/etc. - result[n++] = *(sp+2); + result[n++] = *(sp + 2); #elif defined(__linux) || defined(__OpenBSD__) // This check is in case the compiler doesn't define _CALL_SYSV. - result[n++] = *(sp+1); + result[n++] = *(sp + 1); #else -#error Need to specify the PPC ABI for your architecture. +# error Need to specify the PPC ABI for your architecture. #endif } // Use strict unwinding rules. diff --git a/src/stacktrace_unittest.cc b/src/stacktrace_unittest.cc index 05f0401f3..997b48ac7 100644 --- a/src/stacktrace_unittest.cc +++ b/src/stacktrace_unittest.cc @@ -38,7 +38,7 @@ #include "utilities.h" #ifdef HAVE_EXECINFO_BACKTRACE_SYMBOLS -# include +# include #endif using namespace google; @@ -59,63 +59,69 @@ struct AddressRange { // Expected function [start,end] range. AddressRange expected_range[BACKTRACE_STEPS]; -#if __GNUC__ +# if __GNUC__ // Using GCC extension: address of a label can be taken with '&&label'. // Start should be a label somewhere before recursive call, end somewhere // after it. -#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ - do { \ - (prange)->start = &&start_label; \ - (prange)->end = &&end_label; \ - CHECK_LT((prange)->start, (prange)->end); \ - } while (0) +# define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ + do { \ + (prange)->start = &&start_label; \ + (prange)->end = &&end_label; \ + CHECK_LT((prange)->start, (prange)->end); \ + } while (0) // This macro expands into "unmovable" code (opaque to GCC), and that // prevents GCC from moving a_label up or down in the code. // Without it, there is no code following the 'end' label, and GCC // (4.3.1, 4.4.0) thinks it safe to assign &&end an address that is before // the recursive call. -#define DECLARE_ADDRESS_LABEL(a_label) \ - a_label: do { __asm__ __volatile__(""); } while (0) +# define DECLARE_ADDRESS_LABEL(a_label) \ + a_label: \ + do { \ + __asm__ __volatile__(""); \ + } while (0) // Gcc 4.4.0 may split function into multiple chunks, and the chunk // performing recursive call may end up later in the code then the return // instruction (this actually happens with FDO). // Adjust function range from __builtin_return_address. -#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ - do { \ - void *ra = __builtin_return_address(0); \ - CHECK_LT((prange)->start, ra); \ - if (ra > (prange)->end) { \ - printf("Adjusting range from %p..%p to %p..%p\n", \ - (prange)->start, (prange)->end, \ - (prange)->start, ra); \ - (prange)->end = ra; \ - } \ - } while (0) -#else +# define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ + do { \ + void *ra = __builtin_return_address(0); \ + CHECK_LT((prange)->start, ra); \ + if (ra > (prange)->end) { \ + printf("Adjusting range from %p..%p to %p..%p\n", (prange)->start, \ + (prange)->end, (prange)->start, ra); \ + (prange)->end = ra; \ + } \ + } while (0) +# else // Assume the Check* functions below are not longer than 256 bytes. -#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ - do { \ - (prange)->start = reinterpret_cast(&fn); \ - (prange)->end = reinterpret_cast(&fn) + 256; \ - } while (0) -#define DECLARE_ADDRESS_LABEL(a_label) do { } while (0) -#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) do { } while (0) -#endif // __GNUC__ +# define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ + do { \ + (prange)->start = reinterpret_cast(&fn); \ + (prange)->end = reinterpret_cast(&fn) + 256; \ + } while (0) +# define DECLARE_ADDRESS_LABEL(a_label) \ + do { \ + } while (0) +# define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ + do { \ + } while (0) +# endif // __GNUC__ //-----------------------------------------------------------------------// -static void CheckRetAddrIsInFunction(void *ret_addr, const AddressRange &range) -{ +static void CheckRetAddrIsInFunction(void *ret_addr, + const AddressRange &range) { CHECK_GE(ret_addr, range.start); CHECK_LE(ret_addr, range.end); } //-----------------------------------------------------------------------// -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu-label-as-value" -#endif +# if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wgnu-label-as-value" +# endif void ATTRIBUTE_NOINLINE CheckStackTrace(int); static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf() { @@ -132,7 +138,7 @@ static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf() { CHECK_LE(size, STACK_LEN); if (true) { -#ifdef HAVE_EXECINFO_BACKTRACE_SYMBOLS +# ifdef HAVE_EXECINFO_BACKTRACE_SYMBOLS char **strings = backtrace_symbols(stack, size); printf("Obtained %d stack frames.\n", size); for (int i = 0; i < size; i++) { @@ -141,16 +147,16 @@ static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf() { union { void (*p1)(int); - void* p2; + void *p2; } p = {&CheckStackTrace}; printf("CheckStackTrace() addr: %p\n", p.p2); free(strings); -#endif +# endif } for (int i = 0; i < BACKTRACE_STEPS; i++) { - printf("Backtrace %d: expected: %p..%p actual: %p ... ", - i, expected_range[i].start, expected_range[i].end, stack[i]); + printf("Backtrace %d: expected: %p..%p actual: %p ... ", i, + expected_range[i].start, expected_range[i].end, stack[i]); fflush(stdout); CheckRetAddrIsInFunction(stack[i], expected_range[i]); printf("OK\n"); @@ -198,7 +204,7 @@ static void ATTRIBUTE_NOINLINE CheckStackTrace1(int i) { DECLARE_ADDRESS_LABEL(end); } -#ifndef __GNUC__ +# ifndef __GNUC__ // On non-GNU environment, we use the address of `CheckStackTrace` to // guess the address range of this function. This guess is wrong for // non-static function on Windows. This is probably because @@ -206,8 +212,9 @@ static void ATTRIBUTE_NOINLINE CheckStackTrace1(int i) { // not the actual address of `CheckStackTrace`. // See https://github.com/google/glog/issues/421 for the detail. static -#endif -void ATTRIBUTE_NOINLINE CheckStackTrace(int i) { +# endif + void ATTRIBUTE_NOINLINE + CheckStackTrace(int i) { INIT_ADDRESS_RANGE(CheckStackTrace, start, end, &expected_range[5]); DECLARE_ADDRESS_LABEL(start); for (int j = i; j >= 0; j--) { @@ -216,13 +223,13 @@ void ATTRIBUTE_NOINLINE CheckStackTrace(int i) { DECLARE_ADDRESS_LABEL(end); } -#if defined(__clang__) -#pragma clang diagnostic pop -#endif +# if defined(__clang__) +# pragma clang diagnostic pop +# endif //-----------------------------------------------------------------------// -int main(int, char ** argv) { +int main(int, char **argv) { FLAGS_logtostderr = true; InitGoogleLogging(argv[0]); @@ -235,12 +242,12 @@ int main(int, char ** argv) { #else int main() { -#ifdef GLOG_BAZEL_BUILD +# ifdef GLOG_BAZEL_BUILD printf("HAVE_STACKTRACE is expected to be defined in Bazel tests\n"); exit(EXIT_FAILURE); -#endif // GLOG_BAZEL_BUILD +# endif // GLOG_BAZEL_BUILD printf("PASS (no stacktrace support)\n"); return 0; } -#endif // HAVE_STACKTRACE +#endif // HAVE_STACKTRACE diff --git a/src/stacktrace_unwind-inl.h b/src/stacktrace_unwind-inl.h index 3bdb84f04..8d2228473 100644 --- a/src/stacktrace_unwind-inl.h +++ b/src/stacktrace_unwind-inl.h @@ -45,34 +45,34 @@ struct trace_arg_t { }; // Workaround for the malloc() in _Unwind_Backtrace() issue. -static _Unwind_Reason_Code nop_backtrace(struct _Unwind_Context */*uc*/, void */*opq*/) { +static _Unwind_Reason_Code nop_backtrace(struct _Unwind_Context * /*uc*/, + void * /*opq*/) { return _URC_NO_REASON; } - // This code is not considered ready to run until // static initializers run so that we are guaranteed // that any malloc-related initialization is done. static bool ready_to_run = false; class StackTraceInit { public: - StackTraceInit() { - // Extra call to force initialization - _Unwind_Backtrace(nop_backtrace, nullptr); - ready_to_run = true; - } + StackTraceInit() { + // Extra call to force initialization + _Unwind_Backtrace(nop_backtrace, nullptr); + ready_to_run = true; + } }; static StackTraceInit module_initializer; // Force initialization static _Unwind_Reason_Code GetOneFrame(struct _Unwind_Context *uc, void *opq) { - auto *targ = static_cast(opq); + auto *targ = static_cast(opq); - if (targ->skip_count > 0) { - targ->skip_count--; - } else { - targ->result[targ->count++] = reinterpret_cast(_Unwind_GetIP(uc)); - } + if (targ->skip_count > 0) { + targ->skip_count--; + } else { + targ->result[targ->count++] = reinterpret_cast(_Unwind_GetIP(uc)); + } if (targ->count == targ->max_depth) { return _URC_END_OF_STACK; @@ -82,14 +82,14 @@ static _Unwind_Reason_Code GetOneFrame(struct _Unwind_Context *uc, void *opq) { } // If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { +int GetStackTrace(void **result, int max_depth, int skip_count) { if (!ready_to_run) { return 0; } trace_arg_t targ; - skip_count += 1; // Do not include the "GetStackTrace" frame + skip_count += 1; // Do not include the "GetStackTrace" frame targ.result = result; targ.max_depth = max_depth; diff --git a/src/stacktrace_windows-inl.h b/src/stacktrace_windows-inl.h index 33a1af775..fedbad099 100644 --- a/src/stacktrace_windows-inl.h +++ b/src/stacktrace_windows-inl.h @@ -31,10 +31,11 @@ // // Windows implementation - just use CaptureStackBackTrace +#include + #include "config.h" #include "port.h" #include "stacktrace.h" -#include namespace google { diff --git a/src/stacktrace_x86-inl.h b/src/stacktrace_x86-inl.h index d2d51222c..4266f5011 100644 --- a/src/stacktrace_x86-inl.h +++ b/src/stacktrace_x86-inl.h @@ -31,11 +31,11 @@ #include // for uintptr_t -#include "utilities.h" // for OS_* macros +#include "utilities.h" // for OS_* macros #if !defined(GLOG_OS_WINDOWS) -#include -#include +# include +# include #endif #include // for nullptr @@ -48,7 +48,7 @@ namespace google { // stackframe, or return nullptr if no stackframe can be found. Perform sanity // checks (the strictness of which is controlled by the boolean parameter // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. -template +template static void **NextStackFrame(void **old_sp) { void **new_sp = static_cast(*old_sp); @@ -104,17 +104,17 @@ static void **NextStackFrame(void **old_sp) { } // If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { +int GetStackTrace(void **result, int max_depth, int skip_count) { void **sp; #ifdef __GNUC__ -#if __GNUC__ * 100 + __GNUC_MINOR__ >= 402 -#define USE_BUILTIN_FRAME_ADDRESS -#endif +# if __GNUC__ * 100 + __GNUC_MINOR__ >= 402 +# define USE_BUILTIN_FRAME_ADDRESS +# endif #endif #ifdef USE_BUILTIN_FRAME_ADDRESS - sp = reinterpret_cast(__builtin_frame_address(0)); + sp = reinterpret_cast(__builtin_frame_address(0)); #elif defined(__i386__) // Stack frame format: // sp[0] pointer to previous frame @@ -132,10 +132,10 @@ int GetStackTrace(void** result, int max_depth, int skip_count) { // would be (before this __asm__ instruction) to call Noop() defined as // static void Noop() __attribute__ ((noinline)); // prevent inlining // static void Noop() { asm(""); } // prevent optimizing-away - __asm__ volatile ("mov %%rbp, %0" : "=r" (rbp)); + __asm__ volatile("mov %%rbp, %0" : "=r"(rbp)); // Arguments are passed in registers on x86-64, so we can't just // offset from &result - sp = (void **) rbp; + sp = (void **)rbp; #endif int n = 0; @@ -148,7 +148,7 @@ int GetStackTrace(void** result, int max_depth, int skip_count) { if (skip_count > 0) { skip_count--; } else { - result[n++] = *(sp+1); + result[n++] = *(sp + 1); } // Use strict unwinding rules. sp = NextStackFrame(sp); diff --git a/src/stl_logging_unittest.cc b/src/stl_logging_unittest.cc index 4cb7c239f..5a8ae2aed 100644 --- a/src/stl_logging_unittest.cc +++ b/src/stl_logging_unittest.cc @@ -62,14 +62,14 @@ static void TestSTLLogging() { { // Test a sorted pair associative container. - map< int, string > m; + map m; m[20] = "twenty"; m[10] = "ten"; m[30] = "thirty"; ostringstream ss; ss << m; EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)"); - map< int, string > copied_m(m); + map copied_m(m); CHECK_EQ(m, copied_m); // This must compile. } @@ -95,14 +95,14 @@ static void TestSTLLogging() { { // Test a sorted pair associative container. // Use a non-default comparison functor. - map > m; + map> m; m[20] = "twenty"; m[10] = "ten"; m[30] = "thirty"; ostringstream ss; ss << m; EXPECT_EQ(ss.str(), "(30, thirty) (20, twenty) (10, ten)"); - map > copied_m(m); + map> copied_m(m); CHECK_EQ(m, copied_m); // This must compile. } } diff --git a/src/symbolize.cc b/src/symbolize.cc index 141bdb168..184c49393 100644 --- a/src/symbolize.cc +++ b/src/symbolize.cc @@ -49,20 +49,19 @@ // macro to add platform specific defines (e.g. GLOG_OS_OPENBSD). #ifdef GLOG_BUILD_CONFIG_INCLUDE -#include GLOG_BUILD_CONFIG_INCLUDE +# include GLOG_BUILD_CONFIG_INCLUDE #endif // GLOG_BUILD_CONFIG_INCLUDE #include "utilities.h" #if defined(HAVE_SYMBOLIZE) -#include +# include +# include +# include -#include -#include - -#include "symbolize.h" -#include "demangle.h" +# include "demangle.h" +# include "symbolize.h" namespace google { @@ -76,7 +75,7 @@ static int AssertFail() { return 0; // Should not reach. } -#define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail()) +# define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail()) static SymbolizeCallback g_symbolize_callback = nullptr; void InstallSymbolizeCallback(SymbolizeCallback callback) { @@ -108,35 +107,37 @@ static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, size_t out_size) { } // namespace google -#if defined(__ELF__) - -#if defined(HAVE_DLFCN_H) -#include -#endif -#if defined(GLOG_OS_OPENBSD) -#include -#else -#include -#endif -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "config.h" -#include "glog/raw_logging.h" -#include "symbolize.h" +# if defined(__ELF__) + +# if defined(HAVE_DLFCN_H) +# include +# endif +# if defined(GLOG_OS_OPENBSD) +# include +# else +# include +# endif +# include +# include +# include +# include + +# include +# include +# include +# include +# include +# include +# include + +# include "config.h" +# include "glog/raw_logging.h" +# include "symbolize.h" // Re-runs fn until it doesn't cause EINTR. -#define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR) +# define NO_INTR(fn) \ + do { \ + } while ((fn) < 0 && errno == EINTR) namespace google { @@ -147,7 +148,8 @@ namespace google { static ssize_t ReadFromOffset(const int fd, void *buf, const size_t count, const size_t offset) { SAFE_ASSERT(fd >= 0); - SAFE_ASSERT(count <= static_cast(std::numeric_limits::max())); + SAFE_ASSERT(count <= + static_cast(std::numeric_limits::max())); char *buf0 = reinterpret_cast(buf); size_t num_bytes = 0; while (num_bytes < count) { @@ -170,8 +172,8 @@ static ssize_t ReadFromOffset(const int fd, void *buf, const size_t count, // pointed by "fd" into the buffer starting at "buf" while handling // short reads and EINTR. On success, return true. Otherwise, return // false. -static bool ReadFromOffsetExact(const int fd, void *buf, - const size_t count, const size_t offset) { +static bool ReadFromOffsetExact(const int fd, void *buf, const size_t count, + const size_t offset) { ssize_t len = ReadFromOffset(fd, buf, count, offset); return static_cast(len) == count; } @@ -193,9 +195,11 @@ static int FileGetElfType(const int fd) { // and return true. Otherwise, return false. // To keep stack consumption low, we would like this function to not get // inlined. -static ATTRIBUTE_NOINLINE bool -GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const size_t sh_offset, - ElfW(Word) type, ElfW(Shdr) *out) { +static ATTRIBUTE_NOINLINE bool GetSectionHeaderByType(const int fd, + ElfW(Half) sh_num, + const size_t sh_offset, + ElfW(Word) type, + ElfW(Shdr) * out) { // Read at most 16 section headers at a time to save read calls. ElfW(Shdr) buf[16]; for (size_t i = 0; i < sh_num;) { @@ -227,7 +231,7 @@ const int kMaxSectionNameLen = 64; // name_len should include terminating '\0'. bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, - ElfW(Shdr) *out) { + ElfW(Shdr) * out) { ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { return false; @@ -242,8 +246,8 @@ bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, } for (size_t i = 0; i < elf_header.e_shnum; ++i) { - size_t section_header_offset = (elf_header.e_shoff + - elf_header.e_shentsize * i); + size_t section_header_offset = + (elf_header.e_shoff + elf_header.e_shentsize * i); if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) { return false; } @@ -277,10 +281,11 @@ bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, // to out. Otherwise, return false. // To keep stack consumption low, we would like this function to not get // inlined. -static ATTRIBUTE_NOINLINE bool -FindSymbol(uint64_t pc, const int fd, char *out, size_t out_size, - uint64_t symbol_offset, const ElfW(Shdr) *strtab, - const ElfW(Shdr) *symtab) { +static ATTRIBUTE_NOINLINE bool FindSymbol(uint64_t pc, const int fd, char *out, + size_t out_size, + uint64_t symbol_offset, + const ElfW(Shdr) * strtab, + const ElfW(Shdr) * symtab) { if (symtab == nullptr) { return false; } @@ -291,11 +296,11 @@ FindSymbol(uint64_t pc, const int fd, char *out, size_t out_size, // If we are reading Elf64_Sym's, we want to limit this array to // 32 elements (to keep stack consumption low), otherwise we can // have a 64 element Elf32_Sym array. -#if defined(__WORDSIZE) && __WORDSIZE == 64 +# if defined(__WORDSIZE) && __WORDSIZE == 64 const size_t NUM_SYMBOLS = 32U; -#else +# else const size_t NUM_SYMBOLS = 64U; -#endif +# endif // Read at most NUM_SYMBOLS symbols at once to save read() calls. ElfW(Sym) buf[NUM_SYMBOLS]; @@ -306,7 +311,7 @@ FindSymbol(uint64_t pc, const int fd, char *out, size_t out_size, const size_t num_symbols_in_buf = static_cast(len) / sizeof(buf[0]); SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read); for (unsigned j = 0; j < num_symbols_in_buf; ++j) { - const ElfW(Sym)& symbol = buf[j]; + const ElfW(Sym) &symbol = buf[j]; uint64_t start_address = symbol.st_value; start_address += symbol_offset; uint64_t end_address = start_address + symbol.st_size; @@ -331,11 +336,8 @@ FindSymbol(uint64_t pc, const int fd, char *out, size_t out_size, // both regular and dynamic symbol tables if necessary. On success, // write the symbol name to "out" and return true. Otherwise, return // false. -static bool GetSymbolFromObjectFile(const int fd, - uint64_t pc, - char* out, - size_t out_size, - uint64_t base_address) { +static bool GetSymbolFromObjectFile(const int fd, uint64_t pc, char *out, + size_t out_size, uint64_t base_address) { // Read the ELF header. ElfW(Ehdr) elf_header; if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { @@ -347,8 +349,9 @@ static bool GetSymbolFromObjectFile(const int fd, // Consult a regular symbol table first. if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, SHT_SYMTAB, &symtab)) { - if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + - symtab.sh_link * sizeof(symtab))) { + if (!ReadFromOffsetExact( + fd, &strtab, sizeof(strtab), + elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) { return false; } if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { @@ -359,8 +362,9 @@ static bool GetSymbolFromObjectFile(const int fd, // If the symbol is not found, then consult a dynamic symbol table. if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, SHT_DYNSYM, &symtab)) { - if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + - symtab.sh_link * sizeof(symtab))) { + if (!ReadFromOffsetExact( + fd, &strtab, sizeof(strtab), + elf_header.e_shoff + symtab.sh_link * sizeof(symtab))) { return false; } if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { @@ -420,14 +424,14 @@ class LineReader { eod_ = buf_ + num_bytes; bol_ = buf_; } else { - bol_ = eol_ + 1; // Advance to the next line in the buffer. + bol_ = eol_ + 1; // Advance to the next line in the buffer. SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_". if (!HasCompleteLine()) { const auto incomplete_line_length = static_cast(eod_ - bol_); // Move the trailing incomplete line to the beginning. memmove(buf_, bol_, incomplete_line_length); // Read text from file and append it. - char * const append_pos = buf_ + incomplete_line_length; + char *const append_pos = buf_ + incomplete_line_length; const size_t capacity_left = buf_len_ - incomplete_line_length; const ssize_t num_bytes = ReadFromOffset(fd_, append_pos, capacity_left, offset_); @@ -451,33 +455,28 @@ class LineReader { } // Beginning of line. - const char *bol() { - return bol_; - } + const char *bol() { return bol_; } // End of line. - const char *eol() { - return eol_; - } + const char *eol() { return eol_; } private: LineReader(const LineReader &) = delete; void operator=(const LineReader &) = delete; char *FindLineFeed() { - return reinterpret_cast(memchr(bol_, '\n', static_cast(eod_ - bol_))); + return reinterpret_cast( + memchr(bol_, '\n', static_cast(eod_ - bol_))); } - bool BufferIsEmpty() { - return buf_ == eod_; - } + bool BufferIsEmpty() { return buf_ == eod_; } bool HasCompleteLine() { return !BufferIsEmpty() && FindLineFeed() != nullptr; } const int fd_; - char * const buf_; + char *const buf_; const size_t buf_len_; size_t offset_; char *bol_; @@ -493,9 +492,10 @@ static char *GetHex(const char *start, const char *end, uint64_t *hex) { const char *p; for (p = start; p < end; ++p) { int ch = *p; - if ((ch >= '0' && ch <= '9') || - (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) { - *hex = (*hex << 4U) | (ch < 'A' ? static_cast(ch - '0') : (ch & 0xF) + 9U); + if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || + (ch >= 'a' && ch <= 'f')) { + *hex = (*hex << 4U) | + (ch < 'A' ? static_cast(ch - '0') : (ch & 0xF) + 9U); } else { // Encountered the first non-hex character. break; } @@ -512,12 +512,9 @@ static char *GetHex(const char *start, const char *end, uint64_t *hex) { // file is opened successfully, returns the file descriptor. Otherwise, // returns -1. |out_file_name_size| is the size of the file name buffer // (including the null-terminator). -static ATTRIBUTE_NOINLINE int -OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, - uint64_t &start_address, - uint64_t &base_address, - char *out_file_name, - size_t out_file_name_size) { +static ATTRIBUTE_NOINLINE int OpenObjectFileContainingPcAndGetStartAddress( + uint64_t pc, uint64_t &start_address, uint64_t &base_address, + char *out_file_name, size_t out_file_name_size) { int object_fd; int maps_fd; @@ -568,7 +565,7 @@ OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, ++cursor; // Skip ' '. // Read flags. Skip flags until we encounter a space or eol. - const char * const flags_start = cursor; + const char *const flags_start = cursor; while (cursor < eol && *cursor != ' ') { ++cursor; } @@ -620,7 +617,7 @@ OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, continue; // We skip this map. PC isn't in this map. } - // Check flags. We are only interested in "r*x" maps. + // Check flags. We are only interested in "r*x" maps. if (flags_start[0] != 'r' || flags_start[2] != 'x') { continue; // We skip this map. } @@ -672,7 +669,8 @@ OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, // "sz" bytes. Output will be truncated as needed, and a NUL character is always // appended. // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc. -static char *itoa_r(uintptr_t i, char *buf, size_t sz, unsigned base, size_t padding) { +static char *itoa_r(uintptr_t i, char *buf, size_t sz, unsigned base, + size_t padding) { // Make sure we can write at least one NUL byte. size_t n = 1; if (n > sz) { @@ -722,7 +720,7 @@ static char *itoa_r(uintptr_t i, char *buf, size_t sz, unsigned base, size_t pad // Safely appends string |source| to string |dest|. Never writes past the // buffer size |dest_size| and guarantees that |dest| is null-terminated. -static void SafeAppendString(const char* source, char* dest, size_t dest_size) { +static void SafeAppendString(const char *source, char *dest, size_t dest_size) { size_t dest_string_length = strlen(dest); SAFE_ASSERT(dest_string_length < dest_size); dest += dest_string_length; @@ -735,7 +733,7 @@ static void SafeAppendString(const char* source, char* dest, size_t dest_size) { // Converts a 64-bit value into a hex string, and safely appends it to |dest|. // Never writes past the buffer size |dest_size| and guarantees that |dest| is // null-terminated. -static void SafeAppendHexNumber(uint64_t value, char* dest, size_t dest_size) { +static void SafeAppendHexNumber(uint64_t value, char *dest, size_t dest_size) { // 64-bit numbers in hex can have up to 16 digits. char buf[17] = {'\0'}; SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size); @@ -763,24 +761,21 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, SafeAppendString("(", out, out_size); if (g_symbolize_open_object_file_callback) { - object_fd = g_symbolize_open_object_file_callback(pc0, start_address, - base_address, out + 1, - out_size - 1); + object_fd = g_symbolize_open_object_file_callback( + pc0, start_address, base_address, out + 1, out_size - 1); } else { - object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address, - base_address, - out + 1, - out_size - 1); + object_fd = OpenObjectFileContainingPcAndGetStartAddress( + pc0, start_address, base_address, out + 1, out_size - 1); } FileDescriptor wrapped_object_fd(object_fd); -#if defined(PRINT_UNSYMBOLIZED_STACK_TRACES) +# if defined(PRINT_UNSYMBOLIZED_STACK_TRACES) { -#else +# else // Check whether a file name was returned. if (object_fd < 0) { -#endif +# endif if (out[1]) { // The object file containing PC was determined successfully however the // object file was not opened successfully. This is still considered @@ -804,16 +799,15 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, // Note: relocation (and much of the rest of this code) will be // wrong for prelinked shared libraries and PIE executables. uint64_t relocation = (elf_type == ET_DYN) ? start_address : 0; - int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(), - pc, out, out_size, - relocation); + int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(), pc, + out, out_size, relocation); if (num_bytes_written > 0) { out += static_cast(num_bytes_written); out_size -= static_cast(num_bytes_written); } } - if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0, - out, out_size, base_address)) { + if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0, out, out_size, + base_address)) { if (out[1] && !g_symbolize_callback) { // The object file containing PC was opened successfully however the // symbol was not found. The object may have been stripped. This is still @@ -835,10 +829,11 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, } // namespace google -#elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) +# elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) + +# include -#include -#include +# include namespace google { @@ -860,19 +855,19 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, } // namespace google -#elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) +# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) -#include -#include +# include +# include -#ifdef _MSC_VER -#pragma comment(lib, "dbghelp") -#endif +# ifdef _MSC_VER +# pragma comment(lib, "dbghelp") +# endif namespace google { class SymInitializer { -public: + public: HANDLE process; bool ready; SymInitializer() : process(nullptr), ready(false) { @@ -891,9 +886,10 @@ class SymInitializer { SymCleanup(process); // We do not need to close `HANDLE process` because it's a "pseudo handle." } -private: - SymInitializer(const SymInitializer&); - SymInitializer& operator=(const SymInitializer&); + + private: + SymInitializer(const SymInitializer &); + SymInitializer &operator=(const SymInitializer &); }; static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, @@ -910,8 +906,8 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, symbol->MaxNameLen = MAX_SYM_NAME; // We use the ANSI version to ensure the string type is always `char *`. // This could break if a symbol has Unicode in it. - BOOL ret = SymFromAddr(symInitializer.process, - reinterpret_cast(pc), 0, symbol); + BOOL ret = SymFromAddr(symInitializer.process, reinterpret_cast(pc), + 0, symbol); if (ret == 1 && static_cast(symbol->NameLen) < out_size) { // `NameLen` does not include the null terminating character. strncpy(out, symbol->Name, static_cast(symbol->NameLen) + 1); @@ -925,9 +921,9 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, } // namespace google -#else -# error BUG: HAVE_SYMBOLIZE was wrongly set -#endif +# else +# error BUG: HAVE_SYMBOLIZE was wrongly set +# endif namespace google { @@ -937,11 +933,11 @@ bool Symbolize(void *pc, char *out, size_t out_size) { } // namespace google -#else /* HAVE_SYMBOLIZE */ +#else /* HAVE_SYMBOLIZE */ -#include +# include -#include "config.h" +# include "config.h" namespace google { diff --git a/src/symbolize.h b/src/symbolize.h index e26d3e417..8b614c87c 100644 --- a/src/symbolize.h +++ b/src/symbolize.h @@ -60,48 +60,48 @@ #ifdef HAVE_SYMBOLIZE -#if defined(__ELF__) // defined by gcc -#if defined(__OpenBSD__) -#include -#else -#include -#endif +# if defined(__ELF__) // defined by gcc +# if defined(__OpenBSD__) +# include +# else +# include +# endif -#if !defined(ANDROID) -#include // For ElfW() macro. -#endif +# if !defined(ANDROID) +# include // For ElfW() macro. +# endif // For systems where SIZEOF_VOID_P is not defined, determine it // based on __LP64__ (defined by gcc on 64-bit systems) -#if !defined(SIZEOF_VOID_P) -# if defined(__LP64__) -# define SIZEOF_VOID_P 8 -# else -# define SIZEOF_VOID_P 4 -# endif -#endif +# if !defined(SIZEOF_VOID_P) +# if defined(__LP64__) +# define SIZEOF_VOID_P 8 +# else +# define SIZEOF_VOID_P 4 +# endif +# endif // If there is no ElfW macro, let's define it by ourself. -#ifndef ElfW -# if SIZEOF_VOID_P == 4 -# define ElfW(type) Elf32_##type -# elif SIZEOF_VOID_P == 8 -# define ElfW(type) Elf64_##type -# else -# error "Unknown sizeof(void *)" -# endif -#endif +# ifndef ElfW +# if SIZEOF_VOID_P == 4 +# define ElfW(type) Elf32_##type +# elif SIZEOF_VOID_P == 8 +# define ElfW(type) Elf64_##type +# else +# error "Unknown sizeof(void *)" +# endif +# endif namespace google { // Gets the section header for the given name, if it exists. Returns true on // success. Otherwise, returns false. bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, - ElfW(Shdr) *out); + ElfW(Shdr) * out); } // namespace google -#endif /* __ELF__ */ +# endif /* __ELF__ */ namespace google { @@ -145,7 +145,7 @@ namespace google { // symbol name to "out". The symbol name is demangled if possible // (supports symbols generated by GCC 3.x or newer). Otherwise, // returns false. -GLOG_EXPORT bool Symbolize(void* pc, char* out, size_t out_size); +GLOG_EXPORT bool Symbolize(void *pc, char *out, size_t out_size); } // namespace google diff --git a/src/symbolize_unittest.cc b/src/symbolize_unittest.cc index 446a67fbf..8f2c29f15 100644 --- a/src/symbolize_unittest.cc +++ b/src/symbolize_unittest.cc @@ -42,7 +42,7 @@ #include "utilities.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif @@ -52,15 +52,15 @@ using namespace google; // Avoid compile error due to "cast between pointer-to-function and // pointer-to-object is an extension" warnings. #if defined(__GNUG__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif #if defined(HAVE_STACKTRACE) -#define always_inline +# define always_inline -#if defined(__ELF__) || defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) +# if defined(__ELF__) || defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) // A wrapper function for Symbolize() to make the unit test simple. static const char *TrySymbolize(void *pc) { static char symbol[4096]; @@ -70,24 +70,25 @@ static const char *TrySymbolize(void *pc) { return nullptr; } } -#endif +# endif -# if defined(__ELF__) +# if defined(__ELF__) // This unit tests make sense only with GCC. // Uses lots of GCC specific features. -#if defined(__GNUC__) && !defined(__OPENCC__) -# if __GNUC__ >= 4 -# define TEST_WITH_MODERN_GCC -# if defined(__i386__) && __i386__ // always_inline isn't supported for x86_64 with GCC 4.1.0. -# undef always_inline -# define always_inline __attribute__((always_inline)) -# define HAVE_ALWAYS_INLINE -# endif // __i386__ -# else -# endif // __GNUC__ >= 4 -# define TEST_WITH_LABEL_ADDRESSES -#endif +# if defined(__GNUC__) && !defined(__OPENCC__) +# if __GNUC__ >= 4 +# define TEST_WITH_MODERN_GCC +# if defined(__i386__) && __i386__ // always_inline isn't supported for + // x86_64 with GCC 4.1.0. +# undef always_inline +# define always_inline __attribute__((always_inline)) +# define HAVE_ALWAYS_INLINE +# endif // __i386__ +# else +# endif // __GNUC__ >= 4 +# define TEST_WITH_LABEL_ADDRESSES +# endif // Make them C linkage to avoid mangled names. extern "C" { @@ -119,11 +120,11 @@ TEST(Symbolize, Symbolize) { const char *static_func_symbol = TrySymbolize(reinterpret_cast(&static_func)); -#if !defined(_MSC_VER) || !defined(NDEBUG) +# if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(nullptr != static_func_symbol); EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 || strcmp("static_func()", static_func_symbol) == 0); -#endif +# endif EXPECT_TRUE(nullptr == TrySymbolize(nullptr)); } @@ -141,14 +142,14 @@ void ATTRIBUTE_NOINLINE Foo::func(int x) { // With a modern GCC, Symbolize() should return demangled symbol // names. Function parameters should be omitted. -#ifdef TEST_WITH_MODERN_GCC +# ifdef TEST_WITH_MODERN_GCC TEST(Symbolize, SymbolizeWithDemangling) { Foo::func(100); -#if !defined(_MSC_VER) || !defined(NDEBUG) +# if !defined(_MSC_VER) || !defined(NDEBUG) EXPECT_STREQ("Foo::func()", TrySymbolize((void *)(&Foo::func))); -#endif +# endif } -#endif +# endif // Tests that verify that Symbolize footprint is within some limit. @@ -192,7 +193,7 @@ static ATTRIBUTE_NOINLINE bool StackGrowsDown(int *x) { int y; return &y < x; } -static int GetStackConsumption(const char* alt_stack) { +static int GetStackConsumption(const char *alt_stack) { int x; if (StackGrowsDown(&x)) { for (int i = 0; i < kAlternateStackSize; i++) { @@ -210,11 +211,10 @@ static int GetStackConsumption(const char* alt_stack) { return -1; } -#ifdef HAVE_SIGALTSTACK +# ifdef HAVE_SIGALTSTACK // Call Symbolize and figure out the stack footprint of this call. static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) { - g_pc_to_symbolize = pc; // The alt-signal-stack cannot be heap allocated because there is a @@ -282,17 +282,17 @@ static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) { return g_symbolize_result; } -#ifdef __ppc64__ +# ifdef __ppc64__ // Symbolize stack consumption should be within 4kB. const int kStackConsumptionUpperLimit = 4096; -#else +# else // Symbolize stack consumption should be within 2kB. const int kStackConsumptionUpperLimit = 2048; -#endif +# endif TEST(Symbolize, SymbolizeStackConsumption) { int stack_consumed; - const char* symbol; + const char *symbol; symbol = SymbolizeStackConsumption(reinterpret_cast(&nonstatic_func), &stack_consumed); @@ -311,11 +311,11 @@ TEST(Symbolize, SymbolizeStackConsumption) { EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); } -#ifdef TEST_WITH_MODERN_GCC +# ifdef TEST_WITH_MODERN_GCC TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) { Foo::func(100); int stack_consumed; - const char* symbol; + const char *symbol; symbol = SymbolizeStackConsumption(reinterpret_cast(&Foo::func), &stack_consumed); @@ -324,78 +324,78 @@ TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) { EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); } -#endif +# endif -#endif // HAVE_SIGALTSTACK +# endif // HAVE_SIGALTSTACK // x86 specific tests. Uses some inline assembler. extern "C" { -inline void* always_inline inline_func() { +inline void *always_inline inline_func() { void *pc = nullptr; -#ifdef TEST_WITH_LABEL_ADDRESSES +# ifdef TEST_WITH_LABEL_ADDRESSES pc = &&curr_pc; - curr_pc: -#endif +curr_pc: +# endif return pc; } -void* ATTRIBUTE_NOINLINE non_inline_func(); -void* ATTRIBUTE_NOINLINE non_inline_func() { +void *ATTRIBUTE_NOINLINE non_inline_func(); +void *ATTRIBUTE_NOINLINE non_inline_func() { void *pc = nullptr; -#ifdef TEST_WITH_LABEL_ADDRESSES +# ifdef TEST_WITH_LABEL_ADDRESSES pc = &&curr_pc; - curr_pc: -#endif +curr_pc: +# endif return pc; } static void ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() { -#if defined(TEST_WITH_LABEL_ADDRESSES) && defined(HAVE_ATTRIBUTE_NOINLINE) +# if defined(TEST_WITH_LABEL_ADDRESSES) && defined(HAVE_ATTRIBUTE_NOINLINE) void *pc = non_inline_func(); const char *symbol = TrySymbolize(pc); -#if !defined(_MSC_VER) || !defined(NDEBUG) +# if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, "non_inline_func"); -#endif +# endif cout << "Test case TestWithPCInsideNonInlineFunction passed." << endl; -#endif +# endif } static void ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() { -#if defined(TEST_WITH_LABEL_ADDRESSES) && defined(HAVE_ALWAYS_INLINE) +# if defined(TEST_WITH_LABEL_ADDRESSES) && defined(HAVE_ALWAYS_INLINE) void *pc = inline_func(); // Must be inlined. const char *symbol = TrySymbolize(pc); -#if !defined(_MSC_VER) || !defined(NDEBUG) +# if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, __FUNCTION__); -#endif +# endif cout << "Test case TestWithPCInsideInlineFunction passed." << endl; -#endif +# endif } } // Test with a return address. static void ATTRIBUTE_NOINLINE TestWithReturnAddress() { -#if defined(HAVE_ATTRIBUTE_NOINLINE) +# if defined(HAVE_ATTRIBUTE_NOINLINE) void *return_address = __builtin_return_address(0); const char *symbol = TrySymbolize(return_address); -#if !defined(_MSC_VER) || !defined(NDEBUG) +# if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, "main"); -#endif +# endif cout << "Test case TestWithReturnAddress passed." << endl; -#endif +# endif } -# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) +# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) -#ifdef _MSC_VER -#include -#pragma intrinsic(_ReturnAddress) -#endif +# ifdef _MSC_VER +# include +# pragma intrinsic(_ReturnAddress) +# endif struct Foo { static void func(int x); @@ -410,37 +410,37 @@ __declspec(noinline) void Foo::func(int x) { TEST(Symbolize, SymbolizeWithDemangling) { Foo::func(100); - const char* ret = TrySymbolize((void *)(&Foo::func)); + const char *ret = TrySymbolize((void *)(&Foo::func)); -#if defined(HAVE_DBGHELP) && !defined(NDEBUG) +# if defined(HAVE_DBGHELP) && !defined(NDEBUG) EXPECT_STREQ("public: static void __cdecl Foo::func(int)", ret); -#endif +# endif } __declspec(noinline) void TestWithReturnAddress() { void *return_address = -#ifdef __GNUC__ // Cygwin and MinGW support - __builtin_return_address(0) -#else - _ReturnAddress() -#endif - ; +# ifdef __GNUC__ // Cygwin and MinGW support + __builtin_return_address(0) +# else + _ReturnAddress() +# endif + ; const char *symbol = TrySymbolize(return_address); -#if !defined(_MSC_VER) || !defined(NDEBUG) +# if !defined(_MSC_VER) || !defined(NDEBUG) CHECK(symbol != nullptr); CHECK_STREQ(symbol, "main"); -#endif +# endif cout << "Test case TestWithReturnAddress passed." << endl; } -# endif // __ELF__ -#endif // HAVE_STACKTRACE +# endif // __ELF__ +#endif // HAVE_STACKTRACE int main(int argc, char **argv) { FLAGS_logtostderr = true; InitGoogleLogging(argv[0]); InitGoogleTest(&argc, argv); #if defined(HAVE_SYMBOLIZE) && defined(HAVE_STACKTRACE) -# if defined(__ELF__) +# if defined(__ELF__) // We don't want to get affected by the callback interface, that may be // used to install some callback function at InitGoogle() time. InstallSymbolizeCallback(nullptr); @@ -449,13 +449,13 @@ int main(int argc, char **argv) { TestWithPCInsideNonInlineFunction(); TestWithReturnAddress(); return RUN_ALL_TESTS(); -# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) +# elif defined(GLOG_OS_WINDOWS) || defined(GLOG_OS_CYGWIN) TestWithReturnAddress(); return RUN_ALL_TESTS(); -# else // GLOG_OS_WINDOWS +# else // GLOG_OS_WINDOWS printf("PASS (no symbolize_unittest support)\n"); return 0; -# endif // __ELF__ +# endif // __ELF__ #else printf("PASS (no symbolize support)\n"); return 0; @@ -463,5 +463,5 @@ int main(int argc, char **argv) { } #if defined(__GNUG__) -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif diff --git a/src/utilities.cc b/src/utilities.cc index 38f84fee1..20ee02dd6 100644 --- a/src/utilities.cc +++ b/src/utilities.cc @@ -29,33 +29,33 @@ // // Author: Shinichiro Hamaji -#include "config.h" #include "utilities.h" +#include #include #include -#include +#include "config.h" #ifdef HAVE_SYS_TIME_H -# include +# include #endif #include #if defined(HAVE_SYSCALL_H) -#include // for syscall() +# include // for syscall() #elif defined(HAVE_SYS_SYSCALL_H) -#include // for syscall() +# include // for syscall() #endif #ifdef HAVE_SYSLOG_H -# include +# include #endif #ifdef HAVE_UNISTD_H -# include // For geteuid. +# include // For geteuid. #endif #ifdef HAVE_PWD_H -# include +# include #endif #ifdef __ANDROID__ -#include +# include #endif #include "base/googleinit.h" @@ -75,9 +75,9 @@ bool IsGoogleLoggingInitialized() { // The following APIs are all internal. #ifdef HAVE_STACKTRACE -#include "stacktrace.h" -#include "symbolize.h" -#include "base/commandlineflags.h" +# include "base/commandlineflags.h" +# include "stacktrace.h" +# include "symbolize.h" GLOG_DEFINE_bool(symbolize_stacktrace, true, "Symbolize the stack trace in the tombstone"); @@ -90,44 +90,44 @@ using DebugWriter = void(const char*, void*); // For some environments, add two extra bytes for the leading "0x". static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*); -static void DebugWriteToStderr(const char* data, void *) { +static void DebugWriteToStderr(const char* data, void*) { // This one is signal-safe. if (write(STDERR_FILENO, data, strlen(data)) < 0) { // Ignore errors. } -#if defined(__ANDROID__) +# if defined(__ANDROID__) // ANDROID_LOG_FATAL as fatal error occurred and now is dumping call stack. __android_log_write(ANDROID_LOG_FATAL, glog_internal_namespace_::ProgramInvocationShortName(), data); -#endif +# endif } -static void DebugWriteToString(const char* data, void *arg) { +static void DebugWriteToString(const char* data, void* arg) { reinterpret_cast(arg)->append(data); } -#ifdef HAVE_SYMBOLIZE +# ifdef HAVE_SYMBOLIZE // Print a program counter and its symbol name. -static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc, - const char * const prefix) { +static void DumpPCAndSymbol(DebugWriter* writerfn, void* arg, void* pc, + const char* const prefix) { char tmp[1024]; - const char *symbol = "(unknown)"; + const char* symbol = "(unknown)"; // Symbolizes the previous address of pc because pc may be in the // next function. The overrun happens when the function ends with // a call to a function annotated noreturn (e.g. CHECK). - if (Symbolize(reinterpret_cast(pc) - 1, tmp, sizeof(tmp))) { - symbol = tmp; + if (Symbolize(reinterpret_cast(pc) - 1, tmp, sizeof(tmp))) { + symbol = tmp; } char buf[1024]; std::snprintf(buf, sizeof(buf), "%s@ %*p %s\n", prefix, kPrintfPointerFieldWidth, pc, symbol); writerfn(buf, arg); } -#endif +# endif -static void DumpPC(DebugWriter *writerfn, void *arg, void *pc, - const char * const prefix) { +static void DumpPC(DebugWriter* writerfn, void* arg, void* pc, + const char* const prefix) { char buf[100]; std::snprintf(buf, sizeof(buf), "%s@ %*p\n", prefix, kPrintfPointerFieldWidth, pc); @@ -135,26 +135,26 @@ static void DumpPC(DebugWriter *writerfn, void *arg, void *pc, } // Dump current stack trace as directed by writerfn -static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) { +static void DumpStackTrace(int skip_count, DebugWriter* writerfn, void* arg) { // Print stack trace void* stack[32]; - int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count+1); + int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count + 1); for (int i = 0; i < depth; i++) { -#if defined(HAVE_SYMBOLIZE) +# if defined(HAVE_SYMBOLIZE) if (FLAGS_symbolize_stacktrace) { DumpPCAndSymbol(writerfn, arg, stack[i], " "); } else { DumpPC(writerfn, arg, stack[i], " "); } -#else +# else DumpPC(writerfn, arg, stack[i], " "); -#endif +# endif } } -#ifdef __GNUC__ +# ifdef __GNUC__ __attribute__((noreturn)) -#endif +# endif static void DumpStackTraceAndExit() { DumpStackTrace(1, DebugWriteToStderr, nullptr); @@ -163,15 +163,15 @@ DumpStackTraceAndExit() { if (IsFailureSignalHandlerInstalled()) { // Set the default signal handler for SIGABRT, to avoid invoking our // own signal handler installed by InstallFailureSignalHandler(). -#ifdef HAVE_SIGACTION +# ifdef HAVE_SIGACTION struct sigaction sig_action; memset(&sig_action, 0, sizeof(sig_action)); sigemptyset(&sig_action.sa_mask); sig_action.sa_handler = SIG_DFL; sigaction(SIGABRT, &sig_action, nullptr); -#elif defined(GLOG_OS_WINDOWS) +# elif defined(GLOG_OS_WINDOWS) signal(SIGABRT, SIG_DFL); -#endif // HAVE_SIGACTION +# endif // HAVE_SIGACTION } abort(); @@ -199,14 +199,15 @@ struct timeval { long tv_sec, tv_usec; }; -// Based on: http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd +// Based on: +// http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd // See COPYING for copyright information. -static int gettimeofday(struct timeval *tv, void* /*tz*/) { -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wlong-long" -#endif -#define EPOCHFILETIME (116444736000000000ULL) +static int gettimeofday(struct timeval* tv, void* /*tz*/) { +# ifdef __GNUC__ +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +# define EPOCHFILETIME (116444736000000000ULL) FILETIME ft; ULARGE_INTEGER li; uint64 tt; @@ -217,9 +218,9 @@ static int gettimeofday(struct timeval *tv, void* /*tz*/) { tt = (li.QuadPart - EPOCHFILETIME) / 10; tv->tv_sec = tt / 1000000; tv->tv_usec = tt % 1000000; -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif +# ifdef __GNUC__ +# pragma GCC diagnostic pop +# endif return 0; } @@ -232,9 +233,7 @@ int64 CycleClock_Now() { return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; } -int64 UsecToCycles(int64 usec) { - return usec; -} +int64 UsecToCycles(int64 usec) { return usec; } WallTime WallTime_Now() { // Now, cycle clock is retuning microseconds since the epoch. @@ -242,9 +241,7 @@ WallTime WallTime_Now() { } static int32 g_main_thread_pid = getpid(); -int32 GetMainThreadPid() { - return g_main_thread_pid; -} +int32 GetMainThreadPid() { return g_main_thread_pid; } bool PidHasChanged() { int32 pid = getpid(); @@ -258,24 +255,24 @@ bool PidHasChanged() { pid_t GetTID() { // On Linux and MacOSX, we try to use gettid(). #if defined GLOG_OS_LINUX || defined GLOG_OS_MACOSX -#ifndef __NR_gettid -#ifdef GLOG_OS_MACOSX -#define __NR_gettid SYS_gettid -#elif ! defined __i386__ -#error "Must define __NR_gettid for non-x86 platforms" -#else -#define __NR_gettid 224 -#endif -#endif +# ifndef __NR_gettid +# ifdef GLOG_OS_MACOSX +# define __NR_gettid SYS_gettid +# elif !defined __i386__ +# error "Must define __NR_gettid for non-x86 platforms" +# else +# define __NR_gettid 224 +# endif +# endif static bool lacks_gettid = false; if (!lacks_gettid) { -#if (defined(GLOG_OS_MACOSX) && defined(HAVE_PTHREAD_THREADID_NP)) +# if (defined(GLOG_OS_MACOSX) && defined(HAVE_PTHREAD_THREADID_NP)) uint64_t tid64; const int error = pthread_threadid_np(nullptr, &tid64); pid_t tid = error ? -1 : static_cast(tid64); -#else +# else auto tid = static_cast(syscall(__NR_gettid)); -#endif +# endif if (tid != -1) { return tid; } @@ -305,16 +302,13 @@ pid_t GetTID() { const char* const_basename(const char* filepath) { const char* base = strrchr(filepath, '/'); #ifdef GLOG_OS_WINDOWS // Look for either path separator in Windows - if (!base) - base = strrchr(filepath, '\\'); + if (!base) base = strrchr(filepath, '\\'); #endif - return base ? (base+1) : filepath; + return base ? (base + 1) : filepath; } static string g_my_user_name; -const string& MyUserName() { - return g_my_user_name; -} +const string& MyUserName() { return g_my_user_name; } static void MyUserNameInitializer() { // TODO(hamaji): Probably this is not portable. #if defined(GLOG_OS_WINDOWS) @@ -356,8 +350,7 @@ void DumpStackTraceToString(string* stacktrace) { static const CrashReason* g_reason = nullptr; void SetCrashReason(const CrashReason* r) { - sync_val_compare_and_swap(&g_reason, - reinterpret_cast(0), + sync_val_compare_and_swap(&g_reason, reinterpret_cast(0), r); } @@ -366,7 +359,7 @@ void InitGoogleLoggingUtilities(const char* argv0) { << "You called InitGoogleLogging() twice!"; const char* slash = strrchr(argv0, '/'); #ifdef GLOG_OS_WINDOWS - if (!slash) slash = strrchr(argv0, '\\'); + if (!slash) slash = strrchr(argv0, '\\'); #endif g_program_invocation_short_name = slash ? slash + 1 : argv0; @@ -377,7 +370,8 @@ void InitGoogleLoggingUtilities(const char* argv0) { void ShutdownGoogleLoggingUtilities() { CHECK(IsGoogleLoggingInitialized()) - << "You called ShutdownGoogleLogging() without calling InitGoogleLogging() first!"; + << "You called ShutdownGoogleLogging() without calling " + "InitGoogleLogging() first!"; g_program_invocation_short_name = nullptr; #ifdef HAVE_SYSLOG_H closelog(); @@ -390,13 +384,13 @@ void ShutdownGoogleLoggingUtilities() { // Make an implementation of stacktrace compiled. #ifdef STACKTRACE_H -# include STACKTRACE_H -# if 0 +# include STACKTRACE_H +# if 0 // For include scanners which can't handle macro expansions. -# include "stacktrace_libunwind-inl.h" -# include "stacktrace_x86-inl.h" -# include "stacktrace_x86_64-inl.h" -# include "stacktrace_powerpc-inl.h" -# include "stacktrace_generic-inl.h" -# endif +# include "stacktrace_generic-inl.h" +# include "stacktrace_libunwind-inl.h" +# include "stacktrace_powerpc-inl.h" +# include "stacktrace_x86-inl.h" +# include "stacktrace_x86_64-inl.h" +# endif #endif diff --git a/src/utilities.h b/src/utilities.h index 757790764..f19c63046 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -36,9 +36,9 @@ // printf macros for size_t, in the style of inttypes.h #ifdef _LP64 -#define __PRIS_PREFIX "z" +# define __PRIS_PREFIX "z" #else -#define __PRIS_PREFIX +# define __PRIS_PREFIX #endif // Use these macros after a % in a printf format string @@ -58,22 +58,22 @@ #include "glog/logging.h" #if defined(GLOG_OS_WINDOWS) -# include "port.h" +# include "port.h" #endif #include "config.h" #if defined(HAVE_UNISTD_H) -#include +# include #endif #if !defined(HAVE_SSIZE_T) -#if defined(GLOG_OS_WINDOWS) -#include +# if defined(GLOG_OS_WINDOWS) +# include using ssize_t = SSIZE_T; -#else +# else using ssize_t = std::ptrdiff_t; -#endif +# endif #endif // There are three different ways we can try to get the stack trace: @@ -99,45 +99,45 @@ using ssize_t = std::ptrdiff_t; // Some code may do that. #if defined(HAVE_LIBUNWIND) -# define STACKTRACE_H "stacktrace_libunwind-inl.h" +# define STACKTRACE_H "stacktrace_libunwind-inl.h" #elif defined(HAVE_UNWIND) -# define STACKTRACE_H "stacktrace_unwind-inl.h" +# define STACKTRACE_H "stacktrace_unwind-inl.h" #elif !defined(NO_FRAME_POINTER) -# if defined(__i386__) && __GNUC__ >= 2 -# define STACKTRACE_H "stacktrace_x86-inl.h" -# elif (defined(__ppc__) || defined(__PPC__)) && __GNUC__ >= 2 -# define STACKTRACE_H "stacktrace_powerpc-inl.h" -# elif defined(GLOG_OS_WINDOWS) -# define STACKTRACE_H "stacktrace_windows-inl.h" -# endif +# if defined(__i386__) && __GNUC__ >= 2 +# define STACKTRACE_H "stacktrace_x86-inl.h" +# elif (defined(__ppc__) || defined(__PPC__)) && __GNUC__ >= 2 +# define STACKTRACE_H "stacktrace_powerpc-inl.h" +# elif defined(GLOG_OS_WINDOWS) +# define STACKTRACE_H "stacktrace_windows-inl.h" +# endif #endif #if !defined(STACKTRACE_H) && defined(HAVE_EXECINFO_BACKTRACE) -# define STACKTRACE_H "stacktrace_generic-inl.h" +# define STACKTRACE_H "stacktrace_generic-inl.h" #endif #if defined(STACKTRACE_H) -# define HAVE_STACKTRACE +# define HAVE_STACKTRACE #endif #ifndef GLOG_NO_SYMBOLIZE_DETECTION -#ifndef HAVE_SYMBOLIZE +# ifndef HAVE_SYMBOLIZE // defined by gcc -#if defined(__ELF__) && defined(GLOG_OS_LINUX) -# define HAVE_SYMBOLIZE -#elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) +# if defined(__ELF__) && defined(GLOG_OS_LINUX) +# define HAVE_SYMBOLIZE +# elif defined(GLOG_OS_MACOSX) && defined(HAVE_DLADDR) // Use dladdr to symbolize. -# define HAVE_SYMBOLIZE -#elif defined(GLOG_OS_WINDOWS) +# define HAVE_SYMBOLIZE +# elif defined(GLOG_OS_WINDOWS) // Use DbgHelp to symbolize -# define HAVE_SYMBOLIZE -#endif -#endif // !defined(HAVE_SYMBOLIZE) -#endif // !defined(GLOG_NO_SYMBOLIZE_DETECTION) +# define HAVE_SYMBOLIZE +# endif +# endif // !defined(HAVE_SYMBOLIZE) +#endif // !defined(GLOG_NO_SYMBOLIZE_DETECTION) #ifndef ARRAYSIZE // There is a better way, but this is good enough for our purpose. -# define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) +# define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) #endif namespace google { @@ -145,21 +145,21 @@ namespace google { namespace glog_internal_namespace_ { #if defined(__has_attribute) -#if __has_attribute(noinline) -# define ATTRIBUTE_NOINLINE __attribute__ ((noinline)) -# define HAVE_ATTRIBUTE_NOINLINE -#endif +# if __has_attribute(noinline) +# define ATTRIBUTE_NOINLINE __attribute__((noinline)) +# define HAVE_ATTRIBUTE_NOINLINE +# endif #endif #if !defined(HAVE_ATTRIBUTE_NOINLINE) -#if defined(GLOG_OS_WINDOWS) -# define ATTRIBUTE_NOINLINE __declspec(noinline) -# define HAVE_ATTRIBUTE_NOINLINE -#endif +# if defined(GLOG_OS_WINDOWS) +# define ATTRIBUTE_NOINLINE __declspec(noinline) +# define HAVE_ATTRIBUTE_NOINLINE +# endif #endif #if !defined(HAVE_ATTRIBUTE_NOINLINE) -# define ATTRIBUTE_NOINLINE +# define ATTRIBUTE_NOINLINE #endif const char* ProgramInvocationShortName(); @@ -184,20 +184,20 @@ const char* const_basename(const char* filepath); // defined, we try the CPU specific logics (we only support x86 and // x86_64 for now) first, then use a naive implementation, which has a // race condition. -template +template inline T sync_val_compare_and_swap(T* ptr, T oldval, T newval) { #if defined(HAVE___SYNC_VAL_COMPARE_AND_SWAP) return __sync_val_compare_and_swap(ptr, oldval, newval); #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) T ret; __asm__ __volatile__("lock; cmpxchg %1, (%2);" - :"=a"(ret) - // GCC may produces %sil or %dil for - // constraint "r", but some of apple's gas - // doesn't know the 8 bit registers. - // We use "q" to avoid these registers. - :"q"(newval), "q"(ptr), "a"(oldval) - :"memory", "cc"); + : "=a"(ret) + // GCC may produces %sil or %dil for + // constraint "r", but some of apple's gas + // doesn't know the 8 bit registers. + // We use "q" to avoid these registers. + : "q"(newval), "q"(ptr), "a"(oldval) + : "memory", "cc"); return ret; #else T ret = *ptr; diff --git a/src/utilities_unittest.cc b/src/utilities_unittest.cc index 7ce930366..0ff9e332c 100644 --- a/src/utilities_unittest.cc +++ b/src/utilities_unittest.cc @@ -34,7 +34,7 @@ #include "googletest.h" #ifdef GLOG_USE_GFLAGS -#include +# include using namespace GFLAGS_NAMESPACE; #endif diff --git a/src/vlog_is_on.cc b/src/vlog_is_on.cc index d4272fe45..b514acf51 100644 --- a/src/vlog_is_on.cc +++ b/src/vlog_is_on.cc @@ -49,14 +49,17 @@ using std::string; -GLOG_DEFINE_int32(v, 0, "Show all VLOG(m) messages for m <= this." -" Overridable by --vmodule."); +GLOG_DEFINE_int32(v, 0, + "Show all VLOG(m) messages for m <= this." + " Overridable by --vmodule."); -GLOG_DEFINE_string(vmodule, "", "per-module verbose level." -" Argument is a comma-separated list of =." -" is a glob pattern, matched against the filename base" -" (that is, name ignoring .cc/.h./-inl.h)." -" overrides any value given by --v."); +GLOG_DEFINE_string( + vmodule, "", + "per-module verbose level." + " Argument is a comma-separated list of =." + " is a glob pattern, matched against the filename base" + " (that is, name ignoring .cc/.h./-inl.h)." + " overrides any value given by --v."); namespace google { @@ -75,18 +78,19 @@ GLOG_EXPORT bool SafeFNMatch_(const char* pattern, size_t patt_len, size_t p = 0; size_t s = 0; while (true) { - if (p == patt_len && s == str_len) return true; + if (p == patt_len && s == str_len) return true; if (p == patt_len) return false; - if (s == str_len) return p+1 == patt_len && pattern[p] == '*'; - if (pattern[p] == str[s] || pattern[p] == '?') { + if (s == str_len) return p + 1 == patt_len && pattern[p] == '*'; + if (pattern[p] == str[s] || pattern[p] == '?') { p += 1; s += 1; continue; } if (pattern[p] == '*') { - if (p+1 == patt_len) return true; + if (p + 1 == patt_len) return true; do { - if (SafeFNMatch_(pattern+(p+1), patt_len-(p+1), str+s, str_len-s)) { + if (SafeFNMatch_(pattern + (p + 1), patt_len - (p + 1), str + s, + str_len - s)) { return true; } s += 1; @@ -177,10 +181,9 @@ int SetVLOGLevel(const char* module_pattern, int log_level) { found = true; } info->vlog_level = log_level; - } else if (!found && - SafeFNMatch_(info->module_pattern.c_str(), - info->module_pattern.size(), - module_pattern, pattern_len)) { + } else if (!found && SafeFNMatch_(info->module_pattern.c_str(), + info->module_pattern.size(), + module_pattern, pattern_len)) { result = info->vlog_level; found = true; } @@ -216,8 +219,8 @@ int SetVLOGLevel(const char* module_pattern, int log_level) { // NOTE: Individual VLOG statements cache the integer log level pointers. // NOTE: This function must not allocate memory or require any locks. -bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, - const char* fname, int32 verbose_level) { +bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, const char* fname, + int32 verbose_level) { MutexLock l(&vmodule_lock); bool read_vmodule_flag = inited_vmodule; if (!read_vmodule_flag) { @@ -240,13 +243,13 @@ bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, } #endif - base = base ? (base+1) : fname; + base = base ? (base + 1) : fname; const char* base_end = strchr(base, '.'); size_t base_length = base_end ? static_cast(base_end - base) : strlen(base); // Trim out trailing "-inl" if any - if (base_length >= 4 && (memcmp(base+base_length-4, "-inl", 4) == 0)) { + if (base_length >= 4 && (memcmp(base + base_length - 4, "-inl", 4) == 0)) { base_length -= 4; } @@ -260,8 +263,8 @@ bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, if (SafeFNMatch_(info->module_pattern.c_str(), info->module_pattern.size(), base, base_length)) { site_flag_value = &info->vlog_level; - // value at info->vlog_level is now what controls - // the VLOG at the caller site forever + // value at info->vlog_level is now what controls + // the VLOG at the caller site forever break; } } diff --git a/src/windows/dirent.h b/src/windows/dirent.h index 097ad20a8..50033fbc8 100644 --- a/src/windows/dirent.h +++ b/src/windows/dirent.h @@ -11,11 +11,11 @@ /* Hide warnings about unreferenced local functions */ #if defined(__clang__) -# pragma clang diagnostic ignored "-Wunused-function" +# pragma clang diagnostic ignored "-Wunused-function" #elif defined(_MSC_VER) -# pragma warning(disable:4505) +# pragma warning(disable : 4505) #elif defined(__GNUC__) -# pragma GCC diagnostic ignored "-Wunused-function" +# pragma GCC diagnostic ignored "-Wunused-function" #endif /* @@ -23,8 +23,10 @@ * Windows Sockets 2.0. */ #ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN #endif +#include +#include #include #include @@ -33,8 +35,6 @@ #include #include #include -#include -#include /* Indicates that d_type field is available in dirent structure */ #define _DIRENT_HAVE_D_TYPE @@ -44,123 +44,123 @@ /* Entries missing from MSVC 6.0 */ #if !defined(FILE_ATTRIBUTE_DEVICE) -# define FILE_ATTRIBUTE_DEVICE 0x40 +# define FILE_ATTRIBUTE_DEVICE 0x40 #endif /* File type and permission flags for stat(), general mask */ #if !defined(S_IFMT) -# define S_IFMT _S_IFMT +# define S_IFMT _S_IFMT #endif /* Directory bit */ #if !defined(S_IFDIR) -# define S_IFDIR _S_IFDIR +# define S_IFDIR _S_IFDIR #endif /* Character device bit */ #if !defined(S_IFCHR) -# define S_IFCHR _S_IFCHR +# define S_IFCHR _S_IFCHR #endif /* Pipe bit */ #if !defined(S_IFFIFO) -# define S_IFFIFO _S_IFFIFO +# define S_IFFIFO _S_IFFIFO #endif /* Regular file bit */ #if !defined(S_IFREG) -# define S_IFREG _S_IFREG +# define S_IFREG _S_IFREG #endif /* Read permission */ #if !defined(S_IREAD) -# define S_IREAD _S_IREAD +# define S_IREAD _S_IREAD #endif /* Write permission */ #if !defined(S_IWRITE) -# define S_IWRITE _S_IWRITE +# define S_IWRITE _S_IWRITE #endif /* Execute permission */ #if !defined(S_IEXEC) -# define S_IEXEC _S_IEXEC +# define S_IEXEC _S_IEXEC #endif /* Pipe */ #if !defined(S_IFIFO) -# define S_IFIFO _S_IFIFO +# define S_IFIFO _S_IFIFO #endif /* Block device */ #if !defined(S_IFBLK) -# define S_IFBLK 0 +# define S_IFBLK 0 #endif /* Link */ #if !defined(S_IFLNK) -# define S_IFLNK 0 +# define S_IFLNK 0 #endif /* Socket */ #if !defined(S_IFSOCK) -# define S_IFSOCK 0 +# define S_IFSOCK 0 #endif /* Read user permission */ #if !defined(S_IRUSR) -# define S_IRUSR S_IREAD +# define S_IRUSR S_IREAD #endif /* Write user permission */ #if !defined(S_IWUSR) -# define S_IWUSR S_IWRITE +# define S_IWUSR S_IWRITE #endif /* Execute user permission */ #if !defined(S_IXUSR) -# define S_IXUSR 0 +# define S_IXUSR 0 #endif /* Read group permission */ #if !defined(S_IRGRP) -# define S_IRGRP 0 +# define S_IRGRP 0 #endif /* Write group permission */ #if !defined(S_IWGRP) -# define S_IWGRP 0 +# define S_IWGRP 0 #endif /* Execute group permission */ #if !defined(S_IXGRP) -# define S_IXGRP 0 +# define S_IXGRP 0 #endif /* Read others permission */ #if !defined(S_IROTH) -# define S_IROTH 0 +# define S_IROTH 0 #endif /* Write others permission */ #if !defined(S_IWOTH) -# define S_IWOTH 0 +# define S_IWOTH 0 #endif /* Execute others permission */ #if !defined(S_IXOTH) -# define S_IXOTH 0 +# define S_IXOTH 0 #endif /* Maximum length of file name */ #if !defined(PATH_MAX) -# define PATH_MAX MAX_PATH +# define PATH_MAX MAX_PATH #endif #if !defined(FILENAME_MAX) -# define FILENAME_MAX MAX_PATH +# define FILENAME_MAX MAX_PATH #endif #if !defined(NAME_MAX) -# define NAME_MAX FILENAME_MAX +# define NAME_MAX FILENAME_MAX #endif /* File type flags for d_type */ @@ -174,7 +174,7 @@ #define DT_LNK S_IFLNK /* Macros for converting between st_mode and d_type */ -#define IFTODT(mode) ((mode) & S_IFMT) +#define IFTODT(mode) ((mode)&S_IFMT) #define DTTOIF(type) (type) /* @@ -184,129 +184,126 @@ * on Windows. */ #if !defined(S_ISFIFO) -# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) +# define S_ISFIFO(mode) (((mode)&S_IFMT) == S_IFIFO) #endif #if !defined(S_ISDIR) -# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +# define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif #if !defined(S_ISREG) -# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) +# define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG) #endif #if !defined(S_ISLNK) -# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) +# define S_ISLNK(mode) (((mode)&S_IFMT) == S_IFLNK) #endif #if !defined(S_ISSOCK) -# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) +# define S_ISSOCK(mode) (((mode)&S_IFMT) == S_IFSOCK) #endif #if !defined(S_ISCHR) -# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) +# define S_ISCHR(mode) (((mode)&S_IFMT) == S_IFCHR) #endif #if !defined(S_ISBLK) -# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) +# define S_ISBLK(mode) (((mode)&S_IFMT) == S_IFBLK) #endif /* Return the exact length of the file name without zero terminator */ #define _D_EXACT_NAMLEN(p) ((p)->d_namlen) /* Return the maximum size of a file name */ -#define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1) - +#define _D_ALLOC_NAMLEN(p) ((PATH_MAX) + 1) #ifdef __cplusplus extern "C" { #endif - /* Wide-character version */ struct _wdirent { - /* Always zero */ - long d_ino; + /* Always zero */ + long d_ino; - /* File position within stream */ - long d_off; + /* File position within stream */ + long d_off; - /* Structure size */ - unsigned short d_reclen; + /* Structure size */ + unsigned short d_reclen; - /* Length of name without \0 */ - size_t d_namlen; + /* Length of name without \0 */ + size_t d_namlen; - /* File type */ - int d_type; + /* File type */ + int d_type; - /* File name */ - wchar_t d_name[PATH_MAX+1]; + /* File name */ + wchar_t d_name[PATH_MAX + 1]; }; struct _WDIR { - /* Current directory entry */ - _wdirent ent; + /* Current directory entry */ + _wdirent ent; - /* Private file data */ - WIN32_FIND_DATAW data; + /* Private file data */ + WIN32_FIND_DATAW data; - /* True if data is valid */ - int cached; + /* True if data is valid */ + int cached; - /* Win32 search handle */ - HANDLE handle; + /* Win32 search handle */ + HANDLE handle; - /* Initial directory name */ - wchar_t *patt; + /* Initial directory name */ + wchar_t *patt; }; /* Multi-byte character version */ struct dirent { - /* Always zero */ - long d_ino; + /* Always zero */ + long d_ino; - /* File position within stream */ - long d_off; + /* File position within stream */ + long d_off; - /* Structure size */ - unsigned short d_reclen; + /* Structure size */ + unsigned short d_reclen; - /* Length of name without \0 */ - size_t d_namlen; + /* Length of name without \0 */ + size_t d_namlen; - /* File type */ - int d_type; + /* File type */ + int d_type; - /* File name */ - char d_name[PATH_MAX+1]; + /* File name */ + char d_name[PATH_MAX + 1]; }; struct DIR { - struct dirent ent; - struct _WDIR *wdirp; + struct dirent ent; + struct _WDIR *wdirp; }; /* Dirent functions */ -static DIR *opendir (const char *dirname); -static _WDIR *_wopendir (const wchar_t *dirname); +static DIR *opendir(const char *dirname); +static _WDIR *_wopendir(const wchar_t *dirname); -static struct dirent *readdir (DIR *dirp); -static struct _wdirent *_wreaddir (_WDIR *dirp); +static struct dirent *readdir(DIR *dirp); +static struct _wdirent *_wreaddir(_WDIR *dirp); -static int readdir_r( - DIR *dirp, struct dirent *entry, struct dirent **result); -static int _wreaddir_r( - _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result); +static int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result); +static int _wreaddir_r(_WDIR *dirp, struct _wdirent *entry, + struct _wdirent **result); -static int closedir (DIR *dirp); -static int _wclosedir (_WDIR *dirp); +static int closedir(DIR *dirp); +static int _wclosedir(_WDIR *dirp); -static void rewinddir (DIR* dirp); -static void _wrewinddir (_WDIR* dirp); +static void rewinddir(DIR *dirp); +static void _wrewinddir(_WDIR *dirp); -static int scandir (const char *dirname, struct dirent ***namelist, - int (*filter)(const struct dirent*), - int (*compare)(const struct dirent**, const struct dirent**)); +static int scandir(const char *dirname, struct dirent ***namelist, + int (*filter)(const struct dirent *), + int (*compare)(const struct dirent **, + const struct dirent **)); -static int alphasort (const struct dirent **a, const struct dirent **b); - -static int versionsort (const struct dirent **a, const struct dirent **b); +static int alphasort(const struct dirent **a, const struct dirent **b); +static int versionsort(const struct dirent **a, const struct dirent **b); /* For compatibility with Symbian */ #define wdirent _wdirent @@ -316,126 +313,115 @@ static int versionsort (const struct dirent **a, const struct dirent **b); #define wclosedir _wclosedir #define wrewinddir _wrewinddir - /* Internal utility functions */ -static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp); -static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp); +static WIN32_FIND_DATAW *dirent_first(_WDIR *dirp); +static WIN32_FIND_DATAW *dirent_next(_WDIR *dirp); -static int dirent_mbstowcs_s( - size_t *pReturnValue, - wchar_t *wcstr, - size_t sizeInWords, - const char *mbstr, - size_t count); +static int dirent_mbstowcs_s(size_t *pReturnValue, wchar_t *wcstr, + size_t sizeInWords, const char *mbstr, + size_t count); -static int dirent_wcstombs_s( - size_t *pReturnValue, - char *mbstr, - size_t sizeInBytes, - const wchar_t *wcstr, - size_t count); - -static void dirent_set_errno (int error); +static int dirent_wcstombs_s(size_t *pReturnValue, char *mbstr, + size_t sizeInBytes, const wchar_t *wcstr, + size_t count); +static void dirent_set_errno(int error); /* * Open directory stream DIRNAME for read and return a pointer to the * internal working area that is used to retrieve individual directory * entries. */ -static _WDIR* -_wopendir( - const wchar_t *dirname) -{ - _WDIR *dirp; - DWORD n; - wchar_t *p; - - /* Must have directory name */ - if (dirname == nullptr || dirname[0] == '\0') { - dirent_set_errno(ENOENT); - return nullptr; - } - - /* Allocate new _WDIR structure */ - dirp = (_WDIR*) malloc (sizeof (struct _WDIR)); - if (!dirp) { - return nullptr; - } - - /* Reset _WDIR structure */ - dirp->handle = INVALID_HANDLE_VALUE; - dirp->patt = nullptr; - dirp->cached = 0; +static _WDIR *_wopendir(const wchar_t *dirname) { + _WDIR *dirp; + DWORD n; + wchar_t *p; + + /* Must have directory name */ + if (dirname == nullptr || dirname[0] == '\0') { + dirent_set_errno(ENOENT); + return nullptr; + } - /* - * Compute the length of full path plus zero terminator - * - * Note that on WinRT there's no way to convert relative paths - * into absolute paths, so just assume it is an absolute path. - */ + /* Allocate new _WDIR structure */ + dirp = (_WDIR *)malloc(sizeof(struct _WDIR)); + if (!dirp) { + return nullptr; + } + + /* Reset _WDIR structure */ + dirp->handle = INVALID_HANDLE_VALUE; + dirp->patt = nullptr; + dirp->cached = 0; + + /* + * Compute the length of full path plus zero terminator + * + * Note that on WinRT there's no way to convert relative paths + * into absolute paths, so just assume it is an absolute path. + */ #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - /* Desktop */ - n = GetFullPathNameW(dirname, 0, nullptr, nullptr); + /* Desktop */ + n = GetFullPathNameW(dirname, 0, nullptr, nullptr); #else - /* WinRT */ - n = wcslen (dirname); + /* WinRT */ + n = wcslen(dirname); #endif - /* Allocate room for absolute directory name and search pattern */ - dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16); - if (dirp->patt == nullptr) { - goto exit_closedir; - } - - /* - * Convert relative directory name to an absolute one. This - * allows rewinddir() to function correctly even when current - * working directory is changed between opendir() and rewinddir(). - * - * Note that on WinRT there's no way to convert relative paths - * into absolute paths, so just assume it is an absolute path. - */ + /* Allocate room for absolute directory name and search pattern */ + dirp->patt = (wchar_t *)malloc(sizeof(wchar_t) * n + 16); + if (dirp->patt == nullptr) { + goto exit_closedir; + } + + /* + * Convert relative directory name to an absolute one. This + * allows rewinddir() to function correctly even when current + * working directory is changed between opendir() and rewinddir(). + * + * Note that on WinRT there's no way to convert relative paths + * into absolute paths, so just assume it is an absolute path. + */ #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - /* Desktop */ - n = GetFullPathNameW(dirname, n, dirp->patt, nullptr); - if (n <= 0) { - goto exit_closedir; - } + /* Desktop */ + n = GetFullPathNameW(dirname, n, dirp->patt, nullptr); + if (n <= 0) { + goto exit_closedir; + } #else - /* WinRT */ - wcsncpy_s (dirp->patt, n+1, dirname, n); + /* WinRT */ + wcsncpy_s(dirp->patt, n + 1, dirname, n); #endif - /* Append search pattern \* to the directory name */ - p = dirp->patt + n; - switch (p[-1]) { + /* Append search pattern \* to the directory name */ + p = dirp->patt + n; + switch (p[-1]) { case '\\': case '/': case ':': /* Directory ends in path separator, e.g. c:\temp\ */ /*NOP*/; - break; + break; default: - /* Directory name doesn't end in path separator */ - *p++ = '\\'; - } - *p++ = '*'; - *p = '\0'; + /* Directory name doesn't end in path separator */ + *p++ = '\\'; + } + *p++ = '*'; + *p = '\0'; - /* Open directory stream and retrieve the first entry */ - if (!dirent_first (dirp)) { - goto exit_closedir; - } + /* Open directory stream and retrieve the first entry */ + if (!dirent_first(dirp)) { + goto exit_closedir; + } - /* Success */ - return dirp; + /* Success */ + return dirp; - /* Failure */ + /* Failure */ exit_closedir: - _wclosedir (dirp); - return nullptr; + _wclosedir(dirp); + return nullptr; } /* @@ -444,20 +430,17 @@ _wopendir( * Returns pointer to static directory entry which may be overwritten by * subsequent calls to _wreaddir(). */ -static struct _wdirent* -_wreaddir( - _WDIR *dirp) -{ - struct _wdirent *entry; +static struct _wdirent *_wreaddir(_WDIR *dirp) { + struct _wdirent *entry; - /* - * Read directory entry to buffer. We can safely ignore the return value - * as entry will be set to nullptr in case of error. - */ - (void) _wreaddir_r (dirp, &dirp->ent, &entry); + /* + * Read directory entry to buffer. We can safely ignore the return value + * as entry will be set to nullptr in case of error. + */ + (void)_wreaddir_r(dirp, &dirp->ent, &entry); - /* Return pointer to statically allocated directory entry */ - return entry; + /* Return pointer to statically allocated directory entry */ + return entry; } /* @@ -466,59 +449,55 @@ _wreaddir( * Returns zero on success. If end of directory stream is reached, then sets * result to nullptr and returns zero. */ -static int -_wreaddir_r( - _WDIR *dirp, - struct _wdirent *entry, - struct _wdirent **result) -{ - WIN32_FIND_DATAW *datap; - - /* Read next directory entry */ - datap = dirent_next (dirp); - if (datap) { - size_t n; - DWORD attr; - - /* - * Copy file name as wide-character string. If the file name is too - * long to fit in to the destination buffer, then truncate file name - * to PATH_MAX characters and zero-terminate the buffer. - */ - n = 0; - while (n < PATH_MAX && datap->cFileName[n] != 0) { - entry->d_name[n] = datap->cFileName[n]; - n++; - } - entry->d_name[n] = 0; +static int _wreaddir_r(_WDIR *dirp, struct _wdirent *entry, + struct _wdirent **result) { + WIN32_FIND_DATAW *datap; - /* Length of file name excluding zero terminator */ - entry->d_namlen = n; - - /* File type */ - attr = datap->dwFileAttributes; - if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { - entry->d_type = DT_CHR; - } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { - entry->d_type = DT_DIR; - } else { - entry->d_type = DT_REG; - } + /* Read next directory entry */ + datap = dirent_next(dirp); + if (datap) { + size_t n; + DWORD attr; - /* Reset dummy fields */ - entry->d_ino = 0; - entry->d_off = 0; - entry->d_reclen = sizeof (struct _wdirent); + /* + * Copy file name as wide-character string. If the file name is too + * long to fit in to the destination buffer, then truncate file name + * to PATH_MAX characters and zero-terminate the buffer. + */ + n = 0; + while (n < PATH_MAX && datap->cFileName[n] != 0) { + entry->d_name[n] = datap->cFileName[n]; + n++; + } + entry->d_name[n] = 0; - /* Set result address */ - *result = entry; + /* Length of file name excluding zero terminator */ + entry->d_namlen = n; + /* File type */ + attr = datap->dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + entry->d_type = DT_CHR; + } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + entry->d_type = DT_DIR; } else { - /* Return nullptr to indicate end of directory */ - *result = nullptr; + entry->d_type = DT_REG; } - return /*OK*/0; + /* Reset dummy fields */ + entry->d_ino = 0; + entry->d_off = 0; + entry->d_reclen = sizeof(struct _wdirent); + + /* Set result address */ + *result = entry; + + } else { + /* Return nullptr to indicate end of directory */ + *result = nullptr; + } + + return /*OK*/ 0; } /* @@ -526,98 +505,83 @@ _wreaddir_r( * DIR structure as well as any directory entry read previously by * _wreaddir(). */ -static int -_wclosedir( - _WDIR *dirp) -{ - int ok; - if (dirp) { - - /* Release search handle */ - if (dirp->handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->handle); - } - - /* Release search pattern */ - free (dirp->patt); +static int _wclosedir(_WDIR *dirp) { + int ok; + if (dirp) { + /* Release search handle */ + if (dirp->handle != INVALID_HANDLE_VALUE) { + FindClose(dirp->handle); + } - /* Release directory structure */ - free (dirp); - ok = /*success*/0; + /* Release search pattern */ + free(dirp->patt); - } else { + /* Release directory structure */ + free(dirp); + ok = /*success*/ 0; - /* Invalid directory stream */ - dirent_set_errno (EBADF); - ok = /*failure*/-1; - - } - return ok; + } else { + /* Invalid directory stream */ + dirent_set_errno(EBADF); + ok = /*failure*/ -1; + } + return ok; } /* * Rewind directory stream such that _wreaddir() returns the very first * file name again. */ -static void -_wrewinddir( - _WDIR* dirp) -{ - if (dirp) { - /* Release existing search handle */ - if (dirp->handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->handle); - } - - /* Open new search handle */ - dirent_first (dirp); +static void _wrewinddir(_WDIR *dirp) { + if (dirp) { + /* Release existing search handle */ + if (dirp->handle != INVALID_HANDLE_VALUE) { + FindClose(dirp->handle); } + + /* Open new search handle */ + dirent_first(dirp); + } } /* Get first directory entry (internal) */ -static WIN32_FIND_DATAW* -dirent_first( - _WDIR *dirp) -{ - WIN32_FIND_DATAW *datap; - DWORD error; - - /* Open directory and retrieve the first entry */ - dirp->handle = FindFirstFileExW(dirp->patt, FindExInfoStandard, &dirp->data, - FindExSearchNameMatch, nullptr, 0); - if (dirp->handle != INVALID_HANDLE_VALUE) { - - /* a directory entry is now waiting in memory */ - datap = &dirp->data; - dirp->cached = 1; - - } else { +static WIN32_FIND_DATAW *dirent_first(_WDIR *dirp) { + WIN32_FIND_DATAW *datap; + DWORD error; + + /* Open directory and retrieve the first entry */ + dirp->handle = FindFirstFileExW(dirp->patt, FindExInfoStandard, &dirp->data, + FindExSearchNameMatch, nullptr, 0); + if (dirp->handle != INVALID_HANDLE_VALUE) { + /* a directory entry is now waiting in memory */ + datap = &dirp->data; + dirp->cached = 1; + + } else { + /* Failed to open directory: no directory entry in memory */ + dirp->cached = 0; + datap = nullptr; + + /* Set error code */ + error = GetLastError(); + switch (error) { + case ERROR_ACCESS_DENIED: + /* No read access to directory */ + dirent_set_errno(EACCES); + break; - /* Failed to open directory: no directory entry in memory */ - dirp->cached = 0; - datap = nullptr; - - /* Set error code */ - error = GetLastError (); - switch (error) { - case ERROR_ACCESS_DENIED: - /* No read access to directory */ - dirent_set_errno (EACCES); - break; - - case ERROR_DIRECTORY: - /* Directory name is invalid */ - dirent_set_errno (ENOTDIR); - break; - - case ERROR_PATH_NOT_FOUND: - default: - /* Cannot find the file */ - dirent_set_errno (ENOENT); - } + case ERROR_DIRECTORY: + /* Directory name is invalid */ + dirent_set_errno(ENOTDIR); + break; + case ERROR_PATH_NOT_FOUND: + default: + /* Cannot find the file */ + dirent_set_errno(ENOENT); } - return datap; + } + return datap; } /* @@ -625,114 +589,99 @@ dirent_first( * * Returns */ -static WIN32_FIND_DATAW* -dirent_next( - _WDIR *dirp) -{ - WIN32_FIND_DATAW *p; - - /* Get next directory entry */ - if (dirp->cached != 0) { - - /* A valid directory entry already in memory */ - p = &dirp->data; - dirp->cached = 0; +static WIN32_FIND_DATAW *dirent_next(_WDIR *dirp) { + WIN32_FIND_DATAW *p; - } else if (dirp->handle != INVALID_HANDLE_VALUE) { - - /* Get the next directory entry from stream */ - if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) { - /* Got a file */ - p = &dirp->data; - } else { - /* The very last entry has been processed or an error occurred */ - FindClose (dirp->handle); - dirp->handle = INVALID_HANDLE_VALUE; - p = nullptr; - } + /* Get next directory entry */ + if (dirp->cached != 0) { + /* A valid directory entry already in memory */ + p = &dirp->data; + dirp->cached = 0; + } else if (dirp->handle != INVALID_HANDLE_VALUE) { + /* Get the next directory entry from stream */ + if (FindNextFileW(dirp->handle, &dirp->data) != FALSE) { + /* Got a file */ + p = &dirp->data; } else { - - /* End of directory stream reached */ - p = nullptr; + /* The very last entry has been processed or an error occurred */ + FindClose(dirp->handle); + dirp->handle = INVALID_HANDLE_VALUE; + p = nullptr; } - return p; + } else { + /* End of directory stream reached */ + p = nullptr; + } + + return p; } /* * Open directory stream using plain old C-string. */ -static DIR* -opendir( - const char *dirname) -{ - struct DIR *dirp; - - /* Must have directory name */ - if (dirname == nullptr || dirname[0] == '\0') { - dirent_set_errno (ENOENT); - return nullptr; - } +static DIR *opendir(const char *dirname) { + struct DIR *dirp; - /* Allocate memory for DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (!dirp) { - return nullptr; - } - { - int error; - wchar_t wname[PATH_MAX + 1]; - size_t n; - - /* Convert directory name to wide-character string */ - error = dirent_mbstowcs_s( - &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1); - if (error) { - /* - * Cannot convert file name to wide-character string. This - * occurs if the string contains invalid multi-byte sequences or - * the output buffer is too small to contain the resulting - * string. - */ - goto exit_free; - } + /* Must have directory name */ + if (dirname == nullptr || dirname[0] == '\0') { + dirent_set_errno(ENOENT); + return nullptr; + } + /* Allocate memory for DIR structure */ + dirp = (DIR *)malloc(sizeof(struct DIR)); + if (!dirp) { + return nullptr; + } + { + int error; + wchar_t wname[PATH_MAX + 1]; + size_t n; - /* Open directory stream using wide-character name */ - dirp->wdirp = _wopendir (wname); - if (!dirp->wdirp) { - goto exit_free; - } + /* Convert directory name to wide-character string */ + error = dirent_mbstowcs_s(&n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1); + if (error) { + /* + * Cannot convert file name to wide-character string. This + * occurs if the string contains invalid multi-byte sequences or + * the output buffer is too small to contain the resulting + * string. + */ + goto exit_free; + } + /* Open directory stream using wide-character name */ + dirp->wdirp = _wopendir(wname); + if (!dirp->wdirp) { + goto exit_free; } + } - /* Success */ - return dirp; + /* Success */ + return dirp; - /* Failure */ + /* Failure */ exit_free: - free (dirp); - return nullptr; + free(dirp); + return nullptr; } /* * Read next directory entry. */ -static struct dirent* -readdir( - DIR *dirp) -{ - struct dirent *entry; +static struct dirent *readdir(DIR *dirp) { + struct dirent *entry; - /* - * Read directory entry to buffer. We can safely ignore the return value - * as entry will be set to nullptr in case of error. - */ - (void) readdir_r (dirp, &dirp->ent, &entry); + /* + * Read directory entry to buffer. We can safely ignore the return value + * as entry will be set to nullptr in case of error. + */ + (void)readdir_r(dirp, &dirp->ent, &entry); - /* Return pointer to statically allocated directory entry */ - return entry; + /* Return pointer to statically allocated directory entry */ + return entry; } /* @@ -741,404 +690,354 @@ readdir( * Returns zero on success. If the end of directory stream is reached, then * sets result to nullptr and returns zero. */ -static int -readdir_r( - DIR *dirp, - struct dirent *entry, - struct dirent **result) -{ - WIN32_FIND_DATAW *datap; - - /* Read next directory entry */ - datap = dirent_next (dirp->wdirp); - if (datap) { - size_t n; - int error; - - /* Attempt to convert file name to multi-byte string */ - error = dirent_wcstombs_s( - &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1); - - /* - * If the file name cannot be represented by a multi-byte string, - * then attempt to use old 8+3 file name. This allows traditional - * Unix-code to access some file names despite of unicode - * characters, although file names may seem unfamiliar to the user. - * - * Be ware that the code below cannot come up with a short file - * name unless the file system provides one. At least - * VirtualBox shared folders fail to do this. - */ - if (error && datap->cAlternateFileName[0] != '\0') { - error = dirent_wcstombs_s( - &n, entry->d_name, PATH_MAX + 1, - datap->cAlternateFileName, PATH_MAX + 1); - } +static int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) { + WIN32_FIND_DATAW *datap; - if (!error) { - DWORD attr; + /* Read next directory entry */ + datap = dirent_next(dirp->wdirp); + if (datap) { + size_t n; + int error; - /* Length of file name excluding zero terminator */ - entry->d_namlen = n - 1; + /* Attempt to convert file name to multi-byte string */ + error = dirent_wcstombs_s(&n, entry->d_name, PATH_MAX + 1, datap->cFileName, + PATH_MAX + 1); - /* File attributes */ - attr = datap->dwFileAttributes; - if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { - entry->d_type = DT_CHR; - } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { - entry->d_type = DT_DIR; - } else { - entry->d_type = DT_REG; - } + /* + * If the file name cannot be represented by a multi-byte string, + * then attempt to use old 8+3 file name. This allows traditional + * Unix-code to access some file names despite of unicode + * characters, although file names may seem unfamiliar to the user. + * + * Be ware that the code below cannot come up with a short file + * name unless the file system provides one. At least + * VirtualBox shared folders fail to do this. + */ + if (error && datap->cAlternateFileName[0] != '\0') { + error = dirent_wcstombs_s(&n, entry->d_name, PATH_MAX + 1, + datap->cAlternateFileName, PATH_MAX + 1); + } - /* Reset dummy fields */ - entry->d_ino = 0; - entry->d_off = 0; - entry->d_reclen = sizeof (struct dirent); + if (!error) { + DWORD attr; - } else { - /* - * Cannot convert file name to multi-byte string so construct - * an erroneous directory entry and return that. Note that - * we cannot return nullptr as that would stop the processing - * of directory entries completely. - */ - entry->d_name[0] = '?'; - entry->d_name[1] = '\0'; - entry->d_namlen = 1; - entry->d_type = DT_UNKNOWN; - entry->d_ino = 0; - entry->d_off = -1; - entry->d_reclen = 0; + /* Length of file name excluding zero terminator */ + entry->d_namlen = n - 1; - } + /* File attributes */ + attr = datap->dwFileAttributes; + if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { + entry->d_type = DT_CHR; + } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { + entry->d_type = DT_DIR; + } else { + entry->d_type = DT_REG; + } - /* Return pointer to directory entry */ - *result = entry; + /* Reset dummy fields */ + entry->d_ino = 0; + entry->d_off = 0; + entry->d_reclen = sizeof(struct dirent); } else { - - /* No more directory entries */ - *result = nullptr; + /* + * Cannot convert file name to multi-byte string so construct + * an erroneous directory entry and return that. Note that + * we cannot return nullptr as that would stop the processing + * of directory entries completely. + */ + entry->d_name[0] = '?'; + entry->d_name[1] = '\0'; + entry->d_namlen = 1; + entry->d_type = DT_UNKNOWN; + entry->d_ino = 0; + entry->d_off = -1; + entry->d_reclen = 0; } - return /*OK*/0; + /* Return pointer to directory entry */ + *result = entry; + + } else { + /* No more directory entries */ + *result = nullptr; + } + + return /*OK*/ 0; } /* * Close directory stream. */ -static int -closedir( - DIR *dirp) -{ - int ok; - if (dirp) { - - /* Close wide-character directory stream */ - ok = _wclosedir (dirp->wdirp); - dirp->wdirp = nullptr; - - /* Release multi-byte character version */ - free (dirp); - - } else { - - /* Invalid directory stream */ - dirent_set_errno (EBADF); - ok = /*failure*/-1; - - } - return ok; +static int closedir(DIR *dirp) { + int ok; + if (dirp) { + /* Close wide-character directory stream */ + ok = _wclosedir(dirp->wdirp); + dirp->wdirp = nullptr; + + /* Release multi-byte character version */ + free(dirp); + + } else { + /* Invalid directory stream */ + dirent_set_errno(EBADF); + ok = /*failure*/ -1; + } + return ok; } /* * Rewind directory stream to beginning. */ -static void -rewinddir( - DIR* dirp) -{ - /* Rewind wide-character string directory stream */ - _wrewinddir (dirp->wdirp); +static void rewinddir(DIR *dirp) { + /* Rewind wide-character string directory stream */ + _wrewinddir(dirp->wdirp); } /* * Scan directory for entries. */ -static int -scandir( - const char *dirname, - struct dirent ***namelist, - int (*filter)(const struct dirent*), - int (*compare)(const struct dirent**, const struct dirent**)) -{ - struct dirent **files = nullptr; - size_t size = 0; - size_t allocated = 0; - const size_t init_size = 1; - DIR *dir = nullptr; - struct dirent *entry; - struct dirent *tmp = nullptr; - size_t i; - int result = 0; - - /* Open directory stream */ - dir = opendir (dirname); - if (dir) { - - /* Read directory entries to memory */ - while (1) { - - /* Enlarge pointer table to make room for another pointer */ - if (size >= allocated) { - void *p; - size_t num_entries; - - /* Compute number of entries in the enlarged pointer table */ - if (size < init_size) { - /* Allocate initial pointer table */ - num_entries = init_size; - } else { - /* Double the size */ - num_entries = size * 2; - } - - /* Allocate first pointer table or enlarge existing table */ - p = realloc (files, sizeof (void*) * num_entries); - if (p != nullptr) { - /* Got the memory */ - files = (dirent**) p; - allocated = num_entries; - } else { - /* Out of memory */ - result = -1; - break; - } - } - - /* Allocate room for temporary directory entry */ - if (tmp == nullptr) { - tmp = (struct dirent*) malloc (sizeof (struct dirent)); - if (tmp == nullptr) { - /* Cannot allocate temporary directory entry */ - result = -1; - break; - } - } - - /* Read directory entry to temporary area */ - if (readdir_r (dir, tmp, &entry) == /*OK*/0) { - - /* Did we get an entry? */ - if (entry != nullptr) { - int pass; - - /* Determine whether to include the entry in result */ - if (filter) { - /* Let the filter function decide */ - pass = filter (tmp); - } else { - /* No filter function, include everything */ - pass = 1; - } - - if (pass) { - /* Store the temporary entry to pointer table */ - files[size++] = tmp; - tmp = nullptr; - - /* Keep up with the number of files */ - result++; - } - - } else { - /* - * End of directory stream reached => sort entries and - * exit. - */ - qsort (files, size, sizeof (void*), - (int (*) (const void*, const void*)) compare); - break; - } - - } else { - /* Error reading directory entry */ - result = /*Error*/ -1; - break; - } +static int scandir(const char *dirname, struct dirent ***namelist, + int (*filter)(const struct dirent *), + int (*compare)(const struct dirent **, + const struct dirent **)) { + struct dirent **files = nullptr; + size_t size = 0; + size_t allocated = 0; + const size_t init_size = 1; + DIR *dir = nullptr; + struct dirent *entry; + struct dirent *tmp = nullptr; + size_t i; + int result = 0; + + /* Open directory stream */ + dir = opendir(dirname); + if (dir) { + /* Read directory entries to memory */ + while (1) { + /* Enlarge pointer table to make room for another pointer */ + if (size >= allocated) { + void *p; + size_t num_entries; + + /* Compute number of entries in the enlarged pointer table */ + if (size < init_size) { + /* Allocate initial pointer table */ + num_entries = init_size; + } else { + /* Double the size */ + num_entries = size * 2; + } + + /* Allocate first pointer table or enlarge existing table */ + p = realloc(files, sizeof(void *) * num_entries); + if (p != nullptr) { + /* Got the memory */ + files = (dirent **)p; + allocated = num_entries; + } else { + /* Out of memory */ + result = -1; + break; + } + } + + /* Allocate room for temporary directory entry */ + if (tmp == nullptr) { + tmp = (struct dirent *)malloc(sizeof(struct dirent)); + if (tmp == nullptr) { + /* Cannot allocate temporary directory entry */ + result = -1; + break; + } + } + + /* Read directory entry to temporary area */ + if (readdir_r(dir, tmp, &entry) == /*OK*/ 0) { + /* Did we get an entry? */ + if (entry != nullptr) { + int pass; + + /* Determine whether to include the entry in result */ + if (filter) { + /* Let the filter function decide */ + pass = filter(tmp); + } else { + /* No filter function, include everything */ + pass = 1; + } + + if (pass) { + /* Store the temporary entry to pointer table */ + files[size++] = tmp; + tmp = nullptr; + + /* Keep up with the number of files */ + result++; + } + } else { + /* + * End of directory stream reached => sort entries and + * exit. + */ + qsort(files, size, sizeof(void *), + (int (*)(const void *, const void *))compare); + break; } - } else { - /* Cannot open directory */ + } else { + /* Error reading directory entry */ result = /*Error*/ -1; + break; + } } - /* Release temporary directory entry */ - free (tmp); + } else { + /* Cannot open directory */ + result = /*Error*/ -1; + } - /* Release allocated memory on error */ - if (result < 0) { - for (i = 0; i < size; i++) { - free (files[i]); - } - free (files); - files = nullptr; - } - - /* Close directory stream */ - if (dir) { - closedir (dir); - } + /* Release temporary directory entry */ + free(tmp); - /* Pass pointer table to caller */ - if (namelist) { - *namelist = files; + /* Release allocated memory on error */ + if (result < 0) { + for (i = 0; i < size; i++) { + free(files[i]); } - return result; + free(files); + files = nullptr; + } + + /* Close directory stream */ + if (dir) { + closedir(dir); + } + + /* Pass pointer table to caller */ + if (namelist) { + *namelist = files; + } + return result; } /* Alphabetical sorting */ -static int -alphasort( - const struct dirent **a, const struct dirent **b) -{ - return strcoll ((*a)->d_name, (*b)->d_name); +static int alphasort(const struct dirent **a, const struct dirent **b) { + return strcoll((*a)->d_name, (*b)->d_name); } /* Sort versions */ -static int -versionsort( - const struct dirent **a, const struct dirent **b) -{ - /* FIXME: implement strverscmp and use that */ - return alphasort (a, b); +static int versionsort(const struct dirent **a, const struct dirent **b) { + /* FIXME: implement strverscmp and use that */ + return alphasort(a, b); } /* Convert multi-byte string to wide character string */ -static int -dirent_mbstowcs_s( - size_t *pReturnValue, - wchar_t *wcstr, - size_t sizeInWords, - const char *mbstr, - size_t count) -{ - int error; +static int dirent_mbstowcs_s(size_t *pReturnValue, wchar_t *wcstr, + size_t sizeInWords, const char *mbstr, + size_t count) { + int error; -#if defined(_MSC_VER) && _MSC_VER >= 1400 +#if defined(_MSC_VER) && _MSC_VER >= 1400 - /* Microsoft Visual Studio 2005 or later */ - error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count); + /* Microsoft Visual Studio 2005 or later */ + error = mbstowcs_s(pReturnValue, wcstr, sizeInWords, mbstr, count); #else - /* Older Visual Studio or non-Microsoft compiler */ - size_t n; - - /* Convert to wide-character string (or count characters) */ - n = mbstowcs (wcstr, mbstr, sizeInWords); - if (!wcstr || n < count) { - - /* Zero-terminate output buffer */ - if (wcstr && sizeInWords) { - if (n >= sizeInWords) { - n = sizeInWords - 1; - } - wcstr[n] = 0; - } - - /* Length of resulting multi-byte string WITH zero terminator */ - if (pReturnValue) { - *pReturnValue = n + 1; - } - - /* Success */ - error = 0; + /* Older Visual Studio or non-Microsoft compiler */ + size_t n; + + /* Convert to wide-character string (or count characters) */ + n = mbstowcs(wcstr, mbstr, sizeInWords); + if (!wcstr || n < count) { + /* Zero-terminate output buffer */ + if (wcstr && sizeInWords) { + if (n >= sizeInWords) { + n = sizeInWords - 1; + } + wcstr[n] = 0; + } - } else { + /* Length of resulting multi-byte string WITH zero terminator */ + if (pReturnValue) { + *pReturnValue = n + 1; + } - /* Could not convert string */ - error = 1; + /* Success */ + error = 0; - } + } else { + /* Could not convert string */ + error = 1; + } #endif - return error; + return error; } /* Convert wide-character string to multi-byte string */ -static int -dirent_wcstombs_s( - size_t *pReturnValue, - char *mbstr, - size_t sizeInBytes, /* max size of mbstr */ - const wchar_t *wcstr, - size_t count) -{ - int error; +static int dirent_wcstombs_s(size_t *pReturnValue, char *mbstr, + size_t sizeInBytes, /* max size of mbstr */ + const wchar_t *wcstr, size_t count) { + int error; -#if defined(_MSC_VER) && _MSC_VER >= 1400 +#if defined(_MSC_VER) && _MSC_VER >= 1400 - /* Microsoft Visual Studio 2005 or later */ - error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count); + /* Microsoft Visual Studio 2005 or later */ + error = wcstombs_s(pReturnValue, mbstr, sizeInBytes, wcstr, count); #else - /* Older Visual Studio or non-Microsoft compiler */ - size_t n; - - /* Convert to multi-byte string (or count the number of bytes needed) */ - n = wcstombs (mbstr, wcstr, sizeInBytes); - if (!mbstr || n < count) { - - /* Zero-terminate output buffer */ - if (mbstr && sizeInBytes) { - if (n >= sizeInBytes) { - n = sizeInBytes - 1; - } - mbstr[n] = '\0'; - } - - /* Length of resulting multi-bytes string WITH zero-terminator */ - if (pReturnValue) { - *pReturnValue = n + 1; - } - - /* Success */ - error = 0; + /* Older Visual Studio or non-Microsoft compiler */ + size_t n; + + /* Convert to multi-byte string (or count the number of bytes needed) */ + n = wcstombs(mbstr, wcstr, sizeInBytes); + if (!mbstr || n < count) { + /* Zero-terminate output buffer */ + if (mbstr && sizeInBytes) { + if (n >= sizeInBytes) { + n = sizeInBytes - 1; + } + mbstr[n] = '\0'; + } - } else { + /* Length of resulting multi-bytes string WITH zero-terminator */ + if (pReturnValue) { + *pReturnValue = n + 1; + } - /* Cannot convert string */ - error = 1; + /* Success */ + error = 0; - } + } else { + /* Cannot convert string */ + error = 1; + } #endif - return error; + return error; } /* Set errno variable */ -static void -dirent_set_errno( - int error) -{ -#if defined(_MSC_VER) && _MSC_VER >= 1400 +static void dirent_set_errno(int error) { +#if defined(_MSC_VER) && _MSC_VER >= 1400 - /* Microsoft Visual Studio 2005 and later */ - _set_errno (error); + /* Microsoft Visual Studio 2005 and later */ + _set_errno(error); #else - /* Non-Microsoft compiler or older Microsoft compiler */ - errno = error; + /* Non-Microsoft compiler or older Microsoft compiler */ + errno = error; #endif } - #ifdef __cplusplus } #endif diff --git a/src/windows/port.cc b/src/windows/port.cc index 9631bed44..6bc473052 100644 --- a/src/windows/port.cc +++ b/src/windows/port.cc @@ -33,7 +33,7 @@ */ #ifndef _WIN32 -# error You should only be including windows/port.cc in a windows environment! +# error You should only be including windows/port.cc in a windows environment! #endif #include "port.h" @@ -47,7 +47,7 @@ struct tm* localtime_r(const std::time_t* timep, std::tm* result) { localtime_s(result, timep); return result; } -#endif // not HAVE_LOCALTIME_R +#endif // not HAVE_LOCALTIME_R #ifndef HAVE_GMTIME_R struct tm* gmtime_r(const std::time_t* timep, std::tm* result) { gmtime_s(result, timep); diff --git a/src/windows/port.h b/src/windows/port.h index 52662f3f3..1846c33ea 100644 --- a/src/windows/port.h +++ b/src/windows/port.h @@ -45,26 +45,26 @@ #ifdef _WIN32 -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN /* We always want minimal includes */ -#endif - -#include /* for _getcwd() */ -#include /* because we so often use open/close/etc */ -#include /* for _getpid() */ -#include -#include /* for gethostname */ - -#include /* template_dictionary.cc uses va_copy */ -#include /* for _strnicmp(), strerror_s() */ -#include /* for localtime_s() */ +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN /* We always want minimal includes */ +# endif + +# include /* for _getcwd() */ +# include /* because we so often use open/close/etc */ +# include /* for _getpid() */ +# include +# include /* for gethostname */ + +# include /* template_dictionary.cc uses va_copy */ +# include /* for _strnicmp(), strerror_s() */ +# include /* for localtime_s() */ /* Note: the C++ #includes are all together at the bottom. This file is * used by both C and C++ code, so we put all the C++ together. */ -#include "glog/logging.h" +# include "glog/logging.h" -#ifdef _MSC_VER +# ifdef _MSC_VER /* 4244: otherwise we get problems when substracting two size_t's to an int * 4251: it's complaining about a private struct I've chosen not to dllexport @@ -76,84 +76,85 @@ * 4267: also subtracting two size_t to int * 4722: Destructor never returns due to abort() */ -#pragma warning(disable:4244 4251 4355 4715 4800 4996 4267 4312 4722) +# pragma warning(disable : 4244 4251 4355 4715 4800 4996 4267 4312 4722) /* file I/O */ -#define PATH_MAX 1024 -#define popen _popen -#define pclose _pclose -#define R_OK 04 /* read-only (for access()) */ -#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) +# define PATH_MAX 1024 +# define popen _popen +# define pclose _pclose +# define R_OK 04 /* read-only (for access()) */ +# define S_ISDIR(m) (((m)&_S_IFMT) == _S_IFDIR) -#define O_WRONLY _O_WRONLY -#define O_CREAT _O_CREAT -#define O_EXCL _O_EXCL +# define O_WRONLY _O_WRONLY +# define O_CREAT _O_CREAT +# define O_EXCL _O_EXCL -#ifndef __MINGW32__ +# ifndef __MINGW32__ enum { STDIN_FILENO = 0, STDOUT_FILENO = 1, STDERR_FILENO = 2 }; -#endif -#define S_IRUSR S_IREAD -#define S_IWUSR S_IWRITE +# endif +# define S_IRUSR S_IREAD +# define S_IWUSR S_IWRITE /* Not quite as lightweight as a hard-link, but more than good enough for us. */ -#define link(oldpath, newpath) CopyFileA(oldpath, newpath, false) +# define link(oldpath, newpath) CopyFileA(oldpath, newpath, false) -#define strcasecmp _stricmp -#define strncasecmp _strnicmp +# define strcasecmp _stricmp +# define strncasecmp _strnicmp /* In windows-land, hash<> is called hash_compare<> (from xhash.h) */ /* VC11 provides std::hash */ -#if defined(_MSC_VER) && (_MSC_VER < 1700) -#define hash hash_compare -#endif +# if defined(_MSC_VER) && (_MSC_VER < 1700) +# define hash hash_compare +# endif /* Sleep is in ms, on windows */ -#define sleep(secs) Sleep((secs) * 1000) +# define sleep(secs) Sleep((secs)*1000) /* Windows doesn't support specifying the number of buckets as a * hash_map constructor arg, so we leave this blank. */ -#define CTEMPLATE_SMALL_HASHTABLE +# define CTEMPLATE_SMALL_HASHTABLE -#define DEFAULT_TEMPLATE_ROOTDIR ".." +# define DEFAULT_TEMPLATE_ROOTDIR ".." // ----------------------------------- SYSTEM/PROCESS typedef int pid_t; -#define getpid _getpid +# define getpid _getpid -#endif // _MSC_VER +# endif // _MSC_VER // ----------------------------------- THREADS -#if defined(HAVE_PTHREAD) -# include -#else // no PTHREAD +# if defined(HAVE_PTHREAD) +# include +# else // no PTHREAD typedef DWORD pthread_t; typedef DWORD pthread_key_t; typedef LONG pthread_once_t; -enum { PTHREAD_ONCE_INIT = 0 }; // important that this be 0! for SpinLock -#define pthread_self GetCurrentThreadId -#define pthread_equal(pthread_t_1, pthread_t_2) ((pthread_t_1)==(pthread_t_2)) -#endif // HAVE_PTHREAD +enum { PTHREAD_ONCE_INIT = 0 }; // important that this be 0! for SpinLock +# define pthread_self GetCurrentThreadId +# define pthread_equal(pthread_t_1, pthread_t_2) \ + ((pthread_t_1) == (pthread_t_2)) +# endif // HAVE_PTHREAD -#ifndef HAVE_LOCALTIME_R +# ifndef HAVE_LOCALTIME_R extern GLOG_EXPORT std::tm* localtime_r(const std::time_t* timep, std::tm* result); -#endif // not HAVE_LOCALTIME_R +# endif // not HAVE_LOCALTIME_R -#ifndef HAVE_GMTIME_R +# ifndef HAVE_GMTIME_R extern GLOG_EXPORT std::tm* gmtime_r(const std::time_t* timep, std::tm* result); -#endif // not HAVE_GMTIME_R +# endif // not HAVE_GMTIME_R inline char* strerror_r(int errnum, char* buf, std::size_t buflen) { strerror_s(buf, buflen, errnum); return buf; } -#ifndef __cplusplus +# ifndef __cplusplus /* I don't see how to get inlining for C code in MSVC. Ah well. */ -#define inline -#endif +# define inline +# endif -#endif /* _WIN32 */ +#endif /* _WIN32 */ -#endif /* CTEMPLATE_WINDOWS_PORT_H_ */ +#endif /* CTEMPLATE_WINDOWS_PORT_H_ */