cctest.h 19.9 KB
Newer Older
1
// Copyright 2008 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
// 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.

#ifndef CCTEST_H_
#define CCTEST_H_

31
#include "include/libplatform/libplatform.h"
32
#include "src/isolate-inl.h"  // TODO(everyone): Make cctest IWYU.
33
#include "src/objects-inl.h"  // TODO(everyone): Make cctest IWYU.
34
#include "src/v8.h"
35

36
#ifndef TEST
37 38 39 40 41 42 43 44 45 46
#define TEST(Name)                                                             \
  static void Test##Name();                                                    \
  CcTest register_test_##Name(Test##Name, __FILE__, #Name, NULL, true, true);  \
  static void Test##Name()
#endif

#ifndef UNINITIALIZED_TEST
#define UNINITIALIZED_TEST(Name)                                               \
  static void Test##Name();                                                    \
  CcTest register_test_##Name(Test##Name, __FILE__, #Name, NULL, true, false); \
47 48 49 50
  static void Test##Name()
#endif

#ifndef DEPENDENT_TEST
51 52 53
#define DEPENDENT_TEST(Name, Dep)                                              \
  static void Test##Name();                                                    \
  CcTest register_test_##Name(Test##Name, __FILE__, #Name, #Dep, true, true);  \
54 55 56
  static void Test##Name()
#endif

57 58 59 60 61 62 63
#ifndef UNINITIALIZED_DEPENDENT_TEST
#define UNINITIALIZED_DEPENDENT_TEST(Name, Dep)                                \
  static void Test##Name();                                                    \
  CcTest register_test_##Name(Test##Name, __FILE__, #Name, #Dep, true, false); \
  static void Test##Name()
#endif

64
#ifndef DISABLED_TEST
65 66 67
#define DISABLED_TEST(Name)                                                    \
  static void Test##Name();                                                    \
  CcTest register_test_##Name(Test##Name, __FILE__, #Name, NULL, false, true); \
68 69 70
  static void Test##Name()
#endif

71 72 73 74 75
#define EXTENSION_LIST(V)                                                      \
  V(GC_EXTENSION,       "v8/gc")                                               \
  V(PRINT_EXTENSION,    "v8/print")                                            \
  V(PROFILER_EXTENSION, "v8/profiler")                                         \
  V(TRACE_EXTENSION,    "v8/trace")
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

#define DEFINE_EXTENSION_ID(Name, Ident) Name##_ID,
enum CcTestExtensionIds {
  EXTENSION_LIST(DEFINE_EXTENSION_ID)
  kMaxExtensions
};
#undef DEFINE_EXTENSION_ID

