blob: 503e0cf7c3ac3d0beef8539dccdd3eb1ebf8a62c [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
2//
3// Tests of logging functions from log.h
4
5#ifdef ENABLE_LOGGING_AND_PROFILING
6
7#ifdef __linux__
8#include <math.h>
9#include <pthread.h>
10#include <signal.h>
11#include <unistd.h>
12#endif // __linux__
13
14#include "v8.h"
15#include "log.h"
Steve Block6ded16b2010-05-10 14:33:55 +010016#include "cpu-profiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000017#include "v8threads.h"
18#include "cctest.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010019#include "vm-state-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000020
21using v8::internal::Address;
22using v8::internal::EmbeddedVector;
23using v8::internal::Logger;
Steve Blockd0582a62009-12-15 09:54:21 +000024using v8::internal::StrLength;
Steve Blocka7e24c12009-10-30 11:49:00 +000025
26namespace i = v8::internal;
27
28static void SetUp() {
29 // Log to memory buffer.
30 i::FLAG_logfile = "*";
31 i::FLAG_log = true;
32 Logger::Setup();
33}
34
35static void TearDown() {
36 Logger::TearDown();
37}
38
39
40TEST(EmptyLog) {
41 SetUp();
42 CHECK_EQ(0, Logger::GetLogLines(0, NULL, 0));
43 CHECK_EQ(0, Logger::GetLogLines(100, NULL, 0));
44 CHECK_EQ(0, Logger::GetLogLines(0, NULL, 100));
45 CHECK_EQ(0, Logger::GetLogLines(100, NULL, 100));
46 TearDown();
47}
48
49
50TEST(GetMessages) {
51 SetUp();
52 Logger::StringEvent("aaa", "bbb");
53 Logger::StringEvent("cccc", "dddd");
54 CHECK_EQ(0, Logger::GetLogLines(0, NULL, 0));
55 char log_lines[100];
56 memset(log_lines, 0, sizeof(log_lines));
Steve Blocka7e24c12009-10-30 11:49:00 +000057 // See Logger::StringEvent.
58 const char* line_1 = "aaa,\"bbb\"\n";
Steve Blockd0582a62009-12-15 09:54:21 +000059 const int line_1_len = StrLength(line_1);
Steve Blocka7e24c12009-10-30 11:49:00 +000060 // The exact size.
61 CHECK_EQ(line_1_len, Logger::GetLogLines(0, log_lines, line_1_len));
62 CHECK_EQ(line_1, log_lines);
63 memset(log_lines, 0, sizeof(log_lines));
64 // A bit more than the first line length.
65 CHECK_EQ(line_1_len, Logger::GetLogLines(0, log_lines, line_1_len + 3));
66 log_lines[line_1_len] = '\0';
67 CHECK_EQ(line_1, log_lines);
68 memset(log_lines, 0, sizeof(log_lines));
69 const char* line_2 = "cccc,\"dddd\"\n";
Steve Blockd0582a62009-12-15 09:54:21 +000070 const int line_2_len = StrLength(line_2);
Steve Blocka7e24c12009-10-30 11:49:00 +000071 // Now start with line_2 beginning.
72 CHECK_EQ(0, Logger::GetLogLines(line_1_len, log_lines, 0));
Steve Blocka7e24c12009-10-30 11:49:00 +000073 CHECK_EQ(line_2_len, Logger::GetLogLines(line_1_len, log_lines, line_2_len));
74 CHECK_EQ(line_2, log_lines);
75 memset(log_lines, 0, sizeof(log_lines));
76 CHECK_EQ(line_2_len,
77 Logger::GetLogLines(line_1_len, log_lines, line_2_len + 3));
78 CHECK_EQ(line_2, log_lines);
79 memset(log_lines, 0, sizeof(log_lines));
80 // Now get entire buffer contents.
81 const char* all_lines = "aaa,\"bbb\"\ncccc,\"dddd\"\n";
Steve Blockd0582a62009-12-15 09:54:21 +000082 const int all_lines_len = StrLength(all_lines);
Steve Blocka7e24c12009-10-30 11:49:00 +000083 CHECK_EQ(all_lines_len, Logger::GetLogLines(0, log_lines, all_lines_len));
84 CHECK_EQ(all_lines, log_lines);
85 memset(log_lines, 0, sizeof(log_lines));
86 CHECK_EQ(all_lines_len, Logger::GetLogLines(0, log_lines, all_lines_len + 3));
87 CHECK_EQ(all_lines, log_lines);
88 memset(log_lines, 0, sizeof(log_lines));
89 TearDown();
90}
91
92
93static int GetLogLines(int start_pos, i::Vector<char>* buffer) {
94 return Logger::GetLogLines(start_pos, buffer->start(), buffer->length());
95}
96
97
98TEST(BeyondWritePosition) {
99 SetUp();
100 Logger::StringEvent("aaa", "bbb");
101 Logger::StringEvent("cccc", "dddd");
102 // See Logger::StringEvent.
103 const char* all_lines = "aaa,\"bbb\"\ncccc,\"dddd\"\n";
Steve Blockd0582a62009-12-15 09:54:21 +0000104 const int all_lines_len = StrLength(all_lines);
Steve Blocka7e24c12009-10-30 11:49:00 +0000105 EmbeddedVector<char, 100> buffer;
106 const int beyond_write_pos = all_lines_len;
107 CHECK_EQ(0, Logger::GetLogLines(beyond_write_pos, buffer.start(), 1));
108 CHECK_EQ(0, GetLogLines(beyond_write_pos, &buffer));
109 CHECK_EQ(0, Logger::GetLogLines(beyond_write_pos + 1, buffer.start(), 1));
110 CHECK_EQ(0, GetLogLines(beyond_write_pos + 1, &buffer));
111 CHECK_EQ(0, Logger::GetLogLines(beyond_write_pos + 100, buffer.start(), 1));
112 CHECK_EQ(0, GetLogLines(beyond_write_pos + 100, &buffer));
113 CHECK_EQ(0, Logger::GetLogLines(10 * 1024 * 1024, buffer.start(), 1));
114 CHECK_EQ(0, GetLogLines(10 * 1024 * 1024, &buffer));
115 TearDown();
116}
117
118
119TEST(MemoryLoggingTurnedOff) {
120 // Log to stdout
121 i::FLAG_logfile = "-";
122 i::FLAG_log = true;
123 Logger::Setup();
124 CHECK_EQ(0, Logger::GetLogLines(0, NULL, 0));
125 CHECK_EQ(0, Logger::GetLogLines(100, NULL, 0));
126 CHECK_EQ(0, Logger::GetLogLines(0, NULL, 100));
127 CHECK_EQ(0, Logger::GetLogLines(100, NULL, 100));
128 Logger::TearDown();
129}
130
131
132static void CompileAndRunScript(const char *src) {
133 v8::Script::Compile(v8::String::New(src))->Run();
134}
135
136
137namespace v8 {
138namespace internal {
139
140class LoggerTestHelper : public AllStatic {
141 public:
142 static bool IsSamplerActive() { return Logger::IsProfilerSamplerActive(); }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800143 static void ResetSamplesTaken() {
144 reinterpret_cast<Sampler*>(Logger::ticker_)->ResetSamplesTaken();
145 }
146 static bool has_samples_taken() {
147 return reinterpret_cast<Sampler*>(Logger::ticker_)->samples_taken() > 0;
148 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000149};
150
151} // namespace v8::internal
152} // namespace v8
153
154using v8::internal::LoggerTestHelper;
155
156
Andrei Popescu402d9372010-02-26 13:31:12 +0000157namespace {
158
159class ScopedLoggerInitializer {
160 public:
Steve Block6ded16b2010-05-10 14:33:55 +0100161 explicit ScopedLoggerInitializer(bool prof_lazy)
162 : saved_prof_lazy_(i::FLAG_prof_lazy),
Andrei Popescu402d9372010-02-26 13:31:12 +0000163 saved_prof_(i::FLAG_prof),
164 saved_prof_auto_(i::FLAG_prof_auto),
Steve Block6ded16b2010-05-10 14:33:55 +0100165 trick_to_run_init_flags_(init_flags_(prof_lazy)),
Andrei Popescu402d9372010-02-26 13:31:12 +0000166 need_to_set_up_logger_(i::V8::IsRunning()),
167 scope_(),
168 env_(v8::Context::New()) {
169 if (need_to_set_up_logger_) Logger::Setup();
170 env_->Enter();
171 }
172
173 ~ScopedLoggerInitializer() {
174 env_->Exit();
175 Logger::TearDown();
176 i::FLAG_prof_lazy = saved_prof_lazy_;
177 i::FLAG_prof = saved_prof_;
178 i::FLAG_prof_auto = saved_prof_auto_;
Andrei Popescu402d9372010-02-26 13:31:12 +0000179 }
180
181 v8::Handle<v8::Context>& env() { return env_; }
182
183 private:
Steve Block6ded16b2010-05-10 14:33:55 +0100184 static bool init_flags_(bool prof_lazy) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000185 i::FLAG_prof = true;
186 i::FLAG_prof_lazy = prof_lazy;
187 i::FLAG_prof_auto = false;
188 i::FLAG_logfile = "*";
189 return prof_lazy;
190 }
191
Andrei Popescu402d9372010-02-26 13:31:12 +0000192 const bool saved_prof_lazy_;
193 const bool saved_prof_;
194 const bool saved_prof_auto_;
195 const bool trick_to_run_init_flags_;
196 const bool need_to_set_up_logger_;
197 v8::HandleScope scope_;
198 v8::Handle<v8::Context> env_;
199
200 DISALLOW_COPY_AND_ASSIGN(ScopedLoggerInitializer);
201};
202
203
204class LogBufferMatcher {
205 public:
206 LogBufferMatcher() {
207 // Skip all initially logged stuff.
208 log_pos_ = GetLogLines(0, &buffer_);
209 }
210
211 int log_pos() { return log_pos_; }
212
213 int GetNextChunk() {
214 int chunk_size = GetLogLines(log_pos_, &buffer_);
215 CHECK_GT(buffer_.length(), chunk_size);
216 buffer_[chunk_size] = '\0';
217 log_pos_ += chunk_size;
218 return chunk_size;
219 }
220
221 const char* Find(const char* substr) {
222 return strstr(buffer_.start(), substr);
223 }
224
225 const char* Find(const i::Vector<char>& substr) {
226 return Find(substr.start());
227 }
228
229 bool IsInSequence(const char* s1, const char* s2) {
230 const char* s1_pos = Find(s1);
231 const char* s2_pos = Find(s2);
232 CHECK_NE(NULL, s1_pos);
233 CHECK_NE(NULL, s2_pos);
234 return s1_pos < s2_pos;
235 }
236
237 void PrintBuffer() {
238 puts(buffer_.start());
239 }
240
241 private:
242 EmbeddedVector<char, 102400> buffer_;
243 int log_pos_;
244};
245
246} // namespace
247
248
249static void CheckThatProfilerWorks(LogBufferMatcher* matcher) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100250 CHECK(i::RuntimeProfiler::IsEnabled() ||
251 !LoggerTestHelper::IsSamplerActive());
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800252 LoggerTestHelper::ResetSamplesTaken();
253
Andrei Popescu402d9372010-02-26 13:31:12 +0000254 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000255 CHECK(LoggerTestHelper::IsSamplerActive());
256
257 // Verify that the current map of compiled functions has been logged.
Andrei Popescu402d9372010-02-26 13:31:12 +0000258 CHECK_GT(matcher->GetNextChunk(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000259 const char* code_creation = "\ncode-creation,"; // eq. to /^code-creation,/
Andrei Popescu402d9372010-02-26 13:31:12 +0000260 CHECK_NE(NULL, matcher->Find(code_creation));
Steve Blocka7e24c12009-10-30 11:49:00 +0000261
Steve Blocka7e24c12009-10-30 11:49:00 +0000262 // Force compiler to generate new code by parametrizing source.
263 EmbeddedVector<char, 100> script_src;
264 i::OS::SNPrintF(script_src,
Leon Clarked91b9f72010-01-27 17:25:45 +0000265 "function f%d(x) { return %d * x; }"
266 "for (var i = 0; i < 10000; ++i) { f%d(i); }",
Andrei Popescu402d9372010-02-26 13:31:12 +0000267 matcher->log_pos(), matcher->log_pos(), matcher->log_pos());
Steve Blocka7e24c12009-10-30 11:49:00 +0000268 // Run code for 200 msecs to get some ticks.
269 const double end_time = i::OS::TimeCurrentMillis() + 200;
270 while (i::OS::TimeCurrentMillis() < end_time) {
271 CompileAndRunScript(script_src.start());
272 // Yield CPU to give Profiler thread a chance to process ticks.
273 i::OS::Sleep(1);
274 }
275
Andrei Popescu402d9372010-02-26 13:31:12 +0000276 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 0);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100277 CHECK(i::RuntimeProfiler::IsEnabled() ||
278 !LoggerTestHelper::IsSamplerActive());
Steve Blocka7e24c12009-10-30 11:49:00 +0000279
280 // Wait 50 msecs to allow Profiler thread to process the last
281 // tick sample it has got.
282 i::OS::Sleep(50);
283
284 // Now we must have compiler and tick records.
Andrei Popescu402d9372010-02-26 13:31:12 +0000285 CHECK_GT(matcher->GetNextChunk(), 0);
286 matcher->PrintBuffer();
287 CHECK_NE(NULL, matcher->Find(code_creation));
Steve Blocka7e24c12009-10-30 11:49:00 +0000288 const char* tick = "\ntick,";
Andrei Popescu402d9372010-02-26 13:31:12 +0000289 const bool ticks_found = matcher->Find(tick) != NULL;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800290 CHECK_EQ(LoggerTestHelper::has_samples_taken(), ticks_found);
Steve Blocka7e24c12009-10-30 11:49:00 +0000291}
292
293
294TEST(ProfLazyMode) {
Steve Block6ded16b2010-05-10 14:33:55 +0100295 ScopedLoggerInitializer initialize_logger(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000296
Ben Murdochb0fe1622011-05-05 13:52:32 +0100297 if (!i::V8::UseCrankshaft()) return;
298
299 // No sampling should happen prior to resuming profiler unless we
300 // are runtime profiling.
301 CHECK(i::RuntimeProfiler::IsEnabled() ||
302 !LoggerTestHelper::IsSamplerActive());
Steve Blocka7e24c12009-10-30 11:49:00 +0000303
Andrei Popescu402d9372010-02-26 13:31:12 +0000304 LogBufferMatcher matcher;
Steve Blockd0582a62009-12-15 09:54:21 +0000305 // Nothing must be logged until profiling is resumed.
Andrei Popescu402d9372010-02-26 13:31:12 +0000306 CHECK_EQ(0, matcher.log_pos());
Steve Blocka7e24c12009-10-30 11:49:00 +0000307
308 CompileAndRunScript("var a = (function(x) { return x + 1; })(10);");
309
310 // Nothing must be logged while profiling is suspended.
Andrei Popescu402d9372010-02-26 13:31:12 +0000311 CHECK_EQ(0, matcher.GetNextChunk());
Steve Blocka7e24c12009-10-30 11:49:00 +0000312
Andrei Popescu402d9372010-02-26 13:31:12 +0000313 CheckThatProfilerWorks(&matcher);
Steve Blocka7e24c12009-10-30 11:49:00 +0000314
315 CompileAndRunScript("var a = (function(x) { return x + 1; })(10);");
316
317 // No new data beyond last retrieved position.
Andrei Popescu402d9372010-02-26 13:31:12 +0000318 CHECK_EQ(0, matcher.GetNextChunk());
Steve Blocka7e24c12009-10-30 11:49:00 +0000319
320 // Check that profiling can be resumed again.
Andrei Popescu402d9372010-02-26 13:31:12 +0000321 CheckThatProfilerWorks(&matcher);
Steve Blocka7e24c12009-10-30 11:49:00 +0000322}
323
324
John Reck59135872010-11-02 12:39:01 -0700325// BUG(913). Need to implement support for profiling multiple VM threads.
326#if 0
Steve Blocka7e24c12009-10-30 11:49:00 +0000327
328namespace {
329
330class LoopingThread : public v8::internal::Thread {
331 public:
332 LoopingThread()
333 : v8::internal::Thread(),
334 semaphore_(v8::internal::OS::CreateSemaphore(0)),
335 run_(true) {
336 }
337
338 virtual ~LoopingThread() { delete semaphore_; }
339
340 void Run() {
341 self_ = pthread_self();
342 RunLoop();
343 }
344
345 void SendSigProf() { pthread_kill(self_, SIGPROF); }
346
347 void Stop() { run_ = false; }
348
349 bool WaitForRunning() { return semaphore_->Wait(1000000); }
350
351 protected:
352 bool IsRunning() { return run_; }
353
354 virtual void RunLoop() = 0;
355
356 void SetV8ThreadId() {
357 v8_thread_id_ = v8::V8::GetCurrentThreadId();
358 }
359
360 void SignalRunning() { semaphore_->Signal(); }
361
362 private:
363 v8::internal::Semaphore* semaphore_;
364 bool run_;
365 pthread_t self_;
366 int v8_thread_id_;
367};
368
369
370class LoopingJsThread : public LoopingThread {
371 public:
372 void RunLoop() {
Steve Block6ded16b2010-05-10 14:33:55 +0100373 v8::Locker locker;
374 CHECK(v8::internal::ThreadManager::HasId());
375 SetV8ThreadId();
Steve Blocka7e24c12009-10-30 11:49:00 +0000376 while (IsRunning()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000377 v8::HandleScope scope;
378 v8::Persistent<v8::Context> context = v8::Context::New();
Steve Block6ded16b2010-05-10 14:33:55 +0100379 CHECK(!context.IsEmpty());
380 {
381 v8::Context::Scope context_scope(context);
382 SignalRunning();
383 CompileAndRunScript(
384 "var j; for (var i=0; i<10000; ++i) { j = Math.sin(i); }");
385 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000386 context.Dispose();
387 i::OS::Sleep(1);
388 }
389 }
390};
391
392
393class LoopingNonJsThread : public LoopingThread {
394 public:
395 void RunLoop() {
396 v8::Locker locker;
397 v8::Unlocker unlocker;
398 // Now thread has V8's id, but will not run VM code.
399 CHECK(v8::internal::ThreadManager::HasId());
400 double i = 10;
401 SignalRunning();
402 while (IsRunning()) {
403 i = sin(i);
404 i::OS::Sleep(1);
405 }
406 }
407};
408
409
410class TestSampler : public v8::internal::Sampler {
411 public:
412 TestSampler()
Ben Murdochb0fe1622011-05-05 13:52:32 +0100413 : Sampler(0, true, true),
Steve Blocka7e24c12009-10-30 11:49:00 +0000414 semaphore_(v8::internal::OS::CreateSemaphore(0)),
415 was_sample_stack_called_(false) {
416 }
417
418 ~TestSampler() { delete semaphore_; }
419
420 void SampleStack(v8::internal::TickSample*) {
421 was_sample_stack_called_ = true;
422 }
423
424 void Tick(v8::internal::TickSample*) { semaphore_->Signal(); }
425
426 bool WaitForTick() { return semaphore_->Wait(1000000); }
427
428 void Reset() { was_sample_stack_called_ = false; }
429
430 bool WasSampleStackCalled() { return was_sample_stack_called_; }
431
432 private:
433 v8::internal::Semaphore* semaphore_;
434 bool was_sample_stack_called_;
435};
436
437
438} // namespace
439
440TEST(ProfMultipleThreads) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100441 TestSampler* sampler = NULL;
442 {
443 v8::Locker locker;
444 sampler = new TestSampler();
445 sampler->Start();
446 CHECK(sampler->IsActive());
447 }
448
Steve Blocka7e24c12009-10-30 11:49:00 +0000449 LoopingJsThread jsThread;
450 jsThread.Start();
451 LoopingNonJsThread nonJsThread;
452 nonJsThread.Start();
453
Ben Murdochb0fe1622011-05-05 13:52:32 +0100454 CHECK(!sampler->WasSampleStackCalled());
Steve Blocka7e24c12009-10-30 11:49:00 +0000455 jsThread.WaitForRunning();
456 jsThread.SendSigProf();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100457 CHECK(sampler->WaitForTick());
458 CHECK(sampler->WasSampleStackCalled());
459 sampler->Reset();
460 CHECK(!sampler->WasSampleStackCalled());
Steve Blocka7e24c12009-10-30 11:49:00 +0000461 nonJsThread.WaitForRunning();
462 nonJsThread.SendSigProf();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100463 CHECK(!sampler->WaitForTick());
464 CHECK(!sampler->WasSampleStackCalled());
465 sampler->Stop();
Steve Blocka7e24c12009-10-30 11:49:00 +0000466
467 jsThread.Stop();
468 nonJsThread.Stop();
469 jsThread.Join();
470 nonJsThread.Join();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100471
472 delete sampler;
Steve Blocka7e24c12009-10-30 11:49:00 +0000473}
474
475#endif // __linux__
476
477
Steve Block3ce2e202009-11-05 08:53:23 +0000478// Test for issue http://crbug.com/23768 in Chromium.
479// Heap can contain scripts with already disposed external sources.
480// We need to verify that LogCompiledFunctions doesn't crash on them.
481namespace {
482
483class SimpleExternalString : public v8::String::ExternalStringResource {
484 public:
485 explicit SimpleExternalString(const char* source)
Steve Blockd0582a62009-12-15 09:54:21 +0000486 : utf_source_(StrLength(source)) {
Steve Block3ce2e202009-11-05 08:53:23 +0000487 for (int i = 0; i < utf_source_.length(); ++i)
488 utf_source_[i] = source[i];
489 }
490 virtual ~SimpleExternalString() {}
491 virtual size_t length() const { return utf_source_.length(); }
492 virtual const uint16_t* data() const { return utf_source_.start(); }
493 private:
494 i::ScopedVector<uint16_t> utf_source_;
495};
496
497} // namespace
498
499TEST(Issue23768) {
500 v8::HandleScope scope;
501 v8::Handle<v8::Context> env = v8::Context::New();
502 env->Enter();
503
504 SimpleExternalString source_ext_str("(function ext() {})();");
505 v8::Local<v8::String> source = v8::String::NewExternal(&source_ext_str);
506 // Script needs to have a name in order to trigger InitLineEnds execution.
507 v8::Handle<v8::String> origin = v8::String::New("issue-23768-test");
508 v8::Handle<v8::Script> evil_script = v8::Script::Compile(source, origin);
509 CHECK(!evil_script.IsEmpty());
510 CHECK(!evil_script->Run().IsEmpty());
511 i::Handle<i::ExternalTwoByteString> i_source(
512 i::ExternalTwoByteString::cast(*v8::Utils::OpenHandle(*source)));
513 // This situation can happen if source was an external string disposed
514 // by its owner.
515 i_source->set_resource(NULL);
516
517 // Must not crash.
518 i::Logger::LogCompiledFunctions();
519}
520
521
Steve Blockd0582a62009-12-15 09:54:21 +0000522static v8::Handle<v8::Value> ObjMethod1(const v8::Arguments& args) {
523 return v8::Handle<v8::Value>();
524}
525
526TEST(LogCallbacks) {
Steve Block6ded16b2010-05-10 14:33:55 +0100527 ScopedLoggerInitializer initialize_logger(false);
Andrei Popescu402d9372010-02-26 13:31:12 +0000528 LogBufferMatcher matcher;
Steve Blockd0582a62009-12-15 09:54:21 +0000529
530 v8::Persistent<v8::FunctionTemplate> obj =
531 v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New());
532 obj->SetClassName(v8::String::New("Obj"));
533 v8::Handle<v8::ObjectTemplate> proto = obj->PrototypeTemplate();
534 v8::Local<v8::Signature> signature = v8::Signature::New(obj);
535 proto->Set(v8::String::New("method1"),
536 v8::FunctionTemplate::New(ObjMethod1,
537 v8::Handle<v8::Value>(),
538 signature),
539 static_cast<v8::PropertyAttribute>(v8::DontDelete));
540
Andrei Popescu402d9372010-02-26 13:31:12 +0000541 initialize_logger.env()->Global()->Set(v8_str("Obj"), obj->GetFunction());
Steve Blockd0582a62009-12-15 09:54:21 +0000542 CompileAndRunScript("Obj.prototype.method1.toString();");
543
544 i::Logger::LogCompiledFunctions();
Andrei Popescu402d9372010-02-26 13:31:12 +0000545 CHECK_GT(matcher.GetNextChunk(), 0);
Steve Blockd0582a62009-12-15 09:54:21 +0000546
547 const char* callback_rec = "code-creation,Callback,";
Andrei Popescu402d9372010-02-26 13:31:12 +0000548 char* pos = const_cast<char*>(matcher.Find(callback_rec));
Steve Blockd0582a62009-12-15 09:54:21 +0000549 CHECK_NE(NULL, pos);
550 pos += strlen(callback_rec);
551 EmbeddedVector<char, 100> ref_data;
552 i::OS::SNPrintF(ref_data,
553 "0x%" V8PRIxPTR ",1,\"method1\"", ObjMethod1);
554 *(pos + strlen(ref_data.start())) = '\0';
555 CHECK_EQ(ref_data.start(), pos);
556
557 obj.Dispose();
Steve Blockd0582a62009-12-15 09:54:21 +0000558}
559
560
561static v8::Handle<v8::Value> Prop1Getter(v8::Local<v8::String> property,
562 const v8::AccessorInfo& info) {
563 return v8::Handle<v8::Value>();
564}
565
566static void Prop1Setter(v8::Local<v8::String> property,
567 v8::Local<v8::Value> value,
568 const v8::AccessorInfo& info) {
569}
570
571static v8::Handle<v8::Value> Prop2Getter(v8::Local<v8::String> property,
572 const v8::AccessorInfo& info) {
573 return v8::Handle<v8::Value>();
574}
575
576TEST(LogAccessorCallbacks) {
Steve Block6ded16b2010-05-10 14:33:55 +0100577 ScopedLoggerInitializer initialize_logger(false);
Andrei Popescu402d9372010-02-26 13:31:12 +0000578 LogBufferMatcher matcher;
Steve Blockd0582a62009-12-15 09:54:21 +0000579
580 v8::Persistent<v8::FunctionTemplate> obj =
581 v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New());
582 obj->SetClassName(v8::String::New("Obj"));
583 v8::Handle<v8::ObjectTemplate> inst = obj->InstanceTemplate();
584 inst->SetAccessor(v8::String::New("prop1"), Prop1Getter, Prop1Setter);
585 inst->SetAccessor(v8::String::New("prop2"), Prop2Getter);
586
587 i::Logger::LogAccessorCallbacks();
Andrei Popescu402d9372010-02-26 13:31:12 +0000588 CHECK_GT(matcher.GetNextChunk(), 0);
589 matcher.PrintBuffer();
Steve Blockd0582a62009-12-15 09:54:21 +0000590
591 EmbeddedVector<char, 100> prop1_getter_record;
592 i::OS::SNPrintF(prop1_getter_record,
593 "code-creation,Callback,0x%" V8PRIxPTR ",1,\"get prop1\"",
594 Prop1Getter);
Andrei Popescu402d9372010-02-26 13:31:12 +0000595 CHECK_NE(NULL, matcher.Find(prop1_getter_record));
Steve Blockd0582a62009-12-15 09:54:21 +0000596 EmbeddedVector<char, 100> prop1_setter_record;
597 i::OS::SNPrintF(prop1_setter_record,
598 "code-creation,Callback,0x%" V8PRIxPTR ",1,\"set prop1\"",
599 Prop1Setter);
Andrei Popescu402d9372010-02-26 13:31:12 +0000600 CHECK_NE(NULL, matcher.Find(prop1_setter_record));
Steve Blockd0582a62009-12-15 09:54:21 +0000601 EmbeddedVector<char, 100> prop2_getter_record;
602 i::OS::SNPrintF(prop2_getter_record,
603 "code-creation,Callback,0x%" V8PRIxPTR ",1,\"get prop2\"",
604 Prop2Getter);
Andrei Popescu402d9372010-02-26 13:31:12 +0000605 CHECK_NE(NULL, matcher.Find(prop2_getter_record));
Steve Blockd0582a62009-12-15 09:54:21 +0000606
607 obj.Dispose();
Andrei Popescu402d9372010-02-26 13:31:12 +0000608}
Steve Blockd0582a62009-12-15 09:54:21 +0000609
Andrei Popescu402d9372010-02-26 13:31:12 +0000610
611TEST(LogTags) {
Steve Block6ded16b2010-05-10 14:33:55 +0100612 ScopedLoggerInitializer initialize_logger(false);
Andrei Popescu402d9372010-02-26 13:31:12 +0000613 LogBufferMatcher matcher;
614
615 const char* open_tag = "open-tag,";
616 const char* close_tag = "close-tag,";
617
618 // Check compatibility with the old style behavior.
619 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
620 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 0);
621 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
622 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 0);
623 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
624 CHECK_EQ(NULL, matcher.Find(open_tag));
625 CHECK_EQ(NULL, matcher.Find(close_tag));
626
627 const char* open_tag1 = "open-tag,1\n";
628 const char* close_tag1 = "close-tag,1\n";
629
630 // Check non-nested tag case.
631 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
632 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 1);
633 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
634 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 1);
635 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
636 CHECK_GT(matcher.GetNextChunk(), 0);
637 CHECK(matcher.IsInSequence(open_tag1, close_tag1));
638
639 const char* open_tag2 = "open-tag,2\n";
640 const char* close_tag2 = "close-tag,2\n";
641
642 // Check nested tags case.
643 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
644 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 1);
645 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
646 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 2);
647 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
648 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 2);
649 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
650 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 1);
651 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
652 CHECK_GT(matcher.GetNextChunk(), 0);
653 // open_tag1 < open_tag2 < close_tag2 < close_tag1
654 CHECK(matcher.IsInSequence(open_tag1, open_tag2));
655 CHECK(matcher.IsInSequence(open_tag2, close_tag2));
656 CHECK(matcher.IsInSequence(close_tag2, close_tag1));
657
658 // Check overlapped tags case.
659 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
660 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 1);
661 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
662 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 2);
663 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
664 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 1);
665 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
666 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 2);
667 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
668 CHECK_GT(matcher.GetNextChunk(), 0);
669 // open_tag1 < open_tag2 < close_tag1 < close_tag2
670 CHECK(matcher.IsInSequence(open_tag1, open_tag2));
671 CHECK(matcher.IsInSequence(open_tag2, close_tag1));
672 CHECK(matcher.IsInSequence(close_tag1, close_tag2));
673
674 const char* open_tag3 = "open-tag,3\n";
675 const char* close_tag3 = "close-tag,3\n";
676
677 // Check pausing overflow case.
678 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
679 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 1);
680 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
681 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 2);
682 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
683 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 2);
684 CHECK_EQ(v8::PROFILER_MODULE_CPU, Logger::GetActiveProfilerModules());
685 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 1);
686 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
687 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 3);
688 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
689 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 3);
690 CHECK_EQ(v8::PROFILER_MODULE_NONE, Logger::GetActiveProfilerModules());
691 // Must be no tags, because logging must be disabled.
692 CHECK_EQ(NULL, matcher.Find(open_tag3));
693 CHECK_EQ(NULL, matcher.Find(close_tag3));
Steve Blockd0582a62009-12-15 09:54:21 +0000694}
695
696
Steve Block6ded16b2010-05-10 14:33:55 +0100697TEST(IsLoggingPreserved) {
698 ScopedLoggerInitializer initialize_logger(false);
699
700 CHECK(Logger::is_logging());
701 Logger::ResumeProfiler(v8::PROFILER_MODULE_CPU, 1);
702 CHECK(Logger::is_logging());
703 Logger::PauseProfiler(v8::PROFILER_MODULE_CPU, 1);
704 CHECK(Logger::is_logging());
705
706 CHECK(Logger::is_logging());
707 Logger::ResumeProfiler(
708 v8::PROFILER_MODULE_HEAP_STATS | v8::PROFILER_MODULE_JS_CONSTRUCTORS, 1);
709 CHECK(Logger::is_logging());
710 Logger::PauseProfiler(
711 v8::PROFILER_MODULE_HEAP_STATS | v8::PROFILER_MODULE_JS_CONSTRUCTORS, 1);
712 CHECK(Logger::is_logging());
713
714 CHECK(Logger::is_logging());
715 Logger::ResumeProfiler(
716 v8::PROFILER_MODULE_CPU |
717 v8::PROFILER_MODULE_HEAP_STATS | v8::PROFILER_MODULE_JS_CONSTRUCTORS, 1);
718 CHECK(Logger::is_logging());
719 Logger::PauseProfiler(
720 v8::PROFILER_MODULE_CPU |
721 v8::PROFILER_MODULE_HEAP_STATS | v8::PROFILER_MODULE_JS_CONSTRUCTORS, 1);
722 CHECK(Logger::is_logging());
723}
724
725
Steve Blocka7e24c12009-10-30 11:49:00 +0000726static inline bool IsStringEqualTo(const char* r, const char* s) {
727 return strncmp(r, s, strlen(r)) == 0;
728}
729
730
731static bool Consume(const char* str, char** buf) {
732 if (IsStringEqualTo(str, *buf)) {
733 *buf += strlen(str);
734 return true;
735 }
736 return false;
737}
738
739
740namespace {
741
742// A code entity is a pointer to a position of code-creation event in buffer log
743// offset to a point where entity size begins, i.e.: '255,"func"\n'. This makes
744// comparing code entities pretty easy.
745typedef char* CodeEntityInfo;
746
747class Interval {
748 public:
749 Interval()
750 : min_addr_(reinterpret_cast<Address>(-1)),
751 max_addr_(reinterpret_cast<Address>(0)), next_(NULL) {}
752
753 ~Interval() { delete next_; }
754
755 size_t Length() {
756 size_t result = max_addr_ - min_addr_ + 1;
757 if (next_ != NULL) result += next_->Length();
758 return result;
759 }
760
761 void CloneFrom(Interval* src) {
762 while (src != NULL) {
763 RegisterAddress(src->min_addr_);
764 RegisterAddress(src->max_addr_);
765 src = src->next_;
766 }
767 }
768
769 bool Contains(Address addr) {
770 if (min_addr_ <= addr && addr <= max_addr_) {
771 return true;
772 }
773 if (next_ != NULL) {
774 return next_->Contains(addr);
775 } else {
776 return false;
777 }
778 }
779
780 size_t GetIndex(Address addr) {
781 if (min_addr_ <= addr && addr <= max_addr_) {
782 return addr - min_addr_;
783 }
784 CHECK_NE(NULL, next_);
785 return (max_addr_ - min_addr_ + 1) + next_->GetIndex(addr);
786 }
787
788 Address GetMinAddr() {
789 return next_ == NULL ? min_addr_ : i::Min(min_addr_, next_->GetMinAddr());
790 }
791
792 Address GetMaxAddr() {
793 return next_ == NULL ? max_addr_ : i::Max(max_addr_, next_->GetMaxAddr());
794 }
795
796 void RegisterAddress(Address addr) {
797 if (min_addr_ == reinterpret_cast<Address>(-1)
798 || (size_t)(addr > min_addr_ ?
799 addr - min_addr_ : min_addr_ - addr) < MAX_DELTA) {
800 if (addr < min_addr_) min_addr_ = addr;
801 if (addr > max_addr_) max_addr_ = addr;
802 } else {
803 if (next_ == NULL) next_ = new Interval();
804 next_->RegisterAddress(addr);
805 }
806 }
807
808 Address raw_min_addr() { return min_addr_; }
809
810 Address raw_max_addr() { return max_addr_; }
811
812 Interval* get_next() { return next_; }
813
814 private:
815 static const size_t MAX_DELTA = 0x100000;
816 Address min_addr_;
817 Address max_addr_;
818 Interval* next_;
819};
820
821
822// A structure used to return log parsing results.
823class ParseLogResult {
824 public:
825 ParseLogResult()
826 : entities_map(NULL), entities(NULL),
827 max_entities(0) {}
828
829 ~ParseLogResult() {
830 i::DeleteArray(entities_map);
831 i::DeleteArray(entities);
832 }
833
834 void AllocateEntities() {
835 // Make sure that the test doesn't operate on a bogus log.
836 CHECK_GT(max_entities, 0);
837 CHECK_GT(bounds.GetMinAddr(), 0);
838 CHECK_GT(bounds.GetMaxAddr(), bounds.GetMinAddr());
839
840 entities = i::NewArray<CodeEntityInfo>(max_entities);
841 for (int i = 0; i < max_entities; ++i) {
842 entities[i] = NULL;
843 }
844 const size_t map_length = bounds.Length();
Steve Blockd0582a62009-12-15 09:54:21 +0000845 entities_map = i::NewArray<int>(static_cast<int>(map_length));
Steve Blocka7e24c12009-10-30 11:49:00 +0000846 for (size_t i = 0; i < map_length; ++i) {
847 entities_map[i] = -1;
848 }
849 }
850
851 bool HasIndexForAddress(Address addr) {
852 return bounds.Contains(addr);
853 }
854
855 size_t GetIndexForAddress(Address addr) {
856 CHECK(HasIndexForAddress(addr));
857 return bounds.GetIndex(addr);
858 }
859
860 CodeEntityInfo GetEntity(Address addr) {
861 if (HasIndexForAddress(addr)) {
862 size_t idx = GetIndexForAddress(addr);
863 int item = entities_map[idx];
864 return item != -1 ? entities[item] : NULL;
865 }
866 return NULL;
867 }
868
869 void ParseAddress(char* start) {
870 Address addr =
871 reinterpret_cast<Address>(strtoul(start, NULL, 16)); // NOLINT
872 bounds.RegisterAddress(addr);
873 }
874
875 Address ConsumeAddress(char** start) {
876 char* end_ptr;
877 Address addr =
878 reinterpret_cast<Address>(strtoul(*start, &end_ptr, 16)); // NOLINT
879 CHECK(HasIndexForAddress(addr));
880 *start = end_ptr;
881 return addr;
882 }
883
884 Interval bounds;
885 // Memory map of entities start addresses.
886 int* entities_map;
887 // An array of code entities.
888 CodeEntityInfo* entities;
889 // Maximal entities count. Actual entities count can be lower,
890 // empty entity slots are pointing to NULL.
891 int max_entities;
892};
893
894} // namespace
895
896
897typedef void (*ParserBlock)(char* start, char* end, ParseLogResult* result);
898
899static void ParserCycle(
900 char* start, char* end, ParseLogResult* result,
901 ParserBlock block_creation, ParserBlock block_delete,
902 ParserBlock block_move) {
903
904 const char* code_creation = "code-creation,";
905 const char* code_delete = "code-delete,";
906 const char* code_move = "code-move,";
907
908 const char* lazy_compile = "LazyCompile,";
909 const char* script = "Script,";
910 const char* function = "Function,";
911
912 while (start < end) {
913 if (Consume(code_creation, &start)) {
914 if (Consume(lazy_compile, &start)
915 || Consume(script, &start)
916 || Consume(function, &start)) {
917 block_creation(start, end, result);
918 }
919 } else if (Consume(code_delete, &start)) {
920 block_delete(start, end, result);
921 } else if (Consume(code_move, &start)) {
922 block_move(start, end, result);
923 }
924 while (start < end && *start != '\n') ++start;
925 ++start;
926 }
927}
928
929
930static void Pass1CodeCreation(char* start, char* end, ParseLogResult* result) {
931 result->ParseAddress(start);
932 ++result->max_entities;
933}
934
935
936static void Pass1CodeDelete(char* start, char* end, ParseLogResult* result) {
937 result->ParseAddress(start);
938}
939
940
941static void Pass1CodeMove(char* start, char* end, ParseLogResult* result) {
942 result->ParseAddress(start);
943 // Skip old address.
944 while (start < end && *start != ',') ++start;
945 CHECK_GT(end, start);
946 ++start; // Skip ','.
947 result->ParseAddress(start);
948}
949
950
951static void Pass2CodeCreation(char* start, char* end, ParseLogResult* result) {
952 Address addr = result->ConsumeAddress(&start);
953 CHECK_GT(end, start);
954 ++start; // Skip ','.
955
956 size_t idx = result->GetIndexForAddress(addr);
957 result->entities_map[idx] = -1;
958 for (int i = 0; i < result->max_entities; ++i) {
959 // Find an empty slot and fill it.
960 if (result->entities[i] == NULL) {
961 result->entities[i] = start;
962 result->entities_map[idx] = i;
963 break;
964 }
965 }
966 // Make sure that a slot was found.
967 CHECK_GE(result->entities_map[idx], 0);
968}
969
970
971static void Pass2CodeDelete(char* start, char* end, ParseLogResult* result) {
972 Address addr = result->ConsumeAddress(&start);
973 size_t idx = result->GetIndexForAddress(addr);
974 // There can be code deletes that are not related to JS code.
975 if (result->entities_map[idx] >= 0) {
976 result->entities[result->entities_map[idx]] = NULL;
977 result->entities_map[idx] = -1;
978 }
979}
980
981
982static void Pass2CodeMove(char* start, char* end, ParseLogResult* result) {
983 Address from_addr = result->ConsumeAddress(&start);
984 CHECK_GT(end, start);
985 ++start; // Skip ','.
986 Address to_addr = result->ConsumeAddress(&start);
987 CHECK_GT(end, start);
988
989 size_t from_idx = result->GetIndexForAddress(from_addr);
990 size_t to_idx = result->GetIndexForAddress(to_addr);
991 // There can be code moves that are not related to JS code.
992 if (from_idx != to_idx && result->entities_map[from_idx] >= 0) {
993 CHECK_EQ(-1, result->entities_map[to_idx]);
994 result->entities_map[to_idx] = result->entities_map[from_idx];
995 result->entities_map[from_idx] = -1;
996 };
997}
998
999
1000static void ParseLog(char* start, char* end, ParseLogResult* result) {
1001 // Pass 1: Calculate boundaries of addresses and entities count.
1002 ParserCycle(start, end, result,
1003 Pass1CodeCreation, Pass1CodeDelete, Pass1CodeMove);
1004
1005 printf("min_addr: %p, max_addr: %p, entities: %d\n",
1006 result->bounds.GetMinAddr(), result->bounds.GetMaxAddr(),
1007 result->max_entities);
1008
1009 result->AllocateEntities();
1010
1011 // Pass 2: Fill in code entries data.
1012 ParserCycle(start, end, result,
1013 Pass2CodeCreation, Pass2CodeDelete, Pass2CodeMove);
1014}
1015
1016
1017static inline void PrintCodeEntityInfo(CodeEntityInfo entity) {
1018 const int max_len = 50;
1019 if (entity != NULL) {
1020 char* eol = strchr(entity, '\n');
Steve Blockd0582a62009-12-15 09:54:21 +00001021 int len = static_cast<int>(eol - entity);
Steve Blocka7e24c12009-10-30 11:49:00 +00001022 len = len <= max_len ? len : max_len;
1023 printf("%-*.*s ", max_len, len, entity);
1024 } else {
1025 printf("%*s", max_len + 1, "");
1026 }
1027}
1028
1029
1030static void PrintCodeEntitiesInfo(
1031 bool is_equal, Address addr,
1032 CodeEntityInfo l_entity, CodeEntityInfo r_entity) {
1033 printf("%c %p ", is_equal ? ' ' : '*', addr);
1034 PrintCodeEntityInfo(l_entity);
1035 PrintCodeEntityInfo(r_entity);
1036 printf("\n");
1037}
1038
1039
1040static inline int StrChrLen(const char* s, char c) {
Steve Blockd0582a62009-12-15 09:54:21 +00001041 return static_cast<int>(strchr(s, c) - s);
Steve Blocka7e24c12009-10-30 11:49:00 +00001042}
1043
1044
1045static bool AreFuncSizesEqual(CodeEntityInfo ref_s, CodeEntityInfo new_s) {
1046 int ref_len = StrChrLen(ref_s, ',');
1047 int new_len = StrChrLen(new_s, ',');
1048 return ref_len == new_len && strncmp(ref_s, new_s, ref_len) == 0;
1049}
1050
1051
1052static bool AreFuncNamesEqual(CodeEntityInfo ref_s, CodeEntityInfo new_s) {
1053 // Skip size.
1054 ref_s = strchr(ref_s, ',') + 1;
1055 new_s = strchr(new_s, ',') + 1;
1056 int ref_len = StrChrLen(ref_s, '\n');
1057 int new_len = StrChrLen(new_s, '\n');
1058 // If reference is anonymous (""), it's OK to have anything in new.
1059 if (ref_len == 2) return true;
1060 // A special case for ErrorPrototype. Haven't yet figured out why they
1061 // are different.
1062 const char* error_prototype = "\"ErrorPrototype";
1063 if (IsStringEqualTo(error_prototype, ref_s)
1064 && IsStringEqualTo(error_prototype, new_s)) {
1065 return true;
1066 }
1067 // Built-in objects have problems too.
1068 const char* built_ins[] = {
1069 "\"Boolean\"", "\"Function\"", "\"Number\"",
1070 "\"Object\"", "\"Script\"", "\"String\""
1071 };
1072 for (size_t i = 0; i < sizeof(built_ins) / sizeof(*built_ins); ++i) {
1073 if (IsStringEqualTo(built_ins[i], new_s)) {
1074 return true;
1075 }
1076 }
1077 return ref_len == new_len && strncmp(ref_s, new_s, ref_len) == 0;
1078}
1079
1080
1081static bool AreEntitiesEqual(CodeEntityInfo ref_e, CodeEntityInfo new_e) {
1082 if (ref_e == NULL && new_e != NULL) return true;
1083 if (ref_e != NULL && new_e != NULL) {
1084 return AreFuncSizesEqual(ref_e, new_e) && AreFuncNamesEqual(ref_e, new_e);
1085 }
1086 if (ref_e != NULL && new_e == NULL) {
1087 // args_count entities (argument adapters) are not found by heap traversal,
1088 // but they are not needed because they doesn't contain any code.
1089 ref_e = strchr(ref_e, ',') + 1;
1090 const char* args_count = "\"args_count:";
1091 return IsStringEqualTo(args_count, ref_e);
1092 }
1093 return false;
1094}
1095
1096
1097// Test that logging of code create / move / delete events
1098// is equivalent to traversal of a resulting heap.
1099TEST(EquivalenceOfLoggingAndTraversal) {
1100 // This test needs to be run on a "clean" V8 to ensure that snapshot log
1101 // is loaded. This is always true when running using tools/test.py because
1102 // it launches a new cctest instance for every test. To be sure that launching
1103 // cctest manually also works, please be sure that no tests below
1104 // are using V8.
1105 //
1106 // P.S. No, V8 can't be re-initialized after disposal, see include/v8.h.
1107 CHECK(!i::V8::IsRunning());
1108
1109 i::FLAG_logfile = "*";
1110 i::FLAG_log = true;
1111 i::FLAG_log_code = true;
1112
1113 // Make sure objects move.
1114 bool saved_always_compact = i::FLAG_always_compact;
1115 if (!i::FLAG_never_compact) {
1116 i::FLAG_always_compact = true;
1117 }
1118
1119 v8::HandleScope scope;
1120 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
1121 v8::Handle<v8::Context> env = v8::Context::New(
1122 0, v8::Handle<v8::ObjectTemplate>(), global_object);
1123 env->Enter();
1124
1125 // Compile and run a function that creates other functions.
1126 CompileAndRunScript(
1127 "(function f(obj) {\n"
1128 " obj.test =\n"
1129 " (function a(j) { return function b() { return j; } })(100);\n"
1130 "})(this);");
1131 i::Heap::CollectAllGarbage(false);
1132
1133 EmbeddedVector<char, 204800> buffer;
1134 int log_size;
1135 ParseLogResult ref_result;
1136
1137 // Retrieve the log.
1138 {
1139 // Make sure that no GCs occur prior to LogCompiledFunctions call.
1140 i::AssertNoAllocation no_alloc;
1141
1142 log_size = GetLogLines(0, &buffer);
1143 CHECK_GT(log_size, 0);
1144 CHECK_GT(buffer.length(), log_size);
1145
1146 // Fill a map of compiled code objects.
1147 ParseLog(buffer.start(), buffer.start() + log_size, &ref_result);
1148 }
1149
1150 // Iterate heap to find compiled functions, will write to log.
1151 i::Logger::LogCompiledFunctions();
1152 char* new_log_start = buffer.start() + log_size;
1153 const int new_log_size = Logger::GetLogLines(
1154 log_size, new_log_start, buffer.length() - log_size);
1155 CHECK_GT(new_log_size, 0);
1156 CHECK_GT(buffer.length(), log_size + new_log_size);
1157
1158 // Fill an equivalent map of compiled code objects.
1159 ParseLogResult new_result;
1160 ParseLog(new_log_start, new_log_start + new_log_size, &new_result);
1161
1162 // Test their actual equivalence.
1163 Interval combined;
1164 combined.CloneFrom(&ref_result.bounds);
1165 combined.CloneFrom(&new_result.bounds);
1166 Interval* iter = &combined;
1167 bool results_equal = true;
1168
1169 while (iter != NULL) {
1170 for (Address addr = iter->raw_min_addr();
1171 addr <= iter->raw_max_addr(); ++addr) {
1172 CodeEntityInfo ref_entity = ref_result.GetEntity(addr);
1173 CodeEntityInfo new_entity = new_result.GetEntity(addr);
1174 if (ref_entity != NULL || new_entity != NULL) {
1175 const bool equal = AreEntitiesEqual(ref_entity, new_entity);
1176 if (!equal) results_equal = false;
1177 PrintCodeEntitiesInfo(equal, addr, ref_entity, new_entity);
1178 }
1179 }
1180 iter = iter->get_next();
1181 }
1182 // Make sure that all log data is written prior crash due to CHECK failure.
1183 fflush(stdout);
1184 CHECK(results_equal);
1185
1186 env->Exit();
1187 Logger::TearDown();
1188 i::FLAG_always_compact = saved_always_compact;
1189}
1190
1191#endif // ENABLE_LOGGING_AND_PROFILING