d8.cc 110 KB
Newer Older
1
/// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include <errno.h>
6
#include <stdlib.h>
7
#include <string.h>
8
#include <sys/stat.h>
9

10
#include <algorithm>
11
#include <fstream>
12
#include <unordered_map>
13
#include <utility>
binji's avatar
binji committed
14
#include <vector>
15

16
#ifdef ENABLE_VTUNE_JIT_INTERFACE
17
#include "src/third_party/vtune/v8-vtune.h"
18 19
#endif

20
#include "src/d8-console.h"
21
#include "src/d8.h"
22
#include "src/ostreams.h"
23

24
#include "include/libplatform/libplatform.h"
25
#include "include/libplatform/v8-tracing.h"
26
#include "include/v8-inspector.h"
27
#include "src/api.h"
28 29 30
#include "src/base/cpu.h"
#include "src/base/logging.h"
#include "src/base/platform/platform.h"
31
#include "src/base/platform/time.h"
32
#include "src/base/sys-info.h"
33
#include "src/basic-block-profiler.h"
34
#include "src/debug/debug-interface.h"
35
#include "src/interpreter/interpreter.h"
36
#include "src/list-inl.h"
37
#include "src/msan.h"
38
#include "src/objects-inl.h"
39
#include "src/objects.h"
40
#include "src/snapshot/natives.h"
eholk's avatar
eholk committed
41
#include "src/trap-handler/trap-handler.h"
42
#include "src/utils.h"
43
#include "src/v8.h"
44

45
#if !defined(_WIN32) && !defined(_WIN64)
46
#include <unistd.h>  // NOLINT
47 48 49 50 51 52
#else
#include <windows.h>  // NOLINT
#if defined(_MSC_VER)
#include <crtdbg.h>  // NOLINT
#endif               // defined(_MSC_VER)
#endif               // !defined(_WIN32) && !defined(_WIN64)
53

54 55
#ifndef DCHECK
#define DCHECK(condition) assert(condition)
Yang Guo's avatar
Yang Guo committed
56 57 58 59
#endif

#ifndef CHECK
#define CHECK(condition) assert(condition)
60
#endif
61

62
namespace v8 {
63

64
namespace {
65 66

const int MB = 1024 * 1024;
67
const int kMaxWorkers = 50;
68
const int kMaxSerializerMemoryUsage = 1 * MB;  // Arbitrary maximum for testing.
69

70 71 72 73 74
#define USE_VM 1
#define VM_THRESHOLD 65536
// TODO(titzer): allocations should fail if >= 2gb because of
// array buffers storing the lengths as a SMI internally.
#define TWO_GB (2u * 1024u * 1024u * 1024u)
75

76 77 78 79 80 81
// Forwards memory reservation and protection functions to the V8 default
// allocator. Used by ShellArrayBufferAllocator and MockArrayBufferAllocator.
class ArrayBufferAllocatorBase : public v8::ArrayBuffer::Allocator {
  std::unique_ptr<Allocator> allocator_ =
      std::unique_ptr<Allocator>(NewDefaultAllocator());

82
 public:
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  void* Reserve(size_t length) override { return allocator_->Reserve(length); }

  void Free(void*, size_t) override = 0;

  void Free(void* data, size_t length, AllocationMode mode) override {
    switch (mode) {
      case AllocationMode::kNormal: {
        return Free(data, length);
      }
      case AllocationMode::kReservation: {
        return allocator_->Free(data, length, mode);
      }
    }
  }

  void SetProtection(void* data, size_t length,
                     Protection protection) override {
    allocator_->SetProtection(data, length, protection);
  }
};

class ShellArrayBufferAllocator : public ArrayBufferAllocatorBase {
 public:
  void* Allocate(size_t length) override {
107 108 109 110
#if USE_VM
    if (RoundToPageSize(&length)) {
      void* data = VirtualMemoryAllocate(length);
#if DEBUG
111 112 113 114 115 116 117
      if (data) {
        // In debug mode, check the memory is zero-initialized.
        size_t limit = length / sizeof(uint64_t);
        uint64_t* ptr = reinterpret_cast<uint64_t*>(data);
        for (size_t i = 0; i < limit; i++) {
          DCHECK_EQ(0u, ptr[i]);
        }
118 119 120 121 122
      }
#endif
      return data;
    }
#endif
123 124 125
    void* data = AllocateUninitialized(length);
    return data == NULL ? data : memset(data, 0, length);
  }
126
  void* AllocateUninitialized(size_t length) override {
127 128 129
#if USE_VM
    if (RoundToPageSize(&length)) return VirtualMemoryAllocate(length);
#endif
130 131 132 133 134
// Work around for GCC bug on AIX
// See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79839
#if V8_OS_AIX && _LINUX_SOURCE_COMPAT
    return __linux_malloc(length);
#else
135
    return malloc(length);
136
#endif
137
  }
138
  using ArrayBufferAllocatorBase::Free;
139
  void Free(void* data, size_t length) override {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
#if USE_VM
    if (RoundToPageSize(&length)) {
      base::VirtualMemory::ReleaseRegion(data, length);
      return;
    }
#endif
    free(data);
  }
  // If {length} is at least {VM_THRESHOLD}, round up to next page size
  // and return {true}. Otherwise return {false}.
  bool RoundToPageSize(size_t* length) {
    const size_t kPageSize = base::OS::CommitPageSize();
    if (*length >= VM_THRESHOLD && *length < TWO_GB) {
      *length = ((*length + kPageSize - 1) / kPageSize) * kPageSize;
      return true;
    }
    return false;
  }
#if USE_VM
  void* VirtualMemoryAllocate(size_t length) {
160
    void* data = base::VirtualMemory::ReserveRegion(length, nullptr);
161 162 163 164 165 166 167 168
    if (data && !base::VirtualMemory::CommitRegion(data, length, false)) {
      base::VirtualMemory::ReleaseRegion(data, length);
      return nullptr;
    }
    MSAN_MEMORY_IS_INITIALIZED(data, length);
    return data;
  }
#endif
169 170
};

171 172 173 174 175
class MockArrayBufferAllocator : public ArrayBufferAllocatorBase {
  const size_t kAllocationLimit = 10 * MB;
  size_t get_actual_length(size_t length) const {
    return length > kAllocationLimit ? base::OS::CommitPageSize() : length;
  }
176 177 178

 public:
  void* Allocate(size_t length) override {
179
    const size_t actual_length = get_actual_length(length);
180 181 182 183
    void* data = AllocateUninitialized(actual_length);
    return data == NULL ? data : memset(data, 0, actual_length);
  }
  void* AllocateUninitialized(size_t length) override {
184
    return malloc(get_actual_length(length));
185 186
  }
  void Free(void* p, size_t) override { free(p); }
187 188 189 190 191 192
  void Free(void* data, size_t length, AllocationMode mode) override {
    ArrayBufferAllocatorBase::Free(data, get_actual_length(length), mode);
  }
  void* Reserve(size_t length) override {
    return ArrayBufferAllocatorBase::Reserve(get_actual_length(length));
  }
193 194
};

195 196 197
// Predictable v8::Platform implementation. Background tasks and idle tasks are
// disallowed, and the time reported by {MonotonicallyIncreasingTime} is
// deterministic.
198 199
class PredictablePlatform : public Platform {
 public:
200 201 202 203
  explicit PredictablePlatform(std::unique_ptr<Platform> platform)
      : platform_(std::move(platform)) {
    DCHECK_NOT_NULL(platform_);
  }
204 205 206

  void CallOnBackgroundThread(Task* task,
                              ExpectedRuntime expected_runtime) override {
207 208
    // It's not defined when background tasks are being executed, so we can just
    // execute them right away.
209 210 211 212 213
    task->Run();
    delete task;
  }

  void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override {
214
    platform_->CallOnForegroundThread(isolate, task);
215 216 217 218
  }

  void CallDelayedOnForegroundThread(v8::Isolate* isolate, Task* task,
                                     double delay_in_seconds) override {
219
    platform_->CallDelayedOnForegroundThread(isolate, task, delay_in_seconds);
220 221
  }

222
  void CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) override {
223 224 225
    UNREACHABLE();
  }

226
  bool IdleTasksEnabled(Isolate* isolate) override { return false; }
227 228 229 230 231

  double MonotonicallyIncreasingTime() override {
    return synthetic_time_in_sec_ += 0.00001;
  }

232 233 234 235
  v8::TracingController* GetTracingController() override {
    return platform_->GetTracingController();
  }

236
  Platform* platform() const { return platform_.get(); }
237

238 239
 private:
  double synthetic_time_in_sec_ = 0.0;
240
  std::unique_ptr<Platform> platform_;
241 242 243 244 245

  DISALLOW_COPY_AND_ASSIGN(PredictablePlatform);
};


246
v8::Platform* g_platform = NULL;
247

248 249 250 251 252 253
v8::Platform* GetDefaultPlatform() {
  return i::FLAG_verify_predictable
             ? static_cast<PredictablePlatform*>(g_platform)->platform()
             : g_platform;
}

254 255 256 257 258 259 260 261 262 263 264
static Local<Value> Throw(Isolate* isolate, const char* message) {
  return isolate->ThrowException(
      String::NewFromUtf8(isolate, message, NewStringType::kNormal)
          .ToLocalChecked());
}

Worker* GetWorkerFromInternalField(Isolate* isolate, Local<Object> object) {
  if (object->InternalFieldCount() != 1) {
    Throw(isolate, "this is not a Worker");
    return NULL;
  }
265

266 267 268 269 270 271
  Worker* worker =
      static_cast<Worker*>(object->GetAlignedPointerFromInternalField(0));
  if (worker == NULL) {
    Throw(isolate, "Worker is defunct because main thread is terminating");
    return NULL;
  }
272

273
  return worker;
274 275 276
}


277 278
}  // namespace

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
namespace tracing {

namespace {

// String options that can be used to initialize TraceOptions.
const char kRecordUntilFull[] = "record-until-full";
const char kRecordContinuously[] = "record-continuously";
const char kRecordAsMuchAsPossible[] = "record-as-much-as-possible";

const char kRecordModeParam[] = "record_mode";
const char kEnableSystraceParam[] = "enable_systrace";
const char kEnableArgumentFilterParam[] = "enable_argument_filter";
const char kIncludedCategoriesParam[] = "included_categories";

class TraceConfigParser {
 public:
  static void FillTraceConfig(v8::Isolate* isolate,
                              platform::tracing::TraceConfig* trace_config,
                              const char* json_str) {
    HandleScope outer_scope(isolate);
    Local<Context> context = Context::New(isolate);
    Context::Scope context_scope(context);
    HandleScope inner_scope(isolate);

    Local<String> source =
        String::NewFromUtf8(isolate, json_str, NewStringType::kNormal)
            .ToLocalChecked();
    Local<Value> result = JSON::Parse(context, source).ToLocalChecked();
    Local<v8::Object> trace_config_object = Local<v8::Object>::Cast(result);

    trace_config->SetTraceRecordMode(
        GetTraceRecordMode(isolate, context, trace_config_object));
    if (GetBoolean(isolate, context, trace_config_object,
                   kEnableSystraceParam)) {
      trace_config->EnableSystrace();
    }
    if (GetBoolean(isolate, context, trace_config_object,
                   kEnableArgumentFilterParam)) {
      trace_config->EnableArgumentFilter();
    }
319 320
    UpdateIncludedCategoriesList(isolate, context, trace_config_object,
                                 trace_config);
321 322 323 324 325 326 327 328 329 330 331 332 333
  }

 private:
  static bool GetBoolean(v8::Isolate* isolate, Local<Context> context,
                         Local<v8::Object> object, const char* property) {
    Local<Value> value = GetValue(isolate, context, object, property);
    if (value->IsNumber()) {
      Local<Boolean> v8_boolean = value->ToBoolean(context).ToLocalChecked();
      return v8_boolean->Value();
    }
    return false;
  }

334
  static int UpdateIncludedCategoriesList(
335
      v8::Isolate* isolate, Local<Context> context, Local<v8::Object> object,
336 337 338
      platform::tracing::TraceConfig* trace_config) {
    Local<Value> value =
        GetValue(isolate, context, object, kIncludedCategoriesParam);
339 340 341 342 343 344 345 346
    if (value->IsArray()) {
      Local<Array> v8_array = Local<Array>::Cast(value);
      for (int i = 0, length = v8_array->Length(); i < length; ++i) {
        Local<Value> v = v8_array->Get(context, i)
                             .ToLocalChecked()
                             ->ToString(context)
                             .ToLocalChecked();
        String::Utf8Value str(v->ToString(context).ToLocalChecked());
347
        trace_config->AddIncludedCategory(*str);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
      }
      return v8_array->Length();
    }
    return 0;
  }

  static platform::tracing::TraceRecordMode GetTraceRecordMode(
      v8::Isolate* isolate, Local<Context> context, Local<v8::Object> object) {
    Local<Value> value = GetValue(isolate, context, object, kRecordModeParam);
    if (value->IsString()) {
      Local<String> v8_string = value->ToString(context).ToLocalChecked();
      String::Utf8Value str(v8_string);
      if (strcmp(kRecordUntilFull, *str) == 0) {
        return platform::tracing::TraceRecordMode::RECORD_UNTIL_FULL;
      } else if (strcmp(kRecordContinuously, *str) == 0) {
        return platform::tracing::TraceRecordMode::RECORD_CONTINUOUSLY;
      } else if (strcmp(kRecordAsMuchAsPossible, *str) == 0) {
        return platform::tracing::TraceRecordMode::RECORD_AS_MUCH_AS_POSSIBLE;
      }
    }
    return platform::tracing::TraceRecordMode::RECORD_UNTIL_FULL;
  }

  static Local<Value> GetValue(v8::Isolate* isolate, Local<Context> context,
                               Local<v8::Object> object, const char* property) {
    Local<String> v8_str =
        String::NewFromUtf8(isolate, property, NewStringType::kNormal)
            .ToLocalChecked();
    return object->Get(context, v8_str).ToLocalChecked();
  }
};

}  // namespace

static platform::tracing::TraceConfig* CreateTraceConfigFromJSON(
    v8::Isolate* isolate, const char* json_str) {
  platform::tracing::TraceConfig* trace_config =
      new platform::tracing::TraceConfig();
  TraceConfigParser::FillTraceConfig(isolate, trace_config, json_str);
  return trace_config;
}

}  // namespace tracing
391

392
class PerIsolateData {
393
 public:
394
  explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
395
    HandleScope scope(isolate);
396
    isolate->SetData(0, this);
397 398
  }

399
  ~PerIsolateData() {
400
    isolate_->SetData(0, NULL);  // Not really needed, just to be sure...
401 402
  }

403
  inline static PerIsolateData* Get(Isolate* isolate) {
404
    return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
405
  }
406 407 408 409 410 411 412 413

  class RealmScope {
   public:
    explicit RealmScope(PerIsolateData* data);
    ~RealmScope();
   private:
    PerIsolateData* data_;
  };
414 415

 private:
416 417
  friend class Shell;
  friend class RealmScope;
418
  Isolate* isolate_;
419 420 421
  int realm_count_;
  int realm_current_;
  int realm_switch_;
422 423
  Global<Context>* realms_;
  Global<Value> realm_shared_;
424

425 426
  int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
                        int arg_offset);
427
  int RealmFind(Local<Context> context);
428 429
};