typedef v8::internal::EnumSet<CcTestExtensionIds> CcTestExtensionFlags;
#define DEFINE_EXTENSION_FLAG(Name, Ident)                               \
  static const CcTestExtensionFlags Name(1 << Name##_ID);
  static const CcTestExtensionFlags NO_EXTENSIONS(0);
  static const CcTestExtensionFlags ALL_EXTENSIONS((1 << kMaxExtensions) - 1);
  EXTENSION_LIST(DEFINE_EXTENSION_FLAG)
#undef DEFINE_EXTENSION_FLAG

92

93 94 95
class CcTest {
 public:
  typedef void (TestFunction)();
96
  CcTest(TestFunction* callback, const char* file, const char* name,
97
         const char* dependency, bool enabled, bool initialize);
98
  ~CcTest() { i::DeleteArray(file_); }
99
  void Run();
100
  static CcTest* last() { return last_; }
101 102 103
  CcTest* prev() { return prev_; }
  const char* file() { return file_; }
  const char* name() { return name_; }
104
  const char* dependency() { return dependency_; }
105
  bool enabled() { return enabled_; }
106

107
  static v8::Isolate* isolate() {
108
    CHECK(isolate_ != NULL);
109
    v8::base::NoBarrier_Store(&isolate_used_, 1);
110
    return isolate_;
111
  }
112

113 114 115 116 117
  static i::Isolate* InitIsolateOnce() {
    if (!initialize_called_) InitializeVM();
    return i_isolate();
  }

118
  static i::Isolate* i_isolate() {
119
    return reinterpret_cast<i::Isolate*>(isolate());
120 121
  }

122 123 124 125
  static i::Heap* heap() {
    return i_isolate()->heap();
  }

126 127 128 129
  static v8::base::RandomNumberGenerator* random_number_generator() {
    return InitIsolateOnce()->random_number_generator();
  }

130 131 132 133
  static v8::Local<v8::Object> global() {
    return isolate()->GetCurrentContext()->Global();
  }

134 135 136 137 138 139 140 141 142
  static v8::ArrayBuffer::Allocator* array_buffer_allocator() {
    return allocator_;
  }

  static void set_array_buffer_allocator(
      v8::ArrayBuffer::Allocator* allocator) {
    allocator_ = allocator;
  }

143 144 145
  // TODO(dcarney): Remove.
  // This must be called first in a test.
  static void InitializeVM() {
146
    CHECK(!v8::base::NoBarrier_Load(&isolate_used_));
147 148 149 150 151 152
    CHECK(!initialize_called_);
    initialize_called_ = true;
    v8::HandleScope handle_scope(CcTest::isolate());
    v8::Context::New(CcTest::isolate())->Enter();
  }

153 154 155
  // Only for UNINITIALIZED_TESTs
  static void DisableAutomaticDispose();

156 157 158 159 160
  // Helper function to configure a context.
  // Must be in a HandleScope.
  static v8::Local<v8::Context> NewContext(
      CcTestExtensionFlags extensions,
      v8::Isolate* isolate = CcTest::isolate());
161

162
  static void TearDown() {
163
    if (isolate_ != NULL) isolate_->Dispose();
164 165
  }

166
 private:
167
  friend int main(int argc, char** argv);
168 169 170
  TestFunction* callback_;
  const char* file_;
  const char* name_;
171
  const char* dependency_;
172
  bool enabled_;
173
  bool initialize_;
174
  CcTest* prev_;
175
  static CcTest* last_;
176
  static v8::ArrayBuffer::Allocator* allocator_;
177 178
  static v8::Isolate* isolate_;
  static bool initialize_called_;
179
  static v8::base::Atomic32 isolate_used_;
180 181
};

182 183 184 185 186 187 188 189 190 191
// Switches between all the Api tests using the threading support.
// In order to get a surprising but repeatable pattern of thread
// switching it has extra semaphores to control the order in which
// the tests alternate, not relying solely on the big V8 lock.
//
// A test is augmented with calls to ApiTestFuzzer::Fuzz() in its
// callbacks.  This will have no effect when we are not running the
// thread fuzzing test.  In the thread fuzzing test it will
// pseudorandomly select a successor thread and switch execution
// to that thread, suspending the current test.
192
class ApiTestFuzzer: public v8::base::Thread {
193 194 195 196 197 198
 public:
  void CallTest();

  // The ApiTestFuzzer is also a Thread, so it has a Run method.
  virtual void Run();

199 200 201 202 203
  enum PartOfTest { FIRST_PART,
                    SECOND_PART,
                    THIRD_PART,
                    FOURTH_PART,
                    LAST_PART = FOURTH_PART };
204

205
  static void SetUp(PartOfTest part);
206 207 208 209 210
  static void RunAllTests();
  static void TearDown();
  // This method switches threads if we are running the Threading test.
  // Otherwise it does nothing.
  static void Fuzz();
211

212
 private:
213
  explicit ApiTestFuzzer(int num)
214
      : Thread(Options("ApiTestFuzzer")),
215
        test_number_(num),
216
        gate_(0),
217
        active_(true) {}
218
  ~ApiTestFuzzer() {}
219

220 221 222 223 224 225
  static bool fuzzing_;
  static int tests_being_run_;
  static int current_;
  static int active_tests_;
  static bool NextThread();
  int test_number_;
226
  v8::base::Semaphore gate_;
227 228 229
  bool active_;
  void ContextSwitch();
  static int GetNextTestNumber();
230
  static v8::base::Semaphore all_tests_done_;
231 232 233 234 235 236 237 238 239 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
};


#define THREADED_TEST(Name)                                          \
  static void Test##Name();                                          \
  RegisterThreadedTest register_##Name(Test##Name, #Name);           \
  /* */ TEST(Name)


class RegisterThreadedTest {
 public:
  explicit RegisterThreadedTest(CcTest::TestFunction* callback,
                                const char* name)
      : fuzzer_(NULL), callback_(callback), name_(name) {
    prev_ = first_;
    first_ = this;
    count_++;
  }
  static int count() { return count_; }
  static RegisterThreadedTest* nth(int i) {
    CHECK(i < count());
    RegisterThreadedTest* current = first_;
    while (i > 0) {
      i--;
      current = current->prev_;
    }
    return current;
  }
  CcTest::TestFunction* callback() { return callback_; }
  ApiTestFuzzer* fuzzer_;
  const char* name() { return name_; }

 private:
  static RegisterThreadedTest* first_;
  static int count_;
  CcTest::TestFunction* callback_;
  RegisterThreadedTest* prev_;
  const char* name_;
};

// A LocalContext holds a reference to a v8::Context.
class LocalContext {
 public:
274 275 276 277
  LocalContext(v8::Isolate* isolate, v8::ExtensionConfiguration* extensions = 0,
               v8::Local<v8::ObjectTemplate> global_template =
                   v8::Local<v8::ObjectTemplate>(),
               v8::Local<v8::Value> global_object = v8::Local<v8::Value>()) {
278 279 280
    Initialize(isolate, extensions, global_template, global_object);
  }

281
  LocalContext(v8::ExtensionConfiguration* extensions = 0,
282 283 284
               v8::Local<v8::ObjectTemplate> global_template =
                   v8::Local<v8::ObjectTemplate>(),
               v8::Local<v8::Value> global_object = v8::Local<v8::Value>()) {
285
    Initialize(CcTest::isolate(), extensions, global_template, global_object);
286 287 288
  }

  virtual ~LocalContext() {
289 290
    v8::HandleScope scope(isolate_);
    v8::Local<v8::Context>::New(isolate_, context_)->Exit();
291
    context_.Reset();
292 293
  }

294 295 296 297
  v8::Context* operator->() {
    return *reinterpret_cast<v8::Context**>(&context_);
  }
  v8::Context* operator*() { return operator->(); }
298 299 300
  bool IsReady() { return !context_.IsEmpty(); }

  v8::Local<v8::Context> local() {
301
    return v8::Local<v8::Context>::New(isolate_, context_);
302 303 304
  }

 private:
305 306 307
  void Initialize(v8::Isolate* isolate, v8::ExtensionConfiguration* extensions,
                  v8::Local<v8::ObjectTemplate> global_template,
                  v8::Local<v8::Value> global_object) {
308 309 310 311 312 313 314 315 316 317 318
     v8::HandleScope scope(isolate);
     v8::Local<v8::Context> context = v8::Context::New(isolate,
                                                       extensions,
                                                       global_template,
                                                       global_object);
     context_.Reset(isolate, context);
     context->Enter();
     // We can't do this later perhaps because of a fatal error.
     isolate_ = isolate;
  }

319
  v8::Persistent<v8::Context> context_;
320
  v8::Isolate* isolate_;
321 322
};

323 324 325 326 327 328 329 330 331

static inline uint16_t* AsciiToTwoByteString(const char* source) {
  int array_length = i::StrLength(source) + 1;
  uint16_t* converted = i::NewArray<uint16_t>(array_length);
  for (int i = 0; i < array_length; i++) converted[i] = source[i];
  return converted;
}


332
static inline v8::Local<v8::Value> v8_num(double x) {
333
  return v8::Number::New(v8::Isolate::GetCurrent(), x);
334 335 336 337
}


static inline v8::Local<v8::String> v8_str(const char* x) {
338 339 340
  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), x,
                                 v8::NewStringType::kNormal)
      .ToLocalChecked();
