d8.cc 59.6 KB
Newer Older
1
// Copyright 2012 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
// 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.


yangguo@chromium.org's avatar
yangguo@chromium.org committed
29 30
// Defined when linking against shared lib on Windows.
#if defined(USING_V8_SHARED) && !defined(V8_SHARED)
31
#define V8_SHARED
32 33
#endif

34 35 36
#ifdef COMPRESS_STARTUP_DATA_BZ2
#include <bzlib.h>
#endif
37

38
#include <errno.h>
39
#include <stdlib.h>
40
#include <string.h>
41
#include <sys/stat.h>
42

43
#ifdef V8_SHARED
44 45
#include <assert.h>
#include "../include/v8-testing.h"
46
#endif  // V8_SHARED
47

48
#include "d8.h"
49

50
#ifndef V8_SHARED
51 52
#include "api.h"
#include "checks.h"
53
#include "d8-debug.h"
54 55
#include "debug.h"
#include "natives.h"
56
#include "platform.h"
57
#include "v8.h"
58
#endif  // V8_SHARED
59

60 61 62
#if !defined(_WIN32) && !defined(_WIN64)
#include <unistd.h>  // NOLINT
#endif
63

64
#ifndef ASSERT
65
#define ASSERT(condition) assert(condition)
66
#endif
67

