log.cc 46.1 KB
Newer Older
1
// Copyright 2009 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// 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 <stdarg.h>

#include "v8.h"

32
#include "bootstrapper.h"
33
#include "code-stubs.h"
34
#include "deoptimizer.h"
35
#include "global-handles.h"
36
#include "log.h"
37
#include "macro-assembler.h"
38
#include "runtime-profiler.h"
39
#include "serialize.h"
40
#include "string-stream.h"
41
#include "vm-state-inl.h"
42

43 44
namespace v8 {
namespace internal {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

#ifdef ENABLE_LOGGING_AND_PROFILING

//
// Sliding state window.  Updates counters to keep track of the last
// window of kBufferSize states.  This is useful to track where we
// spent our time.
//
class SlidingStateWindow {
 public:
  SlidingStateWindow();
  ~SlidingStateWindow();
  void AddState(StateTag state);

 private:
  static const int kBufferSize = 256;
  int current_index_;
  bool is_full_;
  byte buffer_[kBufferSize];


  void IncrementStateCounter(StateTag state) {
    Counters::state_counters[state].Increment();
  }


  void DecrementStateCounter(StateTag state) {
    Counters::state_counters[state].Decrement();
  }
};


//
// 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:
  Profiler();
  void Engage();
  void Disengage();

  // Inserts collected profiling data into buffer.
  void Insert(TickSample* sample) {
91 92 93
    if (paused_)
      return;

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    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();

115 116 117 118 119
  // Pause and Resume TickSample data collection.
  static bool paused() { return paused_; }
  static void pause() { paused_ = true; }
  static void resume() { paused_ = false; }

120 121 122 123 124 125 126 127 128 129 130 131 132
 private:
  // Returns the next index in the cyclic buffer.
  int Succ(int index) { return (index + 1) % kBufferSize; }

  // 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.

133 134 135
  // Tells whether profiler is engaged, that is, processing thread is stated.
  bool engaged_;

136 137
  // Tells whether worker thread should continue running.
  bool running_;
138 139 140

  // Tells whether we are currently recording tick samples.
  static bool paused_;
141 142
};

143 144
bool Profiler::paused_ = false;

145

146 147 148 149
//
// StackTracer implementation
//
void StackTracer::Trace(TickSample* sample) {
150 151 152
  sample->function = NULL;
  sample->frames_count = 0;

153
  // Avoid collecting traces while doing GC.
154
  if (sample->state == GC) return;
155

156 157 158 159 160 161
  const Address js_entry_sp = Top::js_entry_sp(Top::GetCurrentThread());
  if (js_entry_sp == 0) {
    // Not executing JS now.
    return;
  }

162
  const Address function_address =
163 164
      sample->fp + JavaScriptFrameConstants::kFunctionOffset;
  if (SafeStackFrameIterator::IsWithinBounds(sample->sp, js_entry_sp,
165 166 167 168 169
                                             function_address)) {
    Object* object = Memory::Object_at(function_address);
    if (object->IsHeapObject()) {
      sample->function = HeapObject::cast(object)->address();
    }
170 171
  }

172
  int i = 0;
173
  const Address callback = Top::external_callback();
174 175 176 177
  // Surprisingly, PC can point _exactly_ to callback start, with good
  // probability, and this will result in reporting fake nested
  // callback call.
  if (callback != NULL && callback != sample->pc) {
178 179 180
    sample->stack[i++] = callback;
  }

181 182
  SafeStackTraceFrameIterator it(sample->fp, sample->sp,
                                 sample->sp, js_entry_sp);
183
  while (!it.done() && i < TickSample::kMaxFramesCount) {
184 185 186 187
    Object* object = it.frame()->function_slot_object();
    if (object->IsHeapObject()) {
      sample->stack[i++] = HeapObject::cast(object)->address();
    }
188
    it.Advance();
189
  }
190
  sample->frames_count = i;
191 192 193
}


194 195 196 197
//
// Ticker used to provide ticks to the profiler and the sliding state
// window.
//
198
class Ticker: public Sampler {
199
 public:
200 201 202 203
  explicit Ticker(int interval) :
      Sampler(interval),
      window_(NULL),
      profiler_(NULL) {}
204 205 206

  ~Ticker() { if (IsActive()) Stop(); }

207
  virtual void Tick(TickSample* sample) {
208
    if (profiler_) profiler_->Insert(sample);
209
    if (window_) window_->AddState(sample->state);
210 211 212 213 214 215 216 217 218
  }

  void SetWindow(SlidingStateWindow* window) {
    window_ = window;
    if (!IsActive()) Start();
  }

  void ClearWindow() {
    window_ = NULL;
219
    if (!profiler_ && IsActive() && !RuntimeProfiler::IsEnabled()) Stop();
220 221 222
  }

  void SetProfiler(Profiler* profiler) {
223
    ASSERT(profiler_ == NULL);
224
    profiler_ = profiler;
225
    IncreaseProfilingDepth();
226
    if (!FLAG_prof_lazy && !IsActive()) Start();
227 228 229
  }