341 342 343
}


344 345 346 347 348 349 350
static inline v8::Local<v8::String> v8_str(v8::Isolate* isolate,
                                           const char* x) {
  return v8::String::NewFromUtf8(isolate, x, v8::NewStringType::kNormal)
      .ToLocalChecked();
}


351 352 353 354 355
static inline v8::Local<v8::Symbol> v8_symbol(const char* name) {
  return v8::Symbol::New(v8::Isolate::GetCurrent(), v8_str(name));
}


356 357 358 359 360 361 362
static inline v8::Local<v8::Script> v8_compile(v8::Local<v8::String> x) {
  v8::Local<v8::Script> result;
  if (v8::Script::Compile(v8::Isolate::GetCurrent()->GetCurrentContext(), x)
          .ToLocal(&result)) {
    return result;
  }
  return v8::Local<v8::Script>();
363 364 365
}


366 367
static inline v8::Local<v8::Script> v8_compile(const char* x) {
  return v8_compile(v8_str(x));
368 369 370
}


371 372 373 374 375 376
static inline int32_t v8_run_int32value(v8::Local<v8::Script> script) {
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
  return script->Run(context).ToLocalChecked()->Int32Value(context).FromJust();
}


377 378 379
static inline v8::Local<v8::Script> CompileWithOrigin(
    v8::Local<v8::String> source, v8::Local<v8::String> origin_url) {
  v8::ScriptOrigin origin(origin_url);
380
  v8::ScriptCompiler::Source script_source(source, origin);
381
  return v8::ScriptCompiler::Compile(
382 383
             v8::Isolate::GetCurrent()->GetCurrentContext(), &script_source)
      .ToLocalChecked();
384 385 386 387 388
}