430 431 432 433 434 435 436 437 438 439 440 441 442 443
class ExternalOwningOneByteStringResource
    : public String::ExternalOneByteStringResource {
 public:
  ExternalOwningOneByteStringResource() : length_(0) {}
  ExternalOwningOneByteStringResource(std::unique_ptr<const char[]> data,
                                      size_t length)
      : data_(std::move(data)), length_(length) {}
  const char* data() const override { return data_.get(); }
  size_t length() const override { return length_; }

 private:
  std::unique_ptr<const char[]> data_;
  size_t length_;
};
444

445
CounterMap* Shell::counter_map_;
446
base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
447 448
CounterCollection Shell::local_counters_;
CounterCollection* Shell::counters_ = &local_counters_;
449
base::LazyMutex Shell::context_mutex_;
450 451
const base::TimeTicks Shell::kInitialTicks =
    base::TimeTicks::HighResolutionNow();
yangguo's avatar
yangguo committed
452
Global<Function> Shell::stringify_function_;
453
base::LazyMutex Shell::workers_mutex_;
454
bool Shell::allow_new_workers_ = true;
455
i::List<Worker*> Shell::workers_;
456
std::vector<ExternalizedContents> Shell::externalized_contents_;
457 458
base::LazyMutex Shell::isolate_status_lock_;
std::map<v8::Isolate*, bool> Shell::isolate_status_;
459

460
Global<Context> Shell::evaluation_context_;
461
ArrayBuffer::Allocator* Shell::array_buffer_allocator;
462
ShellOptions Shell::options;
463
base::OnceType Shell::quit_once_ = V8_ONCE_INIT;
464

465 466 467
bool CounterMap::Match(void* key1, void* key2) {
  const char* name1 = reinterpret_cast<const char*>(key1);
  const char* name2 = reinterpret_cast<const char*>(key2);
468
  return strcmp(name1, name2) == 0;
469 470 471
}


472 473 474 475 476 477 478 479 480
ScriptCompiler::CachedData* CompileForCachedData(
    Local<String> source, Local<Value> name,
    ScriptCompiler::CompileOptions compile_options) {
  int source_length = source->Length();
  uint16_t* source_buffer = new uint16_t[source_length];
  source->Write(source_buffer, 0, source_length);
  int name_length = 0;
  uint16_t* name_buffer = NULL;
  if (name->IsString()) {
481
    Local<String> name_string = Local<String>::Cast(name);
482 483 484 485
    name_length = name_string->Length();
    name_buffer = new uint16_t[name_length];
    name_string->Write(name_buffer, 0, name_length);
  }
486
  Isolate::CreateParams create_params;
487
  create_params.array_buffer_allocator = Shell::array_buffer_allocator;
488
  Isolate* temp_isolate = Isolate::New(create_params);
489 490
  temp_isolate->SetHostImportModuleDynamicallyCallback(
      Shell::HostImportModuleDynamically);
491 492 493 494 495
  ScriptCompiler::CachedData* result = NULL;
  {
    Isolate::Scope isolate_scope(temp_isolate);
    HandleScope handle_scope(temp_isolate);
    Context::Scope context_scope(Context::New(temp_isolate));
496 497
    Local<String> source_copy =
        v8::String::NewFromTwoByte(temp_isolate, source_buffer,
498 499
                                   v8::NewStringType::kNormal, source_length)
            .ToLocalChecked();
500 501
    Local<Value> name_copy;
    if (name_buffer) {
502 503 504 505
      name_copy =
          v8::String::NewFromTwoByte(temp_isolate, name_buffer,
                                     v8::NewStringType::kNormal, name_length)
              .ToLocalChecked();
506 507 508 509
    } else {
      name_copy = v8::Undefined(temp_isolate);
    }
    ScriptCompiler::Source script_source(source_copy, ScriptOrigin(name_copy));
510
    if (!ScriptCompiler::CompileUnboundScript(temp_isolate, &script_source,
511 512
                                              compile_options)
             .IsEmpty() &&
513
        script_source.GetCachedData()) {
514 515 516 517 518 519 520 521 522
      int length = script_source.GetCachedData()->length;
      uint8_t* cache = new uint8_t[length];
      memcpy(cache, script_source.GetCachedData()->data, length);
      result = new ScriptCompiler::CachedData(
          cache, length, ScriptCompiler::CachedData::BufferOwned);
    }
  }
  temp_isolate->Dispose();
  delete[] source_buffer;
yangguo@chromium.org's avatar
yangguo@chromium.org committed
523
  delete[] name_buffer;
524 525 526 527
  return result;
}


528
// Compile a string within the current v8 context.
529
MaybeLocal<Script> Shell::CompileString(
530
    Isolate* isolate, Local<String> source, Local<Value> name,
531
    ScriptCompiler::CompileOptions compile_options) {
532
  Local<Context> context(isolate->GetCurrentContext());
533
  ScriptOrigin origin(name);
534
  if (compile_options == ScriptCompiler::kNoCompileOptions) {
535
    ScriptCompiler::Source script_source(source, origin);
536
    return ScriptCompiler::Compile(context, &script_source, compile_options);
537 538 539 540 541 542 543 544 545 546 547
  }

  ScriptCompiler::CachedData* data =
      CompileForCachedData(source, name, compile_options);
  ScriptCompiler::Source cached_source(source, origin, data);
  if (compile_options == ScriptCompiler::kProduceCodeCache) {
    compile_options = ScriptCompiler::kConsumeCodeCache;
  } else if (compile_options == ScriptCompiler::kProduceParserCache) {
    compile_options = ScriptCompiler::kConsumeParserCache;
  } else {
    DCHECK(false);  // A new compile option?
548
  }
549
  if (data == NULL) compile_options = ScriptCompiler::kNoCompileOptions;
550
  MaybeLocal<Script> result =
551
      ScriptCompiler::Compile(context, &cached_source, compile_options);
552 553
  CHECK(data == NULL || !data->rejected);
  return result;
554 555 556
}


557
// Executes a string within the current v8 context.
558 559
bool Shell::ExecuteString(Isolate* isolate, Local<String> source,
                          Local<Value> name, bool print_result,
560
                          bool report_exceptions) {
561
  HandleScope handle_scope(isolate);
562
  TryCatch try_catch(isolate);
563
  try_catch.SetVerbose(true);
564

565
  MaybeLocal<Value> maybe_result;
566
  {
567 568
    PerIsolateData* data = PerIsolateData::Get(isolate);
    Local<Context> realm =
569
        Local<Context>::New(isolate, data->realms_[data->realm_current_]);
570
    Context::Scope context_scope(realm);
571 572 573 574 575 576
    Local<Script> script;
    if (!Shell::CompileString(isolate, source, name, options.compile_options)
             .ToLocal(&script)) {
      // Print errors that happened during compilation.
      if (report_exceptions) ReportException(isolate, &try_catch);
      return false;
577
    }
578
    maybe_result = script->Run(realm);
579
    EmptyMessageQueues(isolate);
580 581
    data->realm_current_ = data->realm_switch_;
  }
582 583
  Local<Value> result;
  if (!maybe_result.ToLocal(&result)) {
584 585
    DCHECK(try_catch.HasCaught());
    // Print errors that happened during execution.
586
    if (report_exceptions) ReportException(isolate, &try_catch);
587 588 589 590 591 592 593 594 595 596 597
    return false;
  }
  DCHECK(!try_catch.HasCaught());
  if (print_result) {
    if (options.test_shell) {
      if (!result->IsUndefined()) {
        // If all went well and the result wasn't undefined then print
        // the returned value.
        v8::String::Utf8Value str(result);
        fwrite(*str, sizeof(**str), str.length(), stdout);
        printf("\n");
598
      }
599
    } else {
yangguo's avatar
yangguo committed
600
      v8::String::Utf8Value str(Stringify(isolate, result));
601 602
      fwrite(*str, sizeof(**str), str.length(), stdout);
      printf("\n");
603 604
    }
  }
605
  return true;
606 607
}

608 609
namespace {

610 611 612 613 614 615 616 617
std::string ToSTLString(Local<String> v8_str) {
  String::Utf8Value utf8(v8_str);
  // Should not be able to fail since the input is a String.
  CHECK(*utf8);
  return *utf8;
}

bool IsAbsolutePath(const std::string& path) {
618 619 620
#if defined(_WIN32) || defined(_WIN64)
  // TODO(adamk): This is an incorrect approximation, but should
  // work for all our test-running cases.
621
  return path.find(':') != std::string::npos;
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
#else
  return path[0] == '/';
#endif
}

std::string GetWorkingDirectory() {
#if defined(_WIN32) || defined(_WIN64)
  char system_buffer[MAX_PATH];
  // TODO(adamk): Support Unicode paths.
  DWORD len = GetCurrentDirectoryA(MAX_PATH, system_buffer);
  CHECK(len > 0);
  return system_buffer;
#else
  char curdir[PATH_MAX];
  CHECK_NOT_NULL(getcwd(curdir, PATH_MAX));
  return curdir;
#endif
}

641
// Returns the directory part of path, without the trailing '/'.
642
std::string DirName(const std::string& path) {
643 644
  DCHECK(IsAbsolutePath(path));
  size_t last_slash = path.find_last_of('/');
645
  DCHECK(last_slash != std::string::npos);
646 647 648
  return path.substr(0, last_slash);
}

649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
// Resolves path to an absolute path if necessary, and does some
// normalization (eliding references to the current directory
// and replacing backslashes with slashes).
std::string NormalizePath(const std::string& path,
                          const std::string& dir_name) {
  std::string result;
  if (IsAbsolutePath(path)) {
    result = path;
  } else {
    result = dir_name + '/' + path;
  }
  std::replace(result.begin(), result.end(), '\\', '/');
  size_t i;
  while ((i = result.find("/./")) != std::string::npos) {
    result.erase(i, 2);
  }
  return result;
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
// Per-context Module data, allowing sharing of module maps
// across top-level module loads.
class ModuleEmbedderData {
 private:
  class ModuleGlobalHash {
   public:
    explicit ModuleGlobalHash(Isolate* isolate) : isolate_(isolate) {}
    size_t operator()(const Global<Module>& module) const {
      return module.Get(isolate_)->GetIdentityHash();
    }

   private:
    Isolate* isolate_;
  };

 public:
  explicit ModuleEmbedderData(Isolate* isolate)
      : module_to_directory_map(10, ModuleGlobalHash(isolate)) {}

  // Map from normalized module specifier to Module.
  std::unordered_map<std::string, Global<Module>> specifier_to_module_map;
  // Map from Module to the directory that Module was loaded from.
  std::unordered_map<Global<Module>, std::string, ModuleGlobalHash>
      module_to_directory_map;
};

enum {
695 696
  kModuleEmbedderDataIndex,
  kInspectorClientIndex
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
};

void InitializeModuleEmbedderData(Local<Context> context) {
  context->SetAlignedPointerInEmbedderData(
      kModuleEmbedderDataIndex, new ModuleEmbedderData(context->GetIsolate()));
}

ModuleEmbedderData* GetModuleDataFromContext(Local<Context> context) {
  return static_cast<ModuleEmbedderData*>(
      context->GetAlignedPointerFromEmbedderData(kModuleEmbedderDataIndex));
}

void DisposeModuleEmbedderData(Local<Context> context) {
  delete GetModuleDataFromContext(context);
  context->SetAlignedPointerInEmbedderData(kModuleEmbedderDataIndex, nullptr);
}

714 715
MaybeLocal<Module> ResolveModuleCallback(Local<Context> context,
                                         Local<String> specifier,
716
                                         Local<Module> referrer) {
717
  Isolate* isolate = context->GetIsolate();
718 719 720 721
  ModuleEmbedderData* d = GetModuleDataFromContext(context);
  auto dir_name_it =
      d->module_to_directory_map.find(Global<Module>(isolate, referrer));
  CHECK(dir_name_it != d->module_to_directory_map.end());
722
  std::string absolute_path =
723 724 725 726
      NormalizePath(ToSTLString(specifier), dir_name_it->second);
  auto module_it = d->specifier_to_module_map.find(absolute_path);
  CHECK(module_it != d->specifier_to_module_map.end());
  return module_it->second.Get(isolate);
727 728 729 730
}

}  // anonymous namespace

731 732
MaybeLocal<Module> Shell::FetchModuleTree(Local<Context> context,
                                          const std::string& file_name) {
733
  DCHECK(IsAbsolutePath(file_name));
734
  Isolate* isolate = context->GetIsolate();
735 736
  Local<String> source_text = ReadFile(isolate, file_name.c_str());
  if (source_text.IsEmpty()) {
737 738 739
    std::string msg = "Error reading: " + file_name;
    Throw(isolate, msg.c_str());
    return MaybeLocal<Module>();
740 741 742
  }
  ScriptOrigin origin(
      String::NewFromUtf8(isolate, file_name.c_str(), NewStringType::kNormal)
743 744 745
          .ToLocalChecked(),
      Local<Integer>(), Local<Integer>(), Local<Boolean>(), Local<Integer>(),
      Local<Value>(), Local<Boolean>(), Local<Boolean>(), True(isolate));
746 747 748 749 750
  ScriptCompiler::Source source(source_text, origin);
  Local<Module> module;
  if (!ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) {
    return MaybeLocal<Module>();
  }
751 752 753 754 755

  ModuleEmbedderData* d = GetModuleDataFromContext(context);
  CHECK(d->specifier_to_module_map
            .insert(std::make_pair(file_name, Global<Module>(isolate, module)))
            .second);
756 757

  std::string dir_name = DirName(file_name);
758 759 760
  CHECK(d->module_to_directory_map
            .insert(std::make_pair(Global<Module>(isolate, module), dir_name))
            .second);
761

762 763
  for (int i = 0, length = module->GetModuleRequestsLength(); i < length; ++i) {
    Local<String> name = module->GetModuleRequest(i);
764
    std::string absolute_path = NormalizePath(ToSTLString(name), dir_name);
765 766
    if (!d->specifier_to_module_map.count(absolute_path)) {
      if (FetchModuleTree(context, absolute_path).IsEmpty()) {
767 768 769 770 771 772 773 774
        return MaybeLocal<Module>();
      }
    }
  }

  return module;
}

775 776 777 778 779
namespace {

struct DynamicImportData {
  DynamicImportData(Isolate* isolate_, Local<String> referrer_,
                    Local<String> specifier_,
780
                    Local<Promise::Resolver> resolver_)
781 782 783
      : isolate(isolate_) {
    referrer.Reset(isolate, referrer_);
    specifier.Reset(isolate, specifier_);
784
    resolver.Reset(isolate, resolver_);
785 786 787 788 789
  }