  void ClearProfiler() {
230
    DecreaseProfilingDepth();
231
    profiler_ = NULL;
232
    if (!window_ && IsActive() && !RuntimeProfiler::IsEnabled()) Stop();
233 234
  }

235 236 237 238 239
 protected:
  virtual void DoSampleStack(TickSample* sample) {
    StackTracer::Trace(sample);
  }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
 private:
  SlidingStateWindow* window_;
  Profiler* profiler_;
};


//
// SlidingStateWindow implementation.
//
SlidingStateWindow::SlidingStateWindow(): current_index_(0), is_full_(false) {
  for (int i = 0; i < kBufferSize; i++) {
    buffer_[i] = static_cast<byte>(OTHER);
  }
  Logger::ticker_->SetWindow(this);
}


SlidingStateWindow::~SlidingStateWindow() {
  Logger::ticker_->ClearWindow();
}


void SlidingStateWindow::AddState(StateTag state) {
  if (is_full_) {
    DecrementStateCounter(static_cast<StateTag>(buffer_[current_index_]));
  } else if (current_index_ == kBufferSize - 1) {
    is_full_ = true;
  }
  buffer_[current_index_] = static_cast<byte>(state);
  IncrementStateCounter(state);
  ASSERT(IsPowerOf2(kBufferSize));
  current_index_ = (current_index_ + 1) & (kBufferSize - 1);
}


//
// Profiler implementation.
//
278
Profiler::Profiler()
279 280
    : Thread("v8:Profiler"),
      head_(0),
281 282 283 284 285
      tail_(0),
      overflow_(false),
      buffer_semaphore_(OS::CreateSemaphore(0)),
      engaged_(false),
      running_(false) {
286 287 288 289
}


void Profiler::Engage() {
290 291 292 293 294 295 296 297
  if (engaged_) return;
  engaged_ = true;

  // TODO(mnaganov): This is actually "Chromium" mode. Flags need to be revised.
  // http://code.google.com/p/v8/issues/detail?id=487
  if (!FLAG_prof_lazy) {
    OS::LogSharedLibraryAddresses();
  }
298 299 300 301 302 303 304 305

  // Start thread processing the profiler buffer.
  running_ = true;
  Start();

  // Register to get ticks.
  Logger::ticker_->SetProfiler(this);

306
  Logger::ProfilerBeginEvent();
307 308 309 310
}


void Profiler::Disengage() {
311 312
  if (!engaged_) return;

313 314 315 316 317 318 319 320
  // 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;
321 322
  // Reset 'paused_' flag, otherwise semaphore may not be signalled.
  resume();
323 324 325
  Insert(&sample);
  Join();

326
  LOG(UncheckedStringEvent("profiler", "end"));
327 328 329 330 331
}


void Profiler::Run() {
  TickSample sample;
332
  bool overflow = Remove(&sample);
333 334
  while (running_) {
    LOG(TickEvent(&sample, overflow));
335
    overflow = Remove(&sample);
336 337 338 339 340 341 342 343 344 345
  }
}


//
// Logger class implementation.
//
Ticker* Logger::ticker_ = NULL;
Profiler* Logger::profiler_ = NULL;
SlidingStateWindow* Logger::sliding_state_window_ = NULL;
346
int Logger::logging_nesting_ = 0;
347 348
int Logger::cpu_profiler_nesting_ = 0;
int Logger::heap_profiler_nesting_ = 0;
349

350 351 352
#define DECLARE_EVENT(ignore1, name) name,
const char* kLogEventsNames[Logger::NUMBER_OF_LOG_EVENTS] = {
  LOG_EVENTS_AND_TAGS_LIST(DECLARE_EVENT)
353
};
354
#undef DECLARE_EVENT
355

356

357 358 359 360
void Logger::ProfilerBeginEvent() {
  if (!Log::IsEnabled()) return;
  LogMessageBuilder msg;
  msg.Append("profiler,\"begin\",%d\n", kSamplingIntervalMs);
361 362 363
  msg.WriteToLogFile();
}

364 365
#endif  // ENABLE_LOGGING_AND_PROFILING

366

367 368
void Logger::StringEvent(const char* name, const char* value) {
#ifdef ENABLE_LOGGING_AND_PROFILING
369 370 371 372 373 374 375
  if (FLAG_log) UncheckedStringEvent(name, value);
#endif
}


#ifdef ENABLE_LOGGING_AND_PROFILING
void Logger::UncheckedStringEvent(const char* name, const char* value) {
376
  if (!Log::IsEnabled()) return;
377 378 379
  LogMessageBuilder msg;
  msg.Append("%s,\"%s\"\n", name, value);
  msg.WriteToLogFile();
380
}
381
#endif
382 383 384 385


void Logger::IntEvent(const char* name, int value) {
#ifdef ENABLE_LOGGING_AND_PROFILING
386 387 388 389 390
  if (FLAG_log) UncheckedIntEvent(name, value);
#endif
}


391 392 393 394 395 396 397
void Logger::IntPtrTEvent(const char* name, intptr_t value) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (FLAG_log) UncheckedIntPtrTEvent(name, value);
#endif
}


398 399 400
#ifdef ENABLE_LOGGING_AND_PROFILING
void Logger::UncheckedIntEvent(const char* name, int value) {
  if (!Log::IsEnabled()) return;
401 402 403
  LogMessageBuilder msg;
  msg.Append("%s,%d\n", name, value);
  msg.WriteToLogFile();
404
}
405
#endif
406 407


408 409 410 411 412 413 414 415 416 417
#ifdef ENABLE_LOGGING_AND_PROFILING
void Logger::UncheckedIntPtrTEvent(const char* name, intptr_t value) {
  if (!Log::IsEnabled()) return;
  LogMessageBuilder msg;
  msg.Append("%s,%" V8_PTR_PREFIX "d\n", name, value);
  msg.WriteToLogFile();
}
#endif


418 419
void Logger::HandleEvent(const char* name, Object** location) {
#ifdef ENABLE_LOGGING_AND_PROFILING
420
  if (!Log::IsEnabled() || !FLAG_log_handles) return;
421
  LogMessageBuilder msg;
422
  msg.Append("%s,0x%" V8PRIxPTR "\n", name, location);
423
  msg.WriteToLogFile();
424 425 426 427 428 429
#endif
}


#ifdef ENABLE_LOGGING_AND_PROFILING
// ApiEvent is private so all the calls come from the Logger class.  It is the
430
// caller's responsibility to ensure that log is enabled and that
431 432
// FLAG_log_api is true.
void Logger::ApiEvent(const char* format, ...) {
433
  ASSERT(Log::IsEnabled() && FLAG_log_api);
434
  LogMessageBuilder msg;
435 436
  va_list ap;
  va_start(ap, format);
437
  msg.AppendVA(format, ap);
438 439
  va_end(ap);
  msg.WriteToLogFile();
440 441 442 443 444 445
}
#endif


void Logger::ApiNamedSecurityCheck(Object* key) {
#ifdef ENABLE_LOGGING_AND_PROFILING
446
  if (!Log::IsEnabled() || !FLAG_log_api) return;
447 448 449 450 451 452 453 454 455 456 457 458 459 460
  if (key->IsString()) {
    SmartPointer<char> str =
        String::cast(key)->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
    ApiEvent("api,check-security,\"%s\"\n", *str);
  } else if (key->IsUndefined()) {
    ApiEvent("api,check-security,undefined\n");
  } else {
    ApiEvent("api,check-security,['no-name']\n");
  }
#endif
}


void Logger::SharedLibraryEvent(const char* library_path,
461 462
                                uintptr_t start,
                                uintptr_t end) {
463
#ifdef ENABLE_LOGGING_AND_PROFILING
464
  if (!Log::IsEnabled() || !FLAG_prof) return;
465
  LogMessageBuilder msg;
466 467 468 469
  msg.Append("shared-library,\"%s\",0x%08" V8PRIxPTR ",0x%08" V8PRIxPTR "\n",
             library_path,
             start,
             end);
470
  msg.WriteToLogFile();
471 472 473 474 475
#endif
}


void Logger::SharedLibraryEvent(const wchar_t* library_path,
476 477
                                uintptr_t start,
                                uintptr_t end) {
478
#ifdef ENABLE_LOGGING_AND_PROFILING
479
  if (!Log::IsEnabled() || !FLAG_prof) return;
480
  LogMessageBuilder msg;
481 482 483 484
  msg.Append("shared-library,\"%ls\",0x%08" V8PRIxPTR ",0x%08" V8PRIxPTR "\n",
             library_path,
             start,
             end);
485
  msg.WriteToLogFile();
486 487 488
#endif
}

489 490

#ifdef ENABLE_LOGGING_AND_PROFILING
491
void Logger::LogRegExpSource(Handle<JSRegExp> regexp) {
492
  // Prints "/" + re.source + "/" +
493
  //      (re.global?"g":"") + (re.ignorecase?"i":"") + (re.multiline?"m":"")
494
  LogMessageBuilder msg;
495 496 497

  Handle<Object> source = GetProperty(regexp, "source");
  if (!source->IsString()) {
498
    msg.Append("no source");
499 500 501
    return;
  }

502
  switch (regexp->TypeTag()) {
503
    case JSRegExp::ATOM:
504
      msg.Append('a');
505 506 507 508
      break;
    default:
      break;
  }
509 510 511
  msg.Append('/');
  msg.AppendDetailed(*Handle<String>::cast(source), false);
  msg.Append('/');
512 513 514 515

  // global flag
  Handle<Object> global = GetProperty(regexp, "global");
  if (global->IsTrue()) {
516
    msg.Append('g');
517 518 519 520
  }
  // ignorecase flag
  Handle<Object> ignorecase = GetProperty(regexp, "ignoreCase");
  if (ignorecase->IsTrue()) {
521
    msg.Append('i');
522 523 524 525
  }
  // multiline flag
  Handle<Object> multiline = GetProperty(regexp, "multiline");
  if (multiline->IsTrue()) {
526
    msg.Append('m');
527
  }
528 529

  msg.WriteToLogFile();
530
}
531
#endif  // ENABLE_LOGGING_AND_PROFILING
532 533


534
void Logger::RegExpCompileEvent(Handle<JSRegExp> regexp, bool in_cache) {
535
#ifdef ENABLE_LOGGING_AND_PROFILING
536
  if (!Log::IsEnabled() || !FLAG_log_regexp) return;
537 538
  LogMessageBuilder msg;
  msg.Append("regexp-compile,");
539
  LogRegExpSource(regexp);
540 541
  msg.Append(in_cache ? ",hit\n" : ",miss\n");
  msg.WriteToLogFile();
542 543 544 545
#endif
}


546
void Logger::LogRuntime(Vector<const char> format, JSArray* args) {
547
#ifdef ENABLE_LOGGING_AND_PROFILING
548
  if (!Log::IsEnabled() || !FLAG_log_runtime) return;
549
  HandleScope scope;
550
  LogMessageBuilder msg;
551 552 553 554 555
  for (int i = 0; i < format.length(); i++) {
    char c = format[i];
    if (c == '%' && i <= format.length() - 2) {
      i++;
      ASSERT('0' <= format[i] && format[i] <= '9');
556 557 558 559 560 561
      MaybeObject* maybe = args->GetElement(format[i] - '0');
      Object* obj;
      if (!maybe->ToObject(&obj)) {
        msg.Append("<exception>");
        continue;
      }
562 563 564
      i++;
      switch (format[i]) {
        case 's':
565
          msg.AppendDetailed(String::cast(obj), false);
566 567
          break;
        case 'S':
568
          msg.AppendDetailed(String::cast(obj), true);
569 570 571 572 573
          break;
        case 'r':
          Logger::LogRegExpSource(Handle<JSRegExp>(JSRegExp::cast(obj)));
          break;
        case 'x':
574
          msg.Append("0x%x", Smi::cast(obj)->value());
575 576
          break;
        case 'i':
577
          msg.Append("%i", Smi::cast(obj)->value());
578 579 580 581 582
          break;
        default:
          UNREACHABLE();
      }
    } else {
583
      msg.Append(c);
584 585
    }
  }
586 587
  msg.Append('\n');
  msg.WriteToLogFile();
588
#endif
589 590 591
}


592 593
void Logger::ApiIndexedSecurityCheck(uint32_t index) {
#ifdef ENABLE_LOGGING_AND_PROFILING
594
  if (!Log::IsEnabled() || !FLAG_log_api) return;
595 596 597 598 599 600 601 602 603 604
  ApiEvent("api,check-security,%u\n", index);
#endif
}


void Logger::ApiNamedPropertyAccess(const char* tag,
                                    JSObject* holder,
                                    Object* name) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  ASSERT(name->IsString());
605
  if (!Log::IsEnabled() || !FLAG_log_api) return;
606 607 608 609 610 611 612 613 614 615 616 617 618
  String* class_name_obj = holder->class_name();
  SmartPointer<char> class_name =
      class_name_obj->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  SmartPointer<char> property_name =
      String::cast(name)->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  Logger::ApiEvent("api,%s,\"%s\",\"%s\"\n", tag, *class_name, *property_name);
#endif
}