static inline v8::Local<v8::Script> CompileWithOrigin(
    v8::Local<v8::String> source, const char* origin_url) {
389 390 391 392 393 394 395
  return CompileWithOrigin(source, v8_str(origin_url));
}


static inline v8::Local<v8::Script> CompileWithOrigin(const char* source,
                                                      const char* origin_url) {
  return CompileWithOrigin(v8_str(source), v8_str(origin_url));
396 397 398 399
}


// Helper functions that compile and run the source.
400 401 402 403 404 405 406 407
static inline v8::MaybeLocal<v8::Value> CompileRun(
    v8::Local<v8::Context> context, const char* source) {
  return v8::Script::Compile(context, v8_str(source))
      .ToLocalChecked()
      ->Run(context);
}


408 409 410 411 412 413 414 415 416 417 418 419
static inline v8::Local<v8::Value> CompileRunChecked(v8::Isolate* isolate,
                                                     const char* source) {
  v8::Local<v8::String> source_string =
      v8::String::NewFromUtf8(isolate, source, v8::NewStringType::kNormal)
          .ToLocalChecked();
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  v8::Local<v8::Script> script =
      v8::Script::Compile(context, source_string).ToLocalChecked();
  return script->Run(context).ToLocalChecked();
}


420 421 422 423 424 425 426 427
static inline v8::Local<v8::Value> CompileRun(v8::Local<v8::String> source) {
  v8::Local<v8::Value> result;
  if (v8_compile(source)
          ->Run(v8::Isolate::GetCurrent()->GetCurrentContext())
          .ToLocal(&result)) {
    return result;
  }
  return v8::Local<v8::Value>();
428 429 430
}


431
// Helper functions that compile and run the source.
432 433
static inline v8::Local<v8::Value> CompileRun(const char* source) {
  return CompileRun(v8_str(source));
434 435 436
}


437 438 439 440 441 442 443 444 445 446 447
static inline v8::Local<v8::Value> CompileRun(
    v8::Local<v8::Context> context, v8::ScriptCompiler::Source* script_source,
    v8::ScriptCompiler::CompileOptions options) {
  v8::Local<v8::Value> result;
  if (v8::ScriptCompiler::Compile(context, script_source, options)
          .ToLocalChecked()
          ->Run(context)
          .ToLocal(&result)) {
    return result;
  }
  return v8::Local<v8::Value>();
448 449
}

450

451
static inline v8::Local<v8::Value> ParserCacheCompileRun(const char* source) {
452 453
  // Compile once just to get the preparse data, then compile the second time
  // using the data.
454
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
455
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
456
  v8::ScriptCompiler::Source script_source(v8_str(source));
457 458 459
  v8::ScriptCompiler::Compile(context, &script_source,
                              v8::ScriptCompiler::kProduceParserCache)
      .ToLocalChecked();
460 461 462 463 464 465

  // Check whether we received cached data, and if so use it.
  v8::ScriptCompiler::CompileOptions options =
      script_source.GetCachedData() ? v8::ScriptCompiler::kConsumeParserCache
                                    : v8::ScriptCompiler::kNoCompileOptions;

466
  return CompileRun(context, &script_source, options);
467 468 469
}


470
// Helper functions that compile and run the source with given origin.
471 472 473 474
static inline v8::Local<v8::Value> CompileRunWithOrigin(const char* source,
                                                        const char* origin_url,
                                                        int line_number,
                                                        int column_number) {
475
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
476
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
477
  v8::ScriptOrigin origin(v8_str(origin_url),
478 479
                          v8::Integer::New(isolate, line_number),
                          v8::Integer::New(isolate, column_number));
480
  v8::ScriptCompiler::Source script_source(v8_str(source), origin);
481 482
  return CompileRun(context, &script_source,
                    v8::ScriptCompiler::CompileOptions());
483 484 485 486
}