68
namespace v8 {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

LineEditor *LineEditor::first_ = NULL;


LineEditor::LineEditor(Type type, const char* name)
    : type_(type),
      name_(name),
      next_(first_) {
  first_ = this;
}


LineEditor* LineEditor::Get() {
  LineEditor* current = first_;
  LineEditor* best = current;
  while (current != NULL) {
    if (current->type_ > best->type_)
      best = current;
    current = current->next_;
  }
  return best;
}


class DumbLineEditor: public LineEditor {
 public:
  DumbLineEditor() : LineEditor(LineEditor::DUMB, "dumb") { }
96
  virtual Handle<String> Prompt(const char* prompt);
97 98 99 100 101 102
};


static DumbLineEditor dumb_line_editor;


103
Handle<String> DumbLineEditor::Prompt(const char* prompt) {
104
  printf("%s", prompt);
105
  return Shell::ReadFromStdin();
106 107 108
}


109
#ifndef V8_SHARED
110
CounterMap* Shell::counter_map_;
111 112 113
i::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
CounterCollection Shell::local_counters_;
CounterCollection* Shell::counters_ = &local_counters_;
114
i::Mutex* Shell::context_mutex_(i::OS::CreateMutex());
115
Persistent<Context> Shell::utility_context_;
116
#endif  // V8_SHARED
117

118
LineEditor* Shell::console = NULL;
119
Persistent<Context> Shell::evaluation_context_;
120
ShellOptions Shell::options;
121
const char* Shell::kPrompt = "d8> ";
122 123


124 125 126
const int MB = 1024 * 1024;


127
#ifndef V8_SHARED
128 129 130
bool CounterMap::Match(void* key1, void* key2) {
  const char* name1 = reinterpret_cast<const char*>(key1);
  const char* name2 = reinterpret_cast<const char*>(key2);
131
  return strcmp(name1, name2) == 0;
132
}
133
#endif  // V8_SHARED
134 135


136
// Converts a V8 value to a C string.
137
const char* Shell::ToCString(const v8::String::Utf8Value& value) {
138 139 140 141
  return *value ? *value : "<string conversion failed>";
}


142 143 144 145 146
// Executes a string within the current v8 context.
bool Shell::ExecuteString(Handle<String> source,
                          Handle<Value> name,
                          bool print_result,
                          bool report_exceptions) {
147
#if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
148 149 150
  bool FLAG_debugger = i::FLAG_debugger;
#else
  bool FLAG_debugger = false;
151
#endif  // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
152 153
  HandleScope handle_scope;
  TryCatch try_catch;
154
  options.script_executed = true;
155
  if (FLAG_debugger) {
156 157 158
    // When debugging make exceptions appear to be uncaught.
    try_catch.SetVerbose(true);
  }
159 160 161
  Handle<Script> script = Script::Compile(source, name);
  if (script.IsEmpty()) {
    // Print errors that happened during compilation.
162
    if (report_exceptions && !FLAG_debugger)
163 164 165 166 167
      ReportException(&try_catch);
    return false;
  } else {
    Handle<Value> result = script->Run();
    if (result.IsEmpty()) {
168
      ASSERT(try_catch.HasCaught());
169
      // Print errors that happened during execution.
170
      if (report_exceptions && !FLAG_debugger)
171 172 173
        ReportException(&try_catch);
      return false;
    } else {
174
      ASSERT(!try_catch.HasCaught());
175 176 177
      if (print_result && !result->IsUndefined()) {
        // If all went well and the result wasn't undefined then print
        // the returned value.
178
        v8::String::Utf8Value str(result);
179 180
        size_t count = fwrite(*str, sizeof(**str), str.length(), stdout);
        (void) count;  // Silence GCC-4.5.x "unused result" warning.
181
        printf("\n");
182 183 184 185 186 187 188 189
      }
      return true;
    }
  }
}


Handle<Value> Shell::Print(const Arguments& args) {
190 191
  Handle<Value> val = Write(args);
  printf("\n");
192
  fflush(stdout);
193 194 195 196 197
  return val;
}


Handle<Value> Shell::Write(const Arguments& args) {
198 199
  for (int i = 0; i < args.Length(); i++) {
    HandleScope handle_scope;
200
    if (i != 0) {
201 202
      printf(" ");
    }
203 204 205 206 207 208 209

    // Explicitly catch potential exceptions in toString().
    v8::TryCatch try_catch;
    Handle<String> str_obj = args[i]->ToString();
    if (try_catch.HasCaught()) return try_catch.ReThrow();

    v8::String::Utf8Value str(str_obj);
210
    int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
211 212
    if (n != str.length()) {
      printf("Error in fwrite\n");
213
      Exit(1);
214
    }
215 216 217 218 219
  }
  return Undefined();
}


220 221 222 223 224 225 226 227 228 229 230 231
Handle<Value> Shell::EnableProfiler(const Arguments& args) {
  V8::ResumeProfiler();
  return Undefined();
}


Handle<Value> Shell::DisableProfiler(const Arguments& args) {
  V8::PauseProfiler();
  return Undefined();
}


232 233 234 235 236 237 238 239 240 241 242 243 244
Handle<Value> Shell::Read(const Arguments& args) {
  String::Utf8Value file(args[0]);
  if (*file == NULL) {
    return ThrowException(String::New("Error loading file"));
  }
  Handle<String> source = ReadFile(*file);
  if (source.IsEmpty()) {
    return ThrowException(String::New("Error loading file"));
  }
  return source;
}


245
Handle<String> Shell::ReadFromStdin() {
246 247 248 249
  static const int kBufferSize = 256;
  char buffer[kBufferSize];
  Handle<String> accumulator = String::New("");
  int length;
250 251 252 253
  while (true) {
    // Continue reading if the line ends with an escape '\\' or the line has
    // not been fully read into the buffer yet (does not end with '\n').
    // If fgets gets an error, just give up.
254 255 256 257 258 259
    char* input = NULL;
    {  // Release lock for blocking input.
      Unlocker unlock(Isolate::GetCurrent());
      input = fgets(buffer, kBufferSize, stdin);
    }
    if (input == NULL) return Handle<String>();
260
    length = static_cast<int>(strlen(buffer));
261 262 263 264 265 266 267 268 269 270 271
    if (length == 0) {
      return accumulator;
    } else if (buffer[length-1] != '\n') {
      accumulator = String::Concat(accumulator, String::New(buffer, length));
    } else if (length > 1 && buffer[length-2] == '\\') {
      buffer[length-2] = '\n';
      accumulator = String::Concat(accumulator, String::New(buffer, length-1));
    } else {
      return String::Concat(accumulator, String::New(buffer, length-1));
    }
  }
272 273 274
}


275 276 277 278
Handle<Value> Shell::Load(const Arguments& args) {
  for (int i = 0; i < args.Length(); i++) {
    HandleScope handle_scope;
    String::Utf8Value file(args[i]);
279 280 281
    if (*file == NULL) {
      return ThrowException(String::New("Error loading file"));
    }
282 283 284 285
    Handle<String> source = ReadFile(*file);
    if (source.IsEmpty()) {
      return ThrowException(String::New("Error loading file"));
    }
286
    if (!ExecuteString(source, String::New(*file), false, true)) {
287
      return ThrowException(String::New("Error executing file"));
288 289 290 291 292
    }
  }
  return Undefined();
}

293
static int32_t convertToInt(Local<Value> value_in, TryCatch* try_catch) {
294 295
  if (value_in->IsInt32()) {
    return value_in->Int32Value();
296 297 298 299 300 301 302 303 304
  }

  Local<Value> number = value_in->ToNumber();
  if (try_catch->HasCaught()) return 0;

  ASSERT(number->IsNumber());
  Local<Int32> int32 = number->ToInt32();
  if (try_catch->HasCaught() || int32.IsEmpty()) return 0;

305 306 307 308 309 310 311 312 313
  int32_t value = int32->Int32Value();
  if (try_catch->HasCaught()) return 0;

  return value;
}


static int32_t convertToUint(Local<Value> value_in, TryCatch* try_catch) {
  int32_t raw_value = convertToInt(value_in, try_catch);
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
  if (try_catch->HasCaught()) return 0;

  if (raw_value < 0) {
    ThrowException(String::New("Array length must not be negative."));
    return 0;
  }

  static const int kMaxLength = 0x3fffffff;
#ifndef V8_SHARED
  ASSERT(kMaxLength == i::ExternalArray::kMaxLength);
#endif  // V8_SHARED
  if (raw_value > static_cast<int32_t>(kMaxLength)) {
    ThrowException(
        String::New("Array length exceeds maximum length."));
  }
329
  return raw_value;
330 331 332
}


333 334
// TODO(rossberg): should replace these by proper uses of HasInstance,
// once we figure out a good way to make the templates global.
335
const char kArrayBufferMarkerPropName[] = "d8::_is_array_buffer_";
336
const char kArrayMarkerPropName[] = "d8::_is_typed_array_";
337

338

339 340
Handle<Value> Shell::CreateExternalArrayBuffer(Handle<Object> buffer,
                                               int32_t length) {
341 342 343 344
  static const int32_t kMaxSize = 0x7fffffff;
  // Make sure the total size fits into a (signed) int.
  if (length < 0 || length > kMaxSize) {
    return ThrowException(String::New("ArrayBuffer exceeds maximum size (2G)"));
345
  }
346 347
  uint8_t* data = new uint8_t[length];
  if (data == NULL) {
348
    return ThrowException(String::New("Memory allocation failed"));
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  }
  memset(data, 0, length);

  buffer->SetHiddenValue(String::New(kArrayBufferMarkerPropName), True());
  Persistent<Object> persistent_array = Persistent<Object>::New(buffer);
  persistent_array.MakeWeak(data, ExternalArrayWeakCallback);
  persistent_array.MarkIndependent();
  V8::AdjustAmountOfExternalAllocatedMemory(length);

  buffer->SetIndexedPropertiesToExternalArrayData(
      data, v8::kExternalByteArray, length);
  buffer->Set(String::New("byteLength"), Int32::New(length), ReadOnly);

  return buffer;
}


366 367 368 369 370 371 372 373 374
Handle<Value> Shell::ArrayBuffer(const Arguments& args) {
  if (!args.IsConstructCall()) {
    Handle<Value>* rec_args = new Handle<Value>[args.Length()];
    for (int i = 0; i < args.Length(); ++i) rec_args[i] = args[i];
    Handle<Value> result = args.Callee()->NewInstance(args.Length(), rec_args);
    delete[] rec_args;
    return result;
  }

375
  if (args.Length() == 0) {
376
    return ThrowException(
377
        String::New("ArrayBuffer constructor must have one argument"));
378
  }
379 380
  TryCatch try_catch;
  int32_t length = convertToUint(args[0], &try_catch);
381
  if (try_catch.HasCaught()) return try_catch.ReThrow();
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
  return CreateExternalArrayBuffer(args.This(), length);
}


Handle<Object> Shell::CreateExternalArray(Handle<Object> array,
                                          Handle<Object> buffer,
                                          ExternalArrayType type,
                                          int32_t length,
                                          int32_t byteLength,
                                          int32_t byteOffset,
                                          int32_t element_size) {
  ASSERT(element_size == 1 || element_size == 2 ||
         element_size == 4 || element_size == 8);
  ASSERT(byteLength == length * element_size);

  void* data = buffer->GetIndexedPropertiesExternalArrayData();
  ASSERT(data != NULL);

  array->SetIndexedPropertiesToExternalArrayData(
      static_cast<uint8_t*>(data) + byteOffset, type, length);
  array->SetHiddenValue(String::New(kArrayMarkerPropName), Int32::New(type));
  array->Set(String::New("byteLength"), Int32::New(byteLength), ReadOnly);
  array->Set(String::New("byteOffset"), Int32::New(byteOffset), ReadOnly);
  array->Set(String::New("length"), Int32::New(length), ReadOnly);
  array->Set(String::New("BYTES_PER_ELEMENT"), Int32::New(element_size));
  array->Set(String::New("buffer"), buffer, ReadOnly);

  return array;
411 412 413 414 415 416
}


Handle<Value> Shell::CreateExternalArray(const Arguments& args,
                                         ExternalArrayType type,
                                         int32_t element_size) {
417 418 419 420 421 422 423 424
  if (!args.IsConstructCall()) {
    Handle<Value>* rec_args = new Handle<Value>[args.Length()];
    for (int i = 0; i < args.Length(); ++i) rec_args[i] = args[i];
    Handle<Value> result = args.Callee()->NewInstance(args.Length(), rec_args);
    delete[] rec_args;
    return result;
  }

425 426 427 428
  TryCatch try_catch;
  ASSERT(element_size == 1 || element_size == 2 ||
         element_size == 4 || element_size == 8);

429
  // All of the following constructors are supported:
430
  //   TypedArray(unsigned long length)
431 432
  //   TypedArray(type[] array)
  //   TypedArray(TypedArray array)
433 434 435
  //   TypedArray(ArrayBuffer buffer,
  //              optional unsigned long byteOffset,
  //              optional unsigned long length)
436 437 438 439
  Handle<Object> buffer;
  int32_t length;
  int32_t byteLength;
  int32_t byteOffset;
440
  bool init_from_array = false;
441 442
  if (args.Length() == 0) {
    return ThrowException(
443
        String::New("Array constructor must have at least one argument"));
444 445
  }
  if (args[0]->IsObject() &&
446 447 448
      !args[0]->ToObject()->GetHiddenValue(
          String::New(kArrayBufferMarkerPropName)).IsEmpty()) {
    // Construct from ArrayBuffer.
449 450
    buffer = args[0]->ToObject();
    int32_t bufferLength =
451
        convertToUint(buffer->Get(String::New("byteLength")), &try_catch);
452
    if (try_catch.HasCaught()) return try_catch.ReThrow();
453

454 455 456 457
    if (args.Length() < 2 || args[1]->IsUndefined()) {
      byteOffset = 0;
    } else {
      byteOffset = convertToUint(args[1], &try_catch);
458
      if (try_catch.HasCaught()) return try_catch.ReThrow();
459
      if (byteOffset > bufferLength) {
460 461
        return ThrowException(String::New("byteOffset out of bounds"));
      }
462
      if (byteOffset % element_size != 0) {
463
        return ThrowException(
464
            String::New("byteOffset must be multiple of element size"));
465 466
      }
    }
467

468
    if (args.Length() < 3 || args[2]->IsUndefined()) {
469 470
      byteLength = bufferLength - byteOffset;
      length = byteLength / element_size;
471
      if (byteLength % element_size != 0) {
472
        return ThrowException(
473
            String::New("buffer size must be multiple of element size"));
474
      }
475 476
    } else {
      length = convertToUint(args[2], &try_catch);
477
      if (try_catch.HasCaught()) return try_catch.ReThrow();
478 479 480 481
      byteLength = length * element_size;
      if (byteOffset + byteLength > bufferLength) {
        return ThrowException(String::New("length out of bounds"));
      }
482
    }
483
  } else {
484 485 486 487 488
    if (args[0]->IsObject() &&
        args[0]->ToObject()->Has(String::New("length"))) {
      // Construct from array.
      length = convertToUint(
          args[0]->ToObject()->Get(String::New("length")), &try_catch);
489
      if (try_catch.HasCaught()) return try_catch.ReThrow();
490 491 492 493
      init_from_array = true;
    } else {
      // Construct from size.
      length = convertToUint(args[0], &try_catch);
494
      if (try_catch.HasCaught()) return try_catch.ReThrow();
495
    }
496 497
    byteLength = length * element_size;
    byteOffset = 0;
498

499 500
    Handle<Object> global = Context::GetCurrent()->Global();
    Handle<Value> array_buffer = global->Get(String::New("ArrayBuffer"));
501 502 503
    ASSERT(!try_catch.HasCaught() && array_buffer->IsFunction());
    Handle<Value> buffer_args[] = { Uint32::New(byteLength) };
    Handle<Value> result = Handle<Function>::Cast(array_buffer)->NewInstance(
504
        1, buffer_args);
505
    if (try_catch.HasCaught()) return result;
506
    buffer = result->ToObject();
507
  }
508

509 510
  Handle<Object> array = CreateExternalArray(
      args.This(), buffer, type, length, byteLength, byteOffset, element_size);
511

512 513 514 515
  if (init_from_array) {
    Handle<Object> init = args[0]->ToObject();
    for (int i = 0; i < length; ++i) array->Set(i, init->Get(i));
  }
516

517 518 519 520
  return array;
}


521
Handle<Value> Shell::ArrayBufferSlice(const Arguments& args) {
522 523 524 525
  TryCatch try_catch;

  if (!args.This()->IsObject()) {
    return ThrowException(
526 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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        String::New("'slice' invoked on non-object receiver"));
  }

  Local<Object> self = args.This();
  Local<Value> marker =
      self->GetHiddenValue(String::New(kArrayBufferMarkerPropName));
  if (marker.IsEmpty()) {
    return ThrowException(
        String::New("'slice' invoked on wrong receiver type"));
  }

  int32_t length =
      convertToUint(self->Get(String::New("byteLength")), &try_catch);
  if (try_catch.HasCaught()) return try_catch.ReThrow();

  if (args.Length() == 0) {
    return ThrowException(
        String::New("'slice' must have at least one argument"));
  }
  int32_t begin = convertToInt(args[0], &try_catch);
  if (try_catch.HasCaught()) return try_catch.ReThrow();
  if (begin < 0) begin += length;
  if (begin < 0) begin = 0;
  if (begin > length) begin = length;

  int32_t end;
  if (args.Length() < 2 || args[1]->IsUndefined()) {
    end = length;
  } else {
    end = convertToInt(args[1], &try_catch);
    if (try_catch.HasCaught()) return try_catch.ReThrow();
    if (end < 0) end += length;
    if (end < 0) end = 0;
    if (end > length) end = length;
    if (end < begin) end = begin;
  }

  Local<Function> constructor = Local<Function>::Cast(self->GetConstructor());
  Handle<Value> new_args[] = { Uint32::New(end - begin) };
  Handle<Value> result = constructor->NewInstance(1, new_args);
  if (try_catch.HasCaught()) return result;
  Handle<Object> buffer = result->ToObject();
  uint8_t* dest =
      static_cast<uint8_t*>(buffer->GetIndexedPropertiesExternalArrayData());
  uint8_t* src = begin + static_cast<uint8_t*>(
      self->GetIndexedPropertiesExternalArrayData());
  memcpy(dest, src, end - begin);

  return buffer;
}


Handle<Value> Shell::ArraySubArray(const Arguments& args) {
  TryCatch try_catch;

  if (!args.This()->IsObject()) {
    return ThrowException(
        String::New("'subarray' invoked on non-object receiver"));
584 585 586 587 588 589
  }

  Local<Object> self = args.This();
  Local<Value> marker = self->GetHiddenValue(String::New(kArrayMarkerPropName));
  if (marker.IsEmpty()) {
    return ThrowException(
590
        String::New("'subarray' invoked on wrong receiver type"));
591 592 593
  }

  Handle<Object> buffer = self->Get(String::New("buffer"))->ToObject();
594
  if (try_catch.HasCaught()) return try_catch.ReThrow();
595 596
  int32_t length =
      convertToUint(self->Get(String::New("length")), &try_catch);
597
  if (try_catch.HasCaught()) return try_catch.ReThrow();
598 599
  int32_t byteOffset =
      convertToUint(self->Get(String::New("byteOffset")), &try_catch);
600
  if (try_catch.HasCaught()) return try_catch.ReThrow();
601 602
  int32_t element_size =
      convertToUint(self->Get(String::New("BYTES_PER_ELEMENT")), &try_catch);
603
  if (try_catch.HasCaught()) return try_catch.ReThrow();
604 605 606

  if (args.Length() == 0) {
    return ThrowException(
607
        String::New("'subarray' must have at least one argument"));
608 609
  }
  int32_t begin = convertToInt(args[0], &try_catch);
610
  if (try_catch.HasCaught()) return try_catch.ReThrow();
611 612 613 614 615 616 617 618 619
  if (begin < 0) begin += length;
  if (begin < 0) begin = 0;
  if (begin > length) begin = length;

  int32_t end;
  if (args.Length() < 2 || args[1]->IsUndefined()) {
    end = length;
  } else {
    end = convertToInt(args[1], &try_catch);
620
    if (try_catch.HasCaught()) return try_catch.ReThrow();
621 622 623 624 625 626 627 628 629 630 631 632 633
    if (end < 0) end += length;
    if (end < 0) end = 0;
    if (end > length) end = length;
    if (end < begin) end = begin;
  }

  length = end - begin;
  byteOffset += begin * element_size;

  Local<Function> constructor = Local<Function>::Cast(self->GetConstructor());
  Handle<Value> construct_args[] = {
    buffer, Uint32::New(byteOffset), Uint32::New(length)
  };
634
  return constructor->NewInstance(3, construct_args);
635 636 637
}


638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 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 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
Handle<Value> Shell::ArraySet(const Arguments& args) {
  TryCatch try_catch;

  if (!args.This()->IsObject()) {
    return ThrowException(
        String::New("'set' invoked on non-object receiver"));
  }

  Local<Object> self = args.This();
  Local<Value> marker = self->GetHiddenValue(String::New(kArrayMarkerPropName));
  if (marker.IsEmpty()) {
    return ThrowException(
        String::New("'set' invoked on wrong receiver type"));
  }
  int32_t length =
      convertToUint(self->Get(String::New("length")), &try_catch);
  if (try_catch.HasCaught()) return try_catch.ReThrow();
  int32_t element_size =
      convertToUint(self->Get(String::New("BYTES_PER_ELEMENT")), &try_catch);
  if (try_catch.HasCaught()) return try_catch.ReThrow();

  if (args.Length() == 0) {
    return ThrowException(
        String::New("'set' must have at least one argument"));
  }
  if (!args[0]->IsObject() ||
      !args[0]->ToObject()->Has(String::New("length"))) {
    return ThrowException(
        String::New("'set' invoked with non-array argument"));
  }
  Handle<Object> source = args[0]->ToObject();
  int32_t source_length =
      convertToUint(source->Get(String::New("length")), &try_catch);
  if (try_catch.HasCaught()) return try_catch.ReThrow();

  int32_t offset;
  if (args.Length() < 2 || args[1]->IsUndefined()) {
    offset = 0;
  } else {
    offset = convertToUint(args[1], &try_catch);
    if (try_catch.HasCaught()) return try_catch.ReThrow();
  }
  if (offset + source_length > length) {
    return ThrowException(String::New("offset or source length out of bounds"));
  }

  int32_t source_element_size;
  if (source->GetHiddenValue(String::New(kArrayMarkerPropName)).IsEmpty()) {
    source_element_size = 0;
  } else {
    source_element_size =
       convertToUint(source->Get(String::New("BYTES_PER_ELEMENT")), &try_catch);
    if (try_catch.HasCaught()) return try_catch.ReThrow();
  }

  if (element_size == source_element_size &&
      self->GetConstructor()->StrictEquals(source->GetConstructor())) {
    // Use memmove on the array buffers.
    Handle<Object> buffer = self->Get(String::New("buffer"))->ToObject();
    if (try_catch.HasCaught()) return try_catch.ReThrow();
    Handle<Object> source_buffer =
        source->Get(String::New("buffer"))->ToObject();
    if (try_catch.HasCaught()) return try_catch.ReThrow();
    int32_t byteOffset =
        convertToUint(self->Get(String::New("byteOffset")), &try_catch);
    if (try_catch.HasCaught()) return try_catch.ReThrow();
    int32_t source_byteOffset =
        convertToUint(source->Get(String::New("byteOffset")), &try_catch);
    if (try_catch.HasCaught()) return try_catch.ReThrow();

    uint8_t* dest = byteOffset + offset * element_size + static_cast<uint8_t*>(
        buffer->GetIndexedPropertiesExternalArrayData());
    uint8_t* src = source_byteOffset + static_cast<uint8_t*>(
        source_buffer->GetIndexedPropertiesExternalArrayData());
    memmove(dest, src, source_length * element_size);
  } else if (source_element_size == 0) {
    // Source is not a typed array, copy element-wise sequentially.
    for (int i = 0; i < source_length; ++i) {
      self->Set(offset + i, source->Get(i));
      if (try_catch.HasCaught()) return try_catch.ReThrow();
    }
  } else {
    // Need to copy element-wise to make the right conversions.
    Handle<Object> buffer = self->Get(String::New("buffer"))->ToObject();
    if (try_catch.HasCaught()) return try_catch.ReThrow();
    Handle<Object> source_buffer =
        source->Get(String::New("buffer"))->ToObject();
    if (try_catch.HasCaught()) return try_catch.ReThrow();

    if (buffer->StrictEquals(source_buffer)) {
      // Same backing store, need to handle overlap correctly.
      // This gets a bit tricky in the case of different element sizes
      // (which, of course, is extremely unlikely to ever occur in practice).
      int32_t byteOffset =
          convertToUint(self->Get(String::New("byteOffset")), &try_catch);
      if (try_catch.HasCaught()) return try_catch.ReThrow();
      int32_t source_byteOffset =
          convertToUint(source->Get(String::New("byteOffset")), &try_catch);
      if (try_catch.HasCaught()) return try_catch.ReThrow();

      // Copy as much as we can from left to right.
      int i = 0;
      int32_t next_dest_offset = byteOffset + (offset + 1) * element_size;
      int32_t next_src_offset = source_byteOffset + source_element_size;
      while (i < length && next_dest_offset <= next_src_offset) {
        self->Set(offset + i, source->Get(i));
        ++i;
        next_dest_offset += element_size;
        next_src_offset += source_element_size;
      }
      // Of what's left, copy as much as we can from right to left.
      int j = length - 1;
      int32_t dest_offset = byteOffset + (offset + j) * element_size;
      int32_t src_offset = source_byteOffset + j * source_element_size;
      while (j >= i && dest_offset >= src_offset) {
        self->Set(offset + j, source->Get(j));
        --j;
        dest_offset -= element_size;
        src_offset -= source_element_size;
      }
      // There can be at most 8 entries left in the middle that need buffering
      // (because the largest element_size is 8 times the smallest).
      ASSERT(j+1 - i <= 8);
      Handle<Value> temp[8];
      for (int k = i; k <= j; ++k) {
        temp[k - i] = source->Get(k);
      }
      for (int k = i; k <= j; ++k) {
        self->Set(offset + k, temp[k - i]);
      }
    } else {
      // Different backing stores, safe to copy element-wise sequentially.
      for (int i = 0; i < source_length; ++i)
        self->Set(offset + i, source->Get(i));
    }
  }

  return Undefined();
}


779
void Shell::ExternalArrayWeakCallback(Persistent<Value> object, void* data) {
780
  HandleScope scope;
781 782 783
  int32_t length =
      object->ToObject()->Get(String::New("byteLength"))->Uint32Value();
  V8::AdjustAmountOfExternalAllocatedMemory(-length);
784
  delete[] static_cast<uint8_t*>(data);
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  object.Dispose();
}


Handle<Value> Shell::Int8Array(const Arguments& args) {
  return CreateExternalArray(args, v8::kExternalByteArray, sizeof(int8_t));
}


Handle<Value> Shell::Uint8Array(const Arguments& args) {
  return CreateExternalArray(args, kExternalUnsignedByteArray, sizeof(uint8_t));
}


Handle<Value> Shell::Int16Array(const Arguments& args) {
  return CreateExternalArray(args, kExternalShortArray, sizeof(int16_t));
}


Handle<Value> Shell::Uint16Array(const Arguments& args) {
805 806
  return CreateExternalArray(
      args, kExternalUnsignedShortArray, sizeof(uint16_t));
807 808
}

809

810 811 812 813 814 815 816 817 818 819 820
Handle<Value> Shell::Int32Array(const Arguments& args) {
  return CreateExternalArray(args, kExternalIntArray, sizeof(int32_t));
}


Handle<Value> Shell::Uint32Array(const Arguments& args) {
  return CreateExternalArray(args, kExternalUnsignedIntArray, sizeof(uint32_t));
}


Handle<Value> Shell::Float32Array(const Arguments& args) {
821 822
  return CreateExternalArray(
      args, kExternalFloatArray, sizeof(float));  // NOLINT
823 824 825 826
}


Handle<Value> Shell::Float64Array(const Arguments& args) {
827 828
  return CreateExternalArray(
      args, kExternalDoubleArray, sizeof(double));  // NOLINT
829 830 831
}


832
Handle<Value> Shell::Uint8ClampedArray(const Arguments& args) {
833 834 835 836
  return CreateExternalArray(args, kExternalPixelArray, sizeof(uint8_t));
}


837 838 839 840 841 842
Handle<Value> Shell::Yield(const Arguments& args) {
  v8::Unlocker unlocker;
  return Undefined();
}


843 844
Handle<Value> Shell::Quit(const Arguments& args) {
  int exit_code = args[0]->Int32Value();
845
#ifndef V8_SHARED
846
  OnExit();
847
#endif  // V8_SHARED
848 849 850 851 852 853 854 855 856 857 858 859
  exit(exit_code);
  return Undefined();
}


Handle<Value> Shell::Version(const Arguments& args) {
  return String::New(V8::GetVersion());
}


void Shell::ReportException(v8::TryCatch* try_catch) {
  HandleScope handle_scope;
860
#if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
861 862
  bool enter_context = !Context::InContext();
  if (enter_context) utility_context_->Enter();
863
#endif  // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
864 865
  v8::String::Utf8Value exception(try_catch->Exception());
  const char* exception_string = ToCString(exception);
866 867 868 869
  Handle<Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    // V8 didn't provide any extra information about this error; just
    // print the exception.
870
    printf("%s\n", exception_string);
871 872
  } else {
    // Print (filename):(line number): (message).
873 874
    v8::String::Utf8Value filename(message->GetScriptResourceName());
    const char* filename_string = ToCString(filename);
875
    int linenum = message->GetLineNumber();
876
    printf("%s:%i: %s\n", filename_string, linenum, exception_string);
877
    // Print line of source code.
878 879 880
    v8::String::Utf8Value sourceline(message->GetSourceLine());
    const char* sourceline_string = ToCString(sourceline);
    printf("%s\n", sourceline_string);
881 882 883 884 885 886 887 888 889 890
    // Print wavy underline (GetUnderline is deprecated).
    int start = message->GetStartColumn();
    for (int i = 0; i < start; i++) {
      printf(" ");
    }
    int end = message->GetEndColumn();
    for (int i = start; i < end; i++) {
      printf("^");
    }
    printf("\n");
891 892 893 894 895
    v8::String::Utf8Value stack_trace(try_catch->StackTrace());
    if (stack_trace.length() > 0) {
      const char* stack_trace_string = ToCString(stack_trace);
      printf("%s\n", stack_trace_string);
    }
896
  }
897
  printf("\n");
898
#if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
899
  if (enter_context) utility_context_->Exit();
900
#endif  // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
901 902 903
}