void Logger::ApiIndexedPropertyAccess(const char* tag,
                                      JSObject* holder,
                                      uint32_t index) {
#ifdef ENABLE_LOGGING_AND_PROFILING
619
  if (!Log::IsEnabled() || !FLAG_log_api) return;
620 621 622 623 624 625 626 627 628
  String* class_name_obj = holder->class_name();
  SmartPointer<char> class_name =
      class_name_obj->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  Logger::ApiEvent("api,%s,\"%s\",%u\n", tag, *class_name, index);
#endif
}

void Logger::ApiObjectAccess(const char* tag, JSObject* object) {
#ifdef ENABLE_LOGGING_AND_PROFILING
629
  if (!Log::IsEnabled() || !FLAG_log_api) return;
630 631 632 633 634 635 636 637 638 639
  String* class_name_obj = object->class_name();
  SmartPointer<char> class_name =
      class_name_obj->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  Logger::ApiEvent("api,%s,\"%s\"\n", tag, *class_name);
#endif
}


void Logger::ApiEntryCall(const char* name) {
#ifdef ENABLE_LOGGING_AND_PROFILING
640
  if (!Log::IsEnabled() || !FLAG_log_api) return;
641 642 643 644 645 646 647
  Logger::ApiEvent("api,%s\n", name);
#endif
}


void Logger::NewEvent(const char* name, void* object, size_t size) {
#ifdef ENABLE_LOGGING_AND_PROFILING
648
  if (!Log::IsEnabled() || !FLAG_log) return;
649
  LogMessageBuilder msg;
650
  msg.Append("new,%s,0x%" V8PRIxPTR ",%u\n", name, object,
651 652
             static_cast<unsigned int>(size));
  msg.WriteToLogFile();
653 654 655 656 657 658
#endif
}


void Logger::DeleteEvent(const char* name, void* object) {
#ifdef ENABLE_LOGGING_AND_PROFILING
659
  if (!Log::IsEnabled() || !FLAG_log) return;
660
  LogMessageBuilder msg;
661
  msg.Append("delete,%s,0x%" V8PRIxPTR "\n", name, object);
662
  msg.WriteToLogFile();
663 664 665 666
#endif
}


667
#ifdef ENABLE_LOGGING_AND_PROFILING
668 669
void Logger::CallbackEventInternal(const char* prefix, const char* name,
                                   Address entry_point) {
670 671 672
  if (!Log::IsEnabled() || !FLAG_log_code) return;
  LogMessageBuilder msg;
  msg.Append("%s,%s,",
673 674
             kLogEventsNames[CODE_CREATION_EVENT],
             kLogEventsNames[CALLBACK_TAG]);
675
  msg.AppendAddress(entry_point);
676
  msg.Append(",1,\"%s%s\"", prefix, name);
677 678
  msg.Append('\n');
  msg.WriteToLogFile();
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
}
#endif


void Logger::CallbackEvent(String* name, Address entry_point) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_code) return;
  SmartPointer<char> str =
      name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  CallbackEventInternal("", *str, entry_point);
#endif
}


void Logger::GetterCallbackEvent(String* name, Address entry_point) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_code) return;
  SmartPointer<char> str =
      name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  CallbackEventInternal("get ", *str, entry_point);
#endif
}


