Reland "[logging] Use OFStream for log events"

This is a reland of 06ff9e974a
Original change's description:
> [logging] Use OFStream for log events
> 
> This simplifies a few operations and removes the size limitations
> implied by the message buffer used.
> 
> Change-Id: I8b873a0ffa399a037ff5c2501ba4b68158810968
> Reviewed-on: https://chromium-review.googlesource.com/724285
> Commit-Queue: Camillo Bruni <cbruni@chromium.org>
> Reviewed-by: Adam Klein <adamk@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#48766}

Change-Id: Iafda1c88d9180d188d6b8bd7d03d6d27100538d8
Reviewed-on: https://chromium-review.googlesource.com/731107
Commit-Queue: Camillo Bruni <cbruni@chromium.org>
Reviewed-by: Adam Klein <adamk@chromium.org>
Cr-Commit-Position: refs/heads/master@{#48804}
This commit is contained in:
Camillo Bruni 2017-10-20 15:07:50 -07:00 committed by Commit Bot
parent 73109dd966
commit 761b4719d3
5 changed files with 359 additions and 417 deletions

View File

@ -18,15 +18,26 @@ namespace internal {
const char* const Log::kLogToTemporaryFile = "&";
const char* const Log::kLogToConsole = "-";
Log::Log(Logger* logger)
// static
FILE* Log::CreateOutputHandle(const char* file_name) {
// If we're logging anything, we need to open the log file.
if (!Log::InitLogAtStart()) {
return nullptr;
} else if (strcmp(file_name, kLogToConsole) == 0) {
return stdout;
} else if (strcmp(file_name, kLogToTemporaryFile) == 0) {
return base::OS::OpenTemporaryFile();
} else {
return base::OS::FOpen(file_name, base::OS::LogFileOpenMode);
}
}
Log::Log(Logger* logger, const char* file_name)
: is_stopped_(false),
output_handle_(nullptr),
message_buffer_(nullptr),
logger_(logger) {}
void Log::Initialize(const char* log_file_name) {
message_buffer_ = NewArray<char>(kMessageBufferSize);
output_handle_(Log::CreateOutputHandle(file_name)),
os_(output_handle_ == nullptr ? stdout : output_handle_),
format_buffer_(NewArray<char>(kMessageBufferSize)),
logger_(logger) {
// --log-all enables all the log flags.
if (FLAG_log_all) {
FLAG_log_api = true;
@ -40,51 +51,21 @@ void Log::Initialize(const char* log_file_name) {
// --prof implies --log-code.
if (FLAG_prof) FLAG_log_code = true;
// If we're logging anything, we need to open the log file.
if (Log::InitLogAtStart()) {
if (strcmp(log_file_name, kLogToConsole) == 0) {
OpenStdout();
} else if (strcmp(log_file_name, kLogToTemporaryFile) == 0) {
OpenTemporaryFile();
if (output_handle_ != nullptr) {
Log::MessageBuilder msg(this);
if (strlen(Version::GetEmbedder()) == 0) {
msg.Append("v8-version,%d,%d,%d,%d,%d", Version::GetMajor(),
Version::GetMinor(), Version::GetBuild(), Version::GetPatch(),
Version::IsCandidate());
} else {
OpenFile(log_file_name);
}
if (output_handle_ != nullptr) {
Log::MessageBuilder msg(this);
if (strlen(Version::GetEmbedder()) == 0) {
msg.Append("v8-version,%d,%d,%d,%d,%d", Version::GetMajor(),
Version::GetMinor(), Version::GetBuild(),
Version::GetPatch(), Version::IsCandidate());
} else {
msg.Append("v8-version,%d,%d,%d,%d,%s,%d", Version::GetMajor(),
Version::GetMinor(), Version::GetBuild(),
Version::GetPatch(), Version::GetEmbedder(),
Version::IsCandidate());
}
msg.WriteToLogFile();
msg.Append("v8-version,%d,%d,%d,%d,%s,%d", Version::GetMajor(),
Version::GetMinor(), Version::GetBuild(), Version::GetPatch(),
Version::GetEmbedder(), Version::IsCandidate());
}
msg.WriteToLogFile();
}
}
void Log::OpenStdout() {
DCHECK(!IsEnabled());
output_handle_ = stdout;
}
void Log::OpenTemporaryFile() {
DCHECK(!IsEnabled());
output_handle_ = base::OS::OpenTemporaryFile();
}
void Log::OpenFile(const char* name) {
DCHECK(!IsEnabled());
output_handle_ = base::OS::FOpen(name, base::OS::LogFileOpenMode);
}
FILE* Log::Close() {
FILE* result = nullptr;
if (output_handle_ != nullptr) {
@ -96,74 +77,63 @@ FILE* Log::Close() {
}
output_handle_ = nullptr;
DeleteArray(message_buffer_);
message_buffer_ = nullptr;
DeleteArray(format_buffer_);
format_buffer_ = nullptr;
is_stopped_ = false;
return result;
}
Log::MessageBuilder::MessageBuilder(Log* log)
: log_(log),
lock_guard_(&log_->mutex_),
pos_(0) {
DCHECK_NOT_NULL(log_->message_buffer_);
: log_(log), lock_guard_(&log_->mutex_) {
DCHECK_NOT_NULL(log_->format_buffer_);
}
void Log::MessageBuilder::Append(const char* format, ...) {
Vector<char> buf(log_->message_buffer_ + pos_,
Log::kMessageBufferSize - pos_);
va_list args;
va_start(args, format);
AppendVA(format, args);
va_end(args);
DCHECK_LE(pos_, Log::kMessageBufferSize);
}
void Log::MessageBuilder::AppendVA(const char* format, va_list args) {
Vector<char> buf(log_->message_buffer_ + pos_,
Log::kMessageBufferSize - pos_);
int result = v8::internal::VSNPrintF(buf, format, args);
// Result is -1 if output was truncated.
if (result >= 0) {
pos_ += result;
} else {
pos_ = Log::kMessageBufferSize;
Vector<char> buf(log_->format_buffer_, Log::kMessageBufferSize);
int length = v8::internal::VSNPrintF(buf, format, args);
// {length} is -1 if output was truncated.
if (length == -1) {
length = Log::kMessageBufferSize;
}
DCHECK_LE(pos_, Log::kMessageBufferSize);
}
void Log::MessageBuilder::Append(const char c) {
if (pos_ < Log::kMessageBufferSize) {
log_->message_buffer_[pos_++] = c;
}
DCHECK_LE(pos_, Log::kMessageBufferSize);
DCHECK_LE(length, Log::kMessageBufferSize);
AppendStringPart(log_->format_buffer_, length);
}
void Log::MessageBuilder::AppendDoubleQuotedString(const char* string) {
Append('"');
OFStream& os = log_->os_;
// TODO(cbruni): unify escaping.
os << '"';
for (const char* p = string; *p != '\0'; p++) {
if (*p == '"') {
Append('\\');
}
Append(*p);
if (*p == '"') os << '\\';
os << *p;
}
Append('"');
os << '"';
}
void Log::MessageBuilder::AppendDoubleQuotedString(String* string) {
OFStream& os = log_->os_;
os << '"';
// TODO(cbruni): unify escaping.
AppendEscapedString(string);
os << '"';
}
void Log::MessageBuilder::Append(String* str) {
void Log::MessageBuilder::Append(String* string) {
DisallowHeapAllocation no_gc; // Ensure string stay valid.
int length = str->length();
for (int i = 0; i < length; i++) {
Append(static_cast<char>(str->Get(i)));
}
std::unique_ptr<char[]> characters =
string->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
log_->os_ << characters.get();
}
void Log::MessageBuilder::AppendAddress(Address addr) {
@ -172,109 +142,69 @@ void Log::MessageBuilder::AppendAddress(Address addr) {
void Log::MessageBuilder::AppendSymbolName(Symbol* symbol) {
DCHECK(symbol);
Append("symbol(");
OFStream& os = log_->os_;
os << "symbol(";
if (!symbol->name()->IsUndefined(symbol->GetIsolate())) {
Append("\"");
os << "\"";
AppendDetailed(String::cast(symbol->name()), false);
Append("\" ");
os << "\" ";
}
Append("hash %x)", symbol->Hash());
os << "hash " << std::hex << symbol->Hash() << std::dec << ")";
}
void Log::MessageBuilder::AppendDetailed(String* str, bool show_impl_info) {
if (str == nullptr) return;
DisallowHeapAllocation no_gc; // Ensure string stay valid.
OFStream& os = log_->os_;
int len = str->length();
if (len > 0x1000)
len = 0x1000;
if (len > 0x1000) len = 0x1000;
if (show_impl_info) {
Append(str->IsOneByteRepresentation() ? 'a' : '2');
if (StringShape(str).IsExternal())
Append('e');
if (StringShape(str).IsInternalized())
Append('#');
Append(":%i:", str->length());
}
for (int i = 0; i < len; i++) {
uc32 c = str->Get(i);
if (c > 0xff) {
Append("\\u%04x", c);
} else if (c < 32 || c > 126) {
Append("\\x%02x", c);
} else if (c == ',') {
Append("\\,");
} else if (c == '\\') {
Append("\\\\");
} else if (c == '\"') {
Append("\"\"");
} else {
Append("%lc", c);
}
os << (str->IsOneByteRepresentation() ? 'a' : '2');
if (StringShape(str).IsExternal()) os << 'e';
if (StringShape(str).IsInternalized()) os << '#';
os << ':' << str->length() << ':';
}
AppendEscapedString(str, len);
}
void Log::MessageBuilder::AppendUnbufferedHeapString(String* str) {
void Log::MessageBuilder::AppendEscapedString(String* str) {
if (str == nullptr) return;
DisallowHeapAllocation no_gc; // Ensure string stay valid.
ScopedVector<char> buffer(16);
int len = str->length();
AppendEscapedString(str, len);
}
void Log::MessageBuilder::AppendEscapedString(String* str, int len) {
DCHECK_LE(len, str->length());
DisallowHeapAllocation no_gc; // Ensure string stay valid.
OFStream& os = log_->os_;
// TODO(cbruni): unify escaping.
for (int i = 0; i < len; i++) {
uc32 c = str->Get(i);
if (c >= 32 && c <= 126) {
if (c == '\"') {
AppendUnbufferedCString("\"\"");
os << "\"\"";
} else if (c == '\\') {
AppendUnbufferedCString("\\\\");
os << "\\\\";
} else if (c == ',') {
os << "\\,";
} else {
AppendUnbufferedChar(c);
os << static_cast<char>(c);
}
} else if (c > 0xff) {
int length = v8::internal::SNPrintF(buffer, "\\u%04x", c);
DCHECK_EQ(6, length);
log_->WriteToFile(buffer.start(), length);
Append("\\u%04x", c);
} else {
DCHECK_LE(c, 0xffff);
int length = v8::internal::SNPrintF(buffer, "\\x%02x", c);
DCHECK_EQ(4, length);
log_->WriteToFile(buffer.start(), length);
DCHECK(c < 32 || (c > 126 && c <= 0xff));
Append("\\x%02x", c);
}
}
}
void Log::MessageBuilder::AppendUnbufferedChar(char c) {
log_->WriteToFile(&c, 1);
}
void Log::MessageBuilder::AppendUnbufferedCString(const char* str) {
log_->WriteToFile(str, static_cast<int>(strlen(str)));
}
void Log::MessageBuilder::AppendStringPart(const char* str, int len) {
if (pos_ + len > Log::kMessageBufferSize) {
len = Log::kMessageBufferSize - pos_;
DCHECK_GE(len, 0);
if (len == 0) return;
}
Vector<char> buf(log_->message_buffer_ + pos_,
Log::kMessageBufferSize - pos_);
StrNCpy(buf, str, len);
pos_ += len;
DCHECK_LE(pos_, Log::kMessageBufferSize);
log_->os_.write(str, len);
}
void Log::MessageBuilder::WriteToLogFile() {
DCHECK_LE(pos_, Log::kMessageBufferSize);
// Assert that we do not already have a new line at the end.
DCHECK(pos_ == 0 || log_->message_buffer_[pos_ - 1] != '\n');
if (pos_ == Log::kMessageBufferSize) pos_--;
log_->message_buffer_[pos_++] = '\n';
const int written = log_->WriteToFile(log_->message_buffer_, pos_);
if (written != pos_) {
log_->stop();
log_->logger_->LogFailure();
}
}
void Log::MessageBuilder::WriteToLogFile() { log_->os_ << std::endl; }
} // namespace internal
} // namespace v8

View File

@ -13,6 +13,7 @@
#include "src/base/compiler-specific.h"
#include "src/base/platform/mutex.h"
#include "src/flags.h"
#include "src/ostreams.h"
namespace v8 {
namespace internal {
@ -22,8 +23,7 @@ class Logger;
// Functions and data for performing output of log messages.
class Log {
public:
// Performs process-wide initialization.
void Initialize(const char* log_file_name);
Log(Logger* log, const char* log_file_name);
// Disables logging, but preserves acquired resources.
void stop() { is_stopped_ = true; }
@ -66,11 +66,9 @@ class Log {
// Append string data to the log message.
void PRINTF_FORMAT(2, 0) AppendVA(const char* format, va_list args);
// Append a character to the log message.
void Append(const char c);
// Append double quoted string to the log message.
void AppendDoubleQuotedString(const char* string);
void AppendDoubleQuotedString(String* string);
// Append a heap string.
void Append(String* str);
@ -88,37 +86,32 @@ class Log {
// Helpers for appending char, C-string and heap string without
// buffering. This is useful for entries that can exceed the 2kB
// limit.
void AppendUnbufferedChar(char c);
void AppendUnbufferedCString(const char* str);
void AppendUnbufferedHeapString(String* source);
void AppendEscapedString(String* source);
void AppendEscapedString(String* source, int len);
// Write the log message to the log file currently opened.
// Delegate insertion to the underlying {log_}.
template <typename T>
MessageBuilder& operator<<(T value) {
log_->os_ << value;
return *this;
}
// Finish the current log line an flush the it to the log file.
void WriteToLogFile();
private:
Log* log_;
base::LockGuard<base::Mutex> lock_guard_;
int pos_;
};
private:
explicit Log(Logger* logger);
// Opens stdout for logging.
void OpenStdout();
// Opens file for logging.
void OpenFile(const char* name);
// Opens a temporary file for logging.
void OpenTemporaryFile();
static FILE* CreateOutputHandle(const char* file_name);
// Implementation of writing to a log file.
int WriteToFile(const char* msg, int length) {
DCHECK_NOT_NULL(output_handle_);
size_t rv = fwrite(msg, 1, length, output_handle_);
DCHECK_EQ(length, rv);
USE(rv);
os_.write(msg, length);
DCHECK(!os_.bad());
return length;
}
@ -128,6 +121,7 @@ class Log {
// When logging is active output_handle_ is used to store a pointer to log
// destination. mutex_ should be acquired before using output_handle_.
FILE* output_handle_;
OFStream os_;
// mutex_ is a Mutex used for enforcing exclusive
// access to the formatting buffer and the log file or log memory buffer.
@ -135,7 +129,7 @@ class Log {
// Buffer used for formatting log messages. This is a singleton buffer and
// mutex_ should be acquired before using it.
char* message_buffer_;
char* format_buffer_;
Logger* logger_;

View File

@ -725,7 +725,7 @@ Logger::Logger(Isolate* isolate)
profiler_(nullptr),
log_events_(nullptr),
is_logging_(false),
log_(new Log(this)),
log_(nullptr),
perf_basic_logger_(nullptr),
perf_jit_logger_(nullptr),
ll_logger_(nullptr),
@ -749,7 +749,7 @@ void Logger::removeCodeEventListener(CodeEventListener* listener) {
void Logger::ProfilerBeginEvent() {
if (!log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg.Append("profiler,\"begin\",%d", FLAG_prof_sampling_interval);
msg << "profiler,\"begin\"," << FLAG_prof_sampling_interval;
msg.WriteToLogFile();
}
@ -762,7 +762,7 @@ void Logger::StringEvent(const char* name, const char* value) {
void Logger::UncheckedStringEvent(const char* name, const char* value) {
if (!log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,\"%s\"", name, value);
msg << name << ",\"" << value << "\"";
msg.WriteToLogFile();
}
@ -780,7 +780,7 @@ void Logger::IntPtrTEvent(const char* name, intptr_t value) {
void Logger::UncheckedIntEvent(const char* name, int value) {
if (!log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,%d", name, value);
msg << name << "," << value;
msg.WriteToLogFile();
}
@ -796,7 +796,7 @@ void Logger::UncheckedIntPtrTEvent(const char* name, intptr_t value) {
void Logger::HandleEvent(const char* name, Object** location) {
if (!log_->IsEnabled() || !FLAG_log_handles) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,%p", name, static_cast<void*>(location));
msg << name << "," << static_cast<void*>(location);
msg.WriteToLogFile();
}
@ -825,9 +825,9 @@ void Logger::SharedLibraryEvent(const std::string& library_path,
intptr_t aslr_slide) {
if (!log_->IsEnabled() || !FLAG_prof_cpp) return;
Log::MessageBuilder msg(log_);
msg.Append("shared-library,\"%s\",0x%08" V8PRIxPTR ",0x%08" V8PRIxPTR
",%" V8PRIdPTR,
library_path.c_str(), start, end, aslr_slide);
msg << "shared-library,\"" << library_path.c_str() << "\","
<< reinterpret_cast<void*>(start) << "," << reinterpret_cast<void*>(end)
<< "," << aslr_slide;
msg.WriteToLogFile();
}
@ -837,7 +837,7 @@ void Logger::CodeDeoptEvent(Code* code, DeoptKind kind, Address pc,
Deoptimizer::DeoptInfo info = Deoptimizer::GetDeoptInfo(code, pc);
Log::MessageBuilder msg(log_);
int since_epoch = static_cast<int>(timer_.Elapsed().InMicroseconds());
msg.Append("code-deopt,%d,%d,", since_epoch, code->CodeSize());
msg << "code-deopt," << since_epoch << "," << code->CodeSize() << ",";
msg.AppendAddress(code->instruction_start());
// Deoptimization position.
@ -851,20 +851,20 @@ void Logger::CodeDeoptEvent(Code* code, DeoptKind kind, Address pc,
} else {
deopt_location << "<unknown>";
}
msg.Append(",%d,%d,", inlining_id, script_offset);
msg << "," << inlining_id << "," << script_offset << ",";
switch (kind) {
case kLazy:
msg.Append("\"lazy\",");
msg << "\"lazy\",";
break;
case kSoft:
msg.Append("\"soft\",");
msg << "\"soft\",";
break;
case kEager:
msg.Append("\"eager\",");
msg << "\"eager\",";
break;
}
msg.AppendDoubleQuotedString(deopt_location.str().c_str());
msg.Append(",");
msg << ",";
msg.AppendDoubleQuotedString(DeoptimizeReasonToString(info.deopt_reason));
msg.WriteToLogFile();
}
@ -875,7 +875,7 @@ void Logger::CurrentTimeEvent() {
DCHECK(FLAG_log_internal_timer_events);
Log::MessageBuilder msg(log_);
int since_epoch = static_cast<int>(timer_.Elapsed().InMicroseconds());
msg.Append("current-time,%d", since_epoch);
msg << "current-time," << since_epoch;
msg.WriteToLogFile();
}
@ -883,12 +883,20 @@ void Logger::CurrentTimeEvent() {
void Logger::TimerEvent(Logger::StartEnd se, const char* name) {
if (!log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
switch (se) {
case START:
msg << "timer-event-start";
break;
case END:
msg << "timer-event-end";
break;
case STAMP:
msg << "timer-event";
}
msg << ",";
int since_epoch = static_cast<int>(timer_.Elapsed().InMicroseconds());
const char* format = (se == START)
? "timer-event-start,\"%s\",%ld"
: (se == END) ? "timer-event-end,\"%s\",%ld"
: "timer-event,\"%s\",%ld";
msg.Append(format, name, since_epoch);
msg.AppendDoubleQuotedString(name);
msg << "," << since_epoch;
msg.WriteToLogFile();
}
@ -972,7 +980,8 @@ void Logger::ApiEntryCall(const char* name) {
void Logger::NewEvent(const char* name, void* object, size_t size) {
if (!log_->IsEnabled() || !FLAG_log) return;
Log::MessageBuilder msg(log_);
msg.Append("new,%s,%p,%u", name, object, static_cast<unsigned int>(size));
msg << "new," << name << "," << object << ","
<< static_cast<unsigned int>(size);
msg.WriteToLogFile();
}
@ -980,7 +989,7 @@ void Logger::NewEvent(const char* name, void* object, size_t size) {
void Logger::DeleteEvent(const char* name, void* object) {
if (!log_->IsEnabled() || !FLAG_log) return;
Log::MessageBuilder msg(log_);
msg.Append("delete,%s,%p", name, object);
msg << "delete," << name << "," << object;
msg.WriteToLogFile();
}
@ -989,27 +998,19 @@ void Logger::CallbackEventInternal(const char* prefix, Name* name,
Address entry_point) {
if (!FLAG_log_code || !log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,%s,-2,",
kLogEventsNames[CodeEventListener::CODE_CREATION_EVENT],
kLogEventsNames[CodeEventListener::CALLBACK_TAG]);
msg << kLogEventsNames[CodeEventListener::CODE_CREATION_EVENT] << ","
<< kLogEventsNames[CodeEventListener::CALLBACK_TAG] << ",-2,";
int timestamp = static_cast<int>(timer_.Elapsed().InMicroseconds());
msg.Append("%d,", timestamp);
msg << timestamp << ",";
msg.AppendAddress(entry_point);
if (name->IsString()) {
std::unique_ptr<char[]> str =
String::cast(name)->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
msg.Append(",1,\"%s%s\"", prefix, str.get());
msg << ",1,\"" << prefix;
msg.AppendEscapedString(String::cast(name));
msg << "\"";
} else {
Symbol* symbol = Symbol::cast(name);
if (symbol->name()->IsUndefined(symbol->GetIsolate())) {
msg.Append(",1,symbol(hash %x)", symbol->Hash());
} else {
std::unique_ptr<char[]> str =
String::cast(symbol->name())
->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
msg.Append(",1,symbol(\"%s%s\" hash %x)", prefix, str.get(),
symbol->Hash());
}
msg << ",1,";
msg.AppendSymbolName(symbol);
}
msg.WriteToLogFile();
}
@ -1031,17 +1032,15 @@ void Logger::SetterCallbackEvent(Name* name, Address entry_point) {
namespace {
void AppendCodeCreateHeader(Log::MessageBuilder* msg,
void AppendCodeCreateHeader(Log::MessageBuilder& msg,
CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, base::ElapsedTimer* timer) {
DCHECK(msg);
msg->Append("%s,%s,%d,",
kLogEventsNames[CodeEventListener::CODE_CREATION_EVENT],
kLogEventsNames[tag], code->kind());
msg << kLogEventsNames[CodeEventListener::CODE_CREATION_EVENT] << ","
<< kLogEventsNames[tag] << "," << code->kind();
int timestamp = static_cast<int>(timer->Elapsed().InMicroseconds());
msg->Append("%d,", timestamp);
msg->AppendAddress(code->instruction_start());
msg->Append(",%d,", code->instruction_size());
msg << "," << timestamp << ",";
msg.AppendAddress(code->instruction_start());
msg << "," << code->instruction_size() << ",";
}
} // namespace
@ -1051,7 +1050,7 @@ void Logger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
if (!is_logging_code_events()) return;
if (!FLAG_log_code || !log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
AppendCodeCreateHeader(&msg, tag, code, &timer_);
AppendCodeCreateHeader(msg, tag, code, &timer_);
msg.AppendDoubleQuotedString(comment);
msg.WriteToLogFile();
}
@ -1061,11 +1060,9 @@ void Logger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
if (!is_logging_code_events()) return;
if (!FLAG_log_code || !log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
AppendCodeCreateHeader(&msg, tag, code, &timer_);
AppendCodeCreateHeader(msg, tag, code, &timer_);
if (name->IsString()) {
msg.Append('"');
msg.AppendDetailed(String::cast(name), false);
msg.Append('"');
msg.AppendDoubleQuotedString(String::cast(name));
} else {
msg.AppendSymbolName(Symbol::cast(name));
}
@ -1083,17 +1080,15 @@ void Logger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
}
Log::MessageBuilder msg(log_);
AppendCodeCreateHeader(&msg, tag, code, &timer_);
AppendCodeCreateHeader(msg, tag, code, &timer_);
if (name->IsString()) {
std::unique_ptr<char[]> str =
String::cast(name)->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
msg.Append("\"%s\"", str.get());
msg.AppendDoubleQuotedString(String::cast(name));
} else {
msg.AppendSymbolName(Symbol::cast(name));
}
msg.Append(',');
msg << ',';
msg.AppendAddress(shared->address());
msg.Append(",%s", ComputeMarker(shared, code));
msg << "," << ComputeMarker(shared, code);
msg.WriteToLogFile();
}
@ -1107,139 +1102,126 @@ void Logger::CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
if (!is_logging_code_events()) return;
if (!FLAG_log_code || !log_->IsEnabled()) return;
{
Log::MessageBuilder msg(log_);
AppendCodeCreateHeader(&msg, tag, code, &timer_);
std::unique_ptr<char[]> name =
shared->DebugName()->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
msg.Append("\"%s ", name.get());
if (source->IsString()) {
std::unique_ptr<char[]> sourcestr = String::cast(source)->ToCString(
DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
msg.Append("%s", sourcestr.get());
Log::MessageBuilder msg(log_);
AppendCodeCreateHeader(msg, tag, code, &timer_);
msg << "\"";
msg.AppendEscapedString(shared->DebugName());
msg << " ";
if (source->IsString()) {
msg.AppendEscapedString(String::cast(source));
} else {
msg.AppendSymbolName(Symbol::cast(source));
}
msg << ":" << line << ":" << column << "\",";
msg.AppendAddress(shared->address());
msg << "," << ComputeMarker(shared, code);
msg.WriteToLogFile();
if (!FLAG_log_source_code) return;
Object* script_object = shared->script();
if (!script_object->IsScript()) return;
// Make sure the script is written to the log file.
Script* script = Script::cast(script_object);
int script_id = script->id();
if (logged_source_code_.find(script_id) != logged_source_code_.end()) {
return;
}
// This script has not been logged yet.
logged_source_code_.insert(script_id);
Object* source_object = script->source();
if (source_object->IsString()) {
String* source_code = String::cast(source_object);
msg << "script," << script_id << ",\"";
// Log the script name.
if (script->name()->IsString()) {
msg.AppendEscapedString(String::cast(script->name()));
msg << "\",\"";
} else {
msg.AppendSymbolName(Symbol::cast(source));
msg << "<unknown>\",\"";
}
msg.Append(":%d:%d\",", line, column);
msg.AppendAddress(shared->address());
msg.Append(",%s", ComputeMarker(shared, code));
// Log the source code.
msg.AppendEscapedString(source_code);
msg << "\"";
msg.WriteToLogFile();
}
if (FLAG_log_source_code) {
Object* script_object = shared->script();
if (script_object->IsScript()) {
// Make sure the script is written to the log file.
std::ostringstream os;
Script* script = Script::cast(script_object);
int script_id = script->id();
if (logged_source_code_.find(script_id) == logged_source_code_.end()) {
// This script has not been logged yet.
logged_source_code_.insert(script_id);
Object* source_object = script->source();
if (source_object->IsString()) {
Log::MessageBuilder msg(log_);
String* source_code = String::cast(source_object);
os << "script," << script_id << ",\"";
msg.AppendUnbufferedCString(os.str().c_str());
// We log source code information in the form:
//
// code-source-info <addr>,<script>,<start>,<end>,<pos>,<inline-pos>,<fns>
//
// where
// <addr> is code object address
// <script> is script id
// <start> is the starting position inside the script
// <end> is the end position inside the script
// <pos> is source position table encoded in the string,
// it is a sequence of C<code-offset>O<script-offset>[I<inlining-id>]
// where
// <code-offset> is the offset within the code object
// <script-offset> is the position within the script
// <inlining-id> is the offset in the <inlining> table
// <inlining> table is a sequence of strings of the form
// F<function-id>O<script-offset>[I<inlining-id>
// where
// <function-id> is an index into the <fns> function table
// <fns> is the function table encoded as a sequence of strings
// S<shared-function-info-address>
msg << "code-source-info," << static_cast<void*>(code->instruction_start())
<< "," << script_id << "," << shared->start_position() << ","
<< shared->end_position() << ",";
// Log the script name.
if (script->name()->IsString()) {
msg.AppendUnbufferedHeapString(String::cast(script->name()));
msg.AppendUnbufferedCString("\",\"");
} else {
msg.AppendUnbufferedCString("<unknown>\",\"");
}
// Log the source code.
msg.AppendUnbufferedHeapString(source_code);
os.str("");
os << "\"" << std::endl;
msg.AppendUnbufferedCString(os.str().c_str());
os.str("");
}
}
// We log source code information in the form:
//
// code-source-info <addr>,<script>,<start>,<end>,<pos>,<inline-pos>,<fns>
//
// where
// <addr> is code object address
// <script> is script id
// <start> is the starting position inside the script
// <end> is the end position inside the script
// <pos> is source position table encoded in the string,
// it is a sequence of C<code-offset>O<script-offset>[I<inlining-id>]
// where
// <code-offset> is the offset within the code object
// <script-offset> is the position within the script
// <inlining-id> is the offset in the <inlining> table
// <inlining> table is a sequence of strings of the form
// F<function-id>O<script-offset>[I<inlining-id>
// where
// <function-id> is an index into the <fns> function table
// <fns> is the function table encoded as a sequence of strings
// S<shared-function-info-address>
os << "code-source-info," << static_cast<void*>(code->instruction_start())
<< "," << script_id << "," << shared->start_position() << ","
<< shared->end_position() << ",";
SourcePositionTableIterator iterator(code->source_position_table());
bool is_first = true;
bool hasInlined = false;
for (; !iterator.done(); iterator.Advance()) {
if (is_first) {
is_first = false;
}
SourcePosition pos = iterator.source_position();
os << "C" << iterator.code_offset();
os << "O" << pos.ScriptOffset();
if (pos.isInlined()) {
os << "I" << pos.InliningId();
hasInlined = true;
}
}
os << ",";
int maxInlinedId = -1;
if (hasInlined) {
PodArray<InliningPosition>* inlining_positions =
DeoptimizationData::cast(Code::cast(code)->deoptimization_data())
->InliningPositions();
for (int i = 0; i < inlining_positions->length(); i++) {
InliningPosition inlining_pos = inlining_positions->get(i);
os << "F";
if (inlining_pos.inlined_function_id != -1) {
os << inlining_pos.inlined_function_id;
if (inlining_pos.inlined_function_id > maxInlinedId) {
maxInlinedId = inlining_pos.inlined_function_id;
}
}
SourcePosition pos = inlining_pos.position;
os << "O" << pos.ScriptOffset();
if (pos.isInlined()) {
os << "I" << pos.InliningId();
}
}
}
os << ",";
if (hasInlined) {
DeoptimizationData* deopt_data =
DeoptimizationData::cast(Code::cast(code)->deoptimization_data());
os << std::hex;
for (int i = 0; i <= maxInlinedId; i++) {
os << "S"
<< static_cast<void*>(
deopt_data->GetInlinedFunction(i)->address());
}
os << std::dec;
}
os << std::endl;
Log::MessageBuilder msg(log_);
msg.AppendUnbufferedCString(os.str().c_str());
SourcePositionTableIterator iterator(code->source_position_table());
bool is_first = true;
bool hasInlined = false;
for (; !iterator.done(); iterator.Advance()) {
if (is_first) {
is_first = false;
}
SourcePosition pos = iterator.source_position();
msg << "C" << iterator.code_offset() << "O" << pos.ScriptOffset();
if (pos.isInlined()) {
msg << "I" << pos.InliningId();
hasInlined = true;
}
}
msg << ",";
int maxInlinedId = -1;
if (hasInlined) {
PodArray<InliningPosition>* inlining_positions =
DeoptimizationData::cast(Code::cast(code)->deoptimization_data())
->InliningPositions();
for (int i = 0; i < inlining_positions->length(); i++) {
InliningPosition inlining_pos = inlining_positions->get(i);
msg << "F";
if (inlining_pos.inlined_function_id != -1) {
msg << inlining_pos.inlined_function_id;
if (inlining_pos.inlined_function_id > maxInlinedId) {
maxInlinedId = inlining_pos.inlined_function_id;
}
}
SourcePosition pos = inlining_pos.position;
msg << "O" << pos.ScriptOffset();
if (pos.isInlined()) {
msg << "I" << pos.InliningId();
}
}
}
msg << ",";
if (hasInlined) {
DeoptimizationData* deopt_data =
DeoptimizationData::cast(Code::cast(code)->deoptimization_data());
msg << std::hex;
for (int i = 0; i <= maxInlinedId; i++) {
msg << "S"
<< static_cast<void*>(deopt_data->GetInlinedFunction(i)->address());
}
msg << std::dec;
}
msg.WriteToLogFile();
}
void Logger::CodeDisableOptEvent(AbstractCode* code,
@ -1247,11 +1229,11 @@ void Logger::CodeDisableOptEvent(AbstractCode* code,
if (!is_logging_code_events()) return;
if (!FLAG_log_code || !log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,", kLogEventsNames[CodeEventListener::CODE_DISABLE_OPT_EVENT]);
std::unique_ptr<char[]> name =
shared->DebugName()->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
msg.Append("\"%s\",", name.get());
msg.Append("\"%s\"", GetBailoutReason(shared->disable_optimization_reason()));
msg << kLogEventsNames[CodeEventListener::CODE_DISABLE_OPT_EVENT] << ",";
msg.AppendDoubleQuotedString(shared->DebugName());
msg << ",";
msg.AppendDoubleQuotedString(
GetBailoutReason(shared->disable_optimization_reason()));
msg.WriteToLogFile();
}
@ -1266,10 +1248,10 @@ void Logger::RegExpCodeCreateEvent(AbstractCode* code, String* source) {
if (!is_logging_code_events()) return;
if (!FLAG_log_code || !log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
AppendCodeCreateHeader(&msg, CodeEventListener::REG_EXP_TAG, code, &timer_);
msg.Append('"');
AppendCodeCreateHeader(msg, CodeEventListener::REG_EXP_TAG, code, &timer_);
msg << '"';
msg.AppendDetailed(source, false);
msg.Append('"');
msg << '"';
msg.WriteToLogFile();
}
@ -1301,8 +1283,8 @@ void Logger::CodeLinePosInfoRecordEvent(AbstractCode* code,
void Logger::CodeNameEvent(Address addr, int pos, const char* code_name) {
if (code_name == nullptr) return; // Not a code object.
Log::MessageBuilder msg(log_);
msg.Append("%s,%d,",
kLogEventsNames[CodeEventListener::SNAPSHOT_CODE_NAME_EVENT], pos);
msg << kLogEventsNames[CodeEventListener::SNAPSHOT_CODE_NAME_EVENT] << ","
<< pos;
msg.AppendDoubleQuotedString(code_name);
msg.WriteToLogFile();
}
@ -1317,9 +1299,9 @@ void Logger::MoveEventInternal(CodeEventListener::LogEventsAndTags event,
Address from, Address to) {
if (!FLAG_log_code || !log_->IsEnabled()) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,", kLogEventsNames[event]);
msg << kLogEventsNames[event] << ",";
msg.AppendAddress(from);
msg.Append(',');
msg << ",";
msg.AppendAddress(to);
msg.WriteToLogFile();
}
@ -1328,11 +1310,11 @@ void Logger::MoveEventInternal(CodeEventListener::LogEventsAndTags event,
void Logger::ResourceEvent(const char* name, const char* tag) {
if (!log_->IsEnabled() || !FLAG_log) return;
Log::MessageBuilder msg(log_);
msg.Append("%s,%s,", name, tag);
msg << name << "," << tag << ",";
uint32_t sec, usec;
if (base::OS::GetUserTime(&sec, &usec) != -1) {
msg.Append("%d,%d,", sec, usec);
msg << sec << "," << usec << ",";
}
msg.Append("%.0f", V8::GetCurrentPlatform()->CurrentClockTimeMillis());
msg.WriteToLogFile();
@ -1345,13 +1327,9 @@ void Logger::SuspectReadEvent(Name* name, Object* obj) {
String* class_name = obj->IsJSObject()
? JSObject::cast(obj)->class_name()
: isolate_->heap()->empty_string();
msg.Append("suspect-read,");
msg.Append(class_name);
msg.Append(',');
msg << "suspect-read," << class_name << ",";
if (name->IsString()) {
msg.Append('"');
msg.Append(String::cast(name));
msg.Append('"');
msg.AppendDoubleQuotedString(String::cast(name));
} else {
msg.AppendSymbolName(Symbol::cast(name));
}
@ -1364,8 +1342,8 @@ void Logger::HeapSampleBeginEvent(const char* space, const char* kind) {
Log::MessageBuilder msg(log_);
// Using non-relative system time in order to be able to synchronize with
// external memory profiling events (e.g. DOM memory size).
msg.Append("heap-sample-begin,\"%s\",\"%s\",%.0f", space, kind,
V8::GetCurrentPlatform()->CurrentClockTimeMillis());
msg << "heap-sample-begin,\"" << space << "\",\"" << kind << "\",";
msg.Append("%.0f", V8::GetCurrentPlatform()->CurrentClockTimeMillis());
msg.WriteToLogFile();
}
@ -1373,7 +1351,7 @@ void Logger::HeapSampleBeginEvent(const char* space, const char* kind) {
void Logger::HeapSampleEndEvent(const char* space, const char* kind) {
if (!log_->IsEnabled() || !FLAG_log_gc) return;
Log::MessageBuilder msg(log_);
msg.Append("heap-sample-end,\"%s\",\"%s\"", space, kind);
msg << "heap-sample-end,\"" << space << "\",\"" << kind << "\"";
msg.WriteToLogFile();
}
@ -1381,7 +1359,7 @@ void Logger::HeapSampleEndEvent(const char* space, const char* kind) {
void Logger::HeapSampleItemEvent(const char* type, int number, int bytes) {
if (!log_->IsEnabled() || !FLAG_log_gc) return;
Log::MessageBuilder msg(log_);
msg.Append("heap-sample-item,%s,%d,%d", type, number, bytes);
msg << "heap-sample-item,\"" << type << "\"," << number << "," << bytes;
msg.WriteToLogFile();
}
@ -1391,7 +1369,7 @@ void Logger::RuntimeCallTimerEvent() {
RuntimeCallCounter* counter = stats->current_counter();
if (counter == nullptr) return;
Log::MessageBuilder msg(log_);
msg.Append("active-runtime-timer,");
msg << "active-runtime-timer,";
msg.AppendDoubleQuotedString(counter->name());
msg.WriteToLogFile();
}
@ -1403,24 +1381,20 @@ void Logger::TickEvent(v8::TickSample* sample, bool overflow) {
RuntimeCallTimerEvent();
}
Log::MessageBuilder msg(log_);
msg.Append("%s,", kLogEventsNames[CodeEventListener::TICK_EVENT]);
msg.AppendAddress(reinterpret_cast<Address>(sample->pc));
msg.Append(",%d", static_cast<int>(timer_.Elapsed().InMicroseconds()));
msg << kLogEventsNames[CodeEventListener::TICK_EVENT] << ','
<< reinterpret_cast<void*>(sample->pc) << ','
<< static_cast<int>(timer_.Elapsed().InMicroseconds());
if (sample->has_external_callback) {
msg.Append(",1,");
msg.AppendAddress(
reinterpret_cast<Address>(sample->external_callback_entry));
msg << ",1," << reinterpret_cast<void*>(sample->external_callback_entry);
} else {
msg.Append(",0,");
msg.AppendAddress(reinterpret_cast<Address>(sample->tos));
msg << ",0," << reinterpret_cast<void*>(sample->tos);
}
msg.Append(",%d", static_cast<int>(sample->state));
msg << ',' << static_cast<int>(sample->state);
if (overflow) {
msg.Append(",overflow");
msg << ",overflow";
}
for (unsigned i = 0; i < sample->frames_count; ++i) {
msg.Append(',');
msg.AppendAddress(reinterpret_cast<Address>(sample->stack[i]));
msg << ',' << reinterpret_cast<void*>(sample->stack[i]);
}
msg.WriteToLogFile();
}
@ -1431,26 +1405,21 @@ void Logger::ICEvent(const char* type, bool keyed, const Address pc, int line,
const char* slow_stub_reason) {
if (!log_->IsEnabled() || !FLAG_trace_ic) return;
Log::MessageBuilder msg(log_);
if (keyed) msg.Append("Keyed");
msg.Append("%s,", type);
if (keyed) msg << "Keyed";
msg << type << ",";
msg.AppendAddress(pc);
msg.Append(",%d,%d,", line, column);
msg.Append(old_state);
msg.Append(",");
msg.Append(new_state);
msg.Append(",");
msg.AppendAddress(reinterpret_cast<Address>(map));
msg.Append(",");
msg << "," << line << "," << column << "," << old_state << "," << new_state
<< "," << reinterpret_cast<void*>(map) << ",";
if (key->IsSmi()) {
msg.Append("%d", Smi::ToInt(key));
msg << Smi::ToInt(key);
} else if (key->IsNumber()) {
msg.Append("%lf", key->Number());
msg << key->Number();
} else if (key->IsString()) {
msg.AppendDetailed(String::cast(key), false);
} else if (key->IsSymbol()) {
msg.AppendSymbolName(Symbol::cast(key));
}
msg.Append(",%s,", modifier);
msg << "," << modifier << ",";
if (slow_stub_reason != nullptr) {
msg.AppendDoubleQuotedString(slow_stub_reason);
}
@ -1466,7 +1435,6 @@ void Logger::StopProfiler() {
}
}
// This function can be called when Log's mutex is acquired,
// either from main or Profiler's thread.
void Logger::LogFailure() {
@ -1782,7 +1750,7 @@ bool Logger::SetUp(Isolate* isolate) {
std::ostringstream log_file_name;
std::ostringstream source_log_file_name;
PrepareLogFileName(log_file_name, isolate, FLAG_logfile);
log_->Initialize(log_file_name.str().c_str());
log_ = new Log(this, log_file_name.str().c_str());
if (FLAG_perf_basic_prof) {
perf_basic_logger_ = new PerfBasicLogger();

View File

@ -187,6 +187,13 @@ if (typeof result !== "string") {
(c[2] ? c[2] : "---") + " " +
(c[3] ? c[3] : "---"));
}
out.push("================================================")
out.push("MAKE SURE TO USE A CLEAN ISOLATiE!");
out.push("Use tools/test.py");
out.push("================================================")
out.push("* Lines are the same");
out.push("--- Line is missing"
out.push("================================================")
}
result[0] ? true : out.join("\n");
} else {

View File

@ -70,7 +70,7 @@ static const char* StrNStr(const char* s1, const char* s2, size_t n) {
// Look for a log line which starts with {prefix} and ends with {suffix}.
static const char* FindLogLine(i::Vector<const char>* log, const char* prefix,
const char* suffix) {
const char* suffix = nullptr) {
const char* start = log->start();
const char* end = start + log->length();
CHECK_EQ(end[0], '\0');
@ -79,6 +79,7 @@ static const char* FindLogLine(i::Vector<const char>* log, const char* prefix,
while (start < end) {
const char* prefixResult = StrNStr(start, prefix, (end - start));
if (!prefixResult) return NULL;
if (suffix == nullptr) return prefixResult;
const char* suffixResult =
StrNStr(prefixResult, suffix, (end - prefixResult));
if (!suffixResult) return NULL;
@ -122,6 +123,8 @@ class ScopedLoggerInitializer {
Logger* logger() { return logger_; }
void PrintLog() { printf("%s", log_.start()); }
v8::Local<v8::String> GetLogString() {
return v8::String::NewFromUtf8(isolate_, log_.start(),
v8::NewStringType::kNormal, log_.length())
@ -134,7 +137,7 @@ class ScopedLoggerInitializer {
CHECK(exists);
}
const char* FindLine(const char* prefix, const char* suffix) {
const char* FindLine(const char* prefix, const char* suffix = nullptr) {
return FindLogLine(&log_, prefix, suffix);
}
@ -176,6 +179,9 @@ TEST(FindLogLine) {
"prefix4 suffix4";
// Make sure the vector contains the terminating \0 character.
i::Vector<const char> log(string, strlen(string));
CHECK(FindLogLine(&log, "prefix1, stuff, suffix1"));
CHECK(FindLogLine(&log, "prefix1, stuff"));
CHECK(FindLogLine(&log, "prefix1"));
CHECK(FindLogLine(&log, "prefix1", "suffix1"));
CHECK(FindLogLine(&log, "prefix1", "suffix1"));
CHECK(!FindLogLine(&log, "prefix2", "suffix2"));
@ -654,3 +660,40 @@ TEST(Issue539892) {
}
isolate->Dispose();
}
TEST(LogAll) {
SETUP_FLAGS();
i::FLAG_log_all = true;
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
ScopedLoggerInitializer logger(saved_log, saved_prof, isolate);
// Function that will
const char* source_text =
"function testAddFn(a,b) { return a + b };"
"let result;"
"for (let i = 0; i < 100000; i++) { result = testAddFn(i, i); };"
"testAddFn('1', 1);"
"for (let i = 0; i < 100000; i++) { result = testAddFn('1', i); }";
CompileRun(source_text);
logger.StopLogging();
// We should find at least one code-creation even for testAddFn();
CHECK(logger.FindLine("api,v8::Context::New"));
CHECK(logger.FindLine("timer-event-start", "V8.CompileCode"));
CHECK(logger.FindLine("timer-event-end", "V8.CompileCode"));
CHECK(logger.FindLine("code-creation,Script", ":1:1"));
CHECK(logger.FindLine("api,v8::Script::Run"));
CHECK(logger.FindLine("code-creation,LazyCompile,", "testAddFn"));
if (i::FLAG_opt && !i::FLAG_always_opt) {
CHECK(logger.FindLine("code-deopt,", "soft"));
CHECK(logger.FindLine("timer-event-start", "V8.DeoptimizeCode"));
CHECK(logger.FindLine("timer-event-end", "V8.DeoptimizeCode"));
}
}
isolate->Dispose();
}