904
#ifndef V8_SHARED
905 906 907 908 909 910 911 912 913 914 915 916
Handle<Array> Shell::GetCompletions(Handle<String> text, Handle<String> full) {
  HandleScope handle_scope;
  Context::Scope context_scope(utility_context_);
  Handle<Object> global = utility_context_->Global();
  Handle<Value> fun = global->Get(String::New("GetCompletions"));
  static const int kArgc = 3;
  Handle<Value> argv[kArgc] = { evaluation_context_->Global(), text, full };
  Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
  return handle_scope.Close(Handle<Array>::Cast(val));
}


917
#ifdef ENABLE_DEBUGGER_SUPPORT
918
Handle<Object> Shell::DebugMessageDetails(Handle<String> message) {
919 920
  Context::Scope context_scope(utility_context_);
  Handle<Object> global = utility_context_->Global();
921
  Handle<Value> fun = global->Get(String::New("DebugMessageDetails"));
922
  static const int kArgc = 1;
923
  Handle<Value> argv[kArgc] = { message };
924
  Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
925
  return Handle<Object>::Cast(val);
926 927 928 929 930 931 932 933 934 935 936 937
}


Handle<Value> Shell::DebugCommandToJSONRequest(Handle<String> command) {
  Context::Scope context_scope(utility_context_);
  Handle<Object> global = utility_context_->Global();
  Handle<Value> fun = global->Get(String::New("DebugCommandToJSONRequest"));
  static const int kArgc = 1;
  Handle<Value> argv[kArgc] = { command };
  Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
  return val;
}
938 939 940 941 942 943