void Logger::SetterCallbackEvent(String* name, Address entry_point) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_code) return;
  SmartPointer<char> str =
      name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  CallbackEventInternal("set ", *str, entry_point);
709 710 711 712
#endif
}


713
#ifdef ENABLE_LOGGING_AND_PROFILING
714 715 716 717 718 719 720
static const char* ComputeMarker(Code* code) {
  switch (code->kind()) {
    case Code::FUNCTION: return code->optimizable() ? "~" : "";
    case Code::OPTIMIZED_FUNCTION: return "*";
    default: return "";
  }
}
721
#endif
722 723


724 725 726
void Logger::CodeCreateEvent(LogEventsAndTags tag,
                             Code* code,
                             const char* comment) {
727
#ifdef ENABLE_LOGGING_AND_PROFILING
728
  if (!Log::IsEnabled() || !FLAG_log_code) return;
729
  LogMessageBuilder msg;
730 731 732
  msg.Append("%s,%s,",
             kLogEventsNames[CODE_CREATION_EVENT],
             kLogEventsNames[tag]);
733
  msg.AppendAddress(code->address());
734
  msg.Append(",%d,\"%s", code->ExecutableSize(), ComputeMarker(code));
735
  for (const char* p = comment; *p != '\0'; p++) {
736 737 738
    if (*p == '"') {
      msg.Append('\\');
    }
739
    msg.Append(*p);
740
  }
741
  msg.Append('"');
742
  LowLevelCodeCreateEvent(code, &msg);
743 744
  msg.Append('\n');
  msg.WriteToLogFile();
745 746 747 748
#endif
}


749
void Logger::CodeCreateEvent(LogEventsAndTags tag, Code* code, String* name) {
750
#ifdef ENABLE_LOGGING_AND_PROFILING
751
  if (!Log::IsEnabled() || !FLAG_log_code) return;
752
  LogMessageBuilder msg;
753 754
  SmartPointer<char> str =
      name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
755 756 757
  msg.Append("%s,%s,",
             kLogEventsNames[CODE_CREATION_EVENT],
             kLogEventsNames[tag]);
758
  msg.AppendAddress(code->address());
759
  msg.Append(",%d,\"%s%s\"", code->ExecutableSize(), ComputeMarker(code), *str);
760
  LowLevelCodeCreateEvent(code, &msg);
761
  msg.Append('\n');
762
  msg.WriteToLogFile();
763 764 765 766
#endif
}


767 768
void Logger::CodeCreateEvent(LogEventsAndTags tag,
                             Code* code, String* name,
769 770
                             String* source, int line) {
#ifdef ENABLE_LOGGING_AND_PROFILING
771
  if (!Log::IsEnabled() || !FLAG_log_code) return;
772
  LogMessageBuilder msg;
773 774 775 776
  SmartPointer<char> str =
      name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  SmartPointer<char> sourcestr =
      source->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
777 778 779
  msg.Append("%s,%s,",
             kLogEventsNames[CODE_CREATION_EVENT],
             kLogEventsNames[tag]);
780
  msg.AppendAddress(code->address());
781 782 783 784 785 786
  msg.Append(",%d,\"%s%s %s:%d\"",
             code->ExecutableSize(),
             ComputeMarker(code),
             *str,
             *sourcestr,
             line);
787
  LowLevelCodeCreateEvent(code, &msg);
788
  msg.Append('\n');
789
  msg.WriteToLogFile();
790 791 792 793
#endif
}


794
void Logger::CodeCreateEvent(LogEventsAndTags tag, Code* code, int args_count) {
795
#ifdef ENABLE_LOGGING_AND_PROFILING
796
  if (!Log::IsEnabled() || !FLAG_log_code) return;
797
  LogMessageBuilder msg;
798 799 800
  msg.Append("%s,%s,",
             kLogEventsNames[CODE_CREATION_EVENT],
             kLogEventsNames[tag]);
801
  msg.AppendAddress(code->address());
802
  msg.Append(",%d,\"args_count: %d\"", code->ExecutableSize(), args_count);
803
  LowLevelCodeCreateEvent(code, &msg);
804
  msg.Append('\n');
805
  msg.WriteToLogFile();
806 807 808 809
#endif
}


810 811 812 813
void Logger::CodeMovingGCEvent() {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_code || !FLAG_ll_prof) return;
  LogMessageBuilder msg;
814
  msg.Append("%s\n", kLogEventsNames[CODE_MOVING_GC]);
815 816 817 818 819 820
  msg.WriteToLogFile();
  OS::SignalCodeMovingGC();
#endif
}


821 822
void Logger::RegExpCodeCreateEvent(Code* code, String* source) {
#ifdef ENABLE_LOGGING_AND_PROFILING
823
  if (!Log::IsEnabled() || !FLAG_log_code) return;
824
  LogMessageBuilder msg;
825
  msg.Append("%s,%s,",
826 827
             kLogEventsNames[CODE_CREATION_EVENT],
             kLogEventsNames[REG_EXP_TAG]);
828 829
  msg.AppendAddress(code->address());
  msg.Append(",%d,\"", code->ExecutableSize());
830
  msg.AppendDetailed(source, false);
831
  msg.Append('\"');
832
  LowLevelCodeCreateEvent(code, &msg);
833
  msg.Append('\n');
834 835 836 837 838
  msg.WriteToLogFile();
#endif
}


839 840
void Logger::CodeMoveEvent(Address from, Address to) {
#ifdef ENABLE_LOGGING_AND_PROFILING
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
  MoveEventInternal(CODE_MOVE_EVENT, from, to);
#endif
}


void Logger::CodeDeleteEvent(Address from) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  DeleteEventInternal(CODE_DELETE_EVENT, from);
#endif
}


void Logger::SnapshotPositionEvent(Address addr, int pos) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_snapshot_positions) return;
  LogMessageBuilder msg;
857
  msg.Append("%s,", kLogEventsNames[SNAPSHOT_POSITION_EVENT]);
858 859 860 861 862 863 864 865 866 867
  msg.AppendAddress(addr);
  msg.Append(",%d", pos);
  msg.Append('\n');
  msg.WriteToLogFile();
#endif
}


void Logger::FunctionCreateEvent(JSFunction* function) {
#ifdef ENABLE_LOGGING_AND_PROFILING
868 869 870
  // This function can be called from GC iterators (during Scavenge,
  // MC, and MS), so marking bits can be set on objects. That's
  // why unchecked accessors are used here.
871
  if (!Log::IsEnabled() || !FLAG_log_code) return;
872
  LogMessageBuilder msg;
873
  msg.Append("%s,", kLogEventsNames[FUNCTION_CREATION_EVENT]);
874
  msg.AppendAddress(function->address());
875
  msg.Append(',');
876
  msg.AppendAddress(function->unchecked_code()->address());
877
  msg.Append('\n');
878
  msg.WriteToLogFile();
879 880 881 882
#endif
}


883
void Logger::FunctionCreateEventFromMove(JSFunction* function) {
884 885 886 887 888 889 890 891
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (function->unchecked_code() != Builtins::builtin(Builtins::LazyCompile)) {
    FunctionCreateEvent(function);
  }
#endif
}


