// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "v8.h" #include "bootstrapper.h" #include "code-stubs.h" #include "deoptimizer.h" #include "global-handles.h" #include "log.h" #include "macro-assembler.h" #include "platform.h" #include "runtime-profiler.h" #include "serialize.h" #include "string-stream.h" #include "vm-state-inl.h" namespace v8 { namespace internal { // The Profiler samples pc and sp values for the main thread. // Each sample is appended to a circular buffer. // An independent thread removes data and writes it to the log. // This design minimizes the time spent in the sampler. // class Profiler: public Thread { public: explicit Profiler(Isolate* isolate); void Engage(); void Disengage(); // Inserts collected profiling data into buffer. void Insert(TickSample* sample) { if (paused_) return; if (Succ(head_) == tail_) { overflow_ = true; } else { buffer_[head_] = *sample; head_ = Succ(head_); buffer_semaphore_->Signal(); // Tell we have an element. } } // Waits for a signal and removes profiling data. bool Remove(TickSample* sample) { buffer_semaphore_->Wait(); // Wait for an element. *sample = buffer_[tail_]; bool result = overflow_; tail_ = Succ(tail_); overflow_ = false; return result; } void Run(); // Pause and Resume TickSample data collection. bool paused() const { return paused_; } void pause() { paused_ = true; } void resume() { paused_ = false; } private: // Returns the next index in the cyclic buffer. int Succ(int index) { return (index + 1) % kBufferSize; } Isolate* isolate_; // Cyclic buffer for communicating profiling samples // between the signal handler and the worker thread. static const int kBufferSize = 128; TickSample buffer_[kBufferSize]; // Buffer storage. int head_; // Index to the buffer head. int tail_; // Index to the buffer tail. bool overflow_; // Tell whether a buffer overflow has occurred. Semaphore* buffer_semaphore_; // Sempahore used for buffer synchronization. // Tells whether profiler is engaged, that is, processing thread is stated. bool engaged_; // Tells whether worker thread should continue running. bool running_; // Tells whether we are currently recording tick samples. bool paused_; }; // // StackTracer implementation // DISABLE_ASAN void StackTracer::Trace(Isolate* isolate, TickSample* sample) { ASSERT(isolate->IsInitialized()); // Avoid collecting traces while doing GC. if (sample->state == GC) return; const Address js_entry_sp = Isolate::js_entry_sp(isolate->thread_local_top()); if (js_entry_sp == 0) { // Not executing JS now. return; } const Address callback = isolate->external_callback(); if (callback != NULL) { sample->external_callback = callback; sample->has_external_callback = true; } else { // Sample potential return address value for frameless invocation of // stubs (we'll figure out later, if this value makes sense). sample->tos = Memory::Address_at(sample->sp); sample->has_external_callback = false; } SafeStackTraceFrameIterator it(isolate, sample->fp, sample->sp, sample->sp, js_entry_sp); int i = 0; while (!it.done() && i < TickSample::kMaxFramesCount) { sample->stack[i++] = it.frame()->pc(); it.Advance(); } sample->frames_count = i; } // // Ticker used to provide ticks to the profiler and the sliding state // window. // class Ticker: public Sampler { public: Ticker(Isolate* isolate, int interval): Sampler(isolate, interval), profiler_(NULL) {} ~Ticker() { if (IsActive()) Stop(); } virtual void Tick(TickSample* sample) { if (profiler_) profiler_->Insert(sample); } void SetProfiler(Profiler* profiler) { ASSERT(profiler_ == NULL); profiler_ = profiler; IncreaseProfilingDepth(); if (!FLAG_prof_lazy && !IsActive()) Start(); } void ClearProfiler() { DecreaseProfilingDepth(); profiler_ = NULL; if (IsActive()) Stop(); } protected: virtual void DoSampleStack(TickSample* sample) { StackTracer::Trace(isolate(), sample); } private: Profiler* profiler_; }; // // Profiler implementation. // Profiler::Profiler(Isolate* isolate) : Thread("v8:Profiler"), isolate_(isolate), head_(0), tail_(0), overflow_(false), buffer_semaphore_(OS::CreateSemaphore(0)), engaged_(false), running_(false), paused_(false) { } void Profiler::Engage() { if (engaged_) return; engaged_ = true; OS::LogSharedLibraryAddresses(); // Start thread processing the profiler buffer. running_ = true; Start(); // Register to get ticks. LOGGER->ticker_->SetProfiler(this); LOGGER->ProfilerBeginEvent(); } void Profiler::Disengage() { if (!engaged_) return; // Stop receiving ticks. LOGGER->ticker_->ClearProfiler(); // Terminate the worker thread by setting running_ to false, // inserting a fake element in the queue and then wait for // the thread to terminate. running_ = false; TickSample sample; // Reset 'paused_' flag, otherwise semaphore may not be signalled. resume(); Insert(&sample); Join(); LOG(ISOLATE, UncheckedStringEvent("profiler", "end")); } void Profiler::Run() { TickSample sample; bool overflow = Remove(&sample); while (running_) { LOG(isolate_, TickEvent(&sample, overflow)); overflow = Remove(&sample); } } // Low-level profiling event structures. struct LowLevelCodeCreateStruct { static const char kTag = 'C'; int32_t name_size; Address code_address; int32_t code_size; }; struct LowLevelCodeMoveStruct { static const char kTag = 'M'; Address from_address; Address to_address; }; struct LowLevelCodeDeleteStruct { static const char kTag = 'D'; Address address; }; struct LowLevelSnapshotPositionStruct { static const char kTag = 'P'; Address address; int32_t position; }; static const char kCodeMovingGCTag = 'G'; // // Logger class implementation. // class Logger::NameMap { public: NameMap() : impl_(&PointerEquals) {} ~NameMap() { for (HashMap::Entry* p = impl_.Start(); p != NULL; p = impl_.Next(p)) { DeleteArray(static_cast(p->value)); } } void Insert(Address code_address, const char* name, int name_size) { HashMap::Entry* entry = FindOrCreateEntry(code_address); if (entry->value == NULL) { entry->value = CopyName(name, name_size); } } const char* Lookup(Address code_address) { HashMap::Entry* entry = FindEntry(code_address); return (entry != NULL) ? static_cast(entry->value) : NULL; } void Remove(Address code_address) { HashMap::Entry* entry = FindEntry(code_address); if (entry != NULL) { DeleteArray(static_cast(entry->value)); RemoveEntry(entry); } } void Move(Address from, Address to) { if (from == to) return; HashMap::Entry* from_entry = FindEntry(from); ASSERT(from_entry != NULL); void* value = from_entry->value; RemoveEntry(from_entry); HashMap::Entry* to_entry = FindOrCreateEntry(to); ASSERT(to_entry->value == NULL); to_entry->value = value; } private: static bool PointerEquals(void* lhs, void* rhs) { return lhs == rhs; } static char* CopyName(const char* name, int name_size) { char* result = NewArray(name_size + 1); for (int i = 0; i < name_size; ++i) { char c = name[i]; if (c == '\0') c = ' '; result[i] = c; } result[name_size] = '\0'; return result; } HashMap::Entry* FindOrCreateEntry(Address code_address) { return impl_.Lookup(code_address, ComputePointerHash(code_address), true); } HashMap::Entry* FindEntry(Address code_address) { return impl_.Lookup(code_address, ComputePointerHash(code_address), false); } void RemoveEntry(HashMap::Entry* entry) { impl_.Remove(entry->key, entry->hash); } HashMap impl_; DISALLOW_COPY_AND_ASSIGN(NameMap); }; class Logger::NameBuffer { public: NameBuffer() { Reset(); } void Reset() { utf8_pos_ = 0; } void AppendString(String* str) { if (str == NULL) return; if (str->HasOnlyAsciiChars()) { int utf8_length = Min(str->length(), kUtf8BufferSize - utf8_pos_); String::WriteToFlat(str, reinterpret_cast(utf8_buffer_ + utf8_pos_), 0, utf8_length); utf8_pos_ += utf8_length; return; } int uc16_length = Min(str->length(), kUtf16BufferSize); String::WriteToFlat(str, utf16_buffer, 0, uc16_length); int previous = unibrow::Utf16::kNoPreviousCharacter; for (int i = 0; i < uc16_length && utf8_pos_ < kUtf8BufferSize; ++i) { uc16 c = utf16_buffer[i]; if (c <= unibrow::Utf8::kMaxOneByteChar) { utf8_buffer_[utf8_pos_++] = static_cast(c); } else { int char_length = unibrow::Utf8::Length(c, previous); if (utf8_pos_ + char_length > kUtf8BufferSize) break; unibrow::Utf8::Encode(utf8_buffer_ + utf8_pos_, c, previous); utf8_pos_ += char_length; } previous = c; } } void AppendBytes(const char* bytes, int size) { size = Min(size, kUtf8BufferSize - utf8_pos_); memcpy(utf8_buffer_ + utf8_pos_, bytes, size); utf8_pos_ += size; } void AppendBytes(const char* bytes) { AppendBytes(bytes, StrLength(bytes)); } void AppendByte(char c) { if (utf8_pos_ >= kUtf8BufferSize) return; utf8_buffer_[utf8_pos_++] = c; } void AppendInt(int n) { Vector buffer(utf8_buffer_ + utf8_pos_, kUtf8BufferSize - utf8_pos_); int size = OS::SNPrintF(buffer, "%d", n); if (size > 0 && utf8_pos_ + size <= kUtf8BufferSize) { utf8_pos_ += size; } } void AppendHex(uint32_t n) { Vector buffer(utf8_buffer_ + utf8_pos_, kUtf8BufferSize - utf8_pos_); int size = OS::SNPrintF(buffer, "%x", n); if (size > 0 && utf8_pos_ + size <= kUtf8BufferSize) { utf8_pos_ += size; } } const char* get() { return utf8_buffer_; } int size() const { return utf8_pos_; } private: static const int kUtf8BufferSize = 512; static const int kUtf16BufferSize = 128; int utf8_pos_; char utf8_buffer_[kUtf8BufferSize]; uc16 utf16_buffer[kUtf16BufferSize]; }; Logger::Logger(Isolate* isolate) : isolate_(isolate), ticker_(NULL), profiler_(NULL), log_events_(NULL), logging_nesting_(0), cpu_profiler_nesting_(0), log_(new Log(this)), name_buffer_(new NameBuffer), address_to_name_map_(NULL), is_initialized_(false), code_event_handler_(NULL), last_address_(NULL), prev_sp_(NULL), prev_function_(NULL), prev_to_(NULL), prev_code_(NULL), epoch_(0) { } Logger::~Logger() { delete address_to_name_map_; delete name_buffer_; delete log_; } void Logger::IssueCodeAddedEvent(Code* code, Script* script, const char* name, size_t name_len) { JitCodeEvent event; memset(&event, 0, sizeof(event)); event.type = JitCodeEvent::CODE_ADDED; event.code_start = code->instruction_start(); event.code_len = code->instruction_size(); Handle