Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "third_party/libjingle/overrides/talk/base/logging.h"
      6 
      7 #if defined(OS_MACOSX) && !defined(OS_IOS)
      8 #include <CoreServices/CoreServices.h>
      9 #endif  // OS_MACOSX
     10 
     11 #include <iomanip>
     12 
     13 #include "base/atomicops.h"
     14 #include "base/strings/string_util.h"
     15 #include "base/threading/platform_thread.h"
     16 #include "third_party/libjingle/source/talk/base/ipaddress.h"
     17 #include "third_party/libjingle/source/talk/base/stream.h"
     18 #include "third_party/libjingle/source/talk/base/stringencode.h"
     19 #include "third_party/libjingle/source/talk/base/stringutils.h"
     20 #include "third_party/libjingle/source/talk/base/timeutils.h"
     21 
     22 // From this file we can't use VLOG since it expands into usage of the __FILE__
     23 // macro (for correct filtering). The actual logging call from DIAGNOSTIC_LOG in
     24 // ~DiagnosticLogMessage. Note that the second parameter to the LAZY_STREAM
     25 // macro is true since the filter check has already been done for
     26 // DIAGNOSTIC_LOG.
     27 #define LOG_LAZY_STREAM_DIRECT(file_name, line_number, sev) \
     28   LAZY_STREAM(logging::LogMessage(file_name, line_number, \
     29                                   -sev).stream(), true)
     30 
     31 namespace talk_base {
     32 
     33 void (*g_logging_delegate_function)(const std::string&) = NULL;
     34 void (*g_extra_logging_init_function)(
     35     void (*logging_delegate_function)(const std::string&)) = NULL;
     36 #ifndef NDEBUG
     37 COMPILE_ASSERT(sizeof(base::subtle::Atomic32) == sizeof(base::PlatformThreadId),
     38                atomic32_not_same_size_as_platformthreadid);
     39 base::subtle::Atomic32 g_init_logging_delegate_thread_id = 0;
     40 #endif
     41 
     42 /////////////////////////////////////////////////////////////////////////////
     43 // Constant Labels
     44 /////////////////////////////////////////////////////////////////////////////
     45 
     46 const char* FindLabel(int value, const ConstantLabel entries[]) {
     47   for (int i = 0; entries[i].label; ++i) {
     48     if (value == entries[i].value) return entries[i].label;
     49   }
     50   return 0;
     51 }
     52 
     53 std::string ErrorName(int err, const ConstantLabel* err_table) {
     54   if (err == 0)
     55     return "No error";
     56 
     57   if (err_table != 0) {
     58     if (const char * value = FindLabel(err, err_table))
     59       return value;
     60   }
     61 
     62   char buffer[16];
     63   base::snprintf(buffer, sizeof(buffer), "0x%08x", err);
     64   return buffer;
     65 }
     66 
     67 /////////////////////////////////////////////////////////////////////////////
     68 // Log helper functions
     69 /////////////////////////////////////////////////////////////////////////////
     70 
     71 // Generates extra information for LOG_E.
     72 static std::string GenerateExtra(LogErrorContext err_ctx,
     73                                  int err,
     74                                  const char* module) {
     75   if (err_ctx != ERRCTX_NONE) {
     76     std::ostringstream tmp;
     77     tmp << ": ";
     78     tmp << "[0x" << std::setfill('0') << std::hex << std::setw(8) << err << "]";
     79     switch (err_ctx) {
     80       case ERRCTX_ERRNO:
     81         tmp << " " << strerror(err);
     82         break;
     83 #if defined(OS_WIN)
     84       case ERRCTX_HRESULT: {
     85         char msgbuf[256];
     86         DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
     87         HMODULE hmod = GetModuleHandleA(module);
     88         if (hmod)
     89           flags |= FORMAT_MESSAGE_FROM_HMODULE;
     90         if (DWORD len = FormatMessageA(
     91             flags, hmod, err,
     92             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
     93             msgbuf, sizeof(msgbuf) / sizeof(msgbuf[0]), NULL)) {
     94           while ((len > 0) &&
     95               isspace(static_cast<unsigned char>(msgbuf[len-1]))) {
     96             msgbuf[--len] = 0;
     97           }
     98           tmp << " " << msgbuf;
     99         }
    100         break;
    101       }
    102 #endif  // OS_WIN
    103 #if defined(OS_IOS)
    104       case ERRCTX_OSSTATUS:
    105         tmp << " " << "Unknown LibJingle error: " << err;
    106         break;
    107 #elif defined(OS_MACOSX)
    108       case ERRCTX_OSSTATUS: {
    109         tmp << " " << nonnull(GetMacOSStatusErrorString(err), "Unknown error");
    110         if (const char* desc = GetMacOSStatusCommentString(err)) {
    111           tmp << ": " << desc;
    112         }
    113         break;
    114       }
    115 #endif  // OS_MACOSX
    116       default:
    117         break;
    118     }
    119     return tmp.str();
    120   }
    121   return "";
    122 }
    123 
    124 DiagnosticLogMessage::DiagnosticLogMessage(const char* file,
    125                                            int line,
    126                                            LoggingSeverity severity,
    127                                            bool log_to_chrome,
    128                                            LogErrorContext err_ctx,
    129                                            int err)
    130     : file_name_(file),
    131       line_(line),
    132       severity_(severity),
    133       log_to_chrome_(log_to_chrome) {
    134   extra_ = GenerateExtra(err_ctx, err, NULL);
    135   CreateTimestamp();
    136 }
    137 
    138 DiagnosticLogMessage::DiagnosticLogMessage(const char* file,
    139                                            int line,
    140                                            LoggingSeverity severity,
    141                                            bool log_to_chrome,
    142                                            LogErrorContext err_ctx,
    143                                            int err,
    144                                            const char* module)
    145     : file_name_(file),
    146       line_(line),
    147       severity_(severity),
    148       log_to_chrome_(log_to_chrome) {
    149   extra_ = GenerateExtra(err_ctx, err, module);
    150   CreateTimestamp();
    151 }
    152 
    153 DiagnosticLogMessage::~DiagnosticLogMessage() {
    154   print_stream_ << extra_;
    155   const std::string& str = print_stream_.str();
    156   if (log_to_chrome_)
    157     LOG_LAZY_STREAM_DIRECT(file_name_, line_, severity_) << str;
    158   if (g_logging_delegate_function && severity_ <= LS_INFO) {
    159     print_stream_with_timestamp_ << str;
    160     g_logging_delegate_function(print_stream_with_timestamp_.str());
    161   }
    162 }
    163 
    164 void DiagnosticLogMessage::CreateTimestamp() {
    165 #if !defined(ANDROID)
    166   static const uint32 g_logging_start_time = talk_base::Time();
    167   uint32 time = talk_base::TimeSince(g_logging_start_time);
    168   print_stream_with_timestamp_ << "[" << std::setfill('0')
    169                                << std::setw(3) << (time / 1000)
    170                                << ":" << std::setw(3) << (time % 1000)
    171                                << std::setfill(' ') << "] ";
    172 #endif
    173 }
    174 
    175 // Note: this function is a copy from the overriden libjingle implementation.
    176 void LogMultiline(LoggingSeverity level, const char* label, bool input,
    177                   const void* data, size_t len, bool hex_mode,
    178                   LogMultilineState* state) {
    179   if (!LOG_CHECK_LEVEL_V(level))
    180     return;
    181 
    182   const char * direction = (input ? " << " : " >> ");
    183 
    184   // NULL data means to flush our count of unprintable characters.
    185   if (!data) {
    186     if (state && state->unprintable_count_[input]) {
    187       LOG_V(level) << label << direction << "## "
    188                    << state->unprintable_count_[input]
    189                    << " consecutive unprintable ##";
    190       state->unprintable_count_[input] = 0;
    191     }
    192     return;
    193   }
    194 
    195   // The ctype classification functions want unsigned chars.
    196   const unsigned char* udata = static_cast<const unsigned char*>(data);
    197 
    198   if (hex_mode) {
    199     const size_t LINE_SIZE = 24;
    200     char hex_line[LINE_SIZE * 9 / 4 + 2], asc_line[LINE_SIZE + 1];
    201     while (len > 0) {
    202       memset(asc_line, ' ', sizeof(asc_line));
    203       memset(hex_line, ' ', sizeof(hex_line));
    204       size_t line_len = _min(len, LINE_SIZE);
    205       for (size_t i = 0; i < line_len; ++i) {
    206         unsigned char ch = udata[i];
    207         asc_line[i] = isprint(ch) ? ch : '.';
    208         hex_line[i*2 + i/4] = hex_encode(ch >> 4);
    209         hex_line[i*2 + i/4 + 1] = hex_encode(ch & 0xf);
    210       }
    211       asc_line[sizeof(asc_line)-1] = 0;
    212       hex_line[sizeof(hex_line)-1] = 0;
    213       LOG_V(level) << label << direction
    214                    << asc_line << " " << hex_line << " ";
    215       udata += line_len;
    216       len -= line_len;
    217     }
    218     return;
    219   }
    220 
    221   size_t consecutive_unprintable = state ? state->unprintable_count_[input] : 0;
    222 
    223   const unsigned char* end = udata + len;
    224   while (udata < end) {
    225     const unsigned char* line = udata;
    226     const unsigned char* end_of_line = strchrn<unsigned char>(udata,
    227                                                               end - udata,
    228                                                               '\n');
    229     if (!end_of_line) {
    230       udata = end_of_line = end;
    231     } else {
    232       udata = end_of_line + 1;
    233     }
    234 
    235     bool is_printable = true;
    236 
    237     // If we are in unprintable mode, we need to see a line of at least
    238     // kMinPrintableLine characters before we'll switch back.
    239     const ptrdiff_t kMinPrintableLine = 4;
    240     if (consecutive_unprintable && ((end_of_line - line) < kMinPrintableLine)) {
    241       is_printable = false;
    242     } else {
    243       // Determine if the line contains only whitespace and printable
    244       // characters.
    245       bool is_entirely_whitespace = true;
    246       for (const unsigned char* pos = line; pos < end_of_line; ++pos) {
    247         if (isspace(*pos))
    248           continue;
    249         is_entirely_whitespace = false;
    250         if (!isprint(*pos)) {
    251           is_printable = false;
    252           break;
    253         }
    254       }
    255       // Treat an empty line following unprintable data as unprintable.
    256       if (consecutive_unprintable && is_entirely_whitespace) {
    257         is_printable = false;
    258       }
    259     }
    260     if (!is_printable) {
    261       consecutive_unprintable += (udata - line);
    262       continue;
    263     }
    264     // Print out the current line, but prefix with a count of prior unprintable
    265     // characters.
    266     if (consecutive_unprintable) {
    267       LOG_V(level) << label << direction << "## " << consecutive_unprintable
    268                   << " consecutive unprintable ##";
    269       consecutive_unprintable = 0;
    270     }
    271     // Strip off trailing whitespace.
    272     while ((end_of_line > line) && isspace(*(end_of_line-1))) {
    273       --end_of_line;
    274     }
    275     // Filter out any private data
    276     std::string substr(reinterpret_cast<const char*>(line), end_of_line - line);
    277     std::string::size_type pos_private = substr.find("Email");
    278     if (pos_private == std::string::npos) {
    279       pos_private = substr.find("Passwd");
    280     }
    281     if (pos_private == std::string::npos) {
    282       LOG_V(level) << label << direction << substr;
    283     } else {
    284       LOG_V(level) << label << direction << "## omitted for privacy ##";
    285     }
    286   }
    287 
    288   if (state) {
    289     state->unprintable_count_[input] = consecutive_unprintable;
    290   }
    291 }
    292 
    293 void InitDiagnosticLoggingDelegateFunction(
    294     void (*delegate)(const std::string&)) {
    295 #ifndef NDEBUG
    296   // Ensure that this function is always called from the same thread.
    297   base::subtle::NoBarrier_CompareAndSwap(&g_init_logging_delegate_thread_id, 0,
    298       static_cast<base::subtle::Atomic32>(base::PlatformThread::CurrentId()));
    299   DCHECK_EQ(g_init_logging_delegate_thread_id,
    300             base::PlatformThread::CurrentId());
    301 #endif
    302   CHECK(delegate);
    303   // This function may be called with the same argument several times if the
    304   // page is reloaded or there are several PeerConnections on one page with
    305   // logging enabled. This is OK, we simply don't have to do anything.
    306   if (delegate == g_logging_delegate_function)
    307     return;
    308   CHECK(!g_logging_delegate_function);
    309 #ifdef NDEBUG
    310   IPAddress::set_strip_sensitive(true);
    311 #endif
    312   g_logging_delegate_function = delegate;
    313 
    314   if (g_extra_logging_init_function)
    315     g_extra_logging_init_function(delegate);
    316 }
    317 
    318 void SetExtraLoggingInit(
    319     void (*function)(void (*delegate)(const std::string&))) {
    320   CHECK(function);
    321   CHECK(!g_extra_logging_init_function);
    322   g_extra_logging_init_function = function;
    323 }
    324 
    325 }  // namespace talk_base
    326