892
void Logger::FunctionMoveEvent(Address from, Address to) {
893
#ifdef ENABLE_LOGGING_AND_PROFILING
894 895 896 897 898 899 900 901 902 903 904 905
  MoveEventInternal(FUNCTION_MOVE_EVENT, from, to);
#endif
}


void Logger::FunctionDeleteEvent(Address from) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  DeleteEventInternal(FUNCTION_DELETE_EVENT, from);
#endif
}


906
#ifdef ENABLE_LOGGING_AND_PROFILING
907 908 909
void Logger::MoveEventInternal(LogEventsAndTags event,
                               Address from,
                               Address to) {
910
  if (!Log::IsEnabled() || !FLAG_log_code) return;
911
  LogMessageBuilder msg;
912
  msg.Append("%s,", kLogEventsNames[event]);
913
  msg.AppendAddress(from);
914
  msg.Append(',');
915
  msg.AppendAddress(to);
916
  msg.Append('\n');
917
  msg.WriteToLogFile();
918
}
919
#endif
920 921


922
#ifdef ENABLE_LOGGING_AND_PROFILING
923
void Logger::DeleteEventInternal(LogEventsAndTags event, Address from) {
924
  if (!Log::IsEnabled() || !FLAG_log_code) return;
925
  LogMessageBuilder msg;
926
  msg.Append("%s,", kLogEventsNames[event]);
927
  msg.AppendAddress(from);
928 929 930
  msg.Append('\n');
  msg.WriteToLogFile();
}
931
#endif
932 933


934 935
void Logger::ResourceEvent(const char* name, const char* tag) {
#ifdef ENABLE_LOGGING_AND_PROFILING
936
  if (!Log::IsEnabled() || !FLAG_log) return;
937 938
  LogMessageBuilder msg;
  msg.Append("%s,%s,", name, tag);
939 940 941

  uint32_t sec, usec;
  if (OS::GetUserTime(&sec, &usec) != -1) {
942
    msg.Append("%d,%d,", sec, usec);
943
  }
944
  msg.Append("%.0f", OS::TimeCurrentMillis());
945

946 947
  msg.Append('\n');
  msg.WriteToLogFile();
948 949 950 951
#endif
}


952
void Logger::SuspectReadEvent(String* name, Object* obj) {
953
#ifdef ENABLE_LOGGING_AND_PROFILING
954
  if (!Log::IsEnabled() || !FLAG_log_suspect) return;
955
  LogMessageBuilder msg;
956 957 958
  String* class_name = obj->IsJSObject()
                       ? JSObject::cast(obj)->class_name()
                       : Heap::empty_string();
959 960 961 962 963 964 965 966
  msg.Append("suspect-read,");
  msg.Append(class_name);
  msg.Append(',');
  msg.Append('"');
  msg.Append(name);
  msg.Append('"');
  msg.Append('\n');
  msg.WriteToLogFile();
967 968 969 970 971 972
#endif
}


void Logger::HeapSampleBeginEvent(const char* space, const char* kind) {
#ifdef ENABLE_LOGGING_AND_PROFILING
973
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
974
  LogMessageBuilder msg;
975 976 977 978 979 980 981 982 983 984
  // 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\n",
             space, kind, OS::TimeCurrentMillis());
  msg.WriteToLogFile();
#endif
}


void Logger::HeapSampleStats(const char* space, const char* kind,
985
                             intptr_t capacity, intptr_t used) {
986 987 988
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
  LogMessageBuilder msg;
989 990
  msg.Append("heap-sample-stats,\"%s\",\"%s\","
                 "%" V8_PTR_PREFIX "d,%" V8_PTR_PREFIX "d\n",
991
             space, kind, capacity, used);
992
  msg.WriteToLogFile();
993 994 995 996 997 998
#endif
}


void Logger::HeapSampleEndEvent(const char* space, const char* kind) {
#ifdef ENABLE_LOGGING_AND_PROFILING
999
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
1000 1001 1002
  LogMessageBuilder msg;
  msg.Append("heap-sample-end,\"%s\",\"%s\"\n", space, kind);
  msg.WriteToLogFile();
1003 1004 1005 1006 1007 1008
#endif
}


void Logger::HeapSampleItemEvent(const char* type, int number, int bytes) {
#ifdef ENABLE_LOGGING_AND_PROFILING
1009
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
1010 1011 1012
  LogMessageBuilder msg;
  msg.Append("heap-sample-item,%s,%d,%d\n", type, number, bytes);
  msg.WriteToLogFile();
1013 1014 1015 1016
#endif
}


1017 1018 1019 1020 1021
void Logger::HeapSampleJSConstructorEvent(const char* constructor,
                                          int number, int bytes) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
  LogMessageBuilder msg;
1022
  msg.Append("heap-js-cons-item,%s,%d,%d\n", constructor, number, bytes);
1023 1024 1025 1026 1027
  msg.WriteToLogFile();
#endif
}


1028 1029
void Logger::HeapSampleJSRetainersEvent(
    const char* constructor, const char* event) {
1030 1031
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
1032 1033 1034
  // Event starts with comma, so we don't have it in the format string.
  static const char* event_text = "heap-js-ret-item,%s";
  // We take placeholder strings into account, but it's OK to be conservative.
1035 1036 1037
  static const int event_text_len = StrLength(event_text);
  const int cons_len = StrLength(constructor);
  const int event_len = StrLength(event);
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
  int pos = 0;
  // Retainer lists can be long. We may need to split them into multiple events.
  do {
    LogMessageBuilder msg;
    msg.Append(event_text, constructor);
    int to_write = event_len - pos;
    if (to_write > Log::kMessageBufferSize - (cons_len + event_text_len)) {
      int cut_pos = pos + Log::kMessageBufferSize - (cons_len + event_text_len);
      ASSERT(cut_pos < event_len);
      while (cut_pos > pos && event[cut_pos] != ',') --cut_pos;
      if (event[cut_pos] != ',') {
        // Crash in debug mode, skip in release mode.
        ASSERT(false);
        return;
      }
      // Append a piece of event that fits, without trailing comma.
      msg.AppendStringPart(event + pos, cut_pos - pos);
      // Start next piece with comma.
      pos = cut_pos;
    } else {
      msg.Append("%s", event + pos);
      pos += event_len;
    }
    msg.Append('\n');
    msg.WriteToLogFile();
  } while (pos < event_len);
1064 1065 1066 1067
#endif
}


1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
void Logger::HeapSampleJSProducerEvent(const char* constructor,
                                       Address* stack) {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_gc) return;
  LogMessageBuilder msg;
  msg.Append("heap-js-prod-item,%s", constructor);
  while (*stack != NULL) {
    msg.Append(",0x%" V8PRIxPTR, *stack++);
  }
  msg.Append("\n");
  msg.WriteToLogFile();
#endif
}


1083 1084
void Logger::DebugTag(const char* call_site_tag) {
#ifdef ENABLE_LOGGING_AND_PROFILING
1085
  if (!Log::IsEnabled() || !FLAG_log) return;
1086 1087 1088
  LogMessageBuilder msg;
  msg.Append("debug-tag,%s\n", call_site_tag);
  msg.WriteToLogFile();
1089 1090 1091 1092 1093 1094
#endif
}