  Isolate* isolate;
  Global<String> referrer;
  Global<String> specifier;
790
  Global<Promise::Resolver> resolver;
791 792 793
};

}  // namespace
794

795 796
MaybeLocal<Promise> Shell::HostImportModuleDynamically(
    Local<Context> context, Local<String> referrer, Local<String> specifier) {
797
  Isolate* isolate = context->GetIsolate();
798 799 800 801 802 803 804 805 806 807 808 809

  MaybeLocal<Promise::Resolver> maybe_resolver =
      Promise::Resolver::New(context);
  Local<Promise::Resolver> resolver;
  if (maybe_resolver.ToLocal(&resolver)) {
    DynamicImportData* data =
        new DynamicImportData(isolate, referrer, specifier, resolver);
    isolate->EnqueueMicrotask(Shell::DoHostImportModuleDynamically, data);
    return resolver->GetPromise();
  }

  return MaybeLocal<Promise>();
810 811 812 813 814 815 816 817 818 819
}

void Shell::DoHostImportModuleDynamically(void* import_data) {
  std::unique_ptr<DynamicImportData> import_data_(
      static_cast<DynamicImportData*>(import_data));
  Isolate* isolate(import_data_->isolate);
  HandleScope handle_scope(isolate);

  Local<String> referrer(import_data_->referrer.Get(isolate));
  Local<String> specifier(import_data_->specifier.Get(isolate));
820
  Local<Promise::Resolver> resolver(import_data_->resolver.Get(isolate));
821 822 823 824 825 826 827

  PerIsolateData* data = PerIsolateData::Get(isolate);
  Local<Context> realm = data->realms_[data->realm_current_].Get(isolate);
  Context::Scope context_scope(realm);

  std::string source_url = ToSTLString(referrer);
  std::string dir_name =
828 829 830
      DirName(IsAbsolutePath(source_url)
                  ? source_url
                  : NormalizePath(source_url, GetWorkingDirectory()));
831
  std::string file_name = ToSTLString(specifier);
832
  std::string absolute_path = NormalizePath(file_name, dir_name);
833 834 835 836 837 838 839 840 841 842 843

  TryCatch try_catch(isolate);
  try_catch.SetVerbose(true);

  ModuleEmbedderData* d = GetModuleDataFromContext(realm);
  Local<Module> root_module;
  auto module_it = d->specifier_to_module_map.find(absolute_path);
  if (module_it != d->specifier_to_module_map.end()) {
    root_module = module_it->second.Get(isolate);
  } else if (!FetchModuleTree(realm, absolute_path).ToLocal(&root_module)) {
    CHECK(try_catch.HasCaught());
844
    resolver->Reject(realm, try_catch.Exception()).ToChecked();
845 846 847 848
    return;
  }

  MaybeLocal<Value> maybe_result;
849 850
  if (root_module->InstantiateModule(realm, ResolveModuleCallback)
          .FromMaybe(false)) {
851 852 853 854 855 856 857
    maybe_result = root_module->Evaluate(realm);
    EmptyMessageQueues(isolate);
  }

  Local<Value> module;
  if (!maybe_result.ToLocal(&module)) {
    DCHECK(try_catch.HasCaught());
858
    resolver->Reject(realm, try_catch.Exception()).ToChecked();
859 860 861 862
    return;
  }

  DCHECK(!try_catch.HasCaught());
863 864
  Local<Value> module_namespace = root_module->GetModuleNamespace();
  resolver->Resolve(realm, module_namespace).ToChecked();
865 866
}

867 868 869
bool Shell::ExecuteModule(Isolate* isolate, const char* file_name) {
  HandleScope handle_scope(isolate);

870 871 872 873
  PerIsolateData* data = PerIsolateData::Get(isolate);
  Local<Context> realm = data->realms_[data->realm_current_].Get(isolate);
  Context::Scope context_scope(realm);

874
  std::string absolute_path = NormalizePath(file_name, GetWorkingDirectory());
875

876 877 878
  TryCatch try_catch(isolate);
  try_catch.SetVerbose(true);

879
  Local<Module> root_module;
880 881
  MaybeLocal<Value> maybe_exception;

882
  if (!FetchModuleTree(realm, absolute_path).ToLocal(&root_module)) {
883 884
    CHECK(try_catch.HasCaught());
    ReportException(isolate, &try_catch);
885 886 887 888
    return false;
  }

  MaybeLocal<Value> maybe_result;
889 890
  if (root_module->InstantiateModule(realm, ResolveModuleCallback)
          .FromMaybe(false)) {
891 892
    maybe_result = root_module->Evaluate(realm);
    EmptyMessageQueues(isolate);
893 894 895 896 897 898 899 900 901 902 903
  }
  Local<Value> result;
  if (!maybe_result.ToLocal(&result)) {
    DCHECK(try_catch.HasCaught());
    // Print errors that happened during execution.
    ReportException(isolate, &try_catch);
    return false;
  }
  DCHECK(!try_catch.HasCaught());
  return true;
}
904

905 906 907 908
PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
  data_->realm_count_ = 1;
  data_->realm_current_ = 0;
  data_->realm_switch_ = 0;
909
  data_->realms_ = new Global<Context>[1];
910 911
  data_->realms_[0].Reset(data_->isolate_,
                          data_->isolate_->GetEnteredContext());
912 913 914 915
}


PerIsolateData::RealmScope::~RealmScope() {
916 917 918 919
  // Drop realms to avoid keeping them alive. We don't dispose the
  // module embedder data for the first realm here, but instead do
  // it in RunShell or in RunMain, if not running in interactive mode
  for (int i = 1; i < data_->realm_count_; ++i) {
920 921 922 923 924 925
    Global<Context>& realm = data_->realms_[i];
    if (realm.IsEmpty()) continue;
    DisposeModuleEmbedderData(realm.Get(data_->isolate_));
    // TODO(adamk): No need to reset manually, Globals reset when destructed.
    realm.Reset();
  }
926
  delete[] data_->realms_;
927
  // TODO(adamk): No need to reset manually, Globals reset when destructed.
928
  if (!data_->realm_shared_.IsEmpty())
929
    data_->realm_shared_.Reset();
930 931 932
}


933
int PerIsolateData::RealmFind(Local<Context> context) {
934 935 936 937 938 939 940
  for (int i = 0; i < realm_count_; ++i) {
    if (realms_[i] == context) return i;
  }
  return -1;
}


941 942 943 944 945 946 947
int PerIsolateData::RealmIndexOrThrow(
    const v8::FunctionCallbackInfo<v8::Value>& args,
    int arg_offset) {
  if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
    Throw(args.GetIsolate(), "Invalid argument");
    return -1;
  }
948 949 950 951
  int index = args[arg_offset]
                  ->Int32Value(args.GetIsolate()->GetCurrentContext())
                  .FromMaybe(-1);
  if (index < 0 || index >= realm_count_ || realms_[index].IsEmpty()) {
952 953 954 955 956 957 958
    Throw(args.GetIsolate(), "Invalid realm index");
    return -1;
  }
  return index;
}


959
// performance.now() returns a time stamp as double, measured in milliseconds.
960 961
// When FLAG_verify_predictable mode is enabled it returns result of
// v8::Platform::MonotonicallyIncreasingTime().
962
void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
963
  if (i::FLAG_verify_predictable) {
964
    args.GetReturnValue().Set(g_platform->MonotonicallyIncreasingTime());
965
  } else {
966 967
    base::TimeDelta delta =
        base::TimeTicks::HighResolutionNow() - kInitialTicks;
968 969
    args.GetReturnValue().Set(delta.InMillisecondsF());
  }
970 971 972
}


973
// Realm.current() returns the index of the currently active realm.
974
void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
975 976
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
977
  int index = data->RealmFind(isolate->GetEnteredContext());
978 979
  if (index == -1) return;
  args.GetReturnValue().Set(index);
980 981 982 983
}


// Realm.owner(o) returns the index of the realm that created o.
984
void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
985 986 987
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
  if (args.Length() < 1 || !args[0]->IsObject()) {
988
    Throw(args.GetIsolate(), "Invalid argument");
989
    return;
990
  }
991 992 993 994
  int index = data->RealmFind(args[0]
                                  ->ToObject(isolate->GetCurrentContext())
                                  .ToLocalChecked()
                                  ->CreationContext());
995 996
  if (index == -1) return;
  args.GetReturnValue().Set(index);
997 998 999 1000 1001
}


// Realm.global(i) returns the global object of realm i.
// (Note that properties of global objects cannot be read/written cross-realm.)
1002
void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
1003
  PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
1004 1005
  int index = data->RealmIndexOrThrow(args, 0);
  if (index == -1) return;
1006 1007
  args.GetReturnValue().Set(
      Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
1008 1009
}

1010
MaybeLocal<Context> Shell::CreateRealm(
1011 1012
    const v8::FunctionCallbackInfo<v8::Value>& args, int index,
    v8::MaybeLocal<Value> global_object) {
1013
  Isolate* isolate = args.GetIsolate();
1014
  TryCatch try_catch(isolate);
1015
  PerIsolateData* data = PerIsolateData::Get(isolate);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  if (index < 0) {
    Global<Context>* old_realms = data->realms_;
    index = data->realm_count_;
    data->realms_ = new Global<Context>[++data->realm_count_];
    for (int i = 0; i < index; ++i) {
      data->realms_[i].Reset(isolate, old_realms[i]);
      old_realms[i].Reset();
    }
    delete[] old_realms;
  }
1026
  Local<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
1027 1028
  Local<Context> context =
      Context::New(isolate, NULL, global_template, global_object);
1029 1030
  DCHECK(!try_catch.HasCaught());
  if (context.IsEmpty()) return MaybeLocal<Context>();
1031
  InitializeModuleEmbedderData(context);
1032
  data->realms_[index].Reset(isolate, context);
1033
  args.GetReturnValue().Set(index);
1034
  return context;
1035 1036
}

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
void Shell::DisposeRealm(const v8::FunctionCallbackInfo<v8::Value>& args,
                         int index) {
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
  DisposeModuleEmbedderData(data->realms_[index].Get(isolate));
  data->realms_[index].Reset();
  isolate->ContextDisposedNotification();
  isolate->IdleNotificationDeadline(g_platform->MonotonicallyIncreasingTime());
}

1047 1048 1049
// Realm.create() creates a new realm with a distinct security token
// and returns its index.
void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
1050
  CreateRealm(args, -1, v8::MaybeLocal<Value>());
1051 1052 1053 1054 1055 1056 1057
}

// Realm.createAllowCrossRealmAccess() creates a new realm with the same
// security token as the current realm.
void Shell::RealmCreateAllowCrossRealmAccess(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  Local<Context> context;
1058
  if (CreateRealm(args, -1, v8::MaybeLocal<Value>()).ToLocal(&context)) {
1059 1060 1061 1062
    context->SetSecurityToken(
        args.GetIsolate()->GetEnteredContext()->GetSecurityToken());
  }
}
1063

1064 1065 1066 1067 1068 1069 1070
// Realm.navigate(i) creates a new realm with a distinct security token
// in place of realm i.
void Shell::RealmNavigate(const v8::FunctionCallbackInfo<v8::Value>& args) {
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
  int index = data->RealmIndexOrThrow(args, 0);
  if (index == -1) return;
1071 1072 1073 1074 1075
  if (index == 0 || index == data->realm_current_ ||
      index == data->realm_switch_) {
    Throw(args.GetIsolate(), "Invalid realm index");
    return;
  }
1076 1077 1078 1079 1080 1081 1082

  Local<Context> context = Local<Context>::New(isolate, data->realms_[index]);
  v8::MaybeLocal<Value> global_object = context->Global();
  DisposeRealm(args, index);
  CreateRealm(args, index, global_object);
}

1083
// Realm.dispose(i) disposes the reference to the realm i.
1084
void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
1085 1086
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
1087 1088 1089
  int index = data->RealmIndexOrThrow(args, 0);
  if (index == -1) return;
  if (index == 0 ||
1090
      index == data->realm_current_ || index == data->realm_switch_) {
1091
    Throw(args.GetIsolate(), "Invalid realm index");
1092
    return;
1093
  }
1094
  DisposeRealm(args, index);
1095 1096 1097 1098
}


// Realm.switch(i) switches to the realm i for consecutive interactive inputs.
1099
void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
1100 1101
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
1102 1103
  int index = data->RealmIndexOrThrow(args, 0);
  if (index == -1) return;
1104 1105 1106 1107 1108
  data->realm_switch_ = index;
}


// Realm.eval(i, s) evaluates s in realm i and returns the result.
1109
void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
1110 1111
  Isolate* isolate = args.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
1112 1113 1114
  int index = data->RealmIndexOrThrow(args, 0);
  if (index == -1) return;
  if (args.Length() < 2 || !args[1]->IsString()) {
1115
    Throw(args.GetIsolate(), "Invalid argument");
1116
    return;
1117
  }
1118 1119 1120 1121 1122 1123 1124
  ScriptCompiler::Source script_source(
      args[1]->ToString(isolate->GetCurrentContext()).ToLocalChecked());
  Local<UnboundScript> script;
  if (!ScriptCompiler::CompileUnboundScript(isolate, &script_source)
           .ToLocal(&script)) {
    return;
  }
1125
  Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
1126
  realm->Enter();
1127 1128
  int previous_index = data->realm_current_;
  data->realm_current_ = data->realm_switch_ = index;
1129 1130 1131
  Local<Value> result;
  if (!script->BindToCurrentContext()->Run(realm).ToLocal(&result)) {
    realm->Exit();
1132
    data->realm_current_ = data->realm_switch_ = previous_index;
1133 1134
    return;
  }
1135
  realm->Exit();
1136
  data->realm_current_ = data->realm_switch_ = previous_index;
1137
  args.GetReturnValue().Set(result);
1138 1139 1140 1141
}


// Realm.shared is an accessor for a single shared value across realms.
1142 1143
void Shell::RealmSharedGet(Local<String> property,
                           const PropertyCallbackInfo<Value>& info) {
1144 1145
  Isolate* isolate = info.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
1146 1147
  if (data->realm_shared_.IsEmpty()) return;
  info.GetReturnValue().Set(data->realm_shared_);
1148 1149 1150 1151
}

void Shell::RealmSharedSet(Local<String> property,
                           Local<Value> value,
1152
                           const PropertyCallbackInfo<void>& info) {
1153 1154
  Isolate* isolate = info.GetIsolate();
  PerIsolateData* data = PerIsolateData::Get(isolate);
1155
  data->realm_shared_.Reset(isolate, value);
1156 1157
}

1158
void WriteToFile(FILE* file, const v8::FunctionCallbackInfo<v8::Value>& args) {
1159
  for (int i = 0; i < args.Length(); i++) {
1160
    HandleScope handle_scope(args.GetIsolate());
1161
    if (i != 0) {
1162
      fprintf(file, " ");
1163
    }
1164 1165

    // Explicitly catch potential exceptions in toString().
1166
    v8::TryCatch try_catch(args.GetIsolate());
1167
    Local<Value> arg = args[i];
1168
    Local<String> str_obj;
1169 1170 1171 1172 1173

    if (arg->IsSymbol()) {
      arg = Local<Symbol>::Cast(arg)->Name();
    }
    if (!arg->ToString(args.GetIsolate()->GetCurrentContext())
1174
             .ToLocal(&str_obj)) {
1175 1176 1177
      try_catch.ReThrow();
      return;
    }
1178 1179

    v8::String::Utf8Value str(str_obj);
1180
    int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), file));
1181 1182
    if (n != str.length()) {
      printf("Error in fwrite\n");
1183
      Shell::Exit(1);
1184
    }
1185 1186 1187
  }
}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
void WriteAndFlush(FILE* file,
                   const v8::FunctionCallbackInfo<v8::Value>& args) {
  WriteToFile(file, args);
  fprintf(file, "\n");
  fflush(file);
}

void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
  WriteAndFlush(stdout, args);
}

void Shell::PrintErr(const v8::FunctionCallbackInfo<v8::Value>& args) {
  WriteAndFlush(stderr, args);
}

void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
  WriteToFile(stdout, args);
}
1206

1207
void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
1208 1209
  String::Utf8Value file(args[0]);
  if (*file == NULL) {
1210
    Throw(args.GetIsolate(), "Error loading file");
1211
    return;
1212
  }
1213 1214 1215 1216 1217 1218 1219
  if (args.Length() == 2) {
    String::Utf8Value format(args[1]);
    if (*format && std::strcmp(*format, "binary") == 0) {
      ReadBuffer(args);
      return;
    }
  }
1220
  Local<String> source = ReadFile(args.GetIsolate(), *file);
1221
  if (source.IsEmpty()) {
1222
    Throw(args.GetIsolate(), "Error loading file");
1223
    return;
1224
  }