void Shell::DispatchDebugMessages() {
  v8::Context::Scope scope(Shell::evaluation_context_);
  v8::Debug::ProcessDebugMessages();
}
944
#endif  // ENABLE_DEBUGGER_SUPPORT
945
#endif  // V8_SHARED
946 947


948
#ifndef V8_SHARED
949
int32_t* Counter::Bind(const char* name, bool is_histogram) {
950 951 952 953
  int i;
  for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
    name_[i] = static_cast<char>(name[i]);
  name_[i] = '\0';
954 955 956 957 958 959 960 961
  is_histogram_ = is_histogram;
  return ptr();
}


void Counter::AddSample(int32_t sample) {
  count_++;
  sample_total_ += sample;
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
}


CounterCollection::CounterCollection() {
  magic_number_ = 0xDEADFACE;
  max_counters_ = kMaxCounters;
  max_name_size_ = Counter::kMaxNameSize;
  counters_in_use_ = 0;
}


Counter* CounterCollection::GetNextCounter() {
  if (counters_in_use_ == kMaxCounters) return NULL;
  return &counters_[counters_in_use_++];
}


void Shell::MapCounters(const char* name) {
980 981
  counters_file_ = i::OS::MemoryMappedFile::create(
      name, sizeof(CounterCollection), &local_counters_);
982 983 984 985
  void* memory = (counters_file_ == NULL) ?
      NULL : counters_file_->memory();
  if (memory == NULL) {
    printf("Could not map counters file %s\n", name);
986
    Exit(1);
987 988 989
  }
  counters_ = static_cast<CounterCollection*>(memory);
  V8::SetCounterFunction(LookupCounter);
990 991
  V8::SetCreateHistogramFunction(CreateHistogram);
  V8::SetAddHistogramSampleFunction(AddHistogramSample);
992 993 994
}