static inline v8::Local<v8::Value> CompileRunWithOrigin(
487
    v8::Local<v8::String> source, const char* origin_url) {
488 489
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
490 491
  v8::ScriptCompiler::Source script_source(
      source, v8::ScriptOrigin(v8_str(origin_url)));
492 493
  return CompileRun(context, &script_source,
                    v8::ScriptCompiler::CompileOptions());
494 495 496 497 498 499
}


static inline v8::Local<v8::Value> CompileRunWithOrigin(
    const char* source, const char* origin_url) {
  return CompileRunWithOrigin(v8_str(source), origin_url);
500 501
}

502

503 504 505 506 507

static inline void ExpectString(const char* code, const char* expected) {
  v8::Local<v8::Value> result = CompileRun(code);
  CHECK(result->IsString());
  v8::String::Utf8Value utf8(result);
508
  CHECK_EQ(0, strcmp(expected, *utf8));
509 510 511 512 513 514
}


static inline void ExpectInt32(const char* code, int expected) {
  v8::Local<v8::Value> result = CompileRun(code);
  CHECK(result->IsInt32());
515 516 517
  CHECK_EQ(expected,
           result->Int32Value(v8::Isolate::GetCurrent()->GetCurrentContext())
               .FromJust());
518 519 520 521 522 523
}


static inline void ExpectBoolean(const char* code, bool expected) {
  v8::Local<v8::Value> result = CompileRun(code);
  CHECK(result->IsBoolean());
524 525 526
  CHECK_EQ(expected,
           result->BooleanValue(v8::Isolate::GetCurrent()->GetCurrentContext())
               .FromJust());
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
}


static inline void ExpectTrue(const char* code) {
  ExpectBoolean(code, true);
}


static inline void ExpectFalse(const char* code) {
  ExpectBoolean(code, false);
}


static inline void ExpectObject(const char* code,
                                v8::Local<v8::Value> expected) {
  v8::Local<v8::Value> result = CompileRun(code);
  CHECK(result->SameValue(expected));
}


static inline void ExpectUndefined(const char* code) {
  v8::Local<v8::Value> result = CompileRun(code);
  CHECK(result->IsUndefined());
}


553 554 555 556 557 558
static inline void ExpectNull(const char* code) {
  v8::Local<v8::Value> result = CompileRun(code);
  CHECK(result->IsNull());
}


559 560 561 562 563 564 565
static inline void CheckDoubleEquals(double expected, double actual) {
  const double kEpsilon = 1e-10;
  CHECK_LE(expected, actual + kEpsilon);
  CHECK_GE(expected, actual - kEpsilon);
}


566 567 568 569
static void DummyDebugEventListener(
    const v8::Debug::EventDetails& event_details) {}


570 571
static inline void EnableDebugger(v8::Isolate* isolate) {
  v8::Debug::SetDebugEventListener(isolate, &DummyDebugEventListener);
572 573 574
}


575 576 577
static inline void DisableDebugger(v8::Isolate* isolate) {
  v8::Debug::SetDebugEventListener(isolate, nullptr);
}
578 579


580 581
static inline void EmptyMessageQueues(v8::Isolate* isolate) {
  while (v8::platform::PumpMessageLoop(v8::internal::V8::GetCurrentPlatform(),
582 583
                                       isolate)) {
  }
584 585 586
}


587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
class InitializedHandleScope {
 public:
  InitializedHandleScope()
      : main_isolate_(CcTest::InitIsolateOnce()),
        handle_scope_(main_isolate_) {}

  // Prefixing the below with main_ reduces a lot of naming clashes.
  i::Isolate* main_isolate() { return main_isolate_; }

 private:
  i::Isolate* main_isolate_;
  i::HandleScope handle_scope_;
};


class HandleAndZoneScope : public InitializedHandleScope {
 public:
604
  HandleAndZoneScope() {}
605 606 607 608 609 610 611 612

  // Prefixing the below with main_ reduces a lot of naming clashes.
  i::Zone* main_zone() { return &main_zone_; }

 private:
  i::Zone main_zone_;
};

613
#endif  // ifndef CCTEST_H_