1225
  args.GetReturnValue().Set(source);
1226 1227 1228
}


1229
Local<String> Shell::ReadFromStdin(Isolate* isolate) {
1230 1231
  static const int kBufferSize = 256;
  char buffer[kBufferSize];
1232 1233
  Local<String> accumulator =
      String::NewFromUtf8(isolate, "", NewStringType::kNormal).ToLocalChecked();
1234
  int length;
1235 1236 1237 1238
  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.
1239
    char* input = NULL;
1240
    input = fgets(buffer, kBufferSize, stdin);
1241
    if (input == NULL) return Local<String>();
1242
    length = static_cast<int>(strlen(buffer));
1243 1244 1245
    if (length == 0) {
      return accumulator;
    } else if (buffer[length-1] != '\n') {
1246 1247
      accumulator = String::Concat(
          accumulator,
1248 1249
          String::NewFromUtf8(isolate, buffer, NewStringType::kNormal, length)
              .ToLocalChecked());
1250 1251
    } else if (length > 1 && buffer[length-2] == '\\') {
      buffer[length-2] = '\n';
1252
      accumulator = String::Concat(
1253 1254 1255
          accumulator,
          String::NewFromUtf8(isolate, buffer, NewStringType::kNormal,
                              length - 1).ToLocalChecked());
1256
    } else {
1257
      return String::Concat(
1258 1259 1260
          accumulator,
          String::NewFromUtf8(isolate, buffer, NewStringType::kNormal,
                              length - 1).ToLocalChecked());
1261 1262
    }
  }
1263 1264 1265
}


1266
void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
1267
  for (int i = 0; i < args.Length(); i++) {
1268
    HandleScope handle_scope(args.GetIsolate());
1269
    String::Utf8Value file(args[i]);
1270
    if (*file == NULL) {
1271
      Throw(args.GetIsolate(), "Error loading file");
1272
      return;
1273
    }
1274
    Local<String> source = ReadFile(args.GetIsolate(), *file);
1275
    if (source.IsEmpty()) {
1276
      Throw(args.GetIsolate(), "Error loading file");
1277
      return;
1278
    }
1279 1280 1281 1282 1283
    if (!ExecuteString(
            args.GetIsolate(), source,
            String::NewFromUtf8(args.GetIsolate(), *file,
                                NewStringType::kNormal).ToLocalChecked(),
            false, true)) {
1284
      Throw(args.GetIsolate(), "Error executing file");
1285
      return;
1286 1287 1288 1289
    }
  }
}

1290

1291 1292 1293
void Shell::WorkerNew(const v8::FunctionCallbackInfo<v8::Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);
1294 1295
  if (args.Length() < 1 || !args[0]->IsString()) {
    Throw(args.GetIsolate(), "1st argument must be string");
1296 1297 1298
    return;
  }

1299 1300 1301 1302 1303
  if (!args.IsConstructCall()) {
    Throw(args.GetIsolate(), "Worker must be constructed with new");
    return;
  }

1304
  {
1305
    base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
1306 1307 1308 1309 1310
    if (workers_.length() >= kMaxWorkers) {
      Throw(args.GetIsolate(), "Too many workers, I won't let you create more");
      return;
    }

1311
    // Initialize the embedder field to NULL; if we return early without
1312 1313 1314 1315
    // creating a new Worker (because the main thread is terminating) we can
    // early-out from the instance calls.
    args.Holder()->SetAlignedPointerInInternalField(0, NULL);

1316 1317 1318
    if (!allow_new_workers_) return;

    Worker* worker = new Worker;
1319
    args.Holder()->SetAlignedPointerInInternalField(0, worker);
1320
    workers_.Add(worker);
1321

1322 1323 1324
    String::Utf8Value script(args[0]);
    if (!*script) {
      Throw(args.GetIsolate(), "Can't get worker script");
1325 1326
      return;
    }
1327
    worker->StartExecuteInThread(*script);
1328
  }
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
}


void Shell::WorkerPostMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);

  if (args.Length() < 1) {
    Throw(isolate, "Invalid argument");
    return;
  }

1341 1342
  Worker* worker = GetWorkerFromInternalField(isolate, args.Holder());
  if (!worker) {
1343 1344 1345
    return;
  }

1346
  Local<Value> message = args[0];
1347 1348 1349 1350 1351 1352
  Local<Value> transfer =
      args.Length() >= 2 ? args[1] : Local<Value>::Cast(Undefined(isolate));
  std::unique_ptr<SerializationData> data =
      Shell::SerializeValue(isolate, message, transfer);
  if (data) {
    worker->PostMessage(std::move(data));
1353 1354 1355 1356 1357 1358 1359
  }
}


void Shell::WorkerGetMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);
1360 1361
  Worker* worker = GetWorkerFromInternalField(isolate, args.Holder());
  if (!worker) {
1362 1363 1364
    return;
  }

1365
  std::unique_ptr<SerializationData> data = worker->GetMessage();
1366
  if (data) {
1367 1368 1369
    Local<Value> value;
    if (Shell::DeserializeValue(isolate, std::move(data)).ToLocal(&value)) {
      args.GetReturnValue().Set(value);
1370 1371 1372 1373 1374 1375 1376 1377
    }
  }
}


void Shell::WorkerTerminate(const v8::FunctionCallbackInfo<v8::Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);
1378 1379
  Worker* worker = GetWorkerFromInternalField(isolate, args.Holder());
  if (!worker) {
1380 1381 1382 1383 1384 1385 1386
    return;
  }

  worker->Terminate();
}


1387
void Shell::QuitOnce(v8::FunctionCallbackInfo<v8::Value>* args) {
1388 1389 1390
  int exit_code = (*args)[0]
                      ->Int32Value(args->GetIsolate()->GetCurrentContext())
                      .FromMaybe(0);
1391
  CleanupWorkers();
1392
  args->GetIsolate()->Exit();
1393
  OnExit(args->GetIsolate());
1394
  Exit(exit_code);
1395 1396 1397
}


1398 1399 1400 1401 1402
void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
  base::CallOnce(&quit_once_, &QuitOnce,
                 const_cast<v8::FunctionCallbackInfo<v8::Value>*>(&args));
}

1403 1404 1405 1406 1407 1408 1409
void Shell::WaitUntilDone(const v8::FunctionCallbackInfo<v8::Value>& args) {
  SetWaitUntilDone(args.GetIsolate(), true);
}

void Shell::NotifyDone(const v8::FunctionCallbackInfo<v8::Value>& args) {
  SetWaitUntilDone(args.GetIsolate(), false);
}
1410

1411
void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
1412
  args.GetReturnValue().Set(
1413 1414
      String::NewFromUtf8(args.GetIsolate(), V8::GetVersion(),
                          NewStringType::kNormal).ToLocalChecked());
1415 1416 1417
}


1418 1419
void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
  HandleScope handle_scope(isolate);
1420 1421
  Local<Context> context = isolate->GetCurrentContext();
  bool enter_context = context.IsEmpty();
1422
  if (enter_context) {
yangguo's avatar
yangguo committed
1423 1424
    context = Local<Context>::New(isolate, evaluation_context_);
    context->Enter();
1425
  }
1426 1427 1428 1429 1430
  // Converts a V8 value to a C string.
  auto ToCString = [](const v8::String::Utf8Value& value) {
    return *value ? *value : "<string conversion failed>";
  };

1431 1432
  v8::String::Utf8Value exception(try_catch->Exception());
  const char* exception_string = ToCString(exception);
1433
  Local<Message> message = try_catch->Message();
1434 1435 1436
  if (message.IsEmpty()) {
    // V8 didn't provide any extra information about this error; just
    // print the exception.
1437
    printf("%s\n", exception_string);
1438
  } else if (message->GetScriptOrigin().Options().IsWasm()) {
1439
    // Print wasm-function[(function index)]:(offset): (message).
1440 1441
    int function_index = message->GetLineNumber(context).FromJust() - 1;
    int offset = message->GetStartColumn(context).FromJust();
1442 1443
    printf("wasm-function[%d]:%d: %s\n", function_index, offset,
           exception_string);
1444 1445
  } else {
    // Print (filename):(line number): (message).
1446
    v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
1447
    const char* filename_string = ToCString(filename);
1448
    int linenum = message->GetLineNumber(context).FromMaybe(-1);
1449
    printf("%s:%i: %s\n", filename_string, linenum, exception_string);
1450
    Local<String> sourceline;
1451
    if (message->GetSourceLine(context).ToLocal(&sourceline)) {
1452
      // Print line of source code.
1453 1454
      v8::String::Utf8Value sourcelinevalue(sourceline);
      const char* sourceline_string = ToCString(sourcelinevalue);
1455 1456
      printf("%s\n", sourceline_string);
      // Print wavy underline (GetUnderline is deprecated).
1457
      int start = message->GetStartColumn(context).FromJust();
1458 1459 1460
      for (int i = 0; i < start; i++) {
        printf(" ");
      }
1461
      int end = message->GetEndColumn(context).FromJust();
1462 1463 1464 1465
      for (int i = start; i < end; i++) {
        printf("^");
      }
      printf("\n");
1466
    }
1467 1468 1469 1470 1471 1472
  }
  Local<Value> stack_trace_string;
  if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
      stack_trace_string->IsString()) {
    v8::String::Utf8Value stack_trace(Local<String>::Cast(stack_trace_string));
    printf("%s\n", ToCString(stack_trace));
1473
  }
1474
  printf("\n");
yangguo's avatar
yangguo committed
1475
  if (enter_context) context->Exit();
1476 1477 1478
}


1479
int32_t* Counter::Bind(const char* name, bool is_histogram) {
1480 1481 1482 1483
  int i;
  for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
    name_[i] = static_cast<char>(name[i]);
  name_[i] = '\0';
1484 1485 1486 1487 1488 1489 1490 1491
  is_histogram_ = is_histogram;
  return ptr();
}


void Counter::AddSample(int32_t sample) {
  count_++;
  sample_total_ += sample;
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
}


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_++];
}


1509
void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
1510
  counters_file_ = base::OS::MemoryMappedFile::create(
1511
      name, sizeof(CounterCollection), &local_counters_);
1512 1513 1514 1515
  void* memory = (counters_file_ == NULL) ?
      NULL : counters_file_->memory();
  if (memory == NULL) {
    printf("Could not map counters file %s\n", name);
1516
    Exit(1);
1517 1518
  }
  counters_ = static_cast<CounterCollection*>(memory);
1519 1520 1521
  isolate->SetCounterFunction(LookupCounter);
  isolate->SetCreateHistogramFunction(CreateHistogram);
  isolate->SetAddHistogramSampleFunction(AddHistogramSample);
1522 1523 1524
}


1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
int CounterMap::Hash(const char* name) {
  int h = 0;
  int c;
  while ((c = *name++) != 0) {
    h += h << 5;
    h += c;
  }
  return h;
}


1536
Counter* Shell::GetCounter(const char* name, bool is_histogram) {
1537
  Counter* counter = counter_map_->Lookup(name);
1538 1539 1540 1541 1542 1543 1544 1545

  if (counter == NULL) {
    counter = counters_->GetNextCounter();
    if (counter != NULL) {
      counter_map_->Set(name, counter);
      counter->Bind(name, is_histogram);
    }
  } else {
1546
    DCHECK(counter->is_histogram() == is_histogram);
1547 1548 1549 1550 1551 1552 1553 1554
  }
  return counter;
}


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

1555 1556
  if (counter != NULL) {
    return counter->ptr();
1557 1558
  } else {
    return NULL;
1559
  }
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
}


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);
1574 1575
}

yangguo's avatar
yangguo committed
1576 1577 1578
// Turn a value into a human-readable string.
Local<String> Shell::Stringify(Isolate* isolate, Local<Value> value) {
  v8::Local<v8::Context> context =
1579
      v8::Local<v8::Context>::New(isolate, evaluation_context_);
yangguo's avatar
yangguo committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
  if (stringify_function_.IsEmpty()) {
    int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
    i::Vector<const char> source_string =
        i::NativesCollection<i::D8>::GetScriptSource(source_index);
    i::Vector<const char> source_name =
        i::NativesCollection<i::D8>::GetScriptName(source_index);
    Local<String> source =
        String::NewFromUtf8(isolate, source_string.start(),
                            NewStringType::kNormal, source_string.length())
            .ToLocalChecked();
    Local<String> name =
        String::NewFromUtf8(isolate, source_name.start(),
                            NewStringType::kNormal, source_name.length())
            .ToLocalChecked();
    ScriptOrigin origin(name);
    Local<Script> script =
        Script::Compile(context, source, &origin).ToLocalChecked();
    stringify_function_.Reset(
        isolate, script->Run(context).ToLocalChecked().As<Function>());
  }
  Local<Function> fun = Local<Function>::New(isolate, stringify_function_);
  Local<Value> argv[1] = {value};
  v8::TryCatch try_catch(isolate);
1603
  MaybeLocal<Value> result = fun->Call(context, Undefined(isolate), 1, argv);
yangguo's avatar
yangguo committed
1604 1605
  if (result.IsEmpty()) return String::Empty(isolate);
  return result.ToLocalChecked().As<String>();
1606
}
1607

1608

1609 1610 1611 1612 1613 1614
Local<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
  Local<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
  global_template->Set(
      String::NewFromUtf8(isolate, "print", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, Print));
1615 1616 1617 1618
  global_template->Set(
      String::NewFromUtf8(isolate, "printErr", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, PrintErr));
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
  global_template->Set(
      String::NewFromUtf8(isolate, "write", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, Write));
  global_template->Set(
      String::NewFromUtf8(isolate, "read", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, Read));
  global_template->Set(
      String::NewFromUtf8(isolate, "readbuffer", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, ReadBuffer));
  global_template->Set(
      String::NewFromUtf8(isolate, "readline", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, ReadLine));
  global_template->Set(
      String::NewFromUtf8(isolate, "load", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, Load));
1639 1640 1641 1642
  // Some Emscripten-generated code tries to call 'quit', which in turn would
  // call C's exit(). This would lead to memory leaks, because there is no way
  // we can terminate cleanly then, so we need a way to hide 'quit'.
  if (!options.omit_quit) {
1643 1644 1645 1646
    global_template->Set(
        String::NewFromUtf8(isolate, "quit", NewStringType::kNormal)
            .ToLocalChecked(),
        FunctionTemplate::New(isolate, Quit));
1647
  }
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
  Local<ObjectTemplate> test_template = ObjectTemplate::New(isolate);
  global_template->Set(
      String::NewFromUtf8(isolate, "testRunner", NewStringType::kNormal)
          .ToLocalChecked(),
      test_template);
  test_template->Set(
      String::NewFromUtf8(isolate, "notifyDone", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, NotifyDone));
  test_template->Set(
      String::NewFromUtf8(isolate, "waitUntilDone", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, WaitUntilDone));
1661 1662 1663 1664
  global_template->Set(
      String::NewFromUtf8(isolate, "version", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, Version));
1665 1666 1667 1668
  global_template->Set(
      Symbol::GetToStringTag(isolate),
      String::NewFromUtf8(isolate, "global", NewStringType::kNormal)
          .ToLocalChecked());
1669

1670
  // Bind the Realm object.
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
  Local<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
  realm_template->Set(
      String::NewFromUtf8(isolate, "current", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmCurrent));
  realm_template->Set(
      String::NewFromUtf8(isolate, "owner", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmOwner));
  realm_template->Set(
      String::NewFromUtf8(isolate, "global", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmGlobal));
  realm_template->Set(
      String::NewFromUtf8(isolate, "create", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmCreate));