995 996 997 998 999 1000 1001 1002 1003 1004 1005
int CounterMap::Hash(const char* name) {
  int h = 0;
  int c;
  while ((c = *name++) != 0) {
    h += h << 5;
    h += c;
  }
  return h;
}


1006
Counter* Shell::GetCounter(const char* name, bool is_histogram) {
1007
  Counter* counter = counter_map_->Lookup(name);
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

  if (counter == NULL) {
    counter = counters_->GetNextCounter();
    if (counter != NULL) {
      counter_map_->Set(name, counter);
      counter->Bind(name, is_histogram);
    }
  } else {
    ASSERT(counter->is_histogram() == is_histogram);
  }
  return counter;
}


int* Shell::LookupCounter(const char* name) {
  Counter* counter = GetCounter(name, false);

1025 1026
  if (counter != NULL) {
    return counter->ptr();
1027 1028
  } else {
    return NULL;
1029
  }
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
}


void* Shell::CreateHistogram(const char* name,
                             int min,
                             int max,
                             size_t buckets) {
  return GetCounter(name, true);
}


void Shell::AddHistogramSample(void* histogram, int sample) {
  Counter* counter = reinterpret_cast<Counter*>(histogram);
  counter->AddSample(sample);
1044 1045
}

1046

1047 1048 1049
void Shell::InstallUtilityScript() {
  Locker lock;
  HandleScope scope;
1050 1051 1052 1053
  // If we use the utility context, we have to set the security tokens so that
  // utility, evaluation and debug context can all access each other.
  utility_context_->SetSecurityToken(Undefined());
  evaluation_context_->SetSecurityToken(Undefined());
1054
  Context::Scope utility_scope(utility_context_);
1055 1056

#ifdef ENABLE_DEBUGGER_SUPPORT
1057
  if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
1058 1059 1060 1061
  // Install the debugger object in the utility scope
  i::Debug* debug = i::Isolate::Current()->debug();
  debug->Load();
  i::Handle<i::JSObject> js_debug
1062
      = i::Handle<i::JSObject>(debug->debug_context()->global_object());
1063 1064 1065
  utility_context_->Global()->Set(String::New("$debug"),
                                  Utils::ToLocal(js_debug));
  debug->debug_context()->set_security_token(HEAP->undefined_value());
1066
#endif  // ENABLE_DEBUGGER_SUPPORT
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
  // Run the d8 shell utility script in the utility context
  int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
  i::Vector<const char> shell_source =
      i::NativesCollection<i::D8>::GetRawScriptSource(source_index);
  i::Vector<const char> shell_source_name =
      i::NativesCollection<i::D8>::GetScriptName(source_index);
  Handle<String> source = String::New(shell_source.start(),
      shell_source.length());
  Handle<String> name = String::New(shell_source_name.start(),
      shell_source_name.length());
  Handle<Script> script = Script::Compile(source, name);
  script->Run();
  // Mark the d8 shell script as native to avoid it showing up as normal source
  // in the debugger.
  i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
  i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
1084 1085 1086 1087
      ? i::Handle<i::Script>(i::Script::cast(
          i::JSFunction::cast(*compiled_script)->shared()->script()))
      : i::Handle<i::Script>(i::Script::cast(
          i::SharedFunctionInfo::cast(*compiled_script)->script()));
1088
  script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
1089 1090 1091 1092 1093 1094

#ifdef ENABLE_DEBUGGER_SUPPORT
  // Start the in-process debugger if requested.
  if (i::FLAG_debugger && !i::FLAG_debugger_agent) {
    v8::Debug::SetDebugEventListener(HandleDebugEvent);
  }
1095
#endif  // ENABLE_DEBUGGER_SUPPORT
1096
}
1097
#endif  // V8_SHARED
1098

1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
#ifdef COMPRESS_STARTUP_DATA_BZ2
class BZip2Decompressor : public v8::StartupDataDecompressor {
 public:
  virtual ~BZip2Decompressor() { }

 protected:
  virtual int DecompressData(char* raw_data,
                             int* raw_data_size,
                             const char* compressed_data,
                             int compressed_data_size) {
    ASSERT_EQ(v8::StartupData::kBZip2,
              v8::V8::GetCompressedStartupDataAlgorithm());
    unsigned int decompressed_size = *raw_data_size;
    int result =
        BZ2_bzBuffToBuffDecompress(raw_data,
                                   &decompressed_size,
                                   const_cast<char*>(compressed_data),
                                   compressed_data_size,
                                   0, 1);
    if (result == BZ_OK) {
      *raw_data_size = decompressed_size;
    }
    return result;
  }
};
#endif

1127

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
Handle<FunctionTemplate> Shell::CreateArrayBufferTemplate(
    InvocationCallback fun) {
  Handle<FunctionTemplate> buffer_template = FunctionTemplate::New(fun);
  Local<Template> proto_template = buffer_template->PrototypeTemplate();
  proto_template->Set(String::New("slice"),
                      FunctionTemplate::New(ArrayBufferSlice));
  return buffer_template;
}


1138 1139 1140
Handle<FunctionTemplate> Shell::CreateArrayTemplate(InvocationCallback fun) {
  Handle<FunctionTemplate> array_template = FunctionTemplate::New(fun);
  Local<Template> proto_template = array_template->PrototypeTemplate();
1141 1142 1143
  proto_template->Set(String::New("set"), FunctionTemplate::New(ArraySet));
  proto_template->Set(String::New("subarray"),
                      FunctionTemplate::New(ArraySubArray));
1144 1145 1146 1147
  return array_template;
}


1148
Handle<ObjectTemplate> Shell::CreateGlobalTemplate() {
1149 1150
  Handle<ObjectTemplate> global_template = ObjectTemplate::New();
  global_template->Set(String::New("print"), FunctionTemplate::New(Print));
1151
  global_template->Set(String::New("write"), FunctionTemplate::New(Write));
1152
  global_template->Set(String::New("read"), FunctionTemplate::New(Read));
1153 1154
  global_template->Set(String::New("readbuffer"),
                       FunctionTemplate::New(ReadBuffer));
1155 1156
  global_template->Set(String::New("readline"),
                       FunctionTemplate::New(ReadLine));
1157 1158 1159
  global_template->Set(String::New("load"), FunctionTemplate::New(Load));
  global_template->Set(String::New("quit"), FunctionTemplate::New(Quit));
  global_template->Set(String::New("version"), FunctionTemplate::New(Version));
1160 1161 1162 1163
  global_template->Set(String::New("enableProfiler"),
                       FunctionTemplate::New(EnableProfiler));
  global_template->Set(String::New("disableProfiler"),
                       FunctionTemplate::New(DisableProfiler));
1164

1165
  // Bind the handlers for external arrays.
1166 1167
  PropertyAttribute attr =
      static_cast<PropertyAttribute>(ReadOnly | DontDelete);
1168
  global_template->Set(String::New("ArrayBuffer"),
1169
                       CreateArrayBufferTemplate(ArrayBuffer), attr);
1170
  global_template->Set(String::New("Int8Array"),
1171
                       CreateArrayTemplate(Int8Array), attr);
1172
  global_template->Set(String::New("Uint8Array"),
1173
                       CreateArrayTemplate(Uint8Array), attr);
1174
  global_template->Set(String::New("Int16Array"),
1175
                       CreateArrayTemplate(Int16Array), attr);
1176
  global_template->Set(String::New("Uint16Array"),
1177
                       CreateArrayTemplate(Uint16Array), attr);
1178
  global_template->Set(String::New("Int32Array"),
1179
                       CreateArrayTemplate(Int32Array), attr);
1180
  global_template->Set(String::New("Uint32Array"),
1181
                       CreateArrayTemplate(Uint32Array), attr);
1182
  global_template->Set(String::New("Float32Array"),
1183
                       CreateArrayTemplate(Float32Array), attr);
1184
  global_template->Set(String::New("Float64Array"),
1185 1186 1187
                       CreateArrayTemplate(Float64Array), attr);
  global_template->Set(String::New("Uint8ClampedArray"),
                       CreateArrayTemplate(Uint8ClampedArray), attr);
1188

1189
#ifdef LIVE_OBJECT_LIST
1190
  global_template->Set(String::New("lol_is_enabled"), True());
1191
#else
1192
  global_template->Set(String::New("lol_is_enabled"), False());
1193 1194
#endif

1195
#if !defined(V8_SHARED) && !defined(_WIN32) && !defined(_WIN64)
1196
  Handle<ObjectTemplate> os_templ = ObjectTemplate::New();
1197
  AddOSMethods(os_templ);
1198
  global_template->Set(String::New("os"), os_templ);
1199
#endif  // V8_SHARED
1200

1201 1202 1203
  return global_template;
}