void Logger::DebugEvent(const char* event_type, Vector<uint16_t> parameter) {
#ifdef ENABLE_LOGGING_AND_PROFILING
1095
  if (!Log::IsEnabled() || !FLAG_log) return;
1096 1097 1098 1099 1100
  StringBuilder s(parameter.length() + 1);
  for (int i = 0; i < parameter.length(); ++i) {
    s.AddCharacter(static_cast<char>(parameter[i]));
  }
  char* parameter_string = s.Finalize();
1101 1102 1103 1104 1105
  LogMessageBuilder msg;
  msg.Append("debug-queue-event,%s,%15.3f,%s\n",
             event_type,
             OS::TimeCurrentMillis(),
             parameter_string);
1106
  DeleteArray(parameter_string);
1107
  msg.WriteToLogFile();
1108 1109 1110 1111
#endif
}


1112 1113
#ifdef ENABLE_LOGGING_AND_PROFILING
void Logger::TickEvent(TickSample* sample, bool overflow) {
1114
  if (!Log::IsEnabled() || !FLAG_prof) return;
1115
  LogMessageBuilder msg;
1116 1117
  msg.Append("%s,", kLogEventsNames[TICK_EVENT]);
  msg.AppendAddress(sample->pc);
1118
  msg.Append(',');
1119
  msg.AppendAddress(sample->sp);
1120
  msg.Append(',');
1121
  msg.AppendAddress(sample->function);
1122
  msg.Append(",%d", static_cast<int>(sample->state));
1123 1124 1125
  if (overflow) {
    msg.Append(",overflow");
  }
1126
  for (int i = 0; i < sample->frames_count; ++i) {
1127
    msg.Append(',');
1128
    msg.AppendAddress(sample->stack[i]);
1129
  }
1130 1131
  msg.Append('\n');
  msg.WriteToLogFile();
1132
}
1133 1134


1135 1136
int Logger::GetActiveProfilerModules() {
  int result = PROFILER_MODULE_NONE;
1137
  if (profiler_ != NULL && !profiler_->paused()) {
1138 1139 1140 1141 1142 1143
    result |= PROFILER_MODULE_CPU;
  }
  if (FLAG_log_gc) {
    result |= PROFILER_MODULE_HEAP_STATS | PROFILER_MODULE_JS_CONSTRUCTORS;
  }
  return result;
1144 1145 1146
}


1147
void Logger::PauseProfiler(int flags, int tag) {
1148
  if (!Log::IsEnabled()) return;
1149
  if (profiler_ != NULL && (flags & PROFILER_MODULE_CPU)) {
1150 1151 1152 1153
    // It is OK to have negative nesting.
    if (--cpu_profiler_nesting_ == 0) {
      profiler_->pause();
      if (FLAG_prof_lazy) {
1154 1155 1156
        if (!FLAG_sliding_state_window && !RuntimeProfiler::IsEnabled()) {
          ticker_->Stop();
        }
1157 1158 1159 1160
        FLAG_log_code = false;
        // Must be the same message as Log::kDynamicBufferSeal.
        LOG(UncheckedStringEvent("profiler", "pause"));
      }
1161
      --logging_nesting_;
1162
    }
1163
  }
1164
  if (flags &
1165
      (PROFILER_MODULE_HEAP_STATS | PROFILER_MODULE_JS_CONSTRUCTORS)) {
1166 1167
    if (--heap_profiler_nesting_ == 0) {
      FLAG_log_gc = false;
1168
      --logging_nesting_;
1169 1170 1171
    }
  }
  if (tag != 0) {
1172
    UncheckedIntEvent("close-tag", tag);
1173
  }
1174 1175 1176
}


1177
void Logger::ResumeProfiler(int flags, int tag) {
1178
  if (!Log::IsEnabled()) return;
1179
  if (tag != 0) {
1180
    UncheckedIntEvent("open-tag", tag);
1181
  }
1182
  if (profiler_ != NULL && (flags & PROFILER_MODULE_CPU)) {
1183
    if (cpu_profiler_nesting_++ == 0) {
1184
      ++logging_nesting_;
1185 1186 1187 1188 1189 1190 1191
      if (FLAG_prof_lazy) {
        profiler_->Engage();
        LOG(UncheckedStringEvent("profiler", "resume"));
        FLAG_log_code = true;
        LogCompiledFunctions();
        LogFunctionObjects();
        LogAccessorCallbacks();
1192 1193 1194
        if (!FLAG_sliding_state_window && !ticker_->IsActive()) {
          ticker_->Start();
        }
1195 1196
      }
      profiler_->resume();
1197
    }
1198
  }
1199
  if (flags &
1200
      (PROFILER_MODULE_HEAP_STATS | PROFILER_MODULE_JS_CONSTRUCTORS)) {
1201
    if (heap_profiler_nesting_++ == 0) {
1202
      ++logging_nesting_;
1203 1204
      FLAG_log_gc = true;
    }
1205
  }
1206
}
1207 1208


1209 1210 1211 1212
// This function can be called when Log's mutex is acquired,
// either from main or Profiler's thread.
void Logger::StopLoggingAndProfiling() {
  Log::stop();
1213
  PauseProfiler(PROFILER_MODULE_CPU, 0);
1214 1215 1216
}


1217 1218 1219 1220 1221
bool Logger::IsProfilerSamplerActive() {
  return ticker_->IsActive();
}


1222 1223 1224 1225
int Logger::GetLogLines(int from_pos, char* dest_buf, int max_size) {
  return Log::GetLogLines(from_pos, dest_buf, max_size);
}

1226

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
class EnumerateOptimizedFunctionsVisitor: public OptimizedFunctionVisitor {
 public:
  EnumerateOptimizedFunctionsVisitor(Handle<SharedFunctionInfo>* sfis,
                                     Handle<Code>* code_objects,
                                     int* count)
      : sfis_(sfis), code_objects_(code_objects), count_(count) { }

  virtual void EnterContext(Context* context) {}
  virtual void LeaveContext(Context* context) {}

  virtual void VisitFunction(JSFunction* function) {
    if (sfis_ != NULL) {
      sfis_[*count_] = Handle<SharedFunctionInfo>(function->shared());
    }
    if (code_objects_ != NULL) {
      ASSERT(function->code()->kind() == Code::OPTIMIZED_FUNCTION);
      code_objects_[*count_] = Handle<Code>(function->code());
    }
    *count_ = *count_ + 1;
  }

 private:
  Handle<SharedFunctionInfo>* sfis_;
  Handle<Code>* code_objects_;
  int* count_;
};


static int EnumerateCompiledFunctions(Handle<SharedFunctionInfo>* sfis,
                                      Handle<Code>* code_objects) {
1257
  AssertNoAllocation no_alloc;
1258
  int compiled_funcs_count = 0;
1259 1260 1261

  // Iterate the heap to find shared function info objects and record
  // the unoptimized code for them.
1262
  HeapIterator iterator;
1263
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
1264 1265 1266 1267 1268
    if (!obj->IsSharedFunctionInfo()) continue;
    SharedFunctionInfo* sfi = SharedFunctionInfo::cast(obj);
    if (sfi->is_compiled()
        && (!sfi->script()->IsScript()
            || Script::cast(sfi->script())->HasValidSource())) {
1269
      if (sfis != NULL) {
1270
        sfis[compiled_funcs_count] = Handle<SharedFunctionInfo>(sfi);
1271 1272 1273 1274
      }
      if (code_objects != NULL) {
        code_objects[compiled_funcs_count] = Handle<Code>(sfi->code());
      }
1275
      ++compiled_funcs_count;
1276
    }
1277
  }