1688 1689 1690 1691 1692
  realm_template->Set(
      String::NewFromUtf8(isolate, "createAllowCrossRealmAccess",
                          NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmCreateAllowCrossRealmAccess));
1693 1694 1695 1696
  realm_template->Set(
      String::NewFromUtf8(isolate, "navigate", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmNavigate));
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
  realm_template->Set(
      String::NewFromUtf8(isolate, "dispose", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmDispose));
  realm_template->Set(
      String::NewFromUtf8(isolate, "switch", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmSwitch));
  realm_template->Set(
      String::NewFromUtf8(isolate, "eval", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, RealmEval));
  realm_template->SetAccessor(
      String::NewFromUtf8(isolate, "shared", NewStringType::kNormal)
          .ToLocalChecked(),
      RealmSharedGet, RealmSharedSet);
  global_template->Set(
      String::NewFromUtf8(isolate, "Realm", NewStringType::kNormal)
          .ToLocalChecked(),
      realm_template);
1717

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
  Local<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
  performance_template->Set(
      String::NewFromUtf8(isolate, "now", NewStringType::kNormal)
          .ToLocalChecked(),
      FunctionTemplate::New(isolate, PerformanceNow));
  global_template->Set(
      String::NewFromUtf8(isolate, "performance", NewStringType::kNormal)
          .ToLocalChecked(),
      performance_template);

  Local<FunctionTemplate> worker_fun_template =
1729
      FunctionTemplate::New(isolate, WorkerNew);
1730 1731 1732 1733 1734
  Local<Signature> worker_signature =
      Signature::New(isolate, worker_fun_template);
  worker_fun_template->SetClassName(
      String::NewFromUtf8(isolate, "Worker", NewStringType::kNormal)
          .ToLocalChecked());
1735
  worker_fun_template->ReadOnlyPrototype();
1736
  worker_fun_template->PrototypeTemplate()->Set(
1737 1738
      String::NewFromUtf8(isolate, "terminate", NewStringType::kNormal)
          .ToLocalChecked(),
1739 1740
      FunctionTemplate::New(isolate, WorkerTerminate, Local<Value>(),
                            worker_signature));
1741
  worker_fun_template->PrototypeTemplate()->Set(
1742 1743
      String::NewFromUtf8(isolate, "postMessage", NewStringType::kNormal)
          .ToLocalChecked(),
1744 1745
      FunctionTemplate::New(isolate, WorkerPostMessage, Local<Value>(),
                            worker_signature));
1746
  worker_fun_template->PrototypeTemplate()->Set(
1747 1748
      String::NewFromUtf8(isolate, "getMessage", NewStringType::kNormal)
          .ToLocalChecked(),
1749 1750
      FunctionTemplate::New(isolate, WorkerGetMessage, Local<Value>(),
                            worker_signature));
1751
  worker_fun_template->InstanceTemplate()->SetInternalFieldCount(1);
1752 1753 1754 1755
  global_template->Set(
      String::NewFromUtf8(isolate, "Worker", NewStringType::kNormal)
          .ToLocalChecked(),
      worker_fun_template);
1756

1757
  Local<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
1758
  AddOSMethods(isolate, os_templ);
1759 1760 1761 1762
  global_template->Set(
      String::NewFromUtf8(isolate, "os", NewStringType::kNormal)
          .ToLocalChecked(),
      os_templ);
1763

1764 1765 1766
  return global_template;
}

1767 1768 1769 1770
static void PrintNonErrorsMessageCallback(Local<Message> message,
                                          Local<Value> error) {
  // Nothing to do here for errors, exceptions thrown up to the shell will be
  // reported
1771
  // separately by {Shell::ReportException} after they are caught.
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
  // Do print other kinds of messages.
  switch (message->ErrorLevel()) {
    case v8::Isolate::kMessageWarning:
    case v8::Isolate::kMessageLog:
    case v8::Isolate::kMessageInfo:
    case v8::Isolate::kMessageDebug: {
      break;
    }

    case v8::Isolate::kMessageError: {
      // Ignore errors, printed elsewhere.
      return;
    }

    default: {
      UNREACHABLE();
      break;
    }
  }
  // Converts a V8 value to a C string.
  auto ToCString = [](const v8::String::Utf8Value& value) {
    return *value ? *value : "<string conversion failed>";
  };
  Isolate* isolate = Isolate::GetCurrent();
  v8::String::Utf8Value msg(message->Get());
  const char* msg_string = ToCString(msg);
  // Print (filename):(line number): (message).
  v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
  const char* filename_string = ToCString(filename);
  Maybe<int> maybeline = message->GetLineNumber(isolate->GetCurrentContext());
  int linenum = maybeline.IsJust() ? maybeline.FromJust() : -1;
  printf("%s:%i: %s\n", filename_string, linenum, msg_string);
1804
}
1805

1806
void Shell::Initialize(Isolate* isolate) {
1807 1808
  // Set up counters
  if (i::StrLength(i::FLAG_map_counters) != 0)
1809
    MapCounters(isolate, i::FLAG_map_counters);
1810
  // Disable default message reporting.
1811 1812 1813 1814 1815
  isolate->AddMessageListenerWithErrorLevel(
      PrintNonErrorsMessageCallback,
      v8::Isolate::kMessageError | v8::Isolate::kMessageWarning |
          v8::Isolate::kMessageInfo | v8::Isolate::kMessageDebug |
          v8::Isolate::kMessageLog);
1816 1817
}

1818

1819
Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
1820
  // This needs to be a critical section since this is not thread-safe
1821
  base::LockGuard<base::Mutex> lock_guard(context_mutex_.Pointer());
1822
  // Initialize the global objects
1823
  Local<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
1824
  EscapableHandleScope handle_scope(isolate);
1825
  Local<Context> context = Context::New(isolate, NULL, global_template);
1826
  DCHECK(!context.IsEmpty());
1827
  InitializeModuleEmbedderData(context);
1828
  Context::Scope scope(context);
1829

1830
  i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
1831 1832
  i::JSArguments js_args = i::FLAG_js_arguments;
  i::Handle<i::FixedArray> arguments_array =
1833 1834
      factory->NewFixedArray(js_args.argc);
  for (int j = 0; j < js_args.argc; j++) {
1835
    i::Handle<i::String> arg =
1836
        factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
1837 1838 1839
    arguments_array->set(j, *arg);
  }
  i::Handle<i::JSArray> arguments_jsarray =
1840
      factory->NewJSArrayWithElements(arguments_array);
1841 1842 1843 1844 1845 1846
  context->Global()
      ->Set(context,
            String::NewFromUtf8(isolate, "arguments", NewStringType::kNormal)
                .ToLocalChecked(),
            Utils::ToLocal(arguments_jsarray))
      .FromJust();
1847
  return handle_scope.Escape(context);
1848 1849
}

1850 1851 1852 1853 1854 1855
struct CounterAndKey {
  Counter* counter;
  const char* key;
};


1856 1857
inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
  return strcmp(lhs.key, rhs.key) < 0;
1858
}
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873

void Shell::WriteIgnitionDispatchCountersFile(v8::Isolate* isolate) {
  HandleScope handle_scope(isolate);
  Local<Context> context = Context::New(isolate);
  Context::Scope context_scope(context);

  Local<Object> dispatch_counters = reinterpret_cast<i::Isolate*>(isolate)
                                        ->interpreter()
                                        ->GetDispatchCountersObject();
  std::ofstream dispatch_counters_stream(
      i::FLAG_trace_ignition_dispatches_output_file);
  dispatch_counters_stream << *String::Utf8Value(
      JSON::Stringify(context, dispatch_counters).ToLocalChecked());
}

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
namespace {
int LineFromOffset(Local<debug::Script> script, int offset) {
  debug::Location location = script->GetSourceLocation(offset);
  return location.GetLineNumber();
}

void WriteLcovDataForRange(std::vector<uint32_t>& lines, int start_line,
                           int end_line, uint32_t count) {
  // Ensure space in the array.
  lines.resize(std::max(static_cast<size_t>(end_line + 1), lines.size()), 0);
  // Boundary lines could be shared between two functions with different
  // invocation counts. Take the maximum.
  lines[start_line] = std::max(lines[start_line], count);
  lines[end_line] = std::max(lines[end_line], count);
  // Invocation counts for non-boundary lines are overwritten.
  for (int k = start_line + 1; k < end_line; k++) lines[k] = count;
}

void WriteLcovDataForNamedRange(std::ostream& sink,
                                std::vector<uint32_t>& lines, std::string name,
                                int start_line, int end_line, uint32_t count) {
  WriteLcovDataForRange(lines, start_line, end_line, count);
  sink << "FN:" << start_line + 1 << "," << name << std::endl;
  sink << "FNDA:" << count << "," << name << std::endl;
}
}  // namespace

1901 1902 1903 1904
// Write coverage data in LCOV format. See man page for geninfo(1).
void Shell::WriteLcovData(v8::Isolate* isolate, const char* file) {
  if (!file) return;
  HandleScope handle_scope(isolate);
1905
  debug::Coverage coverage = debug::Coverage::CollectPrecise(isolate);
1906
  std::ofstream sink(file, std::ofstream::app);
1907
  for (size_t i = 0; i < coverage.ScriptCount(); i++) {
1908 1909
    debug::Coverage::ScriptData script_data = coverage.GetScriptData(i);
    Local<debug::Script> script = script_data.GetScript();
1910
    // Skip unnamed scripts.
1911 1912 1913
    Local<String> name;
    if (!script->Name().ToLocal(&name)) continue;
    std::string file_name = ToSTLString(name);
1914 1915 1916 1917 1918
    // Skip scripts not backed by a file.
    if (!std::ifstream(file_name).good()) continue;
    sink << "SF:";
    sink << NormalizePath(file_name, GetWorkingDirectory()) << std::endl;
    std::vector<uint32_t> lines;
1919 1920 1921
    for (size_t j = 0; j < script_data.FunctionCount(); j++) {
      debug::Coverage::FunctionData function_data =
          script_data.GetFunctionData(j);
1922

1923
      // Write function stats.
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
      {
        debug::Location start =
            script->GetSourceLocation(function_data.StartOffset());
        debug::Location end =
            script->GetSourceLocation(function_data.EndOffset());
        int start_line = start.GetLineNumber();
        int end_line = end.GetLineNumber();
        uint32_t count = function_data.Count();

        Local<String> name;
        std::stringstream name_stream;
        if (function_data.Name().ToLocal(&name)) {
          name_stream << ToSTLString(name);
        } else {
          name_stream << "<" << start_line + 1 << "-";
          name_stream << start.GetColumnNumber() << ">";
        }

        WriteLcovDataForNamedRange(sink, lines, name_stream.str(), start_line,
                                   end_line, count);
      }

      // Process inner blocks.
      for (size_t k = 0; k < function_data.BlockCount(); k++) {
        debug::Coverage::BlockData block_data = function_data.GetBlockData(k);
        int start_line = LineFromOffset(script, block_data.StartOffset());
1950
        int end_line = LineFromOffset(script, block_data.EndOffset() - 1);
1951 1952
        uint32_t count = block_data.Count();
        WriteLcovDataForRange(lines, start_line, end_line, count);
1953 1954
      }
    }
1955 1956 1957 1958 1959 1960 1961
    // Write per-line coverage. LCOV uses 1-based line numbers.
    for (size_t i = 0; i < lines.size(); i++) {
      sink << "DA:" << (i + 1) << "," << lines[i] << std::endl;
    }
    sink << "end_of_record" << std::endl;
  }
}
1962

1963
void Shell::OnExit(v8::Isolate* isolate) {
1964 1965 1966 1967 1968 1969 1970 1971
  // Dump basic block profiling data.
  if (i::BasicBlockProfiler* profiler =
          reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) {
    i::OFStream os(stdout);
    os << *profiler;
  }
  isolate->Dispose();

1972
  if (i::FLAG_dump_counters || i::FLAG_dump_counters_nvp) {
1973
    int number_of_counters = 0;
1974
    for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1975 1976 1977 1978 1979 1980 1981 1982
      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();
    }
1983
    std::sort(counters, counters + number_of_counters);
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016

    if (i::FLAG_dump_counters_nvp) {
      // Dump counters as name-value pairs.
      for (j = 0; j < number_of_counters; j++) {
        Counter* counter = counters[j].counter;
        const char* key = counters[j].key;
        if (counter->is_histogram()) {
          printf("\"c:%s\"=%i\n", key, counter->count());
          printf("\"t:%s\"=%i\n", key, counter->sample_total());
        } else {
          printf("\"%s\"=%i\n", key, counter->count());
        }
      }
    } else {
      // Dump counters in formatted boxes.
      printf(
          "+----------------------------------------------------------------+"
          "-------------+\n");
      printf(
          "| Name                                                           |"
          " Value       |\n");
      printf(
          "+----------------------------------------------------------------+"
          "-------------+\n");
      for (j = 0; j < number_of_counters; j++) {
        Counter* counter = counters[j].counter;
        const char* key = counters[j].key;
        if (counter->is_histogram()) {
          printf("| c:%-60s | %11i |\n", key, counter->count());
          printf("| t:%-60s | %11i |\n", key, counter->sample_total());
        } else {
          printf("| %-62s | %11i |\n", key, counter->count());
        }
2017
      }
2018 2019 2020
      printf(
          "+----------------------------------------------------------------+"
          "-------------+\n");
2021
    }
2022
    delete [] counters;
2023
  }
2024

2025 2026
  delete counters_file_;
  delete counter_map_;
2027 2028
}

2029 2030

static FILE* FOpen(const char* path, const char* mode) {
2031
#if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
2032 2033
  FILE* result;
  if (fopen_s(&result, path, mode) == 0) {
2034
    return result;
2035
  } else {
2036
    return NULL;
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
  }
#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
}
2049

2050
static char* ReadChars(const char* name, int* size_out) {
2051
  FILE* file = FOpen(name, "rb");
2052
  if (file == NULL) return NULL;
2053 2054

  fseek(file, 0, SEEK_END);
2055
  size_t size = ftell(file);
2056 2057 2058 2059
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
2060 2061 2062 2063 2064 2065 2066
  for (size_t i = 0; i < size;) {
    i += fread(&chars[i], 1, size - i, file);
    if (ferror(file)) {
      fclose(file);
      delete[] chars;
      return nullptr;
    }
2067 2068
  }
  fclose(file);
2069
  *size_out = static_cast<int>(size);
2070 2071 2072
  return chars;
}

2073 2074 2075

struct DataAndPersistent {
  uint8_t* data;
2076 2077
  int byte_length;
  Global<ArrayBuffer> handle;
2078 2079 2080 2081
};


static void ReadBufferWeakCallback(
2082 2083
    const v8::WeakCallbackInfo<DataAndPersistent>& data) {
  int byte_length = data.GetParameter()->byte_length;
2084
  data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
2085 2086
      -static_cast<intptr_t>(byte_length));

2087 2088 2089
  delete[] data.GetParameter()->data;
  data.GetParameter()->handle.Reset();
  delete data.GetParameter();
2090
}
2091

2092

2093
void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
2094
  DCHECK(sizeof(char) == sizeof(uint8_t));  // NOLINT
2095 2096
  String::Utf8Value filename(args[0]);
  int length;
2097
  Isolate* isolate = args.GetIsolate();
2098
  if (*filename == NULL) {
2099
    Throw(isolate, "Error loading file");
2100
    return;
2101
  }
2102

2103
  DataAndPersistent* data = new DataAndPersistent;