1204

1205
void Shell::Initialize() {
1206 1207 1208 1209 1210
#ifdef COMPRESS_STARTUP_DATA_BZ2
  BZip2Decompressor startup_data_decompressor;
  int bz2_result = startup_data_decompressor.Decompress();
  if (bz2_result != BZ_OK) {
    fprintf(stderr, "bzip error code: %d\n", bz2_result);
1211
    Exit(1);
1212 1213 1214
  }
#endif

1215
#ifndef V8_SHARED
1216 1217 1218 1219
  Shell::counter_map_ = new CounterMap();
  // Set up counters
  if (i::StrLength(i::FLAG_map_counters) != 0)
    MapCounters(i::FLAG_map_counters);
1220
  if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
1221 1222 1223 1224
    V8::SetCounterFunction(LookupCounter);
    V8::SetCreateHistogramFunction(CreateHistogram);
    V8::SetAddHistogramSampleFunction(AddHistogramSample);
  }
1225
#endif  // V8_SHARED
1226
  if (options.test_shell) return;
1227

1228
#ifndef V8_SHARED
1229
  Locker lock;
1230 1231
  HandleScope scope;
  Handle<ObjectTemplate> global_template = CreateGlobalTemplate();
1232 1233
  utility_context_ = Context::New(NULL, global_template);

1234
#ifdef ENABLE_DEBUGGER_SUPPORT
1235 1236 1237
  // Start the debugger agent if requested.
  if (i::FLAG_debugger_agent) {
    v8::Debug::EnableAgent("d8 shell", i::FLAG_debugger_port, true);
1238
    v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true);
1239
  }
1240
#endif  // ENABLE_DEBUGGER_SUPPORT
1241
#endif  // V8_SHARED
1242
}
1243

1244

1245
Persistent<Context> Shell::CreateEvaluationContext() {
1246
#ifndef V8_SHARED
1247 1248
  // This needs to be a critical section since this is not thread-safe
  i::ScopedLock lock(context_mutex_);
1249
#endif  // V8_SHARED
1250 1251
  // Initialize the global objects
  Handle<ObjectTemplate> global_template = CreateGlobalTemplate();
1252
  Persistent<Context> context = Context::New(NULL, global_template);
1253
  ASSERT(!context.IsEmpty());
1254
  Context::Scope scope(context);
1255

1256
#ifndef V8_SHARED
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
  i::JSArguments js_args = i::FLAG_js_arguments;
  i::Handle<i::FixedArray> arguments_array =
      FACTORY->NewFixedArray(js_args.argc());
  for (int j = 0; j < js_args.argc(); j++) {
    i::Handle<i::String> arg =
        FACTORY->NewStringFromUtf8(i::CStrVector(js_args[j]));
    arguments_array->set(j, *arg);
  }
  i::Handle<i::JSArray> arguments_jsarray =
      FACTORY->NewJSArrayWithElements(arguments_array);
1267
  context->Global()->Set(String::New("arguments"),
1268
                         Utils::ToLocal(arguments_jsarray));
1269
#endif  // V8_SHARED
1270
  return context;
1271 1272 1273
}


1274 1275 1276 1277 1278 1279 1280 1281 1282
void Shell::Exit(int exit_code) {
  // Use _exit instead of exit to avoid races between isolate
  // threads and static destructors.
  fflush(stdout);
  fflush(stderr);
  _exit(exit_code);
}


1283
#ifndef V8_SHARED
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
struct CounterAndKey {
  Counter* counter;
  const char* key;
};


int CompareKeys(const void* a, const void* b) {
  return strcmp(static_cast<const CounterAndKey*>(a)->key,
                static_cast<const CounterAndKey*>(b)->key);
}


1296
void Shell::OnExit() {
1297
  if (console != NULL) console->Close();
1298
  if (i::FLAG_dump_counters) {
1299
    int number_of_counters = 0;
1300
    for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1301 1302 1303 1304 1305 1306 1307 1308 1309
      number_of_counters++;
    }
    CounterAndKey* counters = new CounterAndKey[number_of_counters];
    int j = 0;
    for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
      counters[j].counter = i.CurrentValue();
      counters[j].key = i.CurrentKey();
    }
    qsort(counters, number_of_counters, sizeof(counters[0]), CompareKeys);
1310 1311 1312 1313 1314 1315
    printf("+----------------------------------------------------------------+"
           "-------------+\n");
    printf("| Name                                                           |"
           " Value       |\n");
    printf("+----------------------------------------------------------------+"
           "-------------+\n");
1316 1317 1318
    for (j = 0; j < number_of_counters; j++) {
      Counter* counter = counters[j].counter;
      const char* key = counters[j].key;
1319
      if (counter->is_histogram()) {
1320 1321
        printf("| c:%-60s | %11i |\n", key, counter->count());
        printf("| t:%-60s | %11i |\n", key, counter->sample_total());
1322
      } else {
1323
        printf("| %-62s | %11i |\n", key, counter->count());
1324
      }
1325
    }
1326 1327
    printf("+----------------------------------------------------------------+"
           "-------------+\n");
1328
    delete [] counters;
1329
  }
1330 1331
  delete counters_file_;
  delete counter_map_;
1332
}
1333 1334 1335 1336
#endif  // V8_SHARED


static FILE* FOpen(const char* path, const char* mode) {
1337
#if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
1338 1339
  FILE* result;
  if (fopen_s(&result, path, mode) == 0) {
1340
    return result;
1341
  } else {
1342
    return NULL;
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
  }
#else
  FILE* file = fopen(path, mode);
  if (file == NULL) return NULL;
  struct stat file_stat;
  if (fstat(fileno(file), &file_stat) != 0) return NULL;
  bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
  if (is_regular_file) return file;
  fclose(file);
  return NULL;
#endif
}
1355 1356


1357
static char* ReadChars(const char* name, int* size_out) {
1358 1359
  // Release the V8 lock while reading files.
  v8::Unlocker unlocker(Isolate::GetCurrent());
1360
  FILE* file = FOpen(name, "rb");
1361
  if (file == NULL) return NULL;
1362 1363 1364 1365 1366 1367 1368 1369

  fseek(file, 0, SEEK_END);
  int size = ftell(file);
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
  for (int i = 0; i < size;) {
1370
    int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1371 1372 1373
    i += read;
  }
  fclose(file);
1374 1375 1376 1377 1378
  *size_out = size;
  return chars;
}


1379
Handle<Value> Shell::ReadBuffer(const Arguments& args) {
1380
  ASSERT(sizeof(char) == sizeof(uint8_t));  // NOLINT
1381 1382 1383 1384 1385
  String::Utf8Value filename(args[0]);
  int length;
  if (*filename == NULL) {
    return ThrowException(String::New("Error loading file"));
  }
1386 1387

  uint8_t* data = reinterpret_cast<uint8_t*>(ReadChars(*filename, &length));
1388 1389 1390 1391
  if (data == NULL) {
    return ThrowException(String::New("Error reading file"));
  }
  Handle<Object> buffer = Object::New();
1392
  buffer->SetHiddenValue(String::New(kArrayBufferMarkerPropName), True());
1393 1394 1395
  Persistent<Object> persistent_buffer = Persistent<Object>::New(buffer);
  persistent_buffer.MakeWeak(data, ExternalArrayWeakCallback);
  persistent_buffer.MarkIndependent();
1396
  V8::AdjustAmountOfExternalAllocatedMemory(length);
1397 1398

  buffer->SetIndexedPropertiesToExternalArrayData(
1399
      data, kExternalUnsignedByteArray, length);
1400
  buffer->Set(String::New("byteLength"),
1401
      Int32::New(static_cast<int32_t>(length)), ReadOnly);
1402 1403 1404 1405
  return buffer;
}


