This commit is contained in:
Sergiu Deitsch 2023-12-30 22:09:15 +01:00
parent a71621cc8a
commit ebbae478e4
27 changed files with 427 additions and 343 deletions

View File

@ -45,69 +45,69 @@
// We also put the type of the variable in the namespace, so that // We also put the type of the variable in the namespace, so that
// people can't DECLARE_int32 something that they DEFINE_bool'd // people can't DECLARE_int32 something that they DEFINE_bool'd
// elsewhere. // elsewhere.
#ifndef BASE_COMMANDLINEFLAGS_H__ #ifndef BASE_COMMANDLINEFLAGS_H_
#define BASE_COMMANDLINEFLAGS_H__ # define BASE_COMMANDLINEFLAGS_H_
#include <cstdlib> // for getenv # include <cstdlib> // for getenv
#include <cstring> // for memchr # include <cstring> // for memchr
#include <string> # include <string>
#include "config.h" # include "config.h"
#ifdef GLOG_USE_GFLAGS # ifdef GLOG_USE_GFLAGS
# include <gflags/gflags.h> # include <gflags/gflags.h>
#else # else
# include "glog/logging.h" # include "glog/logging.h"
# define DECLARE_VARIABLE(type, shorttype, name, tn) \ # define DECLARE_VARIABLE(type, shorttype, name, tn) \
namespace fL##shorttype { \ namespace fL##shorttype { \
extern GLOG_EXPORT type FLAGS_##name; \ extern GLOG_EXPORT type FLAGS_##name; \
} \ } \
using fL##shorttype::FLAGS_##name using fL##shorttype::FLAGS_##name
# define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \ # define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \
namespace fL##shorttype { \ namespace fL##shorttype { \
GLOG_EXPORT type FLAGS_##name(value); \ GLOG_EXPORT type FLAGS_##name(value); \
char FLAGS_no##name; \ char FLAGS_no##name; \
} \ } \
using fL##shorttype::FLAGS_##name using fL##shorttype::FLAGS_##name
// bool specialization // bool specialization
# define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name, bool) # define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name, bool)
# define DEFINE_bool(name, value, meaning) \ # define DEFINE_bool(name, value, meaning) \
DEFINE_VARIABLE(bool, B, name, value, meaning, bool) DEFINE_VARIABLE(bool, B, name, value, meaning, bool)
// int32 specialization // int32 specialization
# define DECLARE_int32(name) DECLARE_VARIABLE(google::int32, I, name, int32) # define DECLARE_int32(name) DECLARE_VARIABLE(google::int32, I, name, int32)
# define DEFINE_int32(name, value, meaning) \ # define DEFINE_int32(name, value, meaning) \
DEFINE_VARIABLE(google::int32, I, name, value, meaning, int32) DEFINE_VARIABLE(google::int32, I, name, value, meaning, int32)
// uint32 specialization // uint32 specialization
# ifndef DECLARE_uint32 # ifndef DECLARE_uint32
# define DECLARE_uint32(name) \ # define DECLARE_uint32(name) \
DECLARE_VARIABLE(google::uint32, U, name, uint32) DECLARE_VARIABLE(google::uint32, U, name, uint32)
# endif // DECLARE_uint64 # endif // DECLARE_uint64
# define DEFINE_uint32(name, value, meaning) \ # define DEFINE_uint32(name, value, meaning) \
DEFINE_VARIABLE(google::uint32, U, name, value, meaning, uint32) DEFINE_VARIABLE(google::uint32, U, name, value, meaning, uint32)
// Special case for string, because we have to specify the namespace // Special case for string, because we have to specify the namespace
// std::string, which doesn't play nicely with our FLAG__namespace hackery. // std::string, which doesn't play nicely with our FLAG__namespace hackery.
# define DECLARE_string(name) \ # define DECLARE_string(name) \
namespace fLS { \ namespace fLS { \
extern GLOG_EXPORT std::string& FLAGS_##name; \ extern GLOG_EXPORT std::string& FLAGS_##name; \
} \ } \
using fLS::FLAGS_##name using fLS::FLAGS_##name
# define DEFINE_string(name, value, meaning) \ # define DEFINE_string(name, value, meaning) \
namespace fLS { \ namespace fLS { \
std::string FLAGS_##name##_buf(value); \ std::string FLAGS_##name##_buf(value); \
GLOG_EXPORT std::string& FLAGS_##name = FLAGS_##name##_buf; \ GLOG_EXPORT std::string& FLAGS_##name = FLAGS_##name##_buf; \
char FLAGS_no##name; \ char FLAGS_no##name; \
} \ } \
using fLS::FLAGS_##name using fLS::FLAGS_##name
#endif // GLOG_USE_GFLAGS # endif // GLOG_USE_GFLAGS
// Define GLOG_DEFINE_* using DEFINE_* . By using these macros, we // Define GLOG_DEFINE_* using DEFINE_* . By using these macros, we
// have GLOG_* environ variables even if we have gflags installed. // have GLOG_* environ variables even if we have gflags installed.
@ -146,4 +146,4 @@
? (dflt) \ ? (dflt) \
: static_cast<unsigned>(strtoul(getenv(envname), nullptr, 10))) : static_cast<unsigned>(strtoul(getenv(envname), nullptr, 10)))
#endif // BASE_COMMANDLINEFLAGS_H__ #endif // BASE_COMMANDLINEFLAGS_H_

View File

@ -30,13 +30,13 @@
// --- // ---
// Author: Jacob Hoffman-Andrews // Author: Jacob Hoffman-Andrews
#ifndef _GOOGLEINIT_H #ifndef GOOGLEINIT_H
#define _GOOGLEINIT_H # define GOOGLEINIT_H
class GoogleInitializer { class GoogleInitializer {
public: public:
using void_function = void (*)(); using void_function = void (*)();
GoogleInitializer(const char*, void_function f) { f(); } GoogleInitializer(const char* /*unused*/, void_function f) { f(); }
}; };
#define REGISTER_MODULE_INITIALIZER(name, body) \ #define REGISTER_MODULE_INITIALIZER(name, body) \
@ -46,4 +46,4 @@ class GoogleInitializer {
#name, google_init_module_##name); \ #name, google_init_module_##name); \
} }
#endif /* _GOOGLEINIT_H */ #endif /* GOOGLEINIT_H */

View File

@ -136,7 +136,7 @@ typedef CRITICAL_SECTION MutexType;
# ifdef __linux__ # ifdef __linux__
# ifndef _XOPEN_SOURCE // Some other header might have already set it for # ifndef _XOPEN_SOURCE // Some other header might have already set it for
// us. // us.
# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls # define XOPEN_SOURCE 500 // may be needed to get the rwlock calls
# endif # endif
# endif # endif
# include <pthread.h> # include <pthread.h>
@ -258,7 +258,9 @@ void Mutex::ReaderUnlock() { Unlock(); }
Mutex::Mutex() { Mutex::Mutex() {
SetIsSafe(); SetIsSafe();
if (is_safe_ && pthread_rwlock_init(&mutex_, nullptr) != 0) abort(); if (is_safe_ && pthread_rwlock_init(&mutex_, nullptr) != 0) {
abort();
}
} }
Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); } Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); }
void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); }

View File

@ -199,7 +199,7 @@ static bool ParseCharClass(State* state, const char* char_class) {
} }
// This function is used for handling an optional non-terminal. // This function is used for handling an optional non-terminal.
static bool Optional(bool) { return true; } static bool Optional(bool /*unused*/) { return true; }
// This function is used for handling <non-terminal>+ syntax. // This function is used for handling <non-terminal>+ syntax.
using ParseFunc = bool (*)(State*); using ParseFunc = bool (*)(State*);
@ -450,10 +450,7 @@ static bool ParseEncoding(State* state) {
} }
*state = copy; *state = copy;
if (ParseName(state) || ParseSpecialName(state)) { return ParseName(state) || ParseSpecialName(state);
return true;
}
return false;
} }
// <name> ::= <nested-name> // <name> ::= <nested-name>
@ -472,10 +469,7 @@ static bool ParseName(State* state) {
*state = copy; *state = copy;
// Less greedy than <unscoped-template-name> <template-args>. // Less greedy than <unscoped-template-name> <template-args>.
if (ParseUnscopedName(state)) { return ParseUnscopedName(state);
return true;
}
return false;
} }
// <unscoped-name> ::= <unqualified-name> // <unscoped-name> ::= <unqualified-name>
@ -538,9 +532,8 @@ static bool ParsePrefix(State* state) {
MaybeCancelLastSeparator(state); MaybeCancelLastSeparator(state);
if (has_something && ParseTemplateArgs(state)) { if (has_something && ParseTemplateArgs(state)) {
return ParsePrefix(state); return ParsePrefix(state);
} else {
break;
} }
break;
} }
return true; return true;
} }
@ -627,7 +620,7 @@ static bool ParseNumber(State* state, int* number_out) {
static bool ParseFloatNumber(State* state) { static bool ParseFloatNumber(State* state) {
const char* p = state->mangled_cur; const char* p = state->mangled_cur;
for (; *p != '\0'; ++p) { for (; *p != '\0'; ++p) {
if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) { if (!IsDigit(*p) && (*p < 'a' || *p > 'f')) {
break; break;
} }
} }
@ -643,7 +636,7 @@ static bool ParseFloatNumber(State* state) {
static bool ParseSeqId(State* state) { static bool ParseSeqId(State* state) {
const char* p = state->mangled_cur; const char* p = state->mangled_cur;
for (; *p != '\0'; ++p) { for (; *p != '\0'; ++p) {
if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) { if (!IsDigit(*p) && (*p < 'A' || *p > 'Z')) {
break; break;
} }
} }
@ -928,11 +921,7 @@ static bool ParseType(State* state) {
*state = copy; *state = copy;
// Less greedy than <template-template-param> <template-args>. // Less greedy than <template-template-param> <template-args>.
if (ParseTemplateParam(state)) { return ParseTemplateParam(state);
return true;
}
return false;
} }
// <CV-qualifiers> ::= [r] [V] [K] // <CV-qualifiers> ::= [r] [V] [K]
@ -940,9 +929,9 @@ static bool ParseType(State* state) {
// ParseType(). // ParseType().
static bool ParseCVQualifiers(State* state) { static bool ParseCVQualifiers(State* state) {
int num_cv_qualifiers = 0; int num_cv_qualifiers = 0;
num_cv_qualifiers += ParseOneCharToken(state, 'r'); num_cv_qualifiers += static_cast<int>(ParseOneCharToken(state, 'r'));
num_cv_qualifiers += ParseOneCharToken(state, 'V'); num_cv_qualifiers += static_cast<int>(ParseOneCharToken(state, 'V'));
num_cv_qualifiers += ParseOneCharToken(state, 'K'); num_cv_qualifiers += static_cast<int>(ParseOneCharToken(state, 'K'));
return num_cv_qualifiers > 0; return num_cv_qualifiers > 0;
} }

View File

@ -58,9 +58,8 @@ static const char* DemangleIt(const char* const mangled) {
static char demangled[4096]; static char demangled[4096];
if (Demangle(mangled, demangled, sizeof(demangled))) { if (Demangle(mangled, demangled, sizeof(demangled))) {
return demangled; return demangled;
} else {
return mangled;
} }
return mangled;
} }
#if defined(GLOG_OS_WINDOWS) #if defined(GLOG_OS_WINDOWS)
@ -159,10 +158,10 @@ int main(int argc, char** argv) {
cout << DemangleIt(line.c_str()) << endl; cout << DemangleIt(line.c_str()) << endl;
} }
return 0; return 0;
} else if (argc > 1) { }
if (argc > 1) {
cout << DemangleIt(argv[1]) << endl; cout << DemangleIt(argv[1]) << endl;
return 0; return 0;
} else {
return RUN_ALL_TESTS();
} }
return RUN_ALL_TESTS();
} }

View File

@ -27,8 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef BASE_LOG_SEVERITY_H__ #ifndef BASE_LOG_SEVERITY_H_
#define BASE_LOG_SEVERITY_H__ #define BASE_LOG_SEVERITY_H_
#if defined(GLOG_USE_GLOG_EXPORT)
# include "glog/export.h"
#endif
// The recommended semantics of the log levels are as follows: // The recommended semantics of the log levels are as follows:
// //
@ -95,4 +99,4 @@ enum { DEBUG_MODE = 1 };
# define IF_DEBUG_MODE(x) x # define IF_DEBUG_MODE(x) x
#endif #endif
#endif // BASE_LOG_SEVERITY_H__ #endif // BASE_LOG_SEVERITY_H_