2104
  data->data = reinterpret_cast<uint8_t*>(ReadChars(*filename, &length));
2105 2106
  if (data->data == NULL) {
    delete data;
2107
    Throw(isolate, "Error reading file");
2108
    return;
2109
  }
2110
  data->byte_length = length;
2111
  Local<v8::ArrayBuffer> buffer = ArrayBuffer::New(isolate, data->data, length);
2112
  data->handle.Reset(isolate, buffer);
2113 2114
  data->handle.SetWeak(data, ReadBufferWeakCallback,
                       v8::WeakCallbackType::kParameter);
2115
  data->handle.MarkIndependent();
2116 2117
  isolate->AdjustAmountOfExternalAllocatedMemory(length);

2118
  args.GetReturnValue().Set(buffer);
2119 2120
}

2121
// Reads a file into a v8 string.
2122
Local<String> Shell::ReadFile(Isolate* isolate, const char* name) {
2123
  int size = 0;
2124
  char* chars = ReadChars(name, &size);
2125
  if (chars == NULL) return Local<String>();
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
  Local<String> result;
  if (i::FLAG_use_external_strings && internal::String::IsAscii(chars, size)) {
    String::ExternalOneByteStringResource* resource =
        new ExternalOwningOneByteStringResource(
            std::unique_ptr<const char[]>(chars), size);
    result = String::NewExternalOneByte(isolate, resource).ToLocalChecked();
  } else {
    result = String::NewFromUtf8(isolate, chars, NewStringType::kNormal, size)
                 .ToLocalChecked();
    delete[] chars;
  }
2137 2138 2139 2140
  return result;
}


2141
void Shell::RunShell(Isolate* isolate) {
2142
  HandleScope outer_scope(isolate);
2143 2144 2145
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(isolate, evaluation_context_);
  v8::Context::Scope context_scope(context);
2146
  PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
2147 2148 2149
  Local<String> name =
      String::NewFromUtf8(isolate, "(d8)", NewStringType::kNormal)
          .ToLocalChecked();
2150
  printf("V8 version %s\n", V8::GetVersion());
2151
  while (true) {
2152
    HandleScope inner_scope(isolate);
2153
    printf("d8> ");
2154
    Local<String> input = Shell::ReadFromStdin(isolate);
2155
    if (input.IsEmpty()) break;
2156
    ExecuteString(isolate, input, name, true, true);
2157 2158
  }
  printf("\n");
2159 2160 2161
  // We need to explicitly clean up the module embedder data for
  // the interative shell context.
  DisposeModuleEmbedderData(context);
2162 2163
}

2164 2165 2166 2167 2168 2169 2170 2171 2172
class InspectorFrontend final : public v8_inspector::V8Inspector::Channel {
 public:
  explicit InspectorFrontend(Local<Context> context) {
    isolate_ = context->GetIsolate();
    context_.Reset(isolate_, context);
  }
  virtual ~InspectorFrontend() = default;

 private:
2173 2174 2175 2176 2177 2178 2179 2180
  void sendResponse(
      int callId,
      std::unique_ptr<v8_inspector::StringBuffer> message) override {
    Send(message->string());
  }
  void sendNotification(
      std::unique_ptr<v8_inspector::StringBuffer> message) override {
    Send(message->string());
2181 2182 2183 2184
  }
  void flushProtocolNotifications() override {}

  void Send(const v8_inspector::StringView& string) {
2185
    v8::Isolate::AllowJavascriptExecutionScope allow_script(isolate_);
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    int length = static_cast<int>(string.length());
    DCHECK(length < v8::String::kMaxLength);
    Local<String> message =
        (string.is8Bit()
             ? v8::String::NewFromOneByte(
                   isolate_,
                   reinterpret_cast<const uint8_t*>(string.characters8()),
                   v8::NewStringType::kNormal, length)
             : v8::String::NewFromTwoByte(
                   isolate_,
                   reinterpret_cast<const uint16_t*>(string.characters16()),
                   v8::NewStringType::kNormal, length))
            .ToLocalChecked();
    Local<String> callback_name =
        v8::String::NewFromUtf8(isolate_, "receive", v8::NewStringType::kNormal)
            .ToLocalChecked();
    Local<Context> context = context_.Get(isolate_);
    Local<Value> callback =
        context->Global()->Get(context, callback_name).ToLocalChecked();
    if (callback->IsFunction()) {
      v8::TryCatch try_catch(isolate_);
      Local<Value> args[] = {message};
2208 2209
      USE(Local<Function>::Cast(callback)->Call(context, Undefined(isolate_), 1,
                                                args));
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
#ifdef DEBUG
      if (try_catch.HasCaught()) {
        Local<Object> exception = Local<Object>::Cast(try_catch.Exception());
        Local<String> key = v8::String::NewFromUtf8(isolate_, "message",
                                                    v8::NewStringType::kNormal)
                                .ToLocalChecked();
        Local<String> expected =
            v8::String::NewFromUtf8(isolate_,
                                    "Maximum call stack size exceeded",
                                    v8::NewStringType::kNormal)
                .ToLocalChecked();
2221 2222
        Local<Value> value = exception->Get(context, key).ToLocalChecked();
        CHECK(value->StrictEquals(expected));
2223 2224
      }
#endif
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
    }
  }

  Isolate* isolate_;
  Global<Context> context_;
};

class InspectorClient : public v8_inspector::V8InspectorClient {
 public:
  InspectorClient(Local<Context> context, bool connect) {
    if (!connect) return;
    isolate_ = context->GetIsolate();
    channel_.reset(new InspectorFrontend(context));
    inspector_ = v8_inspector::V8Inspector::create(isolate_, this);
    session_ =
        inspector_->connect(1, channel_.get(), v8_inspector::StringView());
    context->SetAlignedPointerInEmbedderData(kInspectorClientIndex, this);
    inspector_->contextCreated(v8_inspector::V8ContextInfo(
        context, kContextGroupId, v8_inspector::StringView()));

    Local<Value> function =
        FunctionTemplate::New(isolate_, SendInspectorMessage)
            ->GetFunction(context)
            .ToLocalChecked();
    Local<String> function_name =
        String::NewFromUtf8(isolate_, "send", NewStringType::kNormal)
            .ToLocalChecked();
    CHECK(context->Global()->Set(context, function_name, function).FromJust());

2254 2255
    v8::debug::SetLiveEditEnabled(isolate_, true);

2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
    context_.Reset(isolate_, context);
  }

 private:
  static v8_inspector::V8InspectorSession* GetSession(Local<Context> context) {
    InspectorClient* inspector_client = static_cast<InspectorClient*>(
        context->GetAlignedPointerFromEmbedderData(kInspectorClientIndex));
    return inspector_client->session_.get();
  }

  Local<Context> ensureDefaultContextInGroup(int group_id) override {
    DCHECK(isolate_);
    DCHECK_EQ(kContextGroupId, group_id);
    return context_.Get(isolate_);
  }

  static void SendInspectorMessage(
      const v8::FunctionCallbackInfo<v8::Value>& args) {
    Isolate* isolate = args.GetIsolate();
    v8::HandleScope handle_scope(isolate);
    Local<Context> context = isolate->GetCurrentContext();
    args.GetReturnValue().Set(Undefined(isolate));
    Local<String> message = args[0]->ToString(context).ToLocalChecked();
    v8_inspector::V8InspectorSession* session =
        InspectorClient::GetSession(context);
    int length = message->Length();
2282
    std::unique_ptr<uint16_t[]> buffer(new uint16_t[length]);
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
    message->Write(buffer.get(), 0, length);
    v8_inspector::StringView message_view(buffer.get(), length);
    session->dispatchProtocolMessage(message_view);
    args.GetReturnValue().Set(True(isolate));
  }

  static const int kContextGroupId = 1;

  std::unique_ptr<v8_inspector::V8Inspector> inspector_;
  std::unique_ptr<v8_inspector::V8InspectorSession> session_;
  std::unique_ptr<v8_inspector::V8Inspector::Channel> channel_;
  Global<Context> context_;
  Isolate* isolate_;
};
2297

2298 2299 2300 2301 2302 2303
SourceGroup::~SourceGroup() {
  delete thread_;
  thread_ = NULL;
}


2304
void SourceGroup::Execute(Isolate* isolate) {
2305
  bool exception_was_thrown = false;
2306 2307 2308 2309
  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.
2310
      HandleScope handle_scope(isolate);
2311 2312 2313 2314 2315 2316
      Local<String> file_name =
          String::NewFromUtf8(isolate, "unnamed", NewStringType::kNormal)
              .ToLocalChecked();
      Local<String> source =
          String::NewFromUtf8(isolate, argv_[i + 1], NewStringType::kNormal)
              .ToLocalChecked();
2317
      Shell::options.script_executed = true;
2318
      if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
2319 2320
        exception_was_thrown = true;
        break;
2321 2322
      }
      ++i;
2323 2324 2325 2326
      continue;
    } else if (strcmp(arg, "--module") == 0 && i + 1 < end_offset_) {
      // Treat the next file as a module.
      arg = argv_[++i];
2327 2328 2329 2330 2331 2332
      Shell::options.script_executed = true;
      if (!Shell::ExecuteModule(isolate, arg)) {
        exception_was_thrown = true;
        break;
      }
      continue;
2333 2334
    } else if (arg[0] == '-') {
      // Ignore other options. They have been parsed already.
2335 2336 2337 2338 2339
      continue;
    }

    // Use all other arguments as names of files to load and run.
    HandleScope handle_scope(isolate);
2340 2341 2342 2343
    Local<String> file_name =
        String::NewFromUtf8(isolate, arg, NewStringType::kNormal)
            .ToLocalChecked();
    Local<String> source = ReadFile(isolate, arg);
2344 2345 2346 2347
    if (source.IsEmpty()) {
      printf("Error reading '%s'\n", arg);
      Shell::Exit(1);
    }
2348
    Shell::options.script_executed = true;
2349
    if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
2350 2351
      exception_was_thrown = true;
      break;
2352
    }
2353
  }
2354 2355 2356
  if (exception_was_thrown != Shell::options.expected_to_throw) {
    Shell::Exit(1);
  }
2357
}
2358

2359
Local<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
2360
  return Shell::ReadFile(isolate, name);
2361 2362 2363
}


2364
base::Thread::Options SourceGroup::GetThreadOptions() {
2365 2366 2367
  // 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
2368
  // OS-specific padding for thread startup code.  2Mbytes seems to be enough.
2369
  return base::Thread::Options("IsolateThread", 2 * MB);
2370 2371 2372
}

void SourceGroup::ExecuteInThread() {
2373
  Isolate::CreateParams create_params;
2374
  create_params.array_buffer_allocator = Shell::array_buffer_allocator;
2375
  Isolate* isolate = Isolate::New(create_params);
2376 2377
  isolate->SetHostImportModuleDynamicallyCallback(
      Shell::HostImportModuleDynamically);
2378 2379

  Shell::EnsureEventLoopInitialized(isolate);
2380 2381
  D8Console console(isolate);
  debug::SetConsoleDelegate(isolate, &console);
binji's avatar
binji committed
2382
  for (int i = 0; i < Shell::options.stress_runs; ++i) {
2383
    next_semaphore_.Wait();
2384 2385 2386
    {
      Isolate::Scope iscope(isolate);
      {
2387 2388 2389 2390 2391
        HandleScope scope(isolate);
        PerIsolateData data(isolate);
        Local<Context> context = Shell::CreateEvaluationContext(isolate);
        {
          Context::Scope cscope(context);
2392 2393
          InspectorClient inspector_client(context,
                                           Shell::options.enable_inspector);
2394 2395 2396
          PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
          Execute(isolate);
        }
2397
        DisposeModuleEmbedderData(context);
2398
      }
2399
      Shell::CollectGarbage(isolate);
2400
      Shell::CompleteMessageLoop(isolate);
2401
    }
2402
    done_semaphore_.Signal();
binji's avatar
binji committed
2403
  }
2404

2405 2406 2407 2408 2409
  isolate->Dispose();
}


void SourceGroup::StartExecuteInThread() {
2410 2411
  if (thread_ == NULL) {
    thread_ = new IsolateThread(this);
2412
    thread_->Start();
2413
  }
2414
  next_semaphore_.Signal();
2415 2416
}

2417

2418
void SourceGroup::WaitForThread() {
2419
  if (thread_ == NULL) return;
binji's avatar
binji committed
2420 2421 2422 2423 2424 2425 2426
  done_semaphore_.Wait();
}


void SourceGroup::JoinThread() {
  if (thread_ == NULL) return;
  thread_->Join();
2427
}
2428

2429 2430
ExternalizedContents::~ExternalizedContents() {
  Shell::array_buffer_allocator->Free(data_, size_);
2431 2432
}

2433
void SerializationDataQueue::Enqueue(std::unique_ptr<SerializationData> data) {
2434
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2435
  data_.push_back(std::move(data));
2436 2437
}

2438 2439 2440
bool SerializationDataQueue::Dequeue(
    std::unique_ptr<SerializationData>* out_data) {
  out_data->reset();
2441
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2442 2443 2444
  if (data_.empty()) return false;
  *out_data = std::move(data_[0]);
  data_.erase(data_.begin());
2445 2446 2447 2448 2449 2450
  return true;
}


bool SerializationDataQueue::IsEmpty() {
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2451
  return data_.empty();
2452 2453 2454 2455 2456
}


void SerializationDataQueue::Clear() {
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2457
  data_.clear();
2458 2459 2460 2461
}


Worker::Worker()
2462 2463 2464 2465
    : in_semaphore_(0),
      out_semaphore_(0),
      thread_(NULL),
      script_(NULL),
2466
      running_(false) {}
2467 2468


2469 2470 2471 2472 2473 2474 2475 2476
Worker::~Worker() {
  delete thread_;
  thread_ = NULL;
  delete[] script_;
  script_ = NULL;
  in_queue_.Clear();
  out_queue_.Clear();
}
2477 2478


2479 2480 2481 2482 2483
void Worker::StartExecuteInThread(const char* script) {
  running_ = true;
  script_ = i::StrDup(script);
  thread_ = new WorkerThread(this);
  thread_->Start();
2484 2485
}

2486 2487
void Worker::PostMessage(std::unique_ptr<SerializationData> data) {
  in_queue_.Enqueue(std::move(data));
2488 2489 2490
  in_semaphore_.Signal();
}

2491 2492 2493
std::unique_ptr<SerializationData> Worker::GetMessage() {
  std::unique_ptr<SerializationData> result;
  while (!out_queue_.Dequeue(&result)) {
binji's avatar
binji committed
2494 2495
    // If the worker is no longer running, and there are no messages in the
    // queue, don't expect any more messages from it.
2496
    if (!base::Relaxed_Load(&running_)) break;
2497 2498
    out_semaphore_.Wait();
  }
2499
  return result;
2500 2501 2502 2503
}


void Worker::Terminate() {
2504
  base::Relaxed_Store(&running_, false);
2505 2506 2507
  // Post NULL to wake the Worker thread message loop, and tell it to stop
  // running.
  PostMessage(NULL);
binji's avatar
binji committed
2508 2509 2510 2511 2512
}


void Worker::WaitForThread() {
  Terminate();
2513
  thread_->Join();
2514 2515 2516 2517 2518 2519 2520
}