1406
#ifndef V8_SHARED
1407 1408
static char* ReadToken(char* data, char token) {
  char* next = i::OS::StrChr(data, token);
1409 1410 1411 1412 1413 1414 1415 1416 1417
  if (next != NULL) {
    *next = '\0';
    return (next + 1);
  }

  return NULL;
}


1418
static char* ReadLine(char* data) {
1419 1420 1421 1422
  return ReadToken(data, '\n');
}


1423
static char* ReadWord(char* data) {
1424 1425
  return ReadToken(data, ' ');
}
1426
#endif  // V8_SHARED
1427 1428


1429 1430 1431 1432 1433 1434
// Reads a file into a v8 string.
Handle<String> Shell::ReadFile(const char* name) {
  int size = 0;
  char* chars = ReadChars(name, &size);
  if (chars == NULL) return Handle<String>();
  Handle<String> result = String::New(chars);
1435 1436 1437 1438 1439 1440
  delete[] chars;
  return result;
}


void Shell::RunShell() {
1441 1442
  Locker locker;
  Context::Scope context_scope(evaluation_context_);
1443
  HandleScope outer_scope;
1444
  Handle<String> name = String::New("(d8)");
1445 1446 1447
  console = LineEditor::Get();
  printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
  console->Open();
1448
  while (true) {
1449
    HandleScope inner_scope;
1450 1451 1452
    Handle<String> input = console->Prompt(Shell::kPrompt);
    if (input.IsEmpty()) break;
    ExecuteString(input, name, true, true);
1453 1454 1455 1456 1457
  }
  printf("\n");
}


1458
#ifndef V8_SHARED
1459 1460
class ShellThread : public i::Thread {
 public:
1461 1462
  // Takes ownership of the underlying char array of |files|.
  ShellThread(int no, char* files)
1463 1464
      : Thread("d8:ShellThread"),
        no_(no), files_(files) { }
1465 1466 1467 1468 1469

  ~ShellThread() {
    delete[] files_;
  }

1470 1471 1472
  virtual void Run();
 private:
  int no_;
1473
  char* files_;
1474 1475 1476 1477
};


void ShellThread::Run() {
1478
  char* ptr = files_;
1479
  while ((ptr != NULL) && (*ptr != '\0')) {
1480
    // For each newline-separated line.
1481 1482 1483 1484 1485 1486
    char* next_line = ReadLine(ptr);

    if (*ptr == '#') {
      // Skip comment lines.
      ptr = next_line;
      continue;
1487
    }
1488

1489 1490
    // Prepare the context for this thread.
    Locker locker;
1491
    HandleScope outer_scope;
1492
    Persistent<Context> thread_context = Shell::CreateEvaluationContext();
1493 1494 1495
    Context::Scope context_scope(thread_context);

    while ((ptr != NULL) && (*ptr != '\0')) {
1496
      HandleScope inner_scope;
1497 1498 1499 1500 1501
      char* filename = ptr;
      ptr = ReadWord(ptr);

      // Skip empty strings.
      if (strlen(filename) == 0) {
1502
        continue;
1503 1504 1505 1506
      }

      Handle<String> str = Shell::ReadFile(filename);
      if (str.IsEmpty()) {
1507 1508
        printf("File '%s' not found\n", filename);
        Shell::Exit(1);
1509 1510 1511 1512 1513 1514 1515 1516
      }

      Shell::ExecuteString(str, String::New(filename), false, false);
    }

    thread_context.Dispose();
    ptr = next_line;
  }
1517
}
1518
#endif  // V8_SHARED
1519

1520

1521
SourceGroup::~SourceGroup() {
1522
#ifndef V8_SHARED
1523 1524 1525 1526 1527 1528
  delete next_semaphore_;
  next_semaphore_ = NULL;
  delete done_semaphore_;
  done_semaphore_ = NULL;
  delete thread_;
  thread_ = NULL;
1529
#endif  // V8_SHARED
1530 1531 1532
}


1533 1534 1535 1536 1537 1538 1539 1540 1541
void SourceGroup::Execute() {
  for (int i = begin_offset_; i < end_offset_; ++i) {
    const char* arg = argv_[i];
    if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
      // Execute argument given to -e option directly.
      HandleScope handle_scope;
      Handle<String> file_name = String::New("unnamed");
      Handle<String> source = String::New(argv_[i + 1]);
      if (!Shell::ExecuteString(source, file_name, false, true)) {
1542
        Shell::Exit(1);
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
      }
      ++i;
    } else if (arg[0] == '-') {
      // Ignore other options. They have been parsed already.
    } else {
      // Use all other arguments as names of files to load and run.
      HandleScope handle_scope;
      Handle<String> file_name = String::New(arg);
      Handle<String> source = ReadFile(arg);
      if (source.IsEmpty()) {
        printf("Error reading '%s'\n", arg);
1554
        Shell::Exit(1);
1555 1556
      }
      if (!Shell::ExecuteString(source, file_name, false, true)) {
1557
        Shell::Exit(1);
1558
      }
1559
    }
1560 1561
  }
}
1562

1563 1564

Handle<String> SourceGroup::ReadFile(const char* name) {
1565
  int size;
1566
  char* chars = ReadChars(name, &size);
1567
  if (chars == NULL) return Handle<String>();
1568 1569 1570 1571 1572 1573
  Handle<String> result = String::New(chars, size);
  delete[] chars;
  return result;
}


1574
#ifndef V8_SHARED
1575 1576 1577 1578
i::Thread::Options SourceGroup::GetThreadOptions() {
  // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
  // which is not enough to parse the big literal expressions used in tests.
  // The stack size should be at least StackGuard::kLimitSize + some
1579 1580
  // OS-specific padding for thread startup code.  2Mbytes seems to be enough.
  return i::Thread::Options("IsolateThread", 2 * MB);
1581 1582 1583 1584 1585 1586
}


void SourceGroup::ExecuteInThread() {
  Isolate* isolate = Isolate::New();
  do {
1587
    if (next_semaphore_ != NULL) next_semaphore_->Wait();
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
    {
      Isolate::Scope iscope(isolate);
      Locker lock(isolate);
      HandleScope scope;
      Persistent<Context> context = Shell::CreateEvaluationContext();
      {
        Context::Scope cscope(context);
        Execute();
      }
      context.Dispose();
1598 1599 1600 1601 1602
      if (Shell::options.send_idle_notification) {
        const int kLongIdlePauseInMs = 1000;
        V8::ContextDisposedNotification();
        V8::IdleNotification(kLongIdlePauseInMs);
      }
1603
    }
1604
    if (done_semaphore_ != NULL) done_semaphore_->Signal();
1605 1606 1607 1608 1609 1610
  } while (!Shell::options.last_run);
  isolate->Dispose();
}


void SourceGroup::StartExecuteInThread() {
1611 1612
  if (thread_ == NULL) {
    thread_ = new IsolateThread(this);
1613
    thread_->Start();
1614
  }
1615 1616 1617
  next_semaphore_->Signal();
}

1618

1619
void SourceGroup::WaitForThread() {
1620
  if (thread_ == NULL) return;
1621 1622 1623 1624
  if (Shell::options.last_run) {
    thread_->Join();
  } else {
    done_semaphore_->Wait();
1625
  }
1626
}
1627
#endif  // V8_SHARED
1628 1629


