log-utils.cc 8.54 KB
Newer Older
1
// Copyright 2009 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/logging/log-utils.h"
6

7 8 9 10
#include <atomic>
#include <memory>

#include "src/base/platform/mutex.h"
11
#include "src/base/platform/platform.h"
12
#include "src/base/strings.h"
13
#include "src/base/vector.h"
14
#include "src/common/assert-scope.h"
15
#include "src/objects/objects-inl.h"
16
#include "src/strings/string-stream.h"
17
#include "src/utils/version.h"
18 19 20 21

namespace v8 {
namespace internal {

22
const char* const Log::kLogToTemporaryFile = "+";
23
const char* const Log::kLogToConsole = "-";
24

25
// static
26
FILE* Log::CreateOutputHandle(std::string file_name) {
27
  // If we're logging anything, we need to open the log file.
28
  if (!FLAG_log) {
29
    return nullptr;
30
  } else if (Log::IsLoggingToConsole(file_name)) {
31
    return stdout;
32
  } else if (Log::IsLoggingToTemporaryFile(file_name)) {
33 34
    return base::OS::OpenTemporaryFile();
  } else {
35
    return base::OS::FOpen(file_name.c_str(), base::OS::LogFileOpenMode);
36 37
  }
}
38

39 40 41 42 43 44 45 46 47 48
// static
bool Log::IsLoggingToConsole(std::string file_name) {
  return file_name.compare(Log::kLogToConsole) == 0;
}

// static
bool Log::IsLoggingToTemporaryFile(std::string file_name) {
  return file_name.compare(Log::kLogToTemporaryFile) == 0;
}

49 50 51
Log::Log(Logger* logger, std::string file_name)
    : logger_(logger),
      file_name_(file_name),
52
      output_handle_(Log::CreateOutputHandle(file_name)),
53
      os_(output_handle_ == nullptr ? stdout : output_handle_),
54
      format_buffer_(NewArray<char>(kMessageBufferSize)) {
55
  if (output_handle_) WriteLogHeader();
56 57 58
}

void Log::WriteLogHeader() {
59
  Log::MessageBuilder msg(this);
60 61 62 63 64 65
  LogSeparator kNext = LogSeparator::kSeparator;
  msg << "v8-version" << kNext << Version::GetMajor() << kNext
      << Version::GetMinor() << kNext << Version::GetBuild() << kNext
      << Version::GetPatch();
  if (strlen(Version::GetEmbedder()) != 0) {
    msg << kNext << Version::GetEmbedder();
66
  }
67 68
  msg << kNext << Version::IsCandidate();
  msg.WriteToLogFile();
69 70
}

71
std::unique_ptr<Log::MessageBuilder> Log::NewMessageBuilder() {
72
  // Fast check of is_logging() without taking the lock. Bail out immediately if
73
  // logging isn't enabled.
74
  if (!logger_->is_logging()) return {};
75

76 77
  std::unique_ptr<Log::MessageBuilder> result(new Log::MessageBuilder(this));

78
  // The first invocation of is_logging() might still read an old value. It is
79
  // fine if a background thread starts logging a bit later, but we want to
80 81
  // avoid background threads continue logging after logging was already closed.
  if (!logger_->is_logging()) return {};
82
  DCHECK_NOT_NULL(format_buffer_.get());
83 84 85 86

  return result;
}

87
FILE* Log::Close() {
88 89
  FILE* result = nullptr;
  if (output_handle_ != nullptr) {
90 91
    fflush(output_handle_);
    result = output_handle_;
92
  }
93
  output_handle_ = nullptr;
94
  format_buffer_.reset();
95
  return result;
96 97
}

98 99
std::string Log::file_name() const { return file_name_; }

100 101
Log::MessageBuilder::MessageBuilder(Log* log)
    : log_(log), lock_guard_(&log_->mutex_) {
102 103
}

104
void Log::MessageBuilder::AppendString(String str,
105
                                       base::Optional<int> length_limit) {
106
  if (str.is_null()) return;
107

108
  DisallowGarbageCollection no_gc;  // Ensure string stays valid.
109
  int length = str.length();
110 111
  if (length_limit) length = std::min(length, *length_limit);
  for (int i = 0; i < length; i++) {
112
    uint16_t c = str.Get(i);
113 114 115 116 117 118 119 120 121
    if (c <= 0xFF) {
      AppendCharacter(static_cast<char>(c));
    } else {
      // Escape non-ascii characters.
      AppendRawFormatString("\\u%04x", c & 0xFFFF);
    }
  }
}

122
void Log::MessageBuilder::AppendString(base::Vector<const char> str) {
123 124 125 126 127 128 129 130
  for (auto i = str.begin(); i < str.end(); i++) AppendCharacter(*i);
}

void Log::MessageBuilder::AppendString(const char* str) {
  if (str == nullptr) return;
  AppendString(str, strlen(str));
}

131 132
void Log::MessageBuilder::AppendString(const char* str, size_t length,
                                       bool is_one_byte) {
133
  if (str == nullptr) return;
134 135 136 137 138 139 140 141 142 143
  if (is_one_byte) {
    for (size_t i = 0; i < length; i++) {
      DCHECK_IMPLIES(is_one_byte, str[i] != '\0');
      AppendCharacter(str[i]);
    }
  } else {
    DCHECK_EQ(length % 2, 0);
    for (size_t i = 0; i + 1 < length; i += 2) {
      AppendTwoByteCharacter(str[i], str[i + 1]);
    }
144 145
  }
}
146

147
void Log::MessageBuilder::AppendFormatString(const char* format, ...) {
148 149
  va_list args;
  va_start(args, format);
150
  const int length = FormatStringIntoBuffer(format, args);
151
  va_end(args);
152 153 154 155
  for (int i = 0; i < length; i++) {
    DCHECK_NE(log_->format_buffer_[i], '\0');
    AppendCharacter(log_->format_buffer_[i]);
  }
156 157
}

158 159 160 161 162 163 164 165
void Log::MessageBuilder::AppendTwoByteCharacter(char c1, char c2) {
  if (c2 == 0) {
    AppendCharacter(c1);
  } else {
    // Escape non-printable characters.
    AppendRawFormatString("\\u%02x%02x", c1 & 0xFF, c2 & 0xFF);
  }
}
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
void Log::MessageBuilder::AppendCharacter(char c) {
  if (c >= 32 && c <= 126) {
    if (c == ',') {
      // Escape commas to avoid adding column separators.
      AppendRawFormatString("\\x2C");
    } else if (c == '\\') {
      AppendRawFormatString("\\\\");
    } else {
      // Safe, printable ascii character.
      AppendRawCharacter(c);
    }
  } else if (c == '\n') {
    // Escape newlines to avoid adding row separators.
    AppendRawFormatString("\\n");
  } else {
    // Escape non-printable characters.
    AppendRawFormatString("\\x%02x", c & 0xFF);
  }
184 185
}

186 187
void Log::MessageBuilder::AppendSymbolName(Symbol symbol) {
  DCHECK(!symbol.is_null());
188 189
  OFStream& os = log_->os_;
  os << "symbol(";
190
  if (!symbol.description().IsUndefined()) {
191
    os << "\"";
192
    AppendSymbolNameDetails(String::cast(symbol.description()), false);
193
    os << "\" ";
194
  }
195
  os << "hash " << std::hex << symbol.hash() << std::dec << ")";
196 197
}

198
void Log::MessageBuilder::AppendSymbolNameDetails(String str,
199
                                                  bool show_impl_info) {
200
  if (str.is_null()) return;
201

202
  DisallowGarbageCollection no_gc;  // Ensure string stays valid.
203
  OFStream& os = log_->os_;
204
  int limit = str.length();
205
  if (limit > 0x1000) limit = 0x1000;
206
  if (show_impl_info) {
207
    os << (str.IsOneByteRepresentation() ? 'a' : '2');
208 209
    if (StringShape(str).IsExternal()) os << 'e';
    if (StringShape(str).IsInternalized()) os << '#';
210
    os << ':' << str.length() << ':';
211
  }
212
  AppendString(str, limit);
213 214
}

215 216
int Log::MessageBuilder::FormatStringIntoBuffer(const char* format,
                                                va_list args) {
217
  base::Vector<char> buf(log_->format_buffer_.get(), Log::kMessageBufferSize);
218
  int length = base::VSNPrintF(buf, format, args);
219 220 221 222 223
  // |length| is -1 if output was truncated.
  if (length == -1) length = Log::kMessageBufferSize;
  DCHECK_LE(length, Log::kMessageBufferSize);
  DCHECK_GE(length, 0);
  return length;
224 225
}

226 227 228 229 230 231 232 233
void Log::MessageBuilder::AppendRawFormatString(const char* format, ...) {
  va_list args;
  va_start(args, format);
  const int length = FormatStringIntoBuffer(format, args);
  va_end(args);
  for (int i = 0; i < length; i++) {
    DCHECK_NE(log_->format_buffer_[i], '\0');
    AppendRawCharacter(log_->format_buffer_[i]);
234 235 236
  }
}

237
void Log::MessageBuilder::AppendRawCharacter(char c) { log_->os_ << c; }
238

239 240 241
void Log::MessageBuilder::WriteToLogFile() {
  log_->os_ << std::endl;
}
242

243 244 245 246 247 248 249
template <>
Log::MessageBuilder& Log::MessageBuilder::operator<<<const char*>(
    const char* string) {
  this->AppendString(string);
  return *this;
}

250 251 252 253 254 255 256 257 258
template <>
Log::MessageBuilder& Log::MessageBuilder::operator<<<void*>(void* pointer) {
  OFStream& os = log_->os_;
  // Manually format the pointer since on Windows we do not consistently
  // get a "0x" prefix.
  os << "0x" << std::hex << reinterpret_cast<intptr_t>(pointer) << std::dec;
  return *this;
}

259 260 261 262 263 264 265
template <>
Log::MessageBuilder& Log::MessageBuilder::operator<<<char>(char c) {
  this->AppendCharacter(c);
  return *this;
}

template <>
266
Log::MessageBuilder& Log::MessageBuilder::operator<<<String>(String string) {
267 268 269 270 271
  this->AppendString(string);
  return *this;
}

template <>
272
Log::MessageBuilder& Log::MessageBuilder::operator<<<Symbol>(Symbol symbol) {
273 274 275 276 277
  this->AppendSymbolName(symbol);
  return *this;
}

template <>
278
Log::MessageBuilder& Log::MessageBuilder::operator<<<Name>(Name name) {
279
  if (name.IsString()) {
280 281 282 283 284 285 286 287 288 289
    this->AppendString(String::cast(name));
  } else {
    this->AppendSymbolName(Symbol::cast(name));
  }
  return *this;
}

template <>
Log::MessageBuilder& Log::MessageBuilder::operator<<<LogSeparator>(
    LogSeparator separator) {
290 291
  // Skip escaping to create a new column.
  this->AppendRawCharacter(',');
292 293 294
  return *this;
}

295 296
}  // namespace internal
}  // namespace v8