void Worker::ExecuteInThread() {
  Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = Shell::array_buffer_allocator;
  Isolate* isolate = Isolate::New(create_params);
2521 2522
  isolate->SetHostImportModuleDynamicallyCallback(
      Shell::HostImportModuleDynamically);
2523 2524
  D8Console console(isolate);
  debug::SetConsoleDelegate(isolate, &console);
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
  {
    Isolate::Scope iscope(isolate);
    {
      HandleScope scope(isolate);
      PerIsolateData data(isolate);
      Local<Context> context = Shell::CreateEvaluationContext(isolate);
      {
        Context::Scope cscope(context);
        PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));

2535 2536 2537
        Local<Object> global = context->Global();
        Local<Value> this_value = External::New(isolate, this);
        Local<FunctionTemplate> postmessage_fun_template =
2538 2539
            FunctionTemplate::New(isolate, PostMessageOut, this_value);

2540
        Local<Function> postmessage_fun;
2541 2542
        if (postmessage_fun_template->GetFunction(context)
                .ToLocal(&postmessage_fun)) {
2543 2544 2545 2546
          global->Set(context, String::NewFromUtf8(isolate, "postMessage",
                                                   NewStringType::kNormal)
                                   .ToLocalChecked(),
                      postmessage_fun).FromJust();
2547 2548 2549
        }

        // First run the script
2550 2551 2552 2553 2554 2555
        Local<String> file_name =
            String::NewFromUtf8(isolate, "unnamed", NewStringType::kNormal)
                .ToLocalChecked();
        Local<String> source =
            String::NewFromUtf8(isolate, script_, NewStringType::kNormal)
                .ToLocalChecked();
2556
        if (Shell::ExecuteString(isolate, source, file_name, false, true)) {
2557
          // Get the message handler
2558 2559 2560 2561
          Local<Value> onmessage =
              global->Get(context, String::NewFromUtf8(isolate, "onmessage",
                                                       NewStringType::kNormal)
                                       .ToLocalChecked()).ToLocalChecked();
2562
          if (onmessage->IsFunction()) {
2563
            Local<Function> onmessage_fun = Local<Function>::Cast(onmessage);
2564
            // Now wait for messages
binji's avatar
binji committed
2565
            while (true) {
2566
              in_semaphore_.Wait();
2567
              std::unique_ptr<SerializationData> data;
2568
              if (!in_queue_.Dequeue(&data)) continue;
2569
              if (!data) {
2570 2571
                break;
              }
2572 2573 2574 2575 2576
              v8::TryCatch try_catch(isolate);
              Local<Value> value;
              if (Shell::DeserializeValue(isolate, std::move(data))
                      .ToLocal(&value)) {
                Local<Value> argv[] = {value};
2577 2578
                (void)onmessage_fun->Call(context, global, 1, argv);
              }
2579 2580 2581
              if (try_catch.HasCaught()) {
                Shell::ReportException(isolate, &try_catch);
              }
2582 2583 2584 2585
            }
          }
        }
      }
2586
      DisposeModuleEmbedderData(context);
2587
    }
2588
    Shell::CollectGarbage(isolate);
2589 2590
  }
  isolate->Dispose();
2591

binji's avatar
binji committed
2592 2593 2594
  // Post NULL to wake the thread waiting on GetMessage() if there is one.
  out_queue_.Enqueue(NULL);
  out_semaphore_.Signal();
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
}


void Worker::PostMessageOut(const v8::FunctionCallbackInfo<v8::Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);

  if (args.Length() < 1) {
    Throw(isolate, "Invalid argument");
    return;
  }

2607
  Local<Value> message = args[0];
2608 2609 2610 2611
  Local<Value> transfer = Undefined(isolate);
  std::unique_ptr<SerializationData> data =
      Shell::SerializeValue(isolate, message, transfer);
  if (data) {
2612
    DCHECK(args.Data()->IsExternal());
2613
    Local<External> this_value = Local<External>::Cast(args.Data());
2614
    Worker* worker = static_cast<Worker*>(this_value->Value());
2615
    worker->out_queue_.Enqueue(std::move(data));
2616 2617 2618
    worker->out_semaphore_.Signal();
  }
}
2619 2620


2621
void SetFlagsFromString(const char* flags) {
2622
  v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags)));
2623 2624 2625
}


2626
bool Shell::SetOptions(int argc, char* argv[]) {
2627
  bool logfile_per_isolate = false;
2628 2629
  for (int i = 0; i < argc; i++) {
    if (strcmp(argv[i], "--stress-opt") == 0) {
2630
      options.stress_opt = true;
2631
      argv[i] = NULL;
2632 2633
    } else if (strcmp(argv[i], "--nostress-opt") == 0 ||
               strcmp(argv[i], "--no-stress-opt") == 0) {
2634 2635
      options.stress_opt = false;
      argv[i] = NULL;
2636
    } else if (strcmp(argv[i], "--stress-deopt") == 0) {
2637
      options.stress_deopt = true;
2638
      argv[i] = NULL;
2639 2640 2641
    } else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) {
      options.mock_arraybuffer_allocator = true;
      argv[i] = NULL;
2642 2643
    } else if (strcmp(argv[i], "--noalways-opt") == 0 ||
               strcmp(argv[i], "--no-always-opt") == 0) {
2644
      // No support for stressing if we can't use --always-opt.
2645 2646
      options.stress_opt = false;
      options.stress_deopt = false;
2647 2648 2649
    } else if (strcmp(argv[i], "--logfile-per-isolate") == 0) {
      logfile_per_isolate = true;
      argv[i] = NULL;
2650
    } else if (strcmp(argv[i], "--shell") == 0) {
2651
      options.interactive_shell = true;
2652 2653
      argv[i] = NULL;
    } else if (strcmp(argv[i], "--test") == 0) {
2654 2655
      options.test_shell = true;
      argv[i] = NULL;
2656 2657 2658 2659
    } else if (strcmp(argv[i], "--notest") == 0 ||
               strcmp(argv[i], "--no-test") == 0) {
      options.test_shell = false;
      argv[i] = NULL;
2660 2661 2662
    } else if (strcmp(argv[i], "--send-idle-notification") == 0) {
      options.send_idle_notification = true;
      argv[i] = NULL;
2663 2664 2665 2666 2667
    } else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) {
      options.invoke_weak_callbacks = true;
      // TODO(jochen) See issue 3351
      options.send_idle_notification = true;
      argv[i] = NULL;
2668 2669 2670
    } else if (strcmp(argv[i], "--omit-quit") == 0) {
      options.omit_quit = true;
      argv[i] = NULL;
2671 2672 2673 2674 2675 2676
    } 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) {
      options.num_isolates++;
2677 2678 2679
    } else if (strcmp(argv[i], "--throws") == 0) {
      options.expected_to_throw = true;
      argv[i] = NULL;
2680 2681 2682
    } else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) {
      options.icu_data_file = argv[i] + 16;
      argv[i] = NULL;
2683 2684 2685 2686 2687 2688 2689 2690
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
    } else if (strncmp(argv[i], "--natives_blob=", 15) == 0) {
      options.natives_blob = argv[i] + 15;
      argv[i] = NULL;
    } else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) {
      options.snapshot_blob = argv[i] + 16;
      argv[i] = NULL;
#endif  // V8_USE_EXTERNAL_STARTUP_DATA
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
    } else if (strcmp(argv[i], "--cache") == 0 ||
               strncmp(argv[i], "--cache=", 8) == 0) {
      const char* value = argv[i] + 7;
      if (!*value || strncmp(value, "=code", 6) == 0) {
        options.compile_options = v8::ScriptCompiler::kProduceCodeCache;
      } else if (strncmp(value, "=parse", 7) == 0) {
        options.compile_options = v8::ScriptCompiler::kProduceParserCache;
      } else if (strncmp(value, "=none", 6) == 0) {
        options.compile_options = v8::ScriptCompiler::kNoCompileOptions;
      } else {
        printf("Unknown option to --cache.\n");
        return false;
      }
      argv[i] = NULL;
2705 2706 2707
    } else if (strcmp(argv[i], "--enable-tracing") == 0) {
      options.trace_enabled = true;
      argv[i] = NULL;
2708 2709 2710
    } else if (strncmp(argv[i], "--trace-config=", 15) == 0) {
      options.trace_config = argv[i] + 15;
      argv[i] = NULL;
2711 2712 2713
    } else if (strcmp(argv[i], "--enable-inspector") == 0) {
      options.enable_inspector = true;
      argv[i] = NULL;
2714 2715 2716
    } else if (strncmp(argv[i], "--lcov=", 7) == 0) {
      options.lcov_file = argv[i] + 7;
      argv[i] = NULL;
2717 2718 2719
    } else if (strcmp(argv[i], "--disable-in-process-stack-traces") == 0) {
      options.disable_in_process_stack_traces = true;
      argv[i] = NULL;
2720 2721 2722
    } else if (strcmp(argv[i], "--enable-os-system") == 0) {
      options.enable_os_system = true;
      argv[i] = NULL;
2723
    }
2724 2725
  }

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

2728
  // Set up isolated source groups.
2729 2730 2731 2732 2733 2734 2735 2736 2737
  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);
2738 2739
    } else if (strcmp(str, "--module") == 0) {
      // Pass on to SourceGroup, which understands this option.
2740 2741
    } else if (strncmp(argv[i], "--", 2) == 0) {
      printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
binji's avatar
binji committed
2742 2743 2744 2745 2746
    } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
      options.script_executed = true;
    } else if (strncmp(str, "-", 1) != 0) {
      // Not a flag, so it must be a script to execute.
      options.script_executed = true;
2747 2748 2749 2750
    }
  }
  current->End(argc);

2751 2752 2753 2754
  if (!logfile_per_isolate && options.num_isolates) {
    SetFlagsFromString("--nologfile_per_isolate");
  }

2755 2756 2757 2758
  return true;
}


binji's avatar
binji committed
2759
int Shell::RunMain(Isolate* isolate, int argc, char* argv[], bool last_run) {
2760 2761 2762
  for (int i = 1; i < options.num_isolates; ++i) {
    options.isolate_sources[i].StartExecuteInThread();
  }
2763
  {
2764
    EnsureEventLoopInitialized(isolate);
2765
    if (options.lcov_file) {
2766 2767 2768 2769
      debug::Coverage::Mode mode = i::FLAG_block_coverage
                                       ? debug::Coverage::kBlockCount
                                       : debug::Coverage::kPreciseCount;
      debug::Coverage::SelectMode(isolate, mode);
2770
    }
2771 2772
    HandleScope scope(isolate);
    Local<Context> context = CreateEvaluationContext(isolate);
2773 2774
    bool use_existing_context = last_run && options.use_interactive_shell();
    if (use_existing_context) {
2775 2776
      // Keep using the same context in the interactive shell.
      evaluation_context_.Reset(isolate, context);
2777
    }
2778 2779
    {
      Context::Scope cscope(context);
2780
      InspectorClient inspector_client(context, options.enable_inspector);
2781 2782 2783
      PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
      options.isolate_sources[0].Execute(isolate);
    }
2784 2785 2786
    if (!use_existing_context) {
      DisposeModuleEmbedderData(context);
    }
2787
    WriteLcovData(isolate, options.lcov_file);
2788
  }
2789
  CollectGarbage(isolate);
2790
  CompleteMessageLoop(isolate);
2791
  for (int i = 1; i < options.num_isolates; ++i) {
binji's avatar
binji committed
2792 2793 2794 2795 2796
    if (last_run) {
      options.isolate_sources[i].JoinThread();
    } else {
      options.isolate_sources[i].WaitForThread();
    }
2797
  }
2798
  CleanupWorkers();
2799 2800 2801 2802 2803
  return 0;
}


void Shell::CollectGarbage(Isolate* isolate) {
2804
  if (options.send_idle_notification) {
2805
    const double kLongIdlePauseInSeconds = 1.0;
2806
    isolate->ContextDisposedNotification();
2807 2808
    isolate->IdleNotificationDeadline(
        g_platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds);
2809
  }
2810 2811 2812 2813
  if (options.invoke_weak_callbacks) {
    // By sending a low memory notifications, we will try hard to collect all
    // garbage and will therefore also invoke all weak callbacks of actually
    // unreachable persistent handles.
2814
    isolate->LowMemoryNotification();
2815
  }
2816 2817
}

2818
void Shell::EnsureEventLoopInitialized(Isolate* isolate) {
2819 2820
  v8::platform::EnsureEventLoopInitialized(GetDefaultPlatform(), isolate);
  SetWaitUntilDone(isolate, false);
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
}

void Shell::SetWaitUntilDone(Isolate* isolate, bool value) {
  base::LockGuard<base::Mutex> guard(isolate_status_lock_.Pointer());
  if (isolate_status_.count(isolate) == 0) {
    isolate_status_.insert(std::make_pair(isolate, value));
  } else {
    isolate_status_[isolate] = value;
  }
}

bool Shell::IsWaitUntilDone(Isolate* isolate) {
  base::LockGuard<base::Mutex> guard(isolate_status_lock_.Pointer());
  DCHECK_GT(isolate_status_.count(isolate), 0);
  return isolate_status_[isolate];
}

void Shell::CompleteMessageLoop(Isolate* isolate) {
2839
  Platform* platform = GetDefaultPlatform();
2840
  while (v8::platform::PumpMessageLoop(
2841
      platform, isolate,
2842 2843 2844 2845
      Shell::IsWaitUntilDone(isolate)
          ? platform::MessageLoopBehavior::kWaitForWork
          : platform::MessageLoopBehavior::kDoNotWait)) {
    isolate->RunMicrotasks();
2846
  }
2847 2848 2849 2850
  if (platform->IdleTasksEnabled(isolate)) {
    v8::platform::RunIdleTasks(platform, isolate,
                               50.0 / base::Time::kMillisecondsPerSecond);
  }
2851 2852 2853
}

void Shell::EmptyMessageQueues(Isolate* isolate) {
2854
  Platform* platform = GetDefaultPlatform();
2855 2856
  // Pump the message loop until it is empty.
  while (v8::platform::PumpMessageLoop(
2857
      platform, isolate, platform::MessageLoopBehavior::kDoNotWait)) {
2858 2859 2860
    isolate->RunMicrotasks();
  }
  // Run the idle tasks.
2861 2862 2863 2864
  if (platform->IdleTasksEnabled(isolate)) {
    v8::platform::RunIdleTasks(platform, isolate,
                               50.0 / base::Time::kMillisecondsPerSecond);
  }
2865 2866
}

2867 2868 2869
class Serializer : public ValueSerializer::Delegate {
 public:
  explicit Serializer(Isolate* isolate)
2870 2871 2872
      : isolate_(isolate),
        serializer_(isolate, this),
        current_memory_usage_(0) {}
2873

2874 2875 2876 2877 2878 2879 2880
  Maybe<bool> WriteValue(Local<Context> context, Local<Value> value,
                         Local<Value> transfer) {
    bool ok;
    DCHECK(!data_);
    data_.reset(new SerializationData);
    if (!PrepareTransfer(context, transfer).To(&ok)) {
      return Nothing<bool>();
2881
    }
2882 2883 2884 2885 2886
    serializer_.WriteHeader();

    if (!serializer_.WriteValue(context, value).To(&ok)) {
      data_.reset();
      return Nothing<bool>();
2887
    }
2888 2889 2890

    if (!FinalizeTransfer().To(&ok)) {
      return Nothing<bool>();
2891 2892
    }

2893 2894 2895 2896 2897
    std::pair<uint8_t*, size_t> pair = serializer_.Release();
    data_->data_.reset(pair.first);
    data_->size_ = pair.second;
    return Just(true);
  }
2898

2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
  std::unique_ptr<SerializationData> Release() { return std::move(data_); }

 protected:
  // Implements ValueSerializer::Delegate.
  void ThrowDataCloneError(Local<String> message) override {
    isolate_->ThrowException(Exception::Error(message));
  }