1630
bool Shell::SetOptions(int argc, char* argv[]) {
1631 1632
  for (int i = 0; i < argc; i++) {
    if (strcmp(argv[i], "--stress-opt") == 0) {
1633
      options.stress_opt = true;
1634 1635
      argv[i] = NULL;
    } else if (strcmp(argv[i], "--stress-deopt") == 0) {
1636
      options.stress_deopt = true;
1637 1638 1639
      argv[i] = NULL;
    } else if (strcmp(argv[i], "--noalways-opt") == 0) {
      // No support for stressing if we can't use --always-opt.
1640 1641
      options.stress_opt = false;
      options.stress_deopt = false;
1642
    } else if (strcmp(argv[i], "--shell") == 0) {
1643
      options.interactive_shell = true;
1644 1645
      argv[i] = NULL;
    } else if (strcmp(argv[i], "--test") == 0) {
1646 1647
      options.test_shell = true;
      argv[i] = NULL;
1648 1649 1650
    } else if (strcmp(argv[i], "--send-idle-notification") == 0) {
      options.send_idle_notification = true;
      argv[i] = NULL;
1651
    } else if (strcmp(argv[i], "--preemption") == 0) {
1652
#ifdef V8_SHARED
1653 1654 1655
      printf("D8 with shared library does not support multi-threading\n");
      return false;
#else
1656
      options.use_preemption = true;
1657
      argv[i] = NULL;
1658
#endif  // V8_SHARED
1659
    } else if (strcmp(argv[i], "--nopreemption") == 0) {
1660
#ifdef V8_SHARED
1661 1662 1663
      printf("D8 with shared library does not support multi-threading\n");
      return false;
#else
1664 1665
      options.use_preemption = false;
      argv[i] = NULL;
1666
#endif  // V8_SHARED
1667
    } else if (strcmp(argv[i], "--preemption-interval") == 0) {
1668
#ifdef V8_SHARED
1669 1670 1671
      printf("D8 with shared library does not support multi-threading\n");
      return false;
#else
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
      if (++i < argc) {
        argv[i-1] = NULL;
        char* end = NULL;
        options.preemption_interval = strtol(argv[i], &end, 10);  // NOLINT
        if (options.preemption_interval <= 0
            || *end != '\0'
            || errno == ERANGE) {
          printf("Invalid value for --preemption-interval '%s'\n", argv[i]);
          return false;
        }
        argv[i] = NULL;
      } else {
        printf("Missing value for --preemption-interval\n");
        return false;
      }
1687
#endif  // V8_SHARED
1688 1689 1690 1691 1692
    } else if (strcmp(argv[i], "-f") == 0) {
      // Ignore any -f flags for compatibility with other stand-alone
      // JavaScript engines.
      continue;
    } else if (strcmp(argv[i], "--isolate") == 0) {
1693
#ifdef V8_SHARED
1694 1695
      printf("D8 with shared library does not support multi-threading\n");
      return false;
1696
#endif  // V8_SHARED
1697
      options.num_isolates++;
1698 1699 1700 1701
    } else if (strcmp(argv[i], "-p") == 0) {
#ifdef V8_SHARED
      printf("D8 with shared library does not support multi-threading\n");
      return false;
1702 1703
#else
      options.num_parallel_files++;
1704
#endif  // V8_SHARED
1705
    }
1706
#ifdef V8_SHARED
1707 1708 1709 1710 1711 1712 1713
    else if (strcmp(argv[i], "--dump-counters") == 0) {
      printf("D8 with shared library does not include counters\n");
      return false;
    } else if (strcmp(argv[i], "--debugger") == 0) {
      printf("Javascript debugger not included\n");
      return false;
    }
1714
#endif  // V8_SHARED
1715 1716
  }

1717
#ifndef V8_SHARED
1718
  // Run parallel threads if we are not using --isolate
1719 1720
  options.parallel_files = new char*[options.num_parallel_files];
  int parallel_files_set = 0;
1721 1722 1723 1724 1725 1726 1727 1728
  for (int i = 1; i < argc; i++) {
    if (argv[i] == NULL) continue;
    if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) {
      if (options.num_isolates > 1) {
        printf("-p is not compatible with --isolate\n");
        return false;
      }
      argv[i] = NULL;
1729 1730 1731
      i++;
      options.parallel_files[parallel_files_set] = argv[i];
      parallel_files_set++;
1732
      argv[i] = NULL;
1733 1734
    }
  }
1735 1736 1737 1738
  if (parallel_files_set != options.num_parallel_files) {
    printf("-p requires a file containing a list of files as parameter\n");
    return false;
  }
1739
#endif  // V8_SHARED
1740 1741 1742

  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);

1743
  // Set up isolated source groups.
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
  options.isolate_sources = new SourceGroup[options.num_isolates];
  SourceGroup* current = options.isolate_sources;
  current->Begin(argv, 1);
  for (int i = 1; i < argc; i++) {
    const char* str = argv[i];
    if (strcmp(str, "--isolate") == 0) {
      current->End(i);
      current++;
      current->Begin(argv, i + 1);
    } else if (strncmp(argv[i], "--", 2) == 0) {
      printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
    }
  }
  current->End(argc);

  return true;
}


int Shell::RunMain(int argc, char* argv[]) {
1764
#ifndef V8_SHARED
1765
  i::List<i::Thread*> threads(1);
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
  if (options.parallel_files != NULL) {
    for (int i = 0; i < options.num_parallel_files; i++) {
      char* files = NULL;
      { Locker lock(Isolate::GetCurrent());
        int size = 0;
        files = ReadChars(options.parallel_files[i], &size);
      }
      if (files == NULL) {
        printf("File list '%s' not found\n", options.parallel_files[i]);
        Exit(1);
      }
1777 1778 1779
      ShellThread* thread = new ShellThread(threads.length(), files);
      thread->Start();
      threads.Add(thread);
1780
    }
1781
  }
1782 1783 1784
  for (int i = 1; i < options.num_isolates; ++i) {
    options.isolate_sources[i].StartExecuteInThread();
  }
1785
#endif  // V8_SHARED
1786
  {  // NOLINT
1787 1788 1789
    Locker lock;
    HandleScope scope;
    Persistent<Context> context = CreateEvaluationContext();
1790 1791 1792
    if (options.last_run) {
      // Keep using the same context in the interactive shell.
      evaluation_context_ = context;
1793
#if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
1794 1795 1796 1797 1798
      // If the interactive debugger is enabled make sure to activate
      // it before running the files passed on the command line.
      if (i::FLAG_debugger) {
        InstallUtilityScript();
      }
1799
#endif  // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
1800
    }
1801 1802 1803 1804
    {
      Context::Scope cscope(context);
      options.isolate_sources[0].Execute();
    }
1805
    if (!options.last_run) {
1806
      context.Dispose();
1807
      if (options.send_idle_notification) {
1808 1809 1810 1811
        const int kLongIdlePauseInMs = 1000;
        V8::ContextDisposedNotification();
        V8::IdleNotification(kLongIdlePauseInMs);
      }
1812
    }
1813

1814
#ifndef V8_SHARED
1815
    // Start preemption if threads have been created and preemption is enabled.
1816
    if (threads.length() > 0
1817 1818 1819
        && options.use_preemption) {
      Locker::StartPreemption(options.preemption_interval);
    }
1820
#endif  // V8_SHARED
1821 1822
  }

1823
#ifndef V8_SHARED
1824 1825 1826 1827
  for (int i = 1; i < options.num_isolates; ++i) {
    options.isolate_sources[i].WaitForThread();
  }

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
  for (int i = 0; i < threads.length(); i++) {
    i::Thread* thread = threads[i];
    thread->Join();
    delete thread;
  }

  if (threads.length() > 0 && options.use_preemption) {
    Locker lock;
    Locker::StopPreemption();
  }
1838
#endif  // V8_SHARED
1839 1840 1841 1842 1843 1844 1845
  return 0;
}


int Shell::Main(int argc, char* argv[]) {
  if (!SetOptions(argc, argv)) return 1;
  Initialize();
1846 1847

  int result = 0;
1848 1849 1850 1851 1852
  if (options.stress_opt || options.stress_deopt) {
    Testing::SetStressRunType(
        options.stress_opt ? Testing::kStressTypeOpt
                           : Testing::kStressTypeDeopt);
    int stress_runs = Testing::GetStressRuns();
1853 1854
    for (int i = 0; i < stress_runs && result == 0; i++) {
      printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1855 1856 1857
      Testing::PrepareStressRun(i);
      options.last_run = (i == stress_runs - 1);
      result = RunMain(argc, argv);
1858 1859
    }
    printf("======== Full Deoptimization =======\n");
1860
    Testing::DeoptimizeAll();
1861
#if !defined(V8_SHARED)
1862 1863 1864 1865
  } else if (i::FLAG_stress_runs > 0) {
    int stress_runs = i::FLAG_stress_runs;
    for (int i = 0; i < stress_runs && result == 0; i++) {
      printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1866
      options.last_run = (i == stress_runs - 1);
1867 1868
      result = RunMain(argc, argv);
    }
1869
#endif
1870
  } else {
1871
    result = RunMain(argc, argv);
1872 1873
  }

1874

1875
#if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
1876
  // Run remote debugger if requested, but never on --test
1877
  if (i::FLAG_remote_debugger && !options.test_shell) {
1878
    InstallUtilityScript();
1879 1880 1881
    RunRemoteDebugger(i::FLAG_debugger_port);
    return 0;
  }
1882
#endif  // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
1883

1884 1885
  // Run interactive shell if explicitly requested or if no script has been
  // executed, but never on --test
1886 1887 1888 1889

  if (( options.interactive_shell
      || !options.script_executed )
      && !options.test_shell ) {
1890
#if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
1891 1892 1893
    if (!i::FLAG_debugger) {
      InstallUtilityScript();
    }
1894
#endif  // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
1895 1896 1897
    RunShell();
  }

1898
  V8::Dispose();
1899 1900

#ifndef V8_SHARED
1901
  OnExit();
1902
#endif  // V8_SHARED
1903 1904 1905 1906

  return result;
}

1907
}  // namespace v8
1908 1909


1910
#ifndef GOOGLE3
1911 1912 1913
int main(int argc, char* argv[]) {
  return v8::Shell::Main(argc, argv);
}
1914
#endif