1278 1279 1280 1281 1282 1283 1284

  // Iterate all optimized functions in all contexts.
  EnumerateOptimizedFunctionsVisitor visitor(sfis,
                                             code_objects,
                                             &compiled_funcs_count);
  Deoptimizer::VisitAllOptimizedFunctions(&visitor);

1285 1286
  return compiled_funcs_count;
}
1287 1288


1289 1290 1291 1292 1293 1294 1295
void Logger::LogCodeObject(Object* object) {
  if (FLAG_log_code) {
    Code* code_object = Code::cast(object);
    LogEventsAndTags tag = Logger::STUB_TAG;
    const char* description = "Unknown code from the snapshot";
    switch (code_object->kind()) {
      case Code::FUNCTION:
1296
      case Code::OPTIMIZED_FUNCTION:
1297
        return;  // We log this later using LogCompiledFunctions.
1298 1299 1300
      case Code::BINARY_OP_IC:  // fall through
      case Code::TYPE_RECORDING_BINARY_OP_IC:   // fall through
      case Code::COMPARE_IC:  // fall through
1301
      case Code::STUB:
1302 1303
        description =
            CodeStub::MajorName(CodeStub::GetMajorKey(code_object), true);
1304 1305
        if (description == NULL)
          description = "A stub from the snapshot";
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
        tag = Logger::STUB_TAG;
        break;
      case Code::BUILTIN:
        description = "A builtin from the snapshot";
        tag = Logger::BUILTIN_TAG;
        break;
      case Code::KEYED_LOAD_IC:
        description = "A keyed load IC from the snapshot";
        tag = Logger::KEYED_LOAD_IC_TAG;
        break;
      case Code::LOAD_IC:
        description = "A load IC from the snapshot";
        tag = Logger::LOAD_IC_TAG;
        break;
      case Code::STORE_IC:
        description = "A store IC from the snapshot";
        tag = Logger::STORE_IC_TAG;
        break;
      case Code::KEYED_STORE_IC:
        description = "A keyed store IC from the snapshot";
        tag = Logger::KEYED_STORE_IC_TAG;
        break;
      case Code::CALL_IC:
        description = "A call IC from the snapshot";
        tag = Logger::CALL_IC_TAG;
        break;
1332 1333 1334 1335
      case Code::KEYED_CALL_IC:
        description = "A keyed call IC from the snapshot";
        tag = Logger::KEYED_CALL_IC_TAG;
        break;
1336
    }
1337
    PROFILE(CodeCreateEvent(tag, code_object, description));
1338 1339 1340 1341
  }
}


1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
void Logger::LogCodeInfo() {
#ifdef ENABLE_LOGGING_AND_PROFILING
  if (!Log::IsEnabled() || !FLAG_log_code || !FLAG_ll_prof) return;
#if V8_TARGET_ARCH_IA32
  const char arch[] = "ia32";
#elif V8_TARGET_ARCH_X64
  const char arch[] = "x64";
#elif V8_TARGET_ARCH_ARM
  const char arch[] = "arm";
#else
  const char arch[] = "unknown";
#endif
  LogMessageBuilder msg;
  msg.Append("code-info,%s,%d\n", arch, Code::kHeaderSize);
  msg.WriteToLogFile();
#endif  // ENABLE_LOGGING_AND_PROFILING
}


void Logger::LowLevelCodeCreateEvent(Code* code, LogMessageBuilder* msg) {
  if (!FLAG_ll_prof || Log::output_code_handle_ == NULL) return;
  int pos = static_cast<int>(ftell(Log::output_code_handle_));
1364 1365
  size_t rv = fwrite(code->instruction_start(), 1, code->instruction_size(),
                     Log::output_code_handle_);
1366 1367
  ASSERT(static_cast<size_t>(code->instruction_size()) == rv);
  USE(rv);
1368 1369 1370 1371
  msg->Append(",%d", pos);
}


1372 1373 1374 1375 1376 1377 1378 1379 1380
void Logger::LogCodeObjects() {
  AssertNoAllocation no_alloc;
  HeapIterator iterator;
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
    if (obj->IsCode()) LogCodeObject(obj);
  }
}


1381 1382
void Logger::LogCompiledFunctions() {
  HandleScope scope;
1383
  const int compiled_funcs_count = EnumerateCompiledFunctions(NULL, NULL);
1384
  ScopedVector< Handle<SharedFunctionInfo> > sfis(compiled_funcs_count);
1385 1386
  ScopedVector< Handle<Code> > code_objects(compiled_funcs_count);
  EnumerateCompiledFunctions(sfis.start(), code_objects.start());
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400

  // During iteration, there can be heap allocation due to
  // GetScriptLineNumber call.
  for (int i = 0; i < compiled_funcs_count; ++i) {
    Handle<SharedFunctionInfo> shared = sfis[i];
    Handle<String> name(String::cast(shared->name()));
    Handle<String> func_name(name->length() > 0 ?
                             *name : shared->inferred_name());
    if (shared->script()->IsScript()) {
      Handle<Script> script(Script::cast(shared->script()));
      if (script->name()->IsString()) {
        Handle<String> script_name(String::cast(script->name()));
        int line_num = GetScriptLineNumber(script, shared->start_position());
        if (line_num > 0) {
1401 1402
          PROFILE(CodeCreateEvent(
              Logger::ToNativeByScript(Logger::LAZY_COMPILE_TAG, *script),
1403
              *code_objects[i], *func_name,
1404
              *script_name, line_num + 1));
1405
        } else {
1406 1407 1408
          // Can't distinguish eval and script here, so always use Script.
          PROFILE(CodeCreateEvent(
              Logger::ToNativeByScript(Logger::SCRIPT_TAG, *script),
1409
              *code_objects[i], *script_name));
1410
        }
1411
      } else {
1412
        PROFILE(CodeCreateEvent(
1413
            Logger::ToNativeByScript(Logger::LAZY_COMPILE_TAG, *script),
1414
            *code_objects[i], *func_name));
1415
      }
1416
    } else if (shared->IsApiFunction()) {
1417
      // API function.
1418
      FunctionTemplateInfo* fun_data = shared->get_api_func_data();
1419 1420 1421 1422 1423
      Object* raw_call_data = fun_data->call_code();
      if (!raw_call_data->IsUndefined()) {
        CallHandlerInfo* call_data = CallHandlerInfo::cast(raw_call_data);
        Object* callback_obj = call_data->callback();
        Address entry_point = v8::ToCData<Address>(callback_obj);
1424
        PROFILE(CallbackEvent(*func_name, entry_point));
1425
      }
1426
    } else {
1427
      PROFILE(CodeCreateEvent(
1428
          Logger::LAZY_COMPILE_TAG, *code_objects[i], *func_name));
1429 1430 1431 1432
    }
  }
}

1433