  Maybe<uint32_t> GetSharedArrayBufferId(
      Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer) override {
    DCHECK(data_ != nullptr);
    for (size_t index = 0; index < shared_array_buffers_.size(); ++index) {
      if (shared_array_buffers_[index] == shared_array_buffer) {
        return Just<uint32_t>(static_cast<uint32_t>(index));
      }
2914 2915
    }

2916 2917 2918 2919 2920 2921 2922
    size_t index = shared_array_buffers_.size();
    shared_array_buffers_.emplace_back(isolate_, shared_array_buffer);
    return Just<uint32_t>(static_cast<uint32_t>(index));
  }

  void* ReallocateBufferMemory(void* old_buffer, size_t size,
                               size_t* actual_size) override {
2923 2924 2925 2926 2927
    // Not accurate, because we don't take into account reallocated buffers,
    // but this is fine for testing.
    current_memory_usage_ += size;
    if (current_memory_usage_ > kMaxSerializerMemoryUsage) return nullptr;

2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
    void* result = realloc(old_buffer, size);
    *actual_size = result ? size : 0;
    return result;
  }

  void FreeBufferMemory(void* buffer) override { free(buffer); }

 private:
  Maybe<bool> PrepareTransfer(Local<Context> context, Local<Value> transfer) {
    if (transfer->IsArray()) {
      Local<Array> transfer_array = Local<Array>::Cast(transfer);
      uint32_t length = transfer_array->Length();
      for (uint32_t i = 0; i < length; ++i) {
        Local<Value> element;
        if (transfer_array->Get(context, i).ToLocal(&element)) {
          if (!element->IsArrayBuffer()) {
            Throw(isolate_, "Transfer array elements must be an ArrayBuffer");
2945
            return Nothing<bool>();
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
          }

          Local<ArrayBuffer> array_buffer = Local<ArrayBuffer>::Cast(element);
          serializer_.TransferArrayBuffer(
              static_cast<uint32_t>(array_buffers_.size()), array_buffer);
          array_buffers_.emplace_back(isolate_, array_buffer);
        } else {
          return Nothing<bool>();
        }
      }
      return Just(true);
    } else if (transfer->IsUndefined()) {
      return Just(true);
2959
    } else {
2960 2961
      Throw(isolate_, "Transfer list must be an Array or undefined");
      return Nothing<bool>();
2962
    }
2963 2964
  }

2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975
  template <typename T>
  typename T::Contents MaybeExternalize(Local<T> array_buffer) {
    if (array_buffer->IsExternal()) {
      return array_buffer->GetContents();
    } else {
      typename T::Contents contents = array_buffer->Externalize();
      data_->externalized_contents_.emplace_back(contents);
      return contents;
    }
  }

2976 2977 2978 2979 2980 2981 2982 2983 2984
  Maybe<bool> FinalizeTransfer() {
    for (const auto& global_array_buffer : array_buffers_) {
      Local<ArrayBuffer> array_buffer =
          Local<ArrayBuffer>::New(isolate_, global_array_buffer);
      if (!array_buffer->IsNeuterable()) {
        Throw(isolate_, "ArrayBuffer could not be transferred");
        return Nothing<bool>();
      }

2985
      ArrayBuffer::Contents contents = MaybeExternalize(array_buffer);
2986 2987
      array_buffer->Neuter();
      data_->array_buffer_contents_.push_back(contents);
2988 2989
    }

2990 2991 2992 2993
    for (const auto& global_shared_array_buffer : shared_array_buffers_) {
      Local<SharedArrayBuffer> shared_array_buffer =
          Local<SharedArrayBuffer>::New(isolate_, global_shared_array_buffer);
      data_->shared_array_buffer_contents_.push_back(
2994
          MaybeExternalize(shared_array_buffer));
2995
    }
2996 2997

    return Just(true);
2998 2999
  }

3000 3001 3002 3003 3004
  Isolate* isolate_;
  ValueSerializer serializer_;
  std::unique_ptr<SerializationData> data_;
  std::vector<Global<ArrayBuffer>> array_buffers_;
  std::vector<Global<SharedArrayBuffer>> shared_array_buffers_;
3005
  size_t current_memory_usage_;
3006

3007 3008
  DISALLOW_COPY_AND_ASSIGN(Serializer);
};
3009

3010 3011 3012 3013 3014 3015 3016 3017
class Deserializer : public ValueDeserializer::Delegate {
 public:
  Deserializer(Isolate* isolate, std::unique_ptr<SerializationData> data)
      : isolate_(isolate),
        deserializer_(isolate, data->data(), data->size(), this),
        data_(std::move(data)) {
    deserializer_.SetSupportsLegacyWireFormat(true);
  }
3018

3019 3020 3021 3022
  MaybeLocal<Value> ReadValue(Local<Context> context) {
    bool read_header;
    if (!deserializer_.ReadHeader(context).To(&read_header)) {
      return MaybeLocal<Value>();
3023
    }
3024 3025 3026 3027 3028 3029

    uint32_t index = 0;
    for (const auto& contents : data_->array_buffer_contents()) {
      Local<ArrayBuffer> array_buffer =
          ArrayBuffer::New(isolate_, contents.Data(), contents.ByteLength());
      deserializer_.TransferArrayBuffer(index++, array_buffer);
3030
    }
3031 3032 3033 3034 3035 3036

    index = 0;
    for (const auto& contents : data_->shared_array_buffer_contents()) {
      Local<SharedArrayBuffer> shared_array_buffer = SharedArrayBuffer::New(
          isolate_, contents.Data(), contents.ByteLength());
      deserializer_.TransferSharedArrayBuffer(index++, shared_array_buffer);
3037
    }
3038

3039
    return deserializer_.ReadValue(context);
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057
  }

 private:
  Isolate* isolate_;
  ValueDeserializer deserializer_;
  std::unique_ptr<SerializationData> data_;

  DISALLOW_COPY_AND_ASSIGN(Deserializer);
};

std::unique_ptr<SerializationData> Shell::SerializeValue(
    Isolate* isolate, Local<Value> value, Local<Value> transfer) {
  bool ok;
  Local<Context> context = isolate->GetCurrentContext();
  Serializer serializer(isolate);
  if (serializer.WriteValue(context, value, transfer).To(&ok)) {
    std::unique_ptr<SerializationData> data = serializer.Release();
    base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
3058
    data->AppendExternalizedContentsTo(&externalized_contents_);
3059
    return data;
3060
  }
3061 3062
  return nullptr;
}
3063

3064 3065 3066 3067 3068 3069
MaybeLocal<Value> Shell::DeserializeValue(
    Isolate* isolate, std::unique_ptr<SerializationData> data) {
  Local<Value> value;
  Local<Context> context = isolate->GetCurrentContext();
  Deserializer deserializer(isolate, std::move(data));
  return deserializer.ReadValue(context);
3070 3071 3072 3073
}


void Shell::CleanupWorkers() {
3074 3075 3076 3077 3078
  // Make a copy of workers_, because we don't want to call Worker::Terminate
  // while holding the workers_mutex_ lock. Otherwise, if a worker is about to
  // create a new Worker, it would deadlock.
  i::List<Worker*> workers_copy;
  {
3079
    base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
3080 3081 3082 3083 3084 3085 3086
    allow_new_workers_ = false;
    workers_copy.AddAll(workers_);
    workers_.Clear();
  }

  for (int i = 0; i < workers_copy.length(); ++i) {
    Worker* worker = workers_copy[i];
binji's avatar
binji committed
3087
    worker->WaitForThread();
3088 3089
    delete worker;
  }
3090 3091

  // Now that all workers are terminated, we can re-enable Worker creation.
binji's avatar
binji committed
3092 3093
  base::LockGuard<base::Mutex> lock_guard(workers_mutex_.Pointer());
  allow_new_workers_ = true;
3094
  externalized_contents_.clear();
3095 3096
}

3097
int Shell::Main(int argc, char* argv[]) {
3098
  std::ofstream trace_file;
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113
#if (defined(_WIN32) || defined(_WIN64))
  UINT new_flags =
      SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
  UINT existing_flags = SetErrorMode(new_flags);
  SetErrorMode(existing_flags | new_flags);
#if defined(_MSC_VER)
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  _set_error_mode(_OUT_TO_STDERR);
#endif  // defined(_MSC_VER)
#endif  // defined(_WIN32) || defined(_WIN64)
3114
  if (!SetOptions(argc, argv)) return 1;
3115
  v8::V8::InitializeICUDefaultLocation(argv[0], options.icu_data_file);
3116 3117 3118 3119 3120 3121

  v8::platform::InProcessStackDumping in_process_stack_dumping =
      options.disable_in_process_stack_traces
          ? v8::platform::InProcessStackDumping::kDisabled
          : v8::platform::InProcessStackDumping::kEnabled;

3122
  platform::tracing::TracingController* tracing_controller = nullptr;
3123
  if (options.trace_enabled && !i::FLAG_verify_predictable) {
3124
    trace_file.open("v8_trace.json");
3125
    tracing_controller = new platform::tracing::TracingController();
3126 3127 3128 3129 3130
    platform::tracing::TraceBuffer* trace_buffer =
        platform::tracing::TraceBuffer::CreateTraceBufferRingBuffer(
            platform::tracing::TraceBuffer::kRingBufferChunks,
            platform::tracing::TraceWriter::CreateJSONTraceWriter(trace_file));
    tracing_controller->Initialize(trace_buffer);
3131 3132 3133 3134 3135 3136 3137
  }

  g_platform = v8::platform::CreateDefaultPlatform(
      0, v8::platform::IdleTaskSupport::kEnabled, in_process_stack_dumping,
      tracing_controller);
  if (i::FLAG_verify_predictable) {
    g_platform = new PredictablePlatform(std::unique_ptr<Platform>(g_platform));
3138 3139
  }

3140
  v8::V8::InitializePlatform(g_platform);
3141
  v8::V8::Initialize();
vogelheim's avatar
vogelheim committed
3142 3143 3144 3145 3146 3147
  if (options.natives_blob || options.snapshot_blob) {
    v8::V8::InitializeExternalStartupData(options.natives_blob,
                                          options.snapshot_blob);
  } else {
    v8::V8::InitializeExternalStartupData(argv[0]);
  }
3148
  SetFlagsFromString("--trace-turbo-cfg-file=turbo.cfg");
3149
  SetFlagsFromString("--redirect-code-traces-to=code.asm");
3150 3151
  int result = 0;
  Isolate::CreateParams create_params;
3152
  ShellArrayBufferAllocator shell_array_buffer_allocator;
3153 3154
  MockArrayBufferAllocator mock_arraybuffer_allocator;
  if (options.mock_arraybuffer_allocator) {
3155
    Shell::array_buffer_allocator = &mock_arraybuffer_allocator;
3156
  } else {
3157
    Shell::array_buffer_allocator = &shell_array_buffer_allocator;
3158
  }
3159
  create_params.array_buffer_allocator = Shell::array_buffer_allocator;
3160
#ifdef ENABLE_VTUNE_JIT_INTERFACE
3161
  create_params.code_event_handler = vTune::GetVtuneCodeEventHandler();
3162
#endif
3163 3164
  create_params.constraints.ConfigureDefaults(
      base::SysInfo::AmountOfPhysicalMemory(),
3165
      base::SysInfo::AmountOfVirtualMemory());
3166 3167

  Shell::counter_map_ = new CounterMap();
3168
  if (i::FLAG_dump_counters || i::FLAG_dump_counters_nvp || i::FLAG_gc_stats) {
3169 3170 3171 3172
    create_params.counter_lookup_callback = LookupCounter;
    create_params.create_histogram_callback = CreateHistogram;
    create_params.add_histogram_sample_callback = AddHistogramSample;
  }
3173

eholk's avatar
eholk committed
3174 3175 3176 3177 3178 3179 3180
  if (i::trap_handler::UseTrapHandler()) {
    if (!v8::V8::RegisterDefaultSignalHandler()) {
      fprintf(stderr, "Could not register signal handler");
      exit(1);
    }
  }

3181
  Isolate* isolate = Isolate::New(create_params);
3182 3183
  isolate->SetHostImportModuleDynamicallyCallback(
      Shell::HostImportModuleDynamically);
3184

3185
  D8Console console(isolate);
3186
  {
3187
    Isolate::Scope scope(isolate);
3188
    Initialize(isolate);
3189
    PerIsolateData data(isolate);
3190
    debug::SetConsoleDelegate(isolate, &console);
3191

3192 3193
    if (options.trace_enabled) {
      platform::tracing::TraceConfig* trace_config;
3194 3195
      if (options.trace_config) {
        int size = 0;
3196
        char* trace_config_json_str = ReadChars(options.trace_config, &size);
3197 3198 3199 3200 3201 3202 3203
        trace_config =
            tracing::CreateTraceConfigFromJSON(isolate, trace_config_json_str);
        delete[] trace_config_json_str;
      } else {
        trace_config =
            platform::tracing::TraceConfig::CreateDefaultTraceConfig();
      }
3204
      tracing_controller->StartTracing(trace_config);
3205 3206
    }

3207 3208 3209 3210
    if (options.stress_opt || options.stress_deopt) {
      Testing::SetStressRunType(options.stress_opt
                                ? Testing::kStressTypeOpt
                                : Testing::kStressTypeDeopt);
binji's avatar
binji committed
3211 3212 3213 3214
      options.stress_runs = Testing::GetStressRuns();
      for (int i = 0; i < options.stress_runs && result == 0; i++) {
        printf("============ Stress %d/%d ============\n", i + 1,
               options.stress_runs);
3215
        Testing::PrepareStressRun(i);
binji's avatar
binji committed
3216 3217
        bool last_run = i == options.stress_runs - 1;
        result = RunMain(isolate, argc, argv, last_run);
3218 3219
      }
      printf("======== Full Deoptimization =======\n");
3220
      Testing::DeoptimizeAll(isolate);
3221
    } else if (i::FLAG_stress_runs > 0) {
binji's avatar
binji committed
3222 3223 3224 3225 3226 3227
      options.stress_runs = i::FLAG_stress_runs;
      for (int i = 0; i < options.stress_runs && result == 0; i++) {
        printf("============ Run %d/%d ============\n", i + 1,
               options.stress_runs);
        bool last_run = i == options.stress_runs - 1;
        result = RunMain(isolate, argc, argv, last_run);
3228 3229
      }
    } else {
binji's avatar
binji committed
3230 3231
      bool last_run = true;
      result = RunMain(isolate, argc, argv, last_run);
3232
    }
3233

3234 3235
    // Run interactive shell if explicitly requested or if no script has been
    // executed, but never on --test
3236
    if (options.use_interactive_shell()) {
3237 3238
      RunShell(isolate);
    }
3239

3240
    if (i::FLAG_trace_ignition_dispatches &&
3241
        i::FLAG_trace_ignition_dispatches_output_file != nullptr) {
3242 3243 3244
      WriteIgnitionDispatchCountersFile(isolate);
    }

3245 3246
    // Shut down contexts and collect garbage.
    evaluation_context_.Reset();
3247
    stringify_function_.Reset();
3248
    CollectGarbage(isolate);
3249
  }
3250
  OnExit(isolate);
3251
  V8::Dispose();
3252
  V8::ShutdownPlatform();
3253
  delete g_platform;
3254

3255 3256 3257
  return result;
}

3258
}  // namespace v8
3259 3260


3261
#ifndef GOOGLE3
3262 3263 3264
int main(int argc, char* argv[]) {
  return v8::Shell::Main(argc, argv);
}
3265
#endif