View File

@ -90,16 +90,16 @@
namespace google { namespace google {
typedef std::int32_t int32; using int32 = std::int32_t;
typedef std::uint32_t uint32; using uint32 = std::uint32_t;
typedef std::int64_t int64; using int64 = std::int64_t;
typedef std::uint64_t uint64; using uint64 = std::uint64_t;
typedef double WallTime; using WallTime = double;
struct GLOG_EXPORT LogMessageTime { struct GLOG_EXPORT LogMessageTime {
LogMessageTime(); LogMessageTime();
LogMessageTime(std::tm t); explicit LogMessageTime(std::tm t);
LogMessageTime(std::time_t timestamp, WallTime now); LogMessageTime(std::time_t timestamp, WallTime now);
const time_t& timestamp() const { return timestamp_; } const time_t& timestamp() const { return timestamp_; }
@ -143,8 +143,8 @@ struct LogMessageInfo {
const LogMessageTime& time; const LogMessageTime& time;
}; };
typedef void (*CustomPrefixCallback)(std::ostream& s, const LogMessageInfo& l, using CustomPrefixCallback = void (*)(std::ostream&, const LogMessageInfo&,
void* data); void*);
} // namespace google } // namespace google
@ -632,9 +632,10 @@ GLOG_EXPORT bool IsGoogleLoggingInitialized();
GLOG_EXPORT void ShutdownGoogleLogging(); GLOG_EXPORT void ShutdownGoogleLogging();
#if defined(__GNUC__) #if defined(__GNUC__)
typedef void (*logging_fail_func_t)() __attribute__((noreturn)); typedef void (*logging_fail_func_t)()
__attribute__((noreturn)); // NOLINT(modernize-use-using)
#else #else
typedef void (*logging_fail_func_t)(); using logging_fail_func_t = void (*)();
#endif #endif
// Install a function which will be called after LOG(FATAL). // Install a function which will be called after LOG(FATAL).
@ -711,10 +712,11 @@ class LogSink; // defined below
// A container for a string pointer which can be evaluated to a bool - // A container for a string pointer which can be evaluated to a bool -
// true iff the pointer is nullptr. // true iff the pointer is nullptr.
struct CheckOpString { struct CheckOpString {
// NOLINTNEXTLINE(google-explicit-constructor)
CheckOpString(std::string* str) : str_(str) {} CheckOpString(std::string* str) : str_(str) {}
// No destructor: if str_ is non-nullptr, we're about to LOG(FATAL), // No destructor: if str_ is non-nullptr, we're about to LOG(FATAL),
// so there's no point in cleaning up str_. // so there's no point in cleaning up str_.
operator bool() const { explicit operator bool() const noexcept {
return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != nullptr); return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != nullptr);
} }
std::string* str_; std::string* str_;
@ -749,8 +751,8 @@ struct DummyClassToDefineOperator {};
// Define global operator<< to declare using ::operator<<. // Define global operator<< to declare using ::operator<<.
// This declaration will allow use to use CHECK macros for user // This declaration will allow use to use CHECK macros for user
// defined classes which have operator<< (e.g., stl_logging.h). // defined classes which have operator<< (e.g., stl_logging.h).
inline std::ostream& operator<<(std::ostream& out, inline std::ostream& operator<<(
const google::DummyClassToDefineOperator&) { std::ostream& out, const google::DummyClassToDefineOperator& /*unused*/) {
return out; return out;
} }
@ -964,8 +966,8 @@ DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2) #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2) #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
#define CHECK_INDEX(I, A) CHECK(I < (sizeof(A) / sizeof(A[0]))) #define CHECK_INDEX(I, A) CHECK((I) < (sizeof(A) / sizeof((A)[0])))
#define CHECK_BOUND(B, A) CHECK(B <= (sizeof(A) / sizeof(A[0]))) #define CHECK_BOUND(B, A) CHECK((B) <= (sizeof(A) / sizeof((A)[0])))
#define CHECK_DOUBLE_EQ(val1, val2) \ #define CHECK_DOUBLE_EQ(val1, val2) \
do { \ do { \
@ -1088,23 +1090,23 @@ namespace google {
GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \
__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \ __FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \
++LOG_OCCURRENCES; \ ++LOG_OCCURRENCES; \
if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ if (++LOG_OCCURRENCES_MOD_N > (n)) LOG_OCCURRENCES_MOD_N -= (n); \
if (LOG_OCCURRENCES_MOD_N == 1) \ if (LOG_OCCURRENCES_MOD_N == 1) \
google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \ google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
LOG_OCCURRENCES, &what_to_do) \ LOG_OCCURRENCES, (what_to_do)) \
.stream() .stream()
#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
static std::atomic<int> LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \ static std::atomic<int> LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \
GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \
__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \ __FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \
GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \
__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \ __FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \
++LOG_OCCURRENCES; \ ++LOG_OCCURRENCES; \
if ((condition) && \ if ((condition) && ((LOG_OCCURRENCES_MOD_N = \
((LOG_OCCURRENCES_MOD_N = (LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \ (LOG_OCCURRENCES_MOD_N + 1) % (n)) == (1 % (n)))) \
google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \ google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
LOG_OCCURRENCES, &what_to_do) \ LOG_OCCURRENCES, (what_to_do)) \
.stream() .stream()
#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
@ -1114,20 +1116,20 @@ namespace google {
GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \
__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \ __FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \
++LOG_OCCURRENCES; \ ++LOG_OCCURRENCES; \
if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ if (++LOG_OCCURRENCES_MOD_N > (n)) LOG_OCCURRENCES_MOD_N -= (n); \
if (LOG_OCCURRENCES_MOD_N == 1) \ if (LOG_OCCURRENCES_MOD_N == 1) \
google::ErrnoLogMessage(__FILE__, __LINE__, google::GLOG_##severity, \ google::ErrnoLogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
LOG_OCCURRENCES, &what_to_do) \ LOG_OCCURRENCES, (what_to_do)) \
.stream() .stream()
#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
static std::atomic<int> LOG_OCCURRENCES(0); \ static std::atomic<int> LOG_OCCURRENCES(0); \
GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \ GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized( \
__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \ __FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \
if (LOG_OCCURRENCES <= n) ++LOG_OCCURRENCES; \ if (LOG_OCCURRENCES <= (n)) ++LOG_OCCURRENCES; \
if (LOG_OCCURRENCES <= n) \ if (LOG_OCCURRENCES <= (n)) \
google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \ google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
LOG_OCCURRENCES, &what_to_do) \ LOG_OCCURRENCES, (what_to_do)) \
.stream() .stream()
namespace glog_internal_namespace_ { namespace glog_internal_namespace_ {
@ -1141,23 +1143,23 @@ GLOG_EXPORT bool IsFailureSignalHandlerInstalled();
} // namespace glog_internal_namespace_ } // namespace glog_internal_namespace_
#define LOG_EVERY_N(severity, n) \ #define LOG_EVERY_N(severity, n) \
SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog) SOME_KIND_OF_LOG_EVERY_N(severity, (n), &google::LogMessage::SendToLog)
#define LOG_EVERY_T(severity, T) SOME_KIND_OF_LOG_EVERY_T(severity, (T)) #define LOG_EVERY_T(severity, T) SOME_KIND_OF_LOG_EVERY_T(severity, (T))
#define SYSLOG_EVERY_N(severity, n) \ #define SYSLOG_EVERY_N(severity, n) \
SOME_KIND_OF_LOG_EVERY_N(severity, (n), \ SOME_KIND_OF_LOG_EVERY_N(severity, (n), \
google::LogMessage::SendToSyslogAndLog) &google::LogMessage::SendToSyslogAndLog)
#define PLOG_EVERY_N(severity, n) \ #define PLOG_EVERY_N(severity, n) \
SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog) SOME_KIND_OF_PLOG_EVERY_N(severity, (n), &google::LogMessage::SendToLog)
#define LOG_FIRST_N(severity, n) \ #define LOG_FIRST_N(severity, n) \
SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog) SOME_KIND_OF_LOG_FIRST_N(severity, (n), &google::LogMessage::SendToLog)
#define LOG_IF_EVERY_N(severity, condition, n) \ #define LOG_IF_EVERY_N(severity, condition, n) \
SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), \ SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), \
google::LogMessage::SendToLog) &google::LogMessage::SendToLog)
// We want the special COUNTER value available for LOG_EVERY_X()'ed messages // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
enum PRIVATE_Counter { COUNTER }; enum PRIVATE_Counter { COUNTER };
@ -1324,7 +1326,7 @@ class GLOG_EXPORT LogStreamBuf : public std::streambuf {
LogStreamBuf(char* buf, int len) { setp(buf, buf + len - 2); } LogStreamBuf(char* buf, int len) { setp(buf, buf + len - 2); }
// This effectively ignores overflow. // This effectively ignores overflow.
int_type overflow(int_type ch) { return ch; } int_type overflow(int_type ch) override { return ch; }
// Legacy public ostrstream method. // Legacy public ostrstream method.
size_t pcount() const { return static_cast<size_t>(pptr() - pbase()); } size_t pcount() const { return static_cast<size_t>(pptr() - pbase()); }
@ -1406,9 +1408,8 @@ class GLOG_EXPORT LogMessage {
LogStream* self_; // Consistency check hack LogStream* self_; // Consistency check hack
}; };
public:
// icc 8 requires this typedef to avoid an internal compiler error. // icc 8 requires this typedef to avoid an internal compiler error.
typedef void (LogMessage::*SendMethod)(); using SendMethod = void (LogMessage::*)();
LogMessage(const char* file, int line, LogSeverity severity, int64 ctr, LogMessage(const char* file, int line, LogSeverity severity, int64 ctr,
SendMethod send_method); SendMethod send_method);
@ -1495,7 +1496,7 @@ class GLOG_EXPORT LogMessage {
void (LogMessage::*send_method)()); void (LogMessage::*send_method)());
// Used to fill in crash information during LOG(FATAL) failures. // Used to fill in crash information during LOG(FATAL) failures.
void RecordCrashReason(glog_internal_namespace_::CrashReason* reason); static void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
// Counts of messages sent at each priority: // Counts of messages sent at each priority:
static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
@ -1576,10 +1577,10 @@ class GLOG_EXPORT ErrnoLogMessage : public LogMessage {
class GLOG_EXPORT LogMessageVoidify { class GLOG_EXPORT LogMessageVoidify {
public: public:
LogMessageVoidify() {} LogMessageVoidify() = default;
// This has to be an operator with a precedence lower than << but // This has to be an operator with a precedence lower than << but
// higher than ?: // higher than ?:
void operator&(std::ostream&) {} void operator&(std::ostream& /*unused*/) {}
}; };
// Flushes all log files that contains messages that are at least of // Flushes all log files that contains messages that are at least of
@ -1817,7 +1818,7 @@ class GLOG_EXPORT NullStream : public LogMessage::LogStream {
// converted to LogStream and the message will be computed and then // converted to LogStream and the message will be computed and then
// quietly discarded. // quietly discarded.
template <class T> template <class T>
inline NullStream& operator<<(NullStream& str, const T&) { inline NullStream& operator<<(NullStream& str, const T& /*unused*/) {
return str; return str;
} }
@ -1828,7 +1829,7 @@ class GLOG_EXPORT NullStreamFatal : public NullStream {
using NullStream::NullStream; using NullStream::NullStream;
[[noreturn]] [[noreturn]]
// Prevent the linker from discarding the destructor. // Prevent the linker from discarding the destructor.
GLOG_USED ~NullStreamFatal(); GLOG_USED ~NullStreamFatal() override;
}; };
// Install a signal handler that will dump signal information and a stack // Install a signal handler that will dump signal information and a stack

View File

@ -97,28 +97,28 @@ namespace google {
#if !defined(STRIP_LOG) || STRIP_LOG == 0 #if !defined(STRIP_LOG) || STRIP_LOG == 0
# define RAW_LOG_INFO(...) \ # define RAW_LOG_INFO(...) \
google::RawLog__(google::GLOG_INFO, __FILE__, __LINE__, __VA_ARGS__) google::RawLog_(google::GLOG_INFO, __FILE__, __LINE__, __VA_ARGS__)
#else #else
# define RAW_LOG_INFO(...) google::RawLogStub__(0, __VA_ARGS__) # define RAW_LOG_INFO(...) google::RawLogStub__(0, __VA_ARGS__)
#endif // STRIP_LOG == 0 #endif // STRIP_LOG == 0
#if !defined(STRIP_LOG) || STRIP_LOG <= 1 #if !defined(STRIP_LOG) || STRIP_LOG <= 1
# define RAW_LOG_WARNING(...) \ # define RAW_LOG_WARNING(...) \
google::RawLog__(google::GLOG_WARNING, __FILE__, __LINE__, __VA_ARGS__) google::RawLog_(google::GLOG_WARNING, __FILE__, __LINE__, __VA_ARGS__)
#else #else
# define RAW_LOG_WARNING(...) google::RawLogStub__(0, __VA_ARGS__) # define RAW_LOG_WARNING(...) google::RawLogStub__(0, __VA_ARGS__)
#endif // STRIP_LOG <= 1 #endif // STRIP_LOG <= 1
#if !defined(STRIP_LOG) || STRIP_LOG <= 2 #if !defined(STRIP_LOG) || STRIP_LOG <= 2
# define RAW_LOG_ERROR(...) \ # define RAW_LOG_ERROR(...) \
google::RawLog__(google::GLOG_ERROR, __FILE__, __LINE__, __VA_ARGS__) google::RawLog_(google::GLOG_ERROR, __FILE__, __LINE__, __VA_ARGS__)
#else #else
# define RAW_LOG_ERROR(...) google::RawLogStub__(0, __VA_ARGS__) # define RAW_LOG_ERROR(...) google::RawLogStub__(0, __VA_ARGS__)
#endif // STRIP_LOG <= 2 #endif // STRIP_LOG <= 2
#if !defined(STRIP_LOG) || STRIP_LOG <= 3 #if !defined(STRIP_LOG) || STRIP_LOG <= 3
# define RAW_LOG_FATAL(...) \ # define RAW_LOG_FATAL(...) \
google::RawLog__(google::GLOG_FATAL, __FILE__, __LINE__, __VA_ARGS__) google::RawLog_(google::GLOG_FATAL, __FILE__, __LINE__, __VA_ARGS__)
#else #else
# define RAW_LOG_FATAL(...) \ # define RAW_LOG_FATAL(...) \
do { \ do { \
@ -160,14 +160,14 @@ namespace google {
// Stub log function used to work around for unused variable warnings when // Stub log function used to work around for unused variable warnings when
// building with STRIP_LOG > 0. // building with STRIP_LOG > 0.
static inline void RawLogStub__(int /* ignored */, ...) {} static inline void RawLogStub_(int /* ignored */, ...) {}
// Helper function to implement RAW_LOG and RAW_VLOG // Helper function to implement RAW_LOG and RAW_VLOG
// Logs format... at "severity" level, reporting it // Logs format... at "severity" level, reporting it
// as called from file:line. // as called from file:line.
// This does not allocate memory or acquire locks. // This does not allocate memory or acquire locks.
GLOG_EXPORT void RawLog__(LogSeverity severity, const char* file, int line, GLOG_EXPORT void RawLog_(LogSeverity severity, const char* file, int line,
const char* format, ...) const char* format, ...)
#if defined(__has_attribute) #if defined(__has_attribute)
# if __has_attribute(used) # if __has_attribute(used)
__attribute__((__format__(__printf__, 4, 5))) __attribute__((__format__(__printf__, 4, 5)))

View File

@ -127,7 +127,9 @@ template <class Iter>
inline void PrintSequence(std::ostream& out, Iter begin, Iter end) { inline void PrintSequence(std::ostream& out, Iter begin, Iter end) {
// Output at most 100 elements -- appropriate if used for logging. // Output at most 100 elements -- appropriate if used for logging.
for (int i = 0; begin != end && i < 100; ++i, ++begin) { for (int i = 0; begin != end && i < 100; ++i, ++begin) {
if (i > 0) out << ' '; if (i > 0) {
out << ' ';
}
out << *begin; out << *begin;
} }
if (begin != end) { if (begin != end) {

View File

@ -79,8 +79,8 @@
__FILE__, __LINE__, &vlocal__, sizeof(google::SiteFlag), "")); \ __FILE__, __LINE__, &vlocal__, sizeof(google::SiteFlag), "")); \
google::int32 verbose_level__ = (verboselevel); \ google::int32 verbose_level__ = (verboselevel); \
(vlocal__.level == nullptr \ (vlocal__.level == nullptr \
? google::InitVLOG3__(&vlocal__, &FLAGS_v, __FILE__, \ ? google::InitVLOG3_(&vlocal__, &FLAGS_v, __FILE__, \
verbose_level__) \ verbose_level__) \
: *vlocal__.level >= verbose_level__); \ : *vlocal__.level >= verbose_level__); \
}) })
#else #else
@ -116,9 +116,9 @@ struct SiteFlag {
// verbose_level is the argument to VLOG_IS_ON // verbose_level is the argument to VLOG_IS_ON
// We will return the return value for VLOG_IS_ON // We will return the return value for VLOG_IS_ON
// and if possible set *site_flag appropriately. // and if possible set *site_flag appropriately.
extern GLOG_EXPORT bool InitVLOG3__(google::SiteFlag* site_flag, extern GLOG_EXPORT bool InitVLOG3_(google::SiteFlag* site_flag,
google::int32* site_default, google::int32* site_default,
const char* fname, const char* fname,
google::int32 verbose_level); google::int32 verbose_level);
#endif // BASE_VLOG_IS_ON_H_ #endif // BASE_VLOG_IS_ON_H_

View File

@ -33,7 +33,7 @@
#ifdef GOOGLETEST_H__ #ifdef GOOGLETEST_H__
# error You must not include this file twice. # error You must not include this file twice.
#endif #endif
#define GOOGLETEST_H__ #define GOOGLETEST_H_
#include <fcntl.h> #include <fcntl.h>
#include <sys/stat.h> #include <sys/stat.h>
@ -256,7 +256,7 @@ static inline void CalledAbort() {
// Benchmark tools. // Benchmark tools.
#define BENCHMARK(n) static BenchmarkRegisterer __benchmark_##n(#n, &n); #define BENCHMARK(n) static BenchmarkRegisterer __benchmark_##n(#n, &(n));
map<string, void (*)(int)> g_benchlist; // the benchmarks to run map<string, void (*)(int)> g_benchlist; // the benchmarks to run
@ -330,7 +330,7 @@ class CapturedStream {
} }
// Remove output redirection // Remove output redirection
void StopCapture() { void StopCapture() const {
// Restore original stream // Restore original stream
if (uncaptured_fd_ != -1) { if (uncaptured_fd_ != -1) {
fflush(nullptr); fflush(nullptr);
@ -420,9 +420,13 @@ static inline bool IsLoggingPrefix(const string& s) {
if (s.size() != kLoggingPrefixLength) { if (s.size() != kLoggingPrefixLength) {
return false; return false;
} }
if (!strchr("IWEF", s[0])) return false; if (strchr("IWEF", s[0]) == nullptr) {
return false;
}
for (size_t i = 1; i <= 8; ++i) { for (size_t i = 1; i <= 8; ++i) {
if (!isdigit(s[i]) && s[i] != "YEARDATE"[i - 1]) return false; if ((isdigit(s[i]) == 0) && s[i] != "YEARDATE"[i - 1]) {
return false;
}
} }
return true; return true;
} }
@ -433,7 +437,10 @@ static inline bool IsLoggingPrefix(const string& s) {
// I20200102 030405 logging_unittest.cc:345] RAW: vlog -1 // I20200102 030405 logging_unittest.cc:345] RAW: vlog -1
// => IYEARDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1 // => IYEARDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1
static inline string MungeLine(const string& line) { static inline string MungeLine(const string& line) {
string before, logcode_date, time, thread_lineinfo; string before;
string logcode_date;
string time;
string thread_lineinfo;
std::size_t begin_of_logging_prefix = 0; std::size_t begin_of_logging_prefix = 0;
for (; begin_of_logging_prefix + kLoggingPrefixLength < line.size(); for (; begin_of_logging_prefix + kLoggingPrefixLength < line.size();
++begin_of_logging_prefix) { ++begin_of_logging_prefix) {
@ -444,7 +451,8 @@ static inline string MungeLine(const string& line) {
} }
if (begin_of_logging_prefix + kLoggingPrefixLength >= line.size()) { if (begin_of_logging_prefix + kLoggingPrefixLength >= line.size()) {
return line; return line;
} else if (begin_of_logging_prefix > 0) { }
if (begin_of_logging_prefix > 0) {
before = line.substr(0, begin_of_logging_prefix - 1); before = line.substr(0, begin_of_logging_prefix - 1);
} }
std::istringstream iss(line.substr(begin_of_logging_prefix)); std::istringstream iss(line.substr(begin_of_logging_prefix));
@ -482,7 +490,7 @@ static inline string Munge(const string& filename) {
CHECK(fp != nullptr) << filename << ": couldn't open"; CHECK(fp != nullptr) << filename << ": couldn't open";
char buf[4096]; char buf[4096];
string result; string result;
while (fgets(buf, 4095, fp)) { while (fgets(buf, 4095, fp) != nullptr) {
string line = MungeLine(buf); string line = MungeLine(buf);
const size_t str_size = 256; const size_t str_size = 256;
char null_str[str_size]; char null_str[str_size];
@ -583,7 +591,7 @@ class Thread {
public: public:
virtual ~Thread() = default; virtual ~Thread() = default;
void SetJoinable(bool) {} void SetJoinable(bool /*unused*/) {}
#if defined(GLOG_OS_WINDOWS) && !defined(GLOG_OS_CYGWIN) #if defined(GLOG_OS_WINDOWS) && !defined(GLOG_OS_CYGWIN)
void Start() { void Start() {
handle_ = CreateThread(nullptr, 0, &Thread::InvokeThreadW, this, 0, &th_); handle_ = CreateThread(nullptr, 0, &Thread::InvokeThreadW, this, 0, &th_);
@ -592,7 +600,7 @@ class Thread {
void Join() { WaitForSingleObject(handle_, INFINITE); } void Join() { WaitForSingleObject(handle_, INFINITE); }
#elif defined(HAVE_PTHREAD) #elif defined(HAVE_PTHREAD)
void Start() { pthread_create(&th_, nullptr, &Thread::InvokeThread, this); } void Start() { pthread_create(&th_, nullptr, &Thread::InvokeThread, this); }
void Join() { pthread_join(th_, nullptr); } void Join() const { pthread_join(th_, nullptr); }
#else #else
void Start() {} void Start() {}
void Join() {} void Join() {}
@ -638,8 +646,8 @@ void (*g_new_hook)() = nullptr;
} // namespace google } // namespace google
void* operator new(size_t size, const std::nothrow_t&) noexcept { void* operator new(size_t size, const std::nothrow_t& /*unused*/) noexcept {
if (google::g_new_hook) { if (google::g_new_hook != nullptr) {
google::g_new_hook(); google::g_new_hook();
} }
return malloc(size); return malloc(size);
@ -659,8 +667,12 @@ void* operator new[](size_t size) GOOGLE_GLOG_THROW_BAD_ALLOC {
void operator delete(void* p) noexcept { free(p); } void operator delete(void* p) noexcept { free(p); }
void operator delete(void* p, size_t) noexcept { ::operator delete(p); } void operator delete(void* p, size_t /*unused*/) noexcept {
::operator delete(p);
}
void operator delete[](void* p) noexcept { ::operator delete(p); } void operator delete[](void* p) noexcept { ::operator delete(p); }
void operator delete[](void* p, size_t) noexcept { ::operator delete(p); } void operator delete[](void* p, size_t /*unused*/) noexcept {
::operator delete(p);
}

View File

@ -27,7 +27,9 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() enum {
GNU_SOURCE = 1 // needed for O_NOFOLLOW and pread()/pwrite()
};
#include "glog/logging.h" #include "glog/logging.h"
@ -127,10 +129,10 @@ using std::fdopen;
static bool BoolFromEnv(const char* varname, bool defval) { static bool BoolFromEnv(const char* varname, bool defval) {
const char* const valstr = getenv(varname); const char* const valstr = getenv(varname);
if (!valstr) { if (valstr == nullptr) {
return defval; return defval;
} }
return memchr("tTyY1\0", valstr[0], 6) != nullptr; return strchr("tTyY1\0", valstr[0]) != nullptr;
} }
GLOG_DEFINE_bool(timestamp_in_logfile_name, GLOG_DEFINE_bool(timestamp_in_logfile_name,
@ -289,11 +291,14 @@ static bool TerminalSupportsColor() {
const char* const term = getenv("TERM"); const char* const term = getenv("TERM");
if (term != nullptr && term[0] != '\0') { if (term != nullptr && term[0] != '\0') {
term_supports_color = term_supports_color =
!strcmp(term, "xterm") || !strcmp(term, "xterm-color") || (strcmp(term, "xterm") == 0) || (strcmp(term, "xterm-color") == 0) ||
!strcmp(term, "xterm-256color") || !strcmp(term, "screen-256color") || (strcmp(term, "xterm-256color") == 0) ||
!strcmp(term, "konsole") || !strcmp(term, "konsole-16color") || (strcmp(term, "screen-256color") == 0) ||
!strcmp(term, "konsole-256color") || !strcmp(term, "screen") || (strcmp(term, "konsole") == 0) ||
!strcmp(term, "linux") || !strcmp(term, "cygwin"); (strcmp(term, "konsole-16color") == 0) ||
(strcmp(term, "konsole-256color") == 0) ||
(strcmp(term, "screen") == 0) || (strcmp(term, "linux") == 0) ||
(strcmp(term, "cygwin") == 0);
} }
#endif #endif
return term_supports_color; return term_supports_color;
@ -507,15 +512,16 @@ class LogCleaner {
bool enabled() const { return enabled_; } bool enabled() const { return enabled_; }
private: private:
vector<string> GetOverdueLogNames(string log_directory, unsigned int days, static vector<string> GetOverdueLogNames(string log_directory,
const string& base_filename, unsigned int days,
const string& filename_extension) const; const string& base_filename,
const string& filename_extension);
bool IsLogFromCurrentProject(const string& filepath, static bool IsLogFromCurrentProject(const string& filepath,
const string& base_filename, const string& base_filename,
const string& filename_extension) const; const string& filename_extension);
bool IsLogLastModifiedOver(const string& filepath, unsigned int days) const; static bool IsLogLastModifiedOver(const string& filepath, unsigned int days);
bool enabled_{false}; bool enabled_{false};
unsigned int overdue_days_{7}; unsigned int overdue_days_{7};
@ -530,8 +536,9 @@ class LogDestination {
public: public:
friend class LogMessage; friend class LogMessage;
friend void ReprintFatalMessage(); friend void ReprintFatalMessage();
friend base::Logger* base::GetLogger(LogSeverity); friend base::Logger* base::GetLogger(LogSeverity /*severity*/);
friend void base::SetLogger(LogSeverity, base::Logger*); friend void base::SetLogger(LogSeverity /*severity*/,
base::Logger* /*logger*/);
// These methods are just forwarded to by their global versions. // These methods are just forwarded to by their global versions.
static void SetLogDestination(LogSeverity severity, static void SetLogDestination(LogSeverity severity,
@ -651,7 +658,7 @@ void LogDestination::SetLoggerImpl(base::Logger* logger) {
return; return;
} }
if (logger_ && logger_ != &fileobject_) { if ((logger_ != nullptr) && logger_ != &fileobject_) {
// Delete user-specified logger set via SetLogger(). // Delete user-specified logger set via SetLogger().
delete logger_; delete logger_;
} }
@ -704,7 +711,9 @@ inline void LogDestination::AddLogSink(LogSink* destination) {
// Prevent any subtle race conditions by wrapping a mutex lock around // Prevent any subtle race conditions by wrapping a mutex lock around
// all this stuff. // all this stuff.
MutexLock l(&sink_mutex_); MutexLock l(&sink_mutex_);
if (!sinks_) sinks_ = new vector<LogSink*>; if (sinks_ == nullptr) {
sinks_ = new vector<LogSink*>;
}
sinks_->push_back(destination); sinks_->push_back(destination);
} }
@ -713,7 +722,7 @@ inline void LogDestination::RemoveLogSink(LogSink* destination) {
// all this stuff. // all this stuff.
MutexLock l(&sink_mutex_); MutexLock l(&sink_mutex_);
// This doesn't keep the sinks in order, but who cares? // This doesn't keep the sinks in order, but who cares?
if (sinks_) { if (sinks_ != nullptr) {
sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination), sinks_->erase(std::remove(sinks_->begin(), sinks_->end(), destination),
sinks_->end()); sinks_->end());
} }
@ -899,7 +908,7 @@ inline void LogDestination::LogToSinks(LogSeverity severity,
const char* message, const char* message,
size_t message_len) { size_t message_len) {
ReaderMutexLock l(&sink_mutex_); ReaderMutexLock l(&sink_mutex_);
if (sinks_) { if (sinks_ != nullptr) {
for (size_t i = sinks_->size(); i-- > 0;) { for (size_t i = sinks_->size(); i-- > 0;) {
(*sinks_)[i]->send(severity, full_filename, base_filename, line, (*sinks_)[i]->send(severity, full_filename, base_filename, line,
logmsgtime, message, message_len); logmsgtime, message, message_len);
@ -909,7 +918,7 @@ inline void LogDestination::LogToSinks(LogSeverity severity,
inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) {
ReaderMutexLock l(&sink_mutex_); ReaderMutexLock l(&sink_mutex_);
if (sinks_) { if (sinks_ != nullptr) {
for (size_t i = sinks_->size(); i-- > 0;) { for (size_t i = sinks_->size(); i-- > 0;) {
(*sinks_)[i]->WaitTillSent(); (*sinks_)[i]->WaitTillSent();
} }
@ -926,7 +935,7 @@ LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES];
inline LogDestination* LogDestination::log_destination(LogSeverity severity) { inline LogDestination* LogDestination::log_destination(LogSeverity severity) {
assert(severity >= 0 && severity < NUM_SEVERITIES); assert(severity >= 0 && severity < NUM_SEVERITIES);
if (!log_destinations_[severity]) { if (log_destinations_[severity] == nullptr) {
log_destinations_[severity] = new LogDestination(severity, nullptr); log_destinations_[severity] = new LogDestination(severity, nullptr);
} }
return log_destinations_[severity]; return log_destinations_[severity];
@ -976,7 +985,6 @@ LogFileObject::LogFileObject(LogSeverity severity, const char* base_filename)
: base_filename_selected_(base_filename != nullptr), : base_filename_selected_(base_filename != nullptr),
base_filename_((base_filename != nullptr) ? base_filename : ""), base_filename_((base_filename != nullptr) ? base_filename : ""),
symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()), symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()),
filename_extension_(),
severity_(severity), severity_(severity),
@ -1057,7 +1065,9 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) {
flags = flags | O_EXCL; flags = flags | O_EXCL;
} }
int fd = open(filename, flags, static_cast<mode_t>(FLAGS_logfile_mode)); int fd = open(filename, flags, static_cast<mode_t>(FLAGS_logfile_mode));
if (fd == -1) return false; if (fd == -1) {
return false;
}
#ifdef HAVE_FCNTL #ifdef HAVE_FCNTL
// Mark the file close-on-exec. We don't really care if this fails // Mark the file close-on-exec. We don't really care if this fails
fcntl(fd, F_SETFD, FD_CLOEXEC); fcntl(fd, F_SETFD, FD_CLOEXEC);
@ -1116,9 +1126,10 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) {
const string linkname = const string linkname =
symlink_basename_ + '.' + LogSeverityNames[severity_]; symlink_basename_ + '.' + LogSeverityNames[severity_];
string linkpath; string linkpath;
if (slash) if (slash != nullptr) {
linkpath = string( linkpath = string(
filename, static_cast<size_t>(slash - filename + 1)); // get dirname filename, static_cast<size_t>(slash - filename + 1)); // get dirname
}
linkpath += linkname; linkpath += linkname;
unlink(linkpath.c_str()); // delete old one if it exists unlink(linkpath.c_str()); // delete old one if it exists
@ -1128,7 +1139,7 @@ bool LogFileObject::CreateLogfile(const string& time_pid_string) {
// We must have unistd.h. // We must have unistd.h.
// Make the symlink be relative (in the same dir) so that if the // Make the symlink be relative (in the same dir) so that if the
// entire log directory gets relocated the link is still valid. // entire log directory gets relocated the link is still valid.
const char* linkdest = slash ? (slash + 1) : filename; const char* linkdest = slash != nullptr ? (slash + 1) : filename;
if (symlink(linkdest, linkpath.c_str()) != 0) { if (symlink(linkdest, linkpath.c_str()) != 0) {
// silently ignore failures // silently ignore failures
} }
@ -1158,7 +1169,9 @@ void LogFileObject::Write(bool force_flush, time_t timestamp,
} }
if (file_length_ >> 20U >= MaxLogSize() || PidHasChanged()) { if (file_length_ >> 20U >= MaxLogSize() || PidHasChanged()) {
if (file_ != nullptr) fclose(file_); if (file_ != nullptr) {
fclose(file_);
}
file_ = nullptr; file_ = nullptr;
file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0; file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0;
rollover_attempt_ = kRolloverAttemptFrequency - 1; rollover_attempt_ = kRolloverAttemptFrequency - 1;
@ -1169,7 +1182,9 @@ void LogFileObject::Write(bool force_flush, time_t timestamp,
// Try to rollover the log file every 32 log messages. The only time // Try to rollover the log file every 32 log messages. The only time
// this could matter would be when we have trouble creating the log // this could matter would be when we have trouble creating the log
// file. If that happens, we'll lose lots of log messages, of course! // file. If that happens, we'll lose lots of log messages, of course!
if (++rollover_attempt_ != kRolloverAttemptFrequency) return; if (++rollover_attempt_ != kRolloverAttemptFrequency) {
return;
}
rollover_attempt_ = 0; rollover_attempt_ = 0;
struct ::tm tm_time; struct ::tm tm_time;
@ -1217,7 +1232,9 @@ void LogFileObject::Write(bool force_flush, time_t timestamp,
// called after holding on to log_mutex. We don't want to // called after holding on to log_mutex. We don't want to
// attempt to hold on to the same mutex, and get into a // attempt to hold on to the same mutex, and get into a
// deadlock. Simply use a name like invalid-user. // deadlock. Simply use a name like invalid-user.
if (uidname.empty()) uidname = "invalid-user"; if (uidname.empty()) {
uidname = "invalid-user";
}
stripped_filename = stripped_filename + '.' + hostname + '.' + uidname + stripped_filename = stripped_filename + '.' + hostname + '.' + uidname +
".log." + LogSeverityNames[severity_] + '.'; ".log." + LogSeverityNames[severity_] + '.';
@ -1235,7 +1252,7 @@ void LogFileObject::Write(bool force_flush, time_t timestamp,
} }
} }
// If we never succeeded, we have to give up // If we never succeeded, we have to give up
if (success == false) { if (!success) {
perror("Could not create logging file"); perror("Could not create logging file");
fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!",
time_pid_string.c_str()); time_pid_string.c_str());
@ -1291,10 +1308,10 @@ void LogFileObject::Write(bool force_flush, time_t timestamp,
errno == ENOSPC) { // disk full, stop writing to disk errno == ENOSPC) { // disk full, stop writing to disk
stop_writing = true; // until the disk is stop_writing = true; // until the disk is
return; return;
} else {
file_length_ += message_len;
bytes_since_flush_ += message_len;
} }
file_length_ += message_len;
bytes_since_flush_ += message_len;
} else { } else {
if (CycleClock_Now() >= next_flush_time_) { if (CycleClock_Now() >= next_flush_time_) {
stop_writing = false; // check to see if disk has free space. stop_writing = false; // check to see if disk has free space.
@ -1389,7 +1406,7 @@ void LogCleaner::Run(bool base_filename_selected, const string& base_filename,
vector<string> LogCleaner::GetOverdueLogNames( vector<string> LogCleaner::GetOverdueLogNames(
string log_directory, unsigned int days, const string& base_filename, string log_directory, unsigned int days, const string& base_filename,
const string& filename_extension) const { const string& filename_extension) {
// The names of overdue logs. // The names of overdue logs.
vector<string> overdue_log_names; vector<string> overdue_log_names;
@ -1397,8 +1414,8 @@ vector<string> LogCleaner::GetOverdueLogNames(
DIR* dir; DIR* dir;
struct dirent* ent; struct dirent* ent;
if ((dir = opendir(log_directory.c_str()))) { if ((dir = opendir(log_directory.c_str())) != nullptr) {
while ((ent = readdir(dir))) { while ((ent = readdir(dir)) != nullptr) {
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
continue; continue;
} }
@ -1425,9 +1442,9 @@ vector<string> LogCleaner::GetOverdueLogNames(
return overdue_log_names; return overdue_log_names;
} }
bool LogCleaner::IsLogFromCurrentProject( bool LogCleaner::IsLogFromCurrentProject(const string& filepath,
const string& filepath, const string& base_filename, const string& base_filename,
const string& filename_extension) const { const string& filename_extension) {
// We should remove duplicated delimiters from `base_filename`, e.g., // We should remove duplicated delimiters from `base_filename`, e.g.,
// before: "/tmp//<base_filename>.<create_time>.<pid>" // before: "/tmp//<base_filename>.<create_time>.<pid>"
// after: "/tmp/<base_filename>.<create_time>.<pid>" // after: "/tmp/<base_filename>.<create_time>.<pid>"
@ -1513,7 +1530,7 @@ bool LogCleaner::IsLogFromCurrentProject(
} }
bool LogCleaner::IsLogLastModifiedOver(const string& filepath, bool LogCleaner::IsLogLastModifiedOver(const string& filepath,
unsigned int days) const { unsigned int days) {
// Try to get the last modified time of this file. // Try to get the last modified time of this file.
struct stat file_stat; struct stat file_stat;
@ -1783,7 +1800,7 @@ static time_t fatal_time;
static char fatal_message[256]; static char fatal_message[256];
void ReprintFatalMessage() { void ReprintFatalMessage() {
if (fatal_message[0]) { if (fatal_message[0] != 0) {
const size_t n = strlen(fatal_message); const size_t n = strlen(fatal_message);
if (!FLAGS_logtostderr) { if (!FLAGS_logtostderr) {
// Also write to stderr (don't color to avoid terminal checks) // Also write to stderr (don't color to avoid terminal checks)
@ -1868,7 +1885,7 @@ void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) {
if (!FLAGS_logtostderr && !FLAGS_logtostdout) { if (!FLAGS_logtostderr && !FLAGS_logtostdout) {
for (auto& log_destination : LogDestination::log_destinations_) { for (auto& log_destination : LogDestination::log_destinations_) {
if (log_destination) { if (log_destination != nullptr) {
log_destination->logger_->Write(true, 0, "", 0); log_destination->logger_->Write(true, 0, "", 0);
} }
} }
@ -2018,7 +2035,7 @@ int64 LogMessage::num_messages(int severity) {
// Output the COUNTER value. This is only valid if ostream is a // Output the COUNTER value. This is only valid if ostream is a
// LogStream. // LogStream.
ostream& operator<<(ostream& os, const PRIVATE_Counter&) { ostream& operator<<(ostream& os, const PRIVATE_Counter& /*unused*/) {
#ifdef DISABLE_RTTI #ifdef DISABLE_RTTI
LogMessage::LogStream* log = static_cast<LogMessage::LogStream*>(&os); LogMessage::LogStream* log = static_cast<LogMessage::LogStream*>(&os);
#else #else
@ -2218,7 +2235,7 @@ static inline void trim(std::string& s) {
static bool SendEmailInternal(const char* dest, const char* subject, static bool SendEmailInternal(const char* dest, const char* subject,
const char* body, bool use_logging) { const char* body, bool use_logging) {
#ifndef GLOG_OS_EMSCRIPTEN #ifndef GLOG_OS_EMSCRIPTEN
if (dest && *dest) { if ((dest != nullptr) && (*dest != 0)) {
// Split the comma-separated list of email addresses, validate each one and // Split the comma-separated list of email addresses, validate each one and
// build a sanitized new comma-separated string without whitespace. // build a sanitized new comma-separated string without whitespace.
std::istringstream ss(dest); std::istringstream ss(dest);
@ -2286,7 +2303,7 @@ static bool SendEmailInternal(const char* dest, const char* subject,
FILE* pipe = popen(cmd.c_str(), "w"); FILE* pipe = popen(cmd.c_str(), "w");
if (pipe != nullptr) { if (pipe != nullptr) {
// Add the body if we have one // Add the body if we have one
if (body) { if (body != nullptr) {
fwrite(body, sizeof(char), strlen(body), pipe); fwrite(body, sizeof(char), strlen(body), pipe);
} }
bool ok = pclose(pipe) != -1; bool ok = pclose(pipe) != -1;
@ -2300,12 +2317,11 @@ static bool SendEmailInternal(const char* dest, const char* subject,
} }
} }
return ok; return ok;
}
if (use_logging) {
LOG(ERROR) << "Unable to send mail to " << dest;
} else { } else {
if (use_logging) { fprintf(stderr, "Unable to send mail to %s\n", dest);
LOG(ERROR) << "Unable to send mail to " << dest;
} else {
fprintf(stderr, "Unable to send mail to %s\n", dest);
}
} }
} }
#else #else
@ -2350,8 +2366,10 @@ static void GetTempDirectories(vector<string>* list) {
"/tmp", "/tmp",
}; };
for (auto d : candidates) { for (const auto* d : candidates) {
if (!d) continue; // Empty env var if (d == nullptr) {
continue; // Empty env var
}
// Make sure we don't surprise anyone who's expecting a '/' // Make sure we don't surprise anyone who's expecting a '/'
string dstr = d; string dstr = d;
@ -2361,7 +2379,7 @@ static void GetTempDirectories(vector<string>* list) {
list->push_back(dstr); list->push_back(dstr);
struct stat statbuf; struct stat statbuf;
if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) { if ((stat(d, &statbuf) == 0) && S_ISDIR(statbuf.st_mode)) {
// We found a dir that exists - we're done. // We found a dir that exists - we're done.
return; return;
} }
@ -2415,7 +2433,7 @@ void GetExistingTempDirectories(vector<string>* list) {
while (i_dir != list->end()) { while (i_dir != list->end()) {
// zero arg to access means test for existence; no constant // zero arg to access means test for existence; no constant
// defined on windows // defined on windows
if (access(i_dir->c_str(), 0)) { if (access(i_dir->c_str(), 0) != 0) {
i_dir = list->erase(i_dir); i_dir = list->erase(i_dir);
} else { } else {
++i_dir; ++i_dir;
@ -2428,13 +2446,17 @@ void TruncateLogFile(const char* path, uint64 limit, uint64 keep) {
struct stat statbuf; struct stat statbuf;
const int kCopyBlockSize = 8 << 10; const int kCopyBlockSize = 8 << 10;
char copybuf[kCopyBlockSize]; char copybuf[kCopyBlockSize];
off_t read_offset, write_offset; off_t read_offset;
off_t write_offset;
// Don't follow symlinks unless they're our own fd symlinks in /proc // Don't follow symlinks unless they're our own fd symlinks in /proc
int flags = O_RDWR; int flags = O_RDWR;
// TODO(hamaji): Support other environments. // TODO(hamaji): Support other environments.
# ifdef GLOG_OS_LINUX # ifdef GLOG_OS_LINUX
const char* procfd_prefix = "/proc/self/fd/"; const char* procfd_prefix = "/proc/self/fd/";
if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW; if (static_cast<int>(strncmp(procfd_prefix, path, strlen(procfd_prefix)) !=
0) != 0) {
flags |= O_NOFOLLOW;
}
# endif # endif
int fd = open(path, flags); int fd = open(path, flags);
@ -2467,9 +2489,15 @@ void TruncateLogFile(const char* path, uint64 limit, uint64 keep) {
// See if the path refers to a regular file bigger than the // See if the path refers to a regular file bigger than the
// specified limit // specified limit
if (!S_ISREG(statbuf.st_mode)) goto out_close_fd; if (!S_ISREG(statbuf.st_mode)) {
if (statbuf.st_size <= static_cast<off_t>(limit)) goto out_close_fd; goto out_close_fd;
if (statbuf.st_size <= static_cast<off_t>(keep)) goto out_close_fd; }
if (statbuf.st_size <= static_cast<off_t>(limit)) {
goto out_close_fd;
}
if (statbuf.st_size <= static_cast<off_t>(keep)) {
goto out_close_fd;
}
// This log file is too large - we need to truncate it // This log file is too large - we need to truncate it
LOG(INFO) << "Truncating " << path << " to " << keep << " bytes"; LOG(INFO) << "Truncating " << path << " to " << keep << " bytes";
@ -2477,19 +2505,23 @@ void TruncateLogFile(const char* path, uint64 limit, uint64 keep) {
// Copy the last "keep" bytes of the file to the beginning of the file // Copy the last "keep" bytes of the file to the beginning of the file
read_offset = statbuf.st_size - static_cast<off_t>(keep); read_offset = statbuf.st_size - static_cast<off_t>(keep);
write_offset = 0; write_offset = 0;
ssize_t bytesin, bytesout; ssize_t bytesin;
ssize_t bytesout;
while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) { while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) {
bytesout = pwrite(fd, copybuf, static_cast<size_t>(bytesin), write_offset); bytesout = pwrite(fd, copybuf, static_cast<size_t>(bytesin), write_offset);
if (bytesout == -1) { if (bytesout == -1) {
PLOG(ERROR) << "Unable to write to " << path; PLOG(ERROR) << "Unable to write to " << path;
break; break;
} else if (bytesout != bytesin) { }
if (bytesout != bytesin) {
LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout; LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout;
} }
read_offset += bytesin; read_offset += bytesin;
write_offset += bytesout; write_offset += bytesout;
} }
if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path; if (bytesin == -1) {
PLOG(ERROR) << "Unable to read from " << path;
}
// Truncate the remainder of the file. If someone else writes to the // 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 // end of the file after our last read() above, we lose their latest
@ -2525,7 +2557,7 @@ void TruncateStdoutStderr() {
string* Check##func##expected##Impl(const char* s1, const char* s2, \ string* Check##func##expected##Impl(const char* s1, const char* s2, \
const char* names) { \ const char* names) { \
bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \ bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \
if (equal == expected) \ if (equal == (expected)) \
return nullptr; \ return nullptr; \
else { \ else { \
ostringstream ss; \ ostringstream ss; \
@ -2571,25 +2603,22 @@ int posix_strerror_r(int err, char* buf, size_t len) {
// If the function succeeded, we can use its exit code to determine the // If the function succeeded, we can use its exit code to determine the
// semantics implemented by glibc // semantics implemented by glibc
if (!rc) { if (rc == nullptr) {
return 0; return 0;
} else { } // GNU semantics detected
// GNU semantics detected if (rc == buf) {
if (rc == buf) { return 0;
return 0; }
} else { buf[0] = '\000';
buf[0] = '\000';
#if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || \ #if defined(GLOG_OS_MACOSX) || defined(GLOG_OS_FREEBSD) || \
defined(GLOG_OS_OPENBSD) defined(GLOG_OS_OPENBSD)
if (reinterpret_cast<intptr_t>(rc) < sys_nerr) { if (reinterpret_cast<intptr_t>(rc) < sys_nerr) {
// This means an error on MacOSX or FreeBSD. // This means an error on MacOSX or FreeBSD.
return -1; return -1;
}
#endif
strncat(buf, rc, len - 1);
return 0;
}
} }
#endif
strncat(buf, rc, len - 1);
return 0;
} }
string StrError(int err) { string StrError(int err) {
@ -2733,8 +2762,8 @@ void LogMessageTime::CalcGmtOffset() {
const long hour_secs = 3600; const long hour_secs = 3600;
// If the Daylight Saving Time(isDst) is active subtract an hour from the // If the Daylight Saving Time(isDst) is active subtract an hour from the
// current timestamp. // current timestamp.
gmtoffset_ = gmtoffset_ = static_cast<long int>(timestamp_ - gmt_sec +
static_cast<long int>(timestamp_ - gmt_sec + (isDst ? hour_secs : 0)); (isDst != 0 ? hour_secs : 0));
} }
} // namespace google } // namespace google

View File

@ -137,14 +137,30 @@ static void CheckFailure(int a, int b, const char* file, int line,
const char* msg); const char* msg);
static void BM_Check3(int n) { static void BM_Check3(int n) {
while (n-- > 0) { while (n-- > 0) {
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) {
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); CheckFailure(n, x, __FILE__, __LINE__, "n < x");
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); }
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) {
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); CheckFailure(n, x, __FILE__, __LINE__, "n < x");
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); }
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); if (n < x) {
if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); CheckFailure(n, x, __FILE__, __LINE__, "n < x");
}
if (n < x) {
CheckFailure(n, x, __FILE__, __LINE__, "n < x");
}
if (n < x) {
CheckFailure(n, x, __FILE__, __LINE__, "n < x");
}
if (n < x) {
CheckFailure(n, x, __FILE__, __LINE__, "n < x");
}
if (n < x) {
CheckFailure(n, x, __FILE__, __LINE__, "n < x");
}
if (n < x) {
CheckFailure(n, x, __FILE__, __LINE__, "n < x");
}
} }
} }
BENCHMARK(BM_Check3) BENCHMARK(BM_Check3)
@ -166,8 +182,8 @@ static void BM_Check2(int n) {
} }
BENCHMARK(BM_Check2) BENCHMARK(BM_Check2)
static void CheckFailure(int, int, const char* /* file */, int /* line */, static void CheckFailure(int /*unused*/, int /*unused*/, const char* /* file */,
const char* /* msg */) {} int /* line */, const char* /* msg */) {}
static void BM_logspeed(int n) { static void BM_logspeed(int n) {
while (n-- > 0) { while (n-- > 0) {
@ -969,8 +985,10 @@ static void TestOneTruncate(const char* path, uint64 limit, uint64 keep,
int fd; int fd;
CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600)); CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600));
const char *discardstr = "DISCARDME!", *keepstr = "KEEPME!"; const char* discardstr = "DISCARDME!";
const size_t discard_size = strlen(discardstr), keep_size = strlen(keepstr); const char* keepstr = "KEEPME!";
const size_t discard_size = strlen(discardstr);
const size_t keep_size = strlen(keepstr);
// Fill the file with the requested data; first discard data, then kept data // Fill the file with the requested data; first discard data, then kept data
size_t written = 0; size_t written = 0;
@ -1296,7 +1314,7 @@ class TestWaitingLogSink : public LogSink {
// Push it to Writer thread if we are the original logging thread. // Push it to Writer thread if we are the original logging thread.
// Note: Something like ThreadLocalLogSink is a better choice // Note: Something like ThreadLocalLogSink is a better choice
// to do thread-specific LogSink logic for real. // to do thread-specific LogSink logic for real.
if (pthread_equal(tid_, pthread_self())) { if (pthread_equal(tid_, pthread_self()) != 0) {
writer_.Buffer(ToString(severity, base_filename, line, logmsgtime, writer_.Buffer(ToString(severity, base_filename, line, logmsgtime,
message, message_len)); message, message_len));
} }
@ -1304,7 +1322,9 @@ class TestWaitingLogSink : public LogSink {
void WaitTillSent() override { void WaitTillSent() override {
// Wait for Writer thread if we are the original logging thread. // 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()) != 0) {
writer_.Wait();
}
} }
private: private:
@ -1495,10 +1515,10 @@ TEST(LogBacktraceAt, DoesBacktraceAtRightLineWhenEnabled) {
#endif // HAVE_LIB_GMOCK #endif // HAVE_LIB_GMOCK
struct UserDefinedClass { struct UserDefinedClass {
bool operator==(const UserDefinedClass&) const { return true; } bool operator==(const UserDefinedClass& /*unused*/) const { return true; }
}; };
inline ostream& operator<<(ostream& out, const UserDefinedClass&) { inline ostream& operator<<(ostream& out, const UserDefinedClass& /*unused*/) {
out << "OK"; out << "OK";
return out; return out;
} }

View File

@ -58,7 +58,6 @@
# include <sys/syscall.h> // for syscall() # include <sys/syscall.h> // for syscall()
#endif #endif
#ifdef HAVE_UNISTD_H #ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif #endif
#if (defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)) && \ #if (defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)) && \
@ -96,7 +95,9 @@ static bool DoRawLog(char** buf, size_t* size, const char* format, ...) {
va_start(ap, format); va_start(ap, format);
int n = std::vsnprintf(*buf, *size, format, ap); int n = std::vsnprintf(*buf, *size, format, ap);
va_end(ap); va_end(ap);
if (n < 0 || static_cast<size_t>(n) > *size) return false; if (n < 0 || static_cast<size_t>(n) > *size) {
return false;
}
*size -= static_cast<size_t>(n); *size -= static_cast<size_t>(n);
*buf += n; *buf += n;
return true; return true;
@ -113,7 +114,9 @@ inline static bool VADoRawLog(char** buf, size_t* size, const char* format,
#if defined(__GNUC__) #if defined(__GNUC__)
# pragma GCC diagnostic pop # pragma GCC diagnostic pop
#endif #endif
if (n < 0 || static_cast<size_t>(n) > *size) return false; if (n < 0 || static_cast<size_t>(n) > *size) {
return false;
}
*size -= static_cast<size_t>(n); *size -= static_cast<size_t>(n);
*buf += n; *buf += n;
return true; return true;
@ -125,11 +128,11 @@ 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) GLOG_ATTRIBUTE_FORMAT(printf, 4, 5)
void RawLog__(LogSeverity severity, const char* file, int line, void RawLog_(LogSeverity severity, const char* file, int line,
const char* format, ...) { const char* format, ...) {
if (!(FLAGS_logtostdout || FLAGS_logtostderr || if (!FLAGS_logtostdout && !FLAGS_logtostderr &&
severity >= FLAGS_stderrthreshold || FLAGS_alsologtostderr || severity < FLAGS_stderrthreshold && !FLAGS_alsologtostderr &&
!IsGoogleLoggingInitialized())) { IsGoogleLoggingInitialized()) {
return; // this stderr log message is suppressed return; // this stderr log message is suppressed
} }
// can't call localtime_r here: it can allocate // can't call localtime_r here: it can allocate

View File

@ -71,7 +71,7 @@ const struct {
{SIGTERM, "SIGTERM"}, {SIGTERM, "SIGTERM"},
}; };
static bool kFailureSignalHandlerInstalled = false; bool kFailureSignalHandlerInstalled = false;
#if !defined(GLOG_OS_WINDOWS) #if !defined(GLOG_OS_WINDOWS)
// Returns the program counter from signal context, nullptr if unknown. // Returns the program counter from signal context, nullptr if unknown.
@ -79,7 +79,7 @@ void* GetPC(void* ucontext_in_void) {
# if (defined(HAVE_UCONTEXT_H) || defined(HAVE_SYS_UCONTEXT_H)) && \ # if (defined(HAVE_UCONTEXT_H) || defined(HAVE_SYS_UCONTEXT_H)) && \
defined(PC_FROM_UCONTEXT) defined(PC_FROM_UCONTEXT)
if (ucontext_in_void != nullptr) { if (ucontext_in_void != nullptr) {
ucontext_t* context = reinterpret_cast<ucontext_t*>(ucontext_in_void); auto* context = reinterpret_cast<ucontext_t*>(ucontext_in_void);
return (void*)context->PC_FROM_UCONTEXT; return (void*)context->PC_FROM_UCONTEXT;
} }
# else # else
@ -192,7 +192,7 @@ void DumpSignalInfo(int signal_number, siginfo_t* siginfo) {
MinimalFormatter formatter(buf, sizeof(buf)); MinimalFormatter formatter(buf, sizeof(buf));
formatter.AppendString("*** "); formatter.AppendString("*** ");
if (signal_name) { if (signal_name != nullptr) {
formatter.AppendString(signal_name); formatter.AppendString(signal_name);
} else { } else {
// Use the signal number if the name is unknown. The signal name // Use the signal number if the name is unknown. The signal name
@ -270,7 +270,7 @@ void InvokeDefaultSignalHandler(int signal_number) {
// dumping stuff while another thread is doing it. Our policy is to let // dumping stuff while another thread is doing it. Our policy is to let
// the first thread dump stuff and let other threads wait. // the first thread dump stuff and let other threads wait.
// See also comments in FailureSignalHandler(). // See also comments in FailureSignalHandler().
static pthread_t* g_entered_thread_id_pointer = nullptr; pthread_t* g_entered_thread_id_pointer = nullptr;
// Dumps signal and stack frame information, and invokes the default // Dumps signal and stack frame information, and invokes the default
// signal handler once our job is done. // signal handler once our job is done.
@ -299,7 +299,7 @@ void FailureSignalHandler(int signal_number, siginfo_t* signal_info,
&my_thread_id); &my_thread_id);
if (old_thread_id_pointer != nullptr) { if (old_thread_id_pointer != nullptr) {
// We've already entered the signal handler. What should we do? // We've already entered the signal handler. What should we do?
if (pthread_equal(my_thread_id, *g_entered_thread_id_pointer)) { if (pthread_equal(my_thread_id, *g_entered_thread_id_pointer) != 0) {
// It looks the current thread is reentering the signal handler. // It looks the current thread is reentering the signal handler.
// Something must be going wrong (maybe we are reentering by another // Something must be going wrong (maybe we are reentering by another
// type of signal?). Kill ourself by the default signal handler. // type of signal?). Kill ourself by the default signal handler.

View File

@ -51,7 +51,7 @@ using namespace GFLAGS_NAMESPACE;
using namespace google; using namespace google;
static void* DieInThread(void*) { static void* DieInThread(void* /*unused*/) {
// We assume pthread_t is an integral number or a pointer, rather // We assume pthread_t is an integral number or a pointer, rather
// than a complex struct. In some environments, pthread_self() // than a complex struct. In some environments, pthread_self()
// returns an uint64 but in some other environments pthread_self() // returns an uint64 but in some other environments pthread_self()
@ -89,8 +89,9 @@ int main(int argc, char** argv) {
*a = 0; *a = 0;
} else if (command == "loop") { } else if (command == "loop") {
fprintf(stderr, "looping\n"); fprintf(stderr, "looping\n");
while (true) while (true) {
; ;
}
} else if (command == "die_in_thread") { } else if (command == "die_in_thread") {
# if defined(HAVE_PTHREAD) # if defined(HAVE_PTHREAD)
pthread_t thread; pthread_t thread;

View File

@ -55,20 +55,28 @@ static void** NextStackFrame(void** old_sp) {
if (STRICT_UNWINDING) { if (STRICT_UNWINDING) {
// With the stack growing downwards, older stack frame must be // With the stack growing downwards, older stack frame must be
// at a greater address that the current one. // at a greater address that the current one.
if (new_sp <= old_sp) return nullptr; if (new_sp <= old_sp) {
return nullptr;
}
// Assume stack frames larger than 100,000 bytes are bogus. // Assume stack frames larger than 100,000 bytes are bogus.
if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return nullptr; if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) {
return nullptr;
}
} else { } else {
// In the non-strict mode, allow discontiguous stack frames. // In the non-strict mode, allow discontiguous stack frames.
// (alternate-signal-stacks for example). // (alternate-signal-stacks for example).
if (new_sp == old_sp) return nullptr; if (new_sp == old_sp) {
return nullptr;
}
// And allow frames upto about 1MB. // And allow frames upto about 1MB.
if ((new_sp > old_sp) && if ((new_sp > old_sp) &&
((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) { ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) {
return nullptr; return nullptr;
} }
} }
if ((uintptr_t)new_sp & (sizeof(void*) - 1)) return nullptr; if ((uintptr_t)new_sp & (sizeof(void*) - 1)) {
return nullptr;
}
return new_sp; return new_sp;
} }
@ -102,7 +110,7 @@ int GetStackTrace(void** result, int max_depth, int skip_count) {
skip_count++; skip_count++;
int n = 0; int n = 0;
while (sp && n < max_depth) { while ((sp != nullptr) && n < max_depth) {
if (skip_count > 0) { if (skip_count > 0) {
skip_count--; skip_count--;
} else { } else {

View File

@ -123,7 +123,7 @@ static void CheckRetAddrIsInFunction(void* ret_addr,
# pragma clang diagnostic ignored "-Wgnu-label-as-value" # pragma clang diagnostic ignored "-Wgnu-label-as-value"
# endif # endif
void ATTRIBUTE_NOINLINE CheckStackTrace(int); void ATTRIBUTE_NOINLINE CheckStackTrace(int /*i*/);
static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf() { static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf() {
const int STACK_LEN = 10; const int STACK_LEN = 10;
void* stack[STACK_LEN]; void* stack[STACK_LEN];
@ -229,7 +229,7 @@ static
//-----------------------------------------------------------------------// //-----------------------------------------------------------------------//
int main(int, char** argv) { int main(int /*unused*/, char** argv) {
FLAGS_logtostderr = true; FLAGS_logtostderr = true;
InitGoogleLogging(argv[0]); InitGoogleLogging(argv[0]);

View File

@ -57,7 +57,9 @@ static void** NextStackFrame(void** old_sp) {
if (STRICT_UNWINDING) { if (STRICT_UNWINDING) {
// With the stack growing downwards, older stack frame must be // With the stack growing downwards, older stack frame must be
// at a greater address that the current one. // at a greater address that the current one.
if (new_sp <= old_sp) return nullptr; if (new_sp <= old_sp) {
return nullptr;
}
// Assume stack frames larger than 100,000 bytes are bogus. // Assume stack frames larger than 100,000 bytes are bogus.
if (reinterpret_cast<uintptr_t>(new_sp) - if (reinterpret_cast<uintptr_t>(new_sp) -
reinterpret_cast<uintptr_t>(old_sp) > reinterpret_cast<uintptr_t>(old_sp) >
@ -67,7 +69,9 @@ static void** NextStackFrame(void** old_sp) {
} else { } else {
// In the non-strict mode, allow discontiguous stack frames. // In the non-strict mode, allow discontiguous stack frames.
// (alternate-signal-stacks for example). // (alternate-signal-stacks for example).
if (new_sp == old_sp) return nullptr; if (new_sp == old_sp) {
return nullptr;
}
// And allow frames upto about 1MB. // And allow frames upto about 1MB.
if ((new_sp > old_sp) && (reinterpret_cast<uintptr_t>(new_sp) - if ((new_sp > old_sp) && (reinterpret_cast<uintptr_t>(new_sp) -
reinterpret_cast<uintptr_t>(old_sp) > reinterpret_cast<uintptr_t>(old_sp) >
@ -139,7 +143,7 @@ int GetStackTrace(void** result, int max_depth, int skip_count) {
#endif #endif
int n = 0; int n = 0;
while (sp && n < max_depth) { while ((sp != nullptr) && n < max_depth) {
if (*(sp + 1) == nullptr) { if (*(sp + 1) == nullptr) {
// In 64-bit code, we often see a frame that // In 64-bit code, we often see a frame that
// points to itself and has a return address of 0. // points to itself and has a return address of 0.

View File

@ -79,7 +79,9 @@ static void TestSTLLogging() {
string expected; string expected;
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
v.push_back(i); v.push_back(i);
if (i > 0) expected += ' '; if (i > 0) {
expected += ' ';
}
const size_t buf_size = 256; const size_t buf_size = 256;
char buf[buf_size]; char buf[buf_size];
std::snprintf(buf, buf_size, "%d", i); std::snprintf(buf, buf_size, "%d", i);
@ -107,7 +109,7 @@ static void TestSTLLogging() {
} }
} }
int main(int, char**) { int main(int /*unused*/, char** /*unused*/) {
TestSTLLogging(); TestSTLLogging();
std::cout << "PASS\n"; std::cout << "PASS\n";
return 0; return 0;

View File

@ -51,19 +51,18 @@ int CheckNoReturn(bool b) {
if (b) { if (b) {
LOG(FATAL) << "Fatal"; LOG(FATAL) << "Fatal";
return 0; // Workaround for MSVC warning C4715 return 0; // Workaround for MSVC warning C4715
} else {
return 0;
} }
return 0;
} }
struct A {}; struct A {};
std::ostream& operator<<(std::ostream& str, const A&) { return str; } std::ostream& operator<<(std::ostream& str, const A& /*unused*/) { return str; }
namespace { namespace {
void handle_abort(int /*code*/) { std::exit(EXIT_FAILURE); } void handle_abort(int /*code*/) { std::exit(EXIT_FAILURE); }
} // namespace } // namespace
int main(int, char* argv[]) { int main(int /*unused*/, char* argv[]) {
#if defined(_MSC_VER) #if defined(_MSC_VER)
// Avoid presenting an interactive dialog that will cause the test to time // Avoid presenting an interactive dialog that will cause the test to time
// out. // out.
@ -74,7 +73,7 @@ int main(int, char* argv[]) {
FLAGS_logtostderr = true; FLAGS_logtostderr = true;
InitGoogleLogging(argv[0]); InitGoogleLogging(argv[0]);
if (FLAGS_check_mode) { if (FLAGS_check_mode) {
printf("%s\n", DEBUG_MODE ? "dbg" : "opt"); printf("%s\n", DEBUG_MODE != 0U ? "dbg" : "opt");
return 0; return 0;
} }
LOG(INFO) << "TESTMESSAGE INFO"; LOG(INFO) << "TESTMESSAGE INFO";

View File

@ -264,7 +264,8 @@ bool GetSectionHeaderByName(int fd, const char* name, size_t name_len,
ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset); ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
if (n_read == -1) { if (n_read == -1) {
return false; return false;
} else if (static_cast<size_t>(n_read) != name_len) { }
if (static_cast<size_t>(n_read) != name_len) {
// Short read -- name could be at end of file. // Short read -- name could be at end of file.
continue; continue;
} }
@ -386,7 +387,7 @@ struct FileDescriptor {
close(fd_); close(fd_);
} }
} }
int get() { return fd_; } int get() const { return fd_; }
private: private:
FileDescriptor(const FileDescriptor&) = delete; FileDescriptor(const FileDescriptor&) = delete;
@ -613,7 +614,7 @@ static ATTRIBUTE_NOINLINE int OpenObjectFileContainingPcAndGetStartAddress(
} }
// Check start and end addresses. // Check start and end addresses.
if (!(start_address <= pc && pc < end_address)) { if (start_address > pc || pc >= end_address) {
continue; // We skip this map. PC isn't in this map. continue; // We skip this map. PC isn't in this map.
} }
@ -760,7 +761,7 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void* pc, char* out,
out[0] = '\0'; out[0] = '\0';
SafeAppendString("(", out, out_size); SafeAppendString("(", out, out_size);
if (g_symbolize_open_object_file_callback) { if (g_symbolize_open_object_file_callback != nullptr) {
object_fd = g_symbolize_open_object_file_callback( object_fd = g_symbolize_open_object_file_callback(
pc0, start_address, base_address, out + 1, out_size - 1); pc0, start_address, base_address, out + 1, out_size - 1);
} else { } else {
@ -776,7 +777,7 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void* pc, char* out,
// Check whether a file name was returned. // Check whether a file name was returned.
if (object_fd < 0) { if (object_fd < 0) {
# endif # endif
if (out[1]) { if (out[1] != 0) {
// The object file containing PC was determined successfully however the // The object file containing PC was determined successfully however the
// object file was not opened successfully. This is still considered // object file was not opened successfully. This is still considered
// success because the object file name and offset are known and tools // success because the object file name and offset are known and tools
@ -794,7 +795,7 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void* pc, char* out,
if (elf_type == -1) { if (elf_type == -1) {
return false; return false;
} }
if (g_symbolize_callback) { if (g_symbolize_callback != nullptr) {
// Run the call back if it's installed. // Run the call back if it's installed.
// Note: relocation (and much of the rest of this code) will be // Note: relocation (and much of the rest of this code) will be
// wrong for prelinked shared libraries and PIE executables. // wrong for prelinked shared libraries and PIE executables.
@ -808,7 +809,7 @@ static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void* pc, char* out,
} }
if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0, out, out_size, if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0, out, out_size,
base_address)) { base_address)) {
if (out[1] && !g_symbolize_callback) { if ((out[1] != 0) && (g_symbolize_callback == nullptr)) {
// The object file containing PC was opened successfully however the // The object file containing PC was opened successfully however the
// symbol was not found. The object may have been stripped. This is still // symbol was not found. The object may have been stripped. This is still
// considered success because the object file name and offset are known // considered success because the object file name and offset are known

View File

@ -66,9 +66,8 @@ static const char* TrySymbolize(void* pc) {
static char symbol[4096]; static char symbol[4096];
if (Symbolize(pc, symbol, sizeof(symbol))) { if (Symbolize(pc, symbol, sizeof(symbol))) {
return symbol; return symbol;
} else {
return nullptr;
} }
return nullptr;
} }
# endif # endif
@ -237,7 +236,8 @@ static const char* SymbolizeStackConsumption(void* pc, int* stack_consumed) {
// Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones). // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones).
struct sigaction sa; struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction)); memset(&sa, 0, sizeof(struct sigaction));
struct sigaction old_sa1, old_sa2; struct sigaction old_sa1;
struct sigaction old_sa2;
sigemptyset(&sa.sa_mask); sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_ONSTACK; sa.sa_flags = SA_ONSTACK;

View File

@ -90,7 +90,7 @@ using DebugWriter = void(const char*, void*);
// For some environments, add two extra bytes for the leading "0x". // For some environments, add two extra bytes for the leading "0x".
static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*); static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*);
static void DebugWriteToStderr(const char* data, void*) { static void DebugWriteToStderr(const char* data, void* /*unused*/) {
// This one is signal-safe. // This one is signal-safe.
if (write(STDERR_FILENO, data, strlen(data)) < 0) { if (write(STDERR_FILENO, data, strlen(data)) < 0) {
// Ignore errors. // Ignore errors.
@ -188,10 +188,8 @@ namespace glog_internal_namespace_ {
const char* ProgramInvocationShortName() { const char* ProgramInvocationShortName() {
if (g_program_invocation_short_name != nullptr) { if (g_program_invocation_short_name != nullptr) {
return g_program_invocation_short_name; return g_program_invocation_short_name;
} else { } // TODO(hamaji): Use /proc/self/cmdline and so?
// TODO(hamaji): Use /proc/self/cmdline and so? return "UNKNOWN";
return "UNKNOWN";
}
} }
#ifdef GLOG_OS_WINDOWS #ifdef GLOG_OS_WINDOWS
@ -304,7 +302,7 @@ const char* const_basename(const char* filepath) {
#ifdef GLOG_OS_WINDOWS // Look for either path separator in Windows #ifdef GLOG_OS_WINDOWS // Look for either path separator in Windows
if (!base) base = strrchr(filepath, '\\'); if (!base) base = strrchr(filepath, '\\');
#endif #endif
return base ? (base + 1) : filepath; return base != nullptr ? (base + 1) : filepath;
} }
static string g_my_user_name; static string g_my_user_name;
@ -325,7 +323,7 @@ static void MyUserNameInitializer() {
char buffer[1024] = {'\0'}; char buffer[1024] = {'\0'};
uid_t uid = geteuid(); uid_t uid = geteuid();
int pwuid_res = getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &result); int pwuid_res = getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &result);
if (pwuid_res == 0 && result) { if (pwuid_res == 0 && (result != nullptr)) {
g_my_user_name = pwd.pw_name; g_my_user_name = pwd.pw_name;
} else { } else {
std::snprintf(buffer, sizeof(buffer), "uid%d", uid); std::snprintf(buffer, sizeof(buffer), "uid%d", uid);
@ -361,7 +359,7 @@ void InitGoogleLoggingUtilities(const char* argv0) {
#ifdef GLOG_OS_WINDOWS #ifdef GLOG_OS_WINDOWS
if (!slash) slash = strrchr(argv0, '\\'); if (!slash) slash = strrchr(argv0, '\\');
#endif #endif
g_program_invocation_short_name = slash ? slash + 1 : argv0; g_program_invocation_short_name = slash != nullptr ? slash + 1 : argv0;
#ifdef HAVE_STACKTRACE #ifdef HAVE_STACKTRACE
InstallFailureFunction(&DumpStackTraceAndExit); InstallFailureFunction(&DumpStackTraceAndExit);

View File

@ -31,12 +31,12 @@
// //
// Define utilities for glog internal usage. // Define utilities for glog internal usage.
#ifndef UTILITIES_H__ #ifndef UTILITIES_H_
#define UTILITIES_H__ #define UTILITIES_H_
// printf macros for size_t, in the style of inttypes.h // printf macros for size_t, in the style of inttypes.h
#ifdef _LP64 #ifdef _LP64
# define __PRIS_PREFIX "z" # define PRIS_PREFIX "z"
#else #else
# define __PRIS_PREFIX # define __PRIS_PREFIX
#endif #endif
@ -234,4 +234,4 @@ void ShutdownGoogleLoggingUtilities();
using namespace google::glog_internal_namespace_; using namespace google::glog_internal_namespace_;
#endif // UTILITIES_H__ #endif // UTILITIES_H_

View File

@ -78,16 +78,24 @@ GLOG_EXPORT bool SafeFNMatch_(const char* pattern, size_t patt_len,
size_t p = 0; size_t p = 0;
size_t s = 0; size_t s = 0;
while (true) { while (true) {
if (p == patt_len && s == str_len) return true; if (p == patt_len && s == str_len) {
if (p == patt_len) return false; return true;
if (s == str_len) return p + 1 == patt_len && pattern[p] == '*'; }
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 (pattern[p] == str[s] || pattern[p] == '?') {
p += 1; p += 1;
s += 1; s += 1;
continue; continue;
} }
if (pattern[p] == '*') { if (pattern[p] == '*') {
if (p + 1 == patt_len) return true; if (p + 1 == patt_len) {
return true;
}
do { do {
if (SafeFNMatch_(pattern + (p + 1), patt_len - (p + 1), str + s, if (SafeFNMatch_(pattern + (p + 1), patt_len - (p + 1), str + s,
str_len - s)) { str_len - s)) {
@ -147,7 +155,7 @@ static void VLOG2Initializer() {
auto* info = new VModuleInfo; auto* info = new VModuleInfo;
info->module_pattern = pattern; info->module_pattern = pattern;
info->vlog_level = module_level; info->vlog_level = module_level;
if (head) { if (head != nullptr) {
tail->next = info; tail->next = info;
} else { } else {
head = info; head = info;
@ -156,10 +164,12 @@ static void VLOG2Initializer() {
} }
// Skip past this entry // Skip past this entry
vmodule = strchr(sep, ','); vmodule = strchr(sep, ',');
if (vmodule == nullptr) break; if (vmodule == nullptr) {
break;
}
vmodule++; // Skip past "," vmodule++; // Skip past ","
} }
if (head) { // Put them into the list at the head: if (head != nullptr) { // Put them into the list at the head:
tail->next = vmodule_list; tail->next = vmodule_list;
vmodule_list = head; vmodule_list = head;
} }
@ -200,7 +210,7 @@ int SetVLOGLevel(const char* module_pattern, int log_level) {
// We traverse the list fully because the pattern can match several items // We traverse the list fully because the pattern can match several items
// from the list. // from the list.
while (item) { while (item != nullptr) {
if (SafeFNMatch_(module_pattern, pattern_len, item->base_name, if (SafeFNMatch_(module_pattern, pattern_len, item->base_name,
item->base_len)) { item->base_len)) {
// Redirect the cached value to its module override. // Redirect the cached value to its module override.
@ -219,8 +229,8 @@ int SetVLOGLevel(const char* module_pattern, int log_level) {
// NOTE: Individual VLOG statements cache the integer log level pointers. // NOTE: Individual VLOG statements cache the integer log level pointers.
// NOTE: This function must not allocate memory or require any locks. // NOTE: This function must not allocate memory or require any locks.
bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, const char* fname, bool InitVLOG3_(SiteFlag* site_flag, int32* level_default, const char* fname,
int32 verbose_level) { int32 verbose_level) {
MutexLock l(&vmodule_lock); MutexLock l(&vmodule_lock);
bool read_vmodule_flag = inited_vmodule; bool read_vmodule_flag = inited_vmodule;
if (!read_vmodule_flag) { if (!read_vmodule_flag) {
@ -243,10 +253,10 @@ bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, const char* fname,
} }
#endif #endif
base = base ? (base + 1) : fname; base = base != nullptr ? (base + 1) : fname;
const char* base_end = strchr(base, '.'); const char* base_end = strchr(base, '.');
size_t base_length = size_t base_length =
base_end ? static_cast<size_t>(base_end - base) : strlen(base); base_end != nullptr ? static_cast<size_t>(base_end - base) : strlen(base);
// Trim out trailing "-inl" if any // 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)) {
@ -280,7 +290,7 @@ bool InitVLOG3__(SiteFlag* site_flag, int32* level_default, const char* fname,
// SetVModule is called afterwards with new modules. // SetVModule is called afterwards with new modules.
// The performance penalty here is neglible, because InitVLOG3__ is called // The performance penalty here is neglible, because InitVLOG3__ is called
// once per site. // once per site.
if (site_flag_value == level_default && !site_flag->base_name) { if (site_flag_value == level_default && (site_flag->base_name == nullptr)) {
site_flag->base_name = base; site_flag->base_name = base;
site_flag->base_len = base_length; site_flag->base_len = base_length;
site_flag->next = cached_site_list; site_flag->next = cached_site_list;

View File

@ -37,10 +37,10 @@
#include <cwchar> #include <cwchar>
/* Indicates that d_type field is available in dirent structure */ /* Indicates that d_type field is available in dirent structure */
#define _DIRENT_HAVE_D_TYPE #define DIRENT_HAVE_D_TYPE
/* Indicates that d_namlen field is available in dirent structure */ /* Indicates that d_namlen field is available in dirent structure */
#define _DIRENT_HAVE_D_NAMLEN #define DIRENT_HAVE_D_NAMLEN
/* Entries missing from MSVC 6.0 */ /* Entries missing from MSVC 6.0 */
#if !defined(FILE_ATTRIBUTE_DEVICE) #if !defined(FILE_ATTRIBUTE_DEVICE)
@ -206,10 +206,10 @@
#endif #endif
/* Return the exact length of the file name without zero terminator */ /* Return the exact length of the file name without zero terminator */
#define _D_EXACT_NAMLEN(p) ((p)->d_namlen) #define D_EXACT_NAMLEN(p) ((p)->d_namlen)
/* Return the maximum size of a file name */ /* 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 #ifdef __cplusplus
extern "C" { extern "C" {
@ -345,7 +345,7 @@ static _WDIR* _wopendir(const wchar_t* dirname) {
/* Allocate new _WDIR structure */ /* Allocate new _WDIR structure */
dirp = (_WDIR*)malloc(sizeof(struct _WDIR)); dirp = (_WDIR*)malloc(sizeof(struct _WDIR));
if (!dirp) { if (dirp == nullptr) {
return nullptr; return nullptr;
} }
@ -507,7 +507,7 @@ static int _wreaddir_r(_WDIR* dirp, struct _wdirent* entry,
*/ */
static int _wclosedir(_WDIR* dirp) { static int _wclosedir(_WDIR* dirp) {
int ok; int ok;
if (dirp) { if (dirp != nullptr) {
/* Release search handle */ /* Release search handle */
if (dirp->handle != INVALID_HANDLE_VALUE) { if (dirp->handle != INVALID_HANDLE_VALUE) {
FindClose(dirp->handle); FindClose(dirp->handle);
@ -533,7 +533,7 @@ static int _wclosedir(_WDIR* dirp) {
* file name again. * file name again.
*/ */
static void _wrewinddir(_WDIR* dirp) { static void _wrewinddir(_WDIR* dirp) {
if (dirp) { if (dirp != nullptr) {
/* Release existing search handle */ /* Release existing search handle */
if (dirp->handle != INVALID_HANDLE_VALUE) { if (dirp->handle != INVALID_HANDLE_VALUE) {
FindClose(dirp->handle); FindClose(dirp->handle);
@ -632,7 +632,7 @@ static DIR* opendir(const char* dirname) {
/* Allocate memory for DIR structure */ /* Allocate memory for DIR structure */
dirp = (DIR*)malloc(sizeof(struct DIR)); dirp = (DIR*)malloc(sizeof(struct DIR));
if (!dirp) { if (dirp == nullptr) {
return nullptr; return nullptr;
} }
{ {
@ -642,7 +642,7 @@ static DIR* opendir(const char* dirname) {
/* Convert directory name to wide-character string */ /* Convert directory name to wide-character string */
error = dirent_mbstowcs_s(&n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1); error = dirent_mbstowcs_s(&n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1);
if (error) { if (error != 0) {
/* /*
* Cannot convert file name to wide-character string. This * Cannot convert file name to wide-character string. This
* occurs if the string contains invalid multi-byte sequences or * occurs if the string contains invalid multi-byte sequences or
@ -654,7 +654,7 @@ static DIR* opendir(const char* dirname) {
/* Open directory stream using wide-character name */ /* Open directory stream using wide-character name */
dirp->wdirp = _wopendir(wname); dirp->wdirp = _wopendir(wname);
if (!dirp->wdirp) { if (dirp->wdirp == nullptr) {
goto exit_free; goto exit_free;
} }
} }
@ -718,7 +718,7 @@ static int readdir_r(DIR* dirp, struct dirent* entry, struct dirent** result) {
datap->cAlternateFileName, PATH_MAX + 1); datap->cAlternateFileName, PATH_MAX + 1);
} }
if (!error) { if (error == 0) {
DWORD attr; DWORD attr;
/* Length of file name excluding zero terminator */ /* Length of file name excluding zero terminator */
@ -771,7 +771,7 @@ static int readdir_r(DIR* dirp, struct dirent* entry, struct dirent** result) {
*/ */
static int closedir(DIR* dirp) { static int closedir(DIR* dirp) {
int ok; int ok;
if (dirp) { if (dirp != nullptr) {
/* Close wide-character directory stream */ /* Close wide-character directory stream */
ok = _wclosedir(dirp->wdirp); ok = _wclosedir(dirp->wdirp);
dirp->wdirp = nullptr; dirp->wdirp = nullptr;
@ -814,7 +814,7 @@ static int scandir(const char* dirname, struct dirent*** namelist,
/* Open directory stream */ /* Open directory stream */
dir = opendir(dirname); dir = opendir(dirname);
if (dir) { if (dir != nullptr) {
/* Read directory entries to memory */ /* Read directory entries to memory */
while (1) { while (1) {
/* Enlarge pointer table to make room for another pointer */ /* Enlarge pointer table to make room for another pointer */
@ -861,7 +861,7 @@ static int scandir(const char* dirname, struct dirent*** namelist,
int pass; int pass;
/* Determine whether to include the entry in result */ /* Determine whether to include the entry in result */
if (filter) { if (filter != nullptr) {
/* Let the filter function decide */ /* Let the filter function decide */
pass = filter(tmp); pass = filter(tmp);
} else { } else {
@ -869,7 +869,7 @@ static int scandir(const char* dirname, struct dirent*** namelist,
pass = 1; pass = 1;
} }
if (pass) { if (pass != 0) {
/* Store the temporary entry to pointer table */ /* Store the temporary entry to pointer table */
files[size++] = tmp; files[size++] = tmp;
tmp = nullptr; tmp = nullptr;
@ -913,12 +913,12 @@ static int scandir(const char* dirname, struct dirent*** namelist,
} }
/* Close directory stream */ /* Close directory stream */
if (dir) { if (dir != nullptr) {
closedir(dir); closedir(dir);
} }
/* Pass pointer table to caller */ /* Pass pointer table to caller */
if (namelist) { if (namelist != nullptr) {
*namelist = files; *namelist = files;
} }
return result; return result;
@ -953,9 +953,9 @@ static int dirent_mbstowcs_s(size_t* pReturnValue, wchar_t* wcstr,
/* Convert to wide-character string (or count characters) */ /* Convert to wide-character string (or count characters) */
n = mbstowcs(wcstr, mbstr, sizeInWords); n = mbstowcs(wcstr, mbstr, sizeInWords);
if (!wcstr || n < count) { if ((wcstr == nullptr) || n < count) {
/* Zero-terminate output buffer */ /* Zero-terminate output buffer */
if (wcstr && sizeInWords) { if ((wcstr != nullptr) && (sizeInWords != 0U)) {
if (n >= sizeInWords) { if (n >= sizeInWords) {
n = sizeInWords - 1; n = sizeInWords - 1;
} }
@ -963,7 +963,7 @@ static int dirent_mbstowcs_s(size_t* pReturnValue, wchar_t* wcstr,
} }
/* Length of resulting multi-byte string WITH zero terminator */ /* Length of resulting multi-byte string WITH zero terminator */
if (pReturnValue) { if (pReturnValue != nullptr) {
*pReturnValue = n + 1; *pReturnValue = n + 1;
} }
@ -997,9 +997,9 @@ static int dirent_wcstombs_s(size_t* pReturnValue, char* mbstr,
/* Convert to multi-byte string (or count the number of bytes needed) */ /* Convert to multi-byte string (or count the number of bytes needed) */
n = wcstombs(mbstr, wcstr, sizeInBytes); n = wcstombs(mbstr, wcstr, sizeInBytes);
if (!mbstr || n < count) { if ((mbstr == nullptr) || n < count) {
/* Zero-terminate output buffer */ /* Zero-terminate output buffer */
if (mbstr && sizeInBytes) { if ((mbstr != nullptr) && (sizeInBytes != 0U)) {
if (n >= sizeInBytes) { if (n >= sizeInBytes) {
n = sizeInBytes - 1; n = sizeInBytes - 1;
} }
@ -1007,7 +1007,7 @@ static int dirent_wcstombs_s(size_t* pReturnValue, char* mbstr,
} }
/* Length of resulting multi-bytes string WITH zero-terminator */ /* Length of resulting multi-bytes string WITH zero-terminator */
if (pReturnValue) { if (pReturnValue != nullptr) {
*pReturnValue = n + 1; *pReturnValue = n + 1;
} }