1434 1435 1436
void Logger::LogFunctionObjects() {
  AssertNoAllocation no_alloc;
  HeapIterator iterator;
1437
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
1438 1439 1440
    if (!obj->IsJSFunction()) continue;
    JSFunction* jsf = JSFunction::cast(obj);
    if (!jsf->is_compiled()) continue;
1441
    PROFILE(FunctionCreateEvent(jsf));
1442 1443 1444 1445
  }
}


1446 1447 1448
void Logger::LogAccessorCallbacks() {
  AssertNoAllocation no_alloc;
  HeapIterator iterator;
1449
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
1450 1451 1452 1453 1454 1455
    if (!obj->IsAccessorInfo()) continue;
    AccessorInfo* ai = AccessorInfo::cast(obj);
    if (!ai->name()->IsString()) continue;
    String* name = String::cast(ai->name());
    Address getter_entry = v8::ToCData<Address>(ai->getter());
    if (getter_entry != 0) {
1456
      PROFILE(GetterCallbackEvent(name, getter_entry));
1457 1458 1459
    }
    Address setter_entry = v8::ToCData<Address>(ai->setter());
    if (setter_entry != 0) {
1460
      PROFILE(SetterCallbackEvent(name, setter_entry));
1461 1462 1463 1464
    }
  }
}

1465 1466 1467 1468 1469 1470 1471
#endif


bool Logger::Setup() {
#ifdef ENABLE_LOGGING_AND_PROFILING
  // --log-all enables all the log flags.
  if (FLAG_log_all) {
1472
    FLAG_log_runtime = true;
1473 1474 1475 1476 1477
    FLAG_log_api = true;
    FLAG_log_code = true;
    FLAG_log_gc = true;
    FLAG_log_suspect = true;
    FLAG_log_handles = true;
1478
    FLAG_log_regexp = true;
1479 1480 1481 1482 1483
  }

  // --prof implies --log-code.
  if (FLAG_prof) FLAG_log_code = true;

1484 1485 1486 1487 1488 1489
  // --ll-prof implies --log-code and --log-snapshot-positions.
  if (FLAG_ll_prof) {
    FLAG_log_code = true;
    FLAG_log_snapshot_positions = true;
  }

1490 1491 1492 1493 1494 1495
  // --prof_lazy controls --log-code, implies --noprof_auto.
  if (FLAG_prof_lazy) {
    FLAG_log_code = false;
    FLAG_prof_auto = false;
  }

1496
  bool start_logging = FLAG_log || FLAG_log_runtime || FLAG_log_api
1497
      || FLAG_log_code || FLAG_log_gc || FLAG_log_handles || FLAG_log_suspect
1498 1499 1500
      || FLAG_log_regexp || FLAG_log_state_changes;

  bool open_log_file = start_logging || FLAG_prof_lazy;
1501 1502

  // If we're logging anything, we need to open the log file.
1503
  if (open_log_file) {
1504
    if (strcmp(FLAG_logfile, "-") == 0) {
1505 1506 1507
      Log::OpenStdout();
    } else if (strcmp(FLAG_logfile, "*") == 0) {
      Log::OpenMemoryBuffer();
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    } else if (strchr(FLAG_logfile, '%') != NULL) {
      // If there's a '%' in the log file name we have to expand
      // placeholders.
      HeapStringAllocator allocator;
      StringStream stream(&allocator);
      for (const char* p = FLAG_logfile; *p; p++) {
        if (*p == '%') {
          p++;
          switch (*p) {
            case '\0':
              // If there's a % at the end of the string we back up
              // one character so we can escape the loop properly.
              p--;
              break;
            case 't': {
              // %t expands to the current time in milliseconds.
1524 1525
              double time = OS::TimeCurrentMillis();
              stream.Add("%.0f", FmtElm(time));
1526 1527
              break;
            }
1528 1529 1530 1531
            case '%':
              // %% expands (contracts really) to %.
              stream.Put('%');
              break;
1532 1533
            default:
              // All other %'s expand to themselves.
1534
              stream.Put('%');
1535 1536 1537 1538 1539 1540 1541
              stream.Put(*p);
              break;
          }
        } else {
          stream.Put(*p);
        }
      }
1542
      SmartPointer<const char> expanded = stream.ToCString();
1543
      Log::OpenFile(*expanded);
1544
    } else {
1545
      Log::OpenFile(FLAG_logfile);
1546 1547 1548
    }
  }

1549 1550
  if (FLAG_ll_prof) LogCodeInfo();

1551
  ticker_ = new Ticker(kSamplingIntervalMs);
1552 1553 1554 1555 1556

  if (FLAG_sliding_state_window && sliding_state_window_ == NULL) {
    sliding_state_window_ = new SlidingStateWindow();
  }

1557 1558 1559
  if (start_logging) {
    logging_nesting_ = 1;
  }
1560

1561 1562
  if (FLAG_prof) {
    profiler_ = new Profiler();
1563
    if (!FLAG_prof_auto) {
1564
      profiler_->pause();
1565
    } else {
1566
      logging_nesting_ = 1;
1567
    }
1568 1569 1570
    if (!FLAG_prof_lazy) {
      profiler_->Engage();
    }
1571 1572
  }

1573
  LogMessageBuilder::set_write_failure_handler(StopLoggingAndProfiling);
1574 1575 1576 1577 1578 1579 1580 1581
  return true;

#else
  return false;
#endif
}


1582
void Logger::EnsureTickerStarted() {
1583
#ifdef ENABLE_LOGGING_AND_PROFILING
1584 1585
  ASSERT(ticker_ != NULL);
  if (!ticker_->IsActive()) ticker_->Start();
1586
#endif
1587 1588 1589 1590
}


void Logger::EnsureTickerStopped() {
1591
#ifdef ENABLE_LOGGING_AND_PROFILING
1592
  if (ticker_ != NULL && ticker_->IsActive()) ticker_->Stop();
1593
#endif
1594 1595 1596
}


1597 1598
void Logger::TearDown() {
#ifdef ENABLE_LOGGING_AND_PROFILING
1599 1600
  LogMessageBuilder::set_write_failure_handler(NULL);

1601 1602 1603 1604 1605 1606 1607 1608
  // Stop the profiler before closing the file.
  if (profiler_ != NULL) {
    profiler_->Disengage();
    delete profiler_;
    profiler_ = NULL;
  }

  delete sliding_state_window_;
1609
  sliding_state_window_ = NULL;
1610 1611

  delete ticker_;
1612
  ticker_ = NULL;
1613

1614
  Log::Close();
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
#endif
}


void Logger::EnableSlidingStateWindow() {
#ifdef ENABLE_LOGGING_AND_PROFILING
  // If the ticker is NULL, Logger::Setup has not been called yet.  In
  // that case, we set the sliding_state_window flag so that the
  // sliding window computation will be started when Logger::Setup is
  // called.
  if (ticker_ == NULL) {
    FLAG_sliding_state_window = true;
    return;
  }
  // Otherwise, if the sliding state window computation has not been
  // started we do it now.
  if (sliding_state_window_ == NULL) {
    sliding_state_window_ = new SlidingStateWindow();
  }
#endif
}

} }  // namespace v8::internal