1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 // Defined when linking against shared lib on Windows.
7 #if defined(USING_V8_SHARED) && !defined(V8_SHARED)
25 #include "include/v8-testing.h"
28 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
29 #include "src/gdb-jit.h"
32 #ifdef ENABLE_VTUNE_JIT_INTERFACE
33 #include "src/third_party/vtune/v8-vtune.h"
38 #include "include/libplatform/libplatform.h"
41 #include "src/base/cpu.h"
42 #include "src/base/logging.h"
43 #include "src/base/platform/platform.h"
44 #include "src/base/sys-info.h"
45 #include "src/basic-block-profiler.h"
46 #include "src/d8-debug.h"
47 #include "src/debug.h"
48 #include "src/natives.h"
52 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
53 #include "src/startup-data-util.h"
54 #endif // V8_USE_EXTERNAL_STARTUP_DATA
56 #if !defined(_WIN32) && !defined(_WIN64)
57 #include <unistd.h> // NOLINT
59 #include <windows.h> // NOLINT
61 #include <crtdbg.h> // NOLINT
62 #endif // defined(_MSC_VER)
63 #endif // !defined(_WIN32) && !defined(_WIN64)
66 #define DCHECK(condition) assert(condition)
70 #define CHECK(condition) assert(condition)
76 static Handle<Value> Throw(Isolate* isolate, const char* message) {
77 return isolate->ThrowException(String::NewFromUtf8(isolate, message));
82 class PerIsolateData {
84 explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
85 HandleScope scope(isolate);
86 isolate->SetData(0, this);
90 isolate_->SetData(0, NULL); // Not really needed, just to be sure...
93 inline static PerIsolateData* Get(Isolate* isolate) {
94 return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
99 explicit RealmScope(PerIsolateData* data);
102 PerIsolateData* data_;
107 friend class RealmScope;
112 Persistent<Context>* realms_;
113 Persistent<Value> realm_shared_;
115 int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
117 int RealmFind(Handle<Context> context);
121 LineEditor *LineEditor::current_ = NULL;
124 LineEditor::LineEditor(Type type, const char* name)
125 : type_(type), name_(name) {
126 if (current_ == NULL || current_->type_ < type) current_ = this;
130 class DumbLineEditor: public LineEditor {
132 explicit DumbLineEditor(Isolate* isolate)
133 : LineEditor(LineEditor::DUMB, "dumb"), isolate_(isolate) { }
134 virtual Handle<String> Prompt(const char* prompt);
140 Handle<String> DumbLineEditor::Prompt(const char* prompt) {
141 printf("%s", prompt);
142 #if defined(__native_client__)
143 // Native Client libc is used to being embedded in Chrome and
144 // has trouble recognizing when to flush.
147 return Shell::ReadFromStdin(isolate_);
152 CounterMap* Shell::counter_map_;
153 base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
154 CounterCollection Shell::local_counters_;
155 CounterCollection* Shell::counters_ = &local_counters_;
156 base::Mutex Shell::context_mutex_;
157 const base::TimeTicks Shell::kInitialTicks =
158 base::TimeTicks::HighResolutionNow();
159 Persistent<Context> Shell::utility_context_;
162 Persistent<Context> Shell::evaluation_context_;
163 ShellOptions Shell::options;
164 const char* Shell::kPrompt = "d8> ";
168 const int MB = 1024 * 1024;
170 bool CounterMap::Match(void* key1, void* key2) {
171 const char* name1 = reinterpret_cast<const char*>(key1);
172 const char* name2 = reinterpret_cast<const char*>(key2);
173 return strcmp(name1, name2) == 0;
178 // Converts a V8 value to a C string.
179 const char* Shell::ToCString(const v8::String::Utf8Value& value) {
180 return *value ? *value : "<string conversion failed>";
184 ScriptCompiler::CachedData* CompileForCachedData(
185 Local<String> source, Local<Value> name,
186 ScriptCompiler::CompileOptions compile_options) {
187 int source_length = source->Length();
188 uint16_t* source_buffer = new uint16_t[source_length];
189 source->Write(source_buffer, 0, source_length);
191 uint16_t* name_buffer = NULL;
192 if (name->IsString()) {
193 Local<String> name_string = Local<String>::Cast(name);
194 name_length = name_string->Length();
195 name_buffer = new uint16_t[name_length];
196 name_string->Write(name_buffer, 0, name_length);
198 Isolate* temp_isolate = Isolate::New();
199 ScriptCompiler::CachedData* result = NULL;
201 Isolate::Scope isolate_scope(temp_isolate);
202 HandleScope handle_scope(temp_isolate);
203 Context::Scope context_scope(Context::New(temp_isolate));
204 Local<String> source_copy = v8::String::NewFromTwoByte(
205 temp_isolate, source_buffer, v8::String::kNormalString, source_length);
206 Local<Value> name_copy;
208 name_copy = v8::String::NewFromTwoByte(
209 temp_isolate, name_buffer, v8::String::kNormalString, name_length);
211 name_copy = v8::Undefined(temp_isolate);
213 ScriptCompiler::Source script_source(source_copy, ScriptOrigin(name_copy));
214 ScriptCompiler::CompileUnbound(temp_isolate, &script_source,
216 if (script_source.GetCachedData()) {
217 int length = script_source.GetCachedData()->length;
218 uint8_t* cache = new uint8_t[length];
219 memcpy(cache, script_source.GetCachedData()->data, length);
220 result = new ScriptCompiler::CachedData(
221 cache, length, ScriptCompiler::CachedData::BufferOwned);
224 temp_isolate->Dispose();
225 delete[] source_buffer;
226 delete[] name_buffer;
231 // Compile a string within the current v8 context.
232 Local<Script> Shell::CompileString(
233 Isolate* isolate, Local<String> source, Local<Value> name,
234 ScriptCompiler::CompileOptions compile_options, SourceType source_type) {
235 ScriptOrigin origin(name);
236 if (compile_options == ScriptCompiler::kNoCompileOptions) {
237 ScriptCompiler::Source script_source(source, origin);
238 return source_type == SCRIPT
239 ? ScriptCompiler::Compile(isolate, &script_source,
241 : ScriptCompiler::CompileModule(isolate, &script_source,
245 ScriptCompiler::CachedData* data =
246 CompileForCachedData(source, name, compile_options);
247 ScriptCompiler::Source cached_source(source, origin, data);
248 if (compile_options == ScriptCompiler::kProduceCodeCache) {
249 compile_options = ScriptCompiler::kConsumeCodeCache;
250 } else if (compile_options == ScriptCompiler::kProduceParserCache) {
251 compile_options = ScriptCompiler::kConsumeParserCache;
253 DCHECK(false); // A new compile option?
255 if (data == NULL) compile_options = ScriptCompiler::kNoCompileOptions;
256 Local<Script> result =
257 source_type == SCRIPT
258 ? ScriptCompiler::Compile(isolate, &cached_source, compile_options)
259 : ScriptCompiler::CompileModule(isolate, &cached_source,
261 CHECK(data == NULL || !data->rejected);
266 // Executes a string within the current v8 context.
267 bool Shell::ExecuteString(Isolate* isolate, Handle<String> source,
268 Handle<Value> name, bool print_result,
269 bool report_exceptions, SourceType source_type) {
271 bool FLAG_debugger = i::FLAG_debugger;
273 bool FLAG_debugger = false;
275 HandleScope handle_scope(isolate);
277 options.script_executed = true;
279 // When debugging make exceptions appear to be uncaught.
280 try_catch.SetVerbose(true);
283 Handle<Value> result;
285 PerIsolateData* data = PerIsolateData::Get(isolate);
286 Local<Context> realm =
287 Local<Context>::New(isolate, data->realms_[data->realm_current_]);
288 Context::Scope context_scope(realm);
289 Handle<Script> script = Shell::CompileString(
290 isolate, source, name, options.compile_options, source_type);
291 if (script.IsEmpty()) {
292 // Print errors that happened during compilation.
293 if (report_exceptions && !FLAG_debugger)
294 ReportException(isolate, &try_catch);
297 result = script->Run();
298 data->realm_current_ = data->realm_switch_;
300 if (result.IsEmpty()) {
301 DCHECK(try_catch.HasCaught());
302 // Print errors that happened during execution.
303 if (report_exceptions && !FLAG_debugger)
304 ReportException(isolate, &try_catch);
307 DCHECK(!try_catch.HasCaught());
309 #if !defined(V8_SHARED)
310 if (options.test_shell) {
312 if (!result->IsUndefined()) {
313 // If all went well and the result wasn't undefined then print
314 // the returned value.
315 v8::String::Utf8Value str(result);
316 fwrite(*str, sizeof(**str), str.length(), stdout);
319 #if !defined(V8_SHARED)
321 v8::TryCatch try_catch;
322 v8::Local<v8::Context> context =
323 v8::Local<v8::Context>::New(isolate, utility_context_);
324 v8::Context::Scope context_scope(context);
325 Handle<Object> global = context->Global();
327 global->Get(String::NewFromUtf8(isolate, "Stringify"));
328 Handle<Value> argv[1] = {result};
329 Handle<Value> s = Handle<Function>::Cast(fun)->Call(global, 1, argv);
330 if (try_catch.HasCaught()) return true;
331 v8::String::Utf8Value str(s);
332 fwrite(*str, sizeof(**str), str.length(), stdout);
341 PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
342 data_->realm_count_ = 1;
343 data_->realm_current_ = 0;
344 data_->realm_switch_ = 0;
345 data_->realms_ = new Persistent<Context>[1];
346 data_->realms_[0].Reset(data_->isolate_,
347 data_->isolate_->GetEnteredContext());
351 PerIsolateData::RealmScope::~RealmScope() {
352 // Drop realms to avoid keeping them alive.
353 for (int i = 0; i < data_->realm_count_; ++i)
354 data_->realms_[i].Reset();
355 delete[] data_->realms_;
356 if (!data_->realm_shared_.IsEmpty())
357 data_->realm_shared_.Reset();
361 int PerIsolateData::RealmFind(Handle<Context> context) {
362 for (int i = 0; i < realm_count_; ++i) {
363 if (realms_[i] == context) return i;
369 int PerIsolateData::RealmIndexOrThrow(
370 const v8::FunctionCallbackInfo<v8::Value>& args,
372 if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
373 Throw(args.GetIsolate(), "Invalid argument");
376 int index = args[arg_offset]->Int32Value();
378 index >= realm_count_ ||
379 realms_[index].IsEmpty()) {
380 Throw(args.GetIsolate(), "Invalid realm index");
388 // performance.now() returns a time stamp as double, measured in milliseconds.
389 // When FLAG_verify_predictable mode is enabled it returns current value
390 // of Heap::allocations_count().
391 void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
392 if (i::FLAG_verify_predictable) {
393 Isolate* v8_isolate = args.GetIsolate();
394 i::Heap* heap = reinterpret_cast<i::Isolate*>(v8_isolate)->heap();
395 args.GetReturnValue().Set(heap->synthetic_time());
397 base::TimeDelta delta =
398 base::TimeTicks::HighResolutionNow() - kInitialTicks;
399 args.GetReturnValue().Set(delta.InMillisecondsF());
405 // Realm.current() returns the index of the currently active realm.
406 void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
407 Isolate* isolate = args.GetIsolate();
408 PerIsolateData* data = PerIsolateData::Get(isolate);
409 int index = data->RealmFind(isolate->GetEnteredContext());
410 if (index == -1) return;
411 args.GetReturnValue().Set(index);
415 // Realm.owner(o) returns the index of the realm that created o.
416 void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
417 Isolate* isolate = args.GetIsolate();
418 PerIsolateData* data = PerIsolateData::Get(isolate);
419 if (args.Length() < 1 || !args[0]->IsObject()) {
420 Throw(args.GetIsolate(), "Invalid argument");
423 int index = data->RealmFind(args[0]->ToObject(isolate)->CreationContext());
424 if (index == -1) return;
425 args.GetReturnValue().Set(index);
429 // Realm.global(i) returns the global object of realm i.
430 // (Note that properties of global objects cannot be read/written cross-realm.)
431 void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
432 PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
433 int index = data->RealmIndexOrThrow(args, 0);
434 if (index == -1) return;
435 args.GetReturnValue().Set(
436 Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
440 // Realm.create() creates a new realm and returns its index.
441 void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
442 Isolate* isolate = args.GetIsolate();
443 PerIsolateData* data = PerIsolateData::Get(isolate);
444 Persistent<Context>* old_realms = data->realms_;
445 int index = data->realm_count_;
446 data->realms_ = new Persistent<Context>[++data->realm_count_];
447 for (int i = 0; i < index; ++i) {
448 data->realms_[i].Reset(isolate, old_realms[i]);
451 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
452 data->realms_[index].Reset(
453 isolate, Context::New(isolate, NULL, global_template));
454 args.GetReturnValue().Set(index);
458 // Realm.dispose(i) disposes the reference to the realm i.
459 void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
460 Isolate* isolate = args.GetIsolate();
461 PerIsolateData* data = PerIsolateData::Get(isolate);
462 int index = data->RealmIndexOrThrow(args, 0);
463 if (index == -1) return;
465 index == data->realm_current_ || index == data->realm_switch_) {
466 Throw(args.GetIsolate(), "Invalid realm index");
469 data->realms_[index].Reset();
473 // Realm.switch(i) switches to the realm i for consecutive interactive inputs.
474 void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
475 Isolate* isolate = args.GetIsolate();
476 PerIsolateData* data = PerIsolateData::Get(isolate);
477 int index = data->RealmIndexOrThrow(args, 0);
478 if (index == -1) return;
479 data->realm_switch_ = index;
483 // Realm.eval(i, s) evaluates s in realm i and returns the result.
484 void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
485 Isolate* isolate = args.GetIsolate();
486 PerIsolateData* data = PerIsolateData::Get(isolate);
487 int index = data->RealmIndexOrThrow(args, 0);
488 if (index == -1) return;
489 if (args.Length() < 2 || !args[1]->IsString()) {
490 Throw(args.GetIsolate(), "Invalid argument");
493 ScriptCompiler::Source script_source(args[1]->ToString(isolate));
494 Handle<UnboundScript> script = ScriptCompiler::CompileUnbound(
495 isolate, &script_source);
496 if (script.IsEmpty()) return;
497 Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
499 Handle<Value> result = script->BindToCurrentContext()->Run();
501 args.GetReturnValue().Set(result);
505 // Realm.shared is an accessor for a single shared value across realms.
506 void Shell::RealmSharedGet(Local<String> property,
507 const PropertyCallbackInfo<Value>& info) {
508 Isolate* isolate = info.GetIsolate();
509 PerIsolateData* data = PerIsolateData::Get(isolate);
510 if (data->realm_shared_.IsEmpty()) return;
511 info.GetReturnValue().Set(data->realm_shared_);
514 void Shell::RealmSharedSet(Local<String> property,
516 const PropertyCallbackInfo<void>& info) {
517 Isolate* isolate = info.GetIsolate();
518 PerIsolateData* data = PerIsolateData::Get(isolate);
519 data->realm_shared_.Reset(isolate, value);
523 void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
530 void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
531 for (int i = 0; i < args.Length(); i++) {
532 HandleScope handle_scope(args.GetIsolate());
537 // Explicitly catch potential exceptions in toString().
538 v8::TryCatch try_catch;
539 Handle<String> str_obj = args[i]->ToString(args.GetIsolate());
540 if (try_catch.HasCaught()) {
545 v8::String::Utf8Value str(str_obj);
546 int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
547 if (n != str.length()) {
548 printf("Error in fwrite\n");
555 void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
556 String::Utf8Value file(args[0]);
558 Throw(args.GetIsolate(), "Error loading file");
561 Handle<String> source = ReadFile(args.GetIsolate(), *file);
562 if (source.IsEmpty()) {
563 Throw(args.GetIsolate(), "Error loading file");
566 args.GetReturnValue().Set(source);
570 Handle<String> Shell::ReadFromStdin(Isolate* isolate) {
571 static const int kBufferSize = 256;
572 char buffer[kBufferSize];
573 Handle<String> accumulator = String::NewFromUtf8(isolate, "");
576 // Continue reading if the line ends with an escape '\\' or the line has
577 // not been fully read into the buffer yet (does not end with '\n').
578 // If fgets gets an error, just give up.
580 input = fgets(buffer, kBufferSize, stdin);
581 if (input == NULL) return Handle<String>();
582 length = static_cast<int>(strlen(buffer));
585 } else if (buffer[length-1] != '\n') {
586 accumulator = String::Concat(
588 String::NewFromUtf8(isolate, buffer, String::kNormalString, length));
589 } else if (length > 1 && buffer[length-2] == '\\') {
590 buffer[length-2] = '\n';
591 accumulator = String::Concat(
592 accumulator, String::NewFromUtf8(isolate, buffer,
593 String::kNormalString, length - 1));
595 return String::Concat(
596 accumulator, String::NewFromUtf8(isolate, buffer,
597 String::kNormalString, length - 1));
603 void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
604 for (int i = 0; i < args.Length(); i++) {
605 HandleScope handle_scope(args.GetIsolate());
606 String::Utf8Value file(args[i]);
608 Throw(args.GetIsolate(), "Error loading file");
611 Handle<String> source = ReadFile(args.GetIsolate(), *file);
612 if (source.IsEmpty()) {
613 Throw(args.GetIsolate(), "Error loading file");
616 if (!ExecuteString(args.GetIsolate(),
618 String::NewFromUtf8(args.GetIsolate(), *file),
621 Throw(args.GetIsolate(), "Error executing file");
628 void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
629 int exit_code = args[0]->Int32Value();
630 OnExit(args.GetIsolate());
635 void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
636 args.GetReturnValue().Set(
637 String::NewFromUtf8(args.GetIsolate(), V8::GetVersion()));
641 void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
642 HandleScope handle_scope(isolate);
644 Handle<Context> utility_context;
645 bool enter_context = !isolate->InContext();
647 utility_context = Local<Context>::New(isolate, utility_context_);
648 utility_context->Enter();
651 v8::String::Utf8Value exception(try_catch->Exception());
652 const char* exception_string = ToCString(exception);
653 Handle<Message> message = try_catch->Message();
654 if (message.IsEmpty()) {
655 // V8 didn't provide any extra information about this error; just
656 // print the exception.
657 printf("%s\n", exception_string);
659 // Print (filename):(line number): (message).
660 v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
661 const char* filename_string = ToCString(filename);
662 int linenum = message->GetLineNumber();
663 printf("%s:%i: %s\n", filename_string, linenum, exception_string);
664 // Print line of source code.
665 v8::String::Utf8Value sourceline(message->GetSourceLine());
666 const char* sourceline_string = ToCString(sourceline);
667 printf("%s\n", sourceline_string);
668 // Print wavy underline (GetUnderline is deprecated).
669 int start = message->GetStartColumn();
670 for (int i = 0; i < start; i++) {
673 int end = message->GetEndColumn();
674 for (int i = start; i < end; i++) {
678 v8::String::Utf8Value stack_trace(try_catch->StackTrace());
679 if (stack_trace.length() > 0) {
680 const char* stack_trace_string = ToCString(stack_trace);
681 printf("%s\n", stack_trace_string);
686 if (enter_context) utility_context->Exit();
692 Handle<Array> Shell::GetCompletions(Isolate* isolate,
694 Handle<String> full) {
695 EscapableHandleScope handle_scope(isolate);
696 v8::Local<v8::Context> utility_context =
697 v8::Local<v8::Context>::New(isolate, utility_context_);
698 v8::Context::Scope context_scope(utility_context);
699 Handle<Object> global = utility_context->Global();
701 global->Get(String::NewFromUtf8(isolate, "GetCompletions"));
702 static const int kArgc = 3;
703 v8::Local<v8::Context> evaluation_context =
704 v8::Local<v8::Context>::New(isolate, evaluation_context_);
705 Handle<Value> argv[kArgc] = { evaluation_context->Global(), text, full };
706 Local<Value> val = Local<Function>::Cast(fun)->Call(global, kArgc, argv);
707 return handle_scope.Escape(Local<Array>::Cast(val));
711 Local<Object> Shell::DebugMessageDetails(Isolate* isolate,
712 Handle<String> message) {
713 EscapableHandleScope handle_scope(isolate);
714 v8::Local<v8::Context> context =
715 v8::Local<v8::Context>::New(isolate, utility_context_);
716 v8::Context::Scope context_scope(context);
717 Handle<Object> global = context->Global();
719 global->Get(String::NewFromUtf8(isolate, "DebugMessageDetails"));
720 static const int kArgc = 1;
721 Handle<Value> argv[kArgc] = { message };
722 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
723 return handle_scope.Escape(Local<Object>(Handle<Object>::Cast(val)));
727 Local<Value> Shell::DebugCommandToJSONRequest(Isolate* isolate,
728 Handle<String> command) {
729 EscapableHandleScope handle_scope(isolate);
730 v8::Local<v8::Context> context =
731 v8::Local<v8::Context>::New(isolate, utility_context_);
732 v8::Context::Scope context_scope(context);
733 Handle<Object> global = context->Global();
735 global->Get(String::NewFromUtf8(isolate, "DebugCommandToJSONRequest"));
736 static const int kArgc = 1;
737 Handle<Value> argv[kArgc] = { command };
738 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
739 return handle_scope.Escape(Local<Value>(val));
743 int32_t* Counter::Bind(const char* name, bool is_histogram) {
745 for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
746 name_[i] = static_cast<char>(name[i]);
748 is_histogram_ = is_histogram;
753 void Counter::AddSample(int32_t sample) {
755 sample_total_ += sample;
759 CounterCollection::CounterCollection() {
760 magic_number_ = 0xDEADFACE;
761 max_counters_ = kMaxCounters;
762 max_name_size_ = Counter::kMaxNameSize;
763 counters_in_use_ = 0;
767 Counter* CounterCollection::GetNextCounter() {
768 if (counters_in_use_ == kMaxCounters) return NULL;
769 return &counters_[counters_in_use_++];
773 void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
774 counters_file_ = base::OS::MemoryMappedFile::create(
775 name, sizeof(CounterCollection), &local_counters_);
776 void* memory = (counters_file_ == NULL) ?
777 NULL : counters_file_->memory();
778 if (memory == NULL) {
779 printf("Could not map counters file %s\n", name);
782 counters_ = static_cast<CounterCollection*>(memory);
783 isolate->SetCounterFunction(LookupCounter);
784 isolate->SetCreateHistogramFunction(CreateHistogram);
785 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
789 int CounterMap::Hash(const char* name) {
792 while ((c = *name++) != 0) {
800 Counter* Shell::GetCounter(const char* name, bool is_histogram) {
801 Counter* counter = counter_map_->Lookup(name);
803 if (counter == NULL) {
804 counter = counters_->GetNextCounter();
805 if (counter != NULL) {
806 counter_map_->Set(name, counter);
807 counter->Bind(name, is_histogram);
810 DCHECK(counter->is_histogram() == is_histogram);
816 int* Shell::LookupCounter(const char* name) {
817 Counter* counter = GetCounter(name, false);
819 if (counter != NULL) {
820 return counter->ptr();
827 void* Shell::CreateHistogram(const char* name,
831 return GetCounter(name, true);
835 void Shell::AddHistogramSample(void* histogram, int sample) {
836 Counter* counter = reinterpret_cast<Counter*>(histogram);
837 counter->AddSample(sample);
841 class NoUseStrongForUtilityScriptScope {
843 NoUseStrongForUtilityScriptScope() : flag_(i::FLAG_use_strong) {
844 i::FLAG_use_strong = false;
846 ~NoUseStrongForUtilityScriptScope() { i::FLAG_use_strong = flag_; }
853 void Shell::InstallUtilityScript(Isolate* isolate) {
854 NoUseStrongForUtilityScriptScope no_use_strong;
855 HandleScope scope(isolate);
856 // If we use the utility context, we have to set the security tokens so that
857 // utility, evaluation and debug context can all access each other.
858 v8::Local<v8::Context> utility_context =
859 v8::Local<v8::Context>::New(isolate, utility_context_);
860 v8::Local<v8::Context> evaluation_context =
861 v8::Local<v8::Context>::New(isolate, evaluation_context_);
862 utility_context->SetSecurityToken(Undefined(isolate));
863 evaluation_context->SetSecurityToken(Undefined(isolate));
864 v8::Context::Scope context_scope(utility_context);
866 if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
867 // Install the debugger object in the utility scope
868 i::Debug* debug = reinterpret_cast<i::Isolate*>(isolate)->debug();
870 i::Handle<i::Context> debug_context = debug->debug_context();
871 i::Handle<i::JSObject> js_debug
872 = i::Handle<i::JSObject>(debug_context->global_object());
873 utility_context->Global()->Set(String::NewFromUtf8(isolate, "$debug"),
874 Utils::ToLocal(js_debug));
875 debug_context->set_security_token(
876 reinterpret_cast<i::Isolate*>(isolate)->heap()->undefined_value());
878 // Run the d8 shell utility script in the utility context
879 int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
880 i::Vector<const char> shell_source =
881 i::NativesCollection<i::D8>::GetScriptSource(source_index);
882 i::Vector<const char> shell_source_name =
883 i::NativesCollection<i::D8>::GetScriptName(source_index);
884 Handle<String> source =
885 String::NewFromUtf8(isolate, shell_source.start(), String::kNormalString,
886 shell_source.length());
887 Handle<String> name =
888 String::NewFromUtf8(isolate, shell_source_name.start(),
889 String::kNormalString, shell_source_name.length());
890 ScriptOrigin origin(name);
891 Handle<Script> script = Script::Compile(source, &origin);
893 // Mark the d8 shell script as native to avoid it showing up as normal source
895 i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
896 i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
897 ? i::Handle<i::Script>(i::Script::cast(
898 i::JSFunction::cast(*compiled_script)->shared()->script()))
899 : i::Handle<i::Script>(i::Script::cast(
900 i::SharedFunctionInfo::cast(*compiled_script)->script()));
901 script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
903 // Start the in-process debugger if requested.
904 if (i::FLAG_debugger) v8::Debug::SetDebugEventListener(HandleDebugEvent);
909 Handle<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
910 Handle<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
911 global_template->Set(String::NewFromUtf8(isolate, "print"),
912 FunctionTemplate::New(isolate, Print));
913 global_template->Set(String::NewFromUtf8(isolate, "write"),
914 FunctionTemplate::New(isolate, Write));
915 global_template->Set(String::NewFromUtf8(isolate, "read"),
916 FunctionTemplate::New(isolate, Read));
917 global_template->Set(String::NewFromUtf8(isolate, "readbuffer"),
918 FunctionTemplate::New(isolate, ReadBuffer));
919 global_template->Set(String::NewFromUtf8(isolate, "readline"),
920 FunctionTemplate::New(isolate, ReadLine));
921 global_template->Set(String::NewFromUtf8(isolate, "load"),
922 FunctionTemplate::New(isolate, Load));
923 global_template->Set(String::NewFromUtf8(isolate, "quit"),
924 FunctionTemplate::New(isolate, Quit));
925 global_template->Set(String::NewFromUtf8(isolate, "version"),
926 FunctionTemplate::New(isolate, Version));
928 // Bind the Realm object.
929 Handle<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
930 realm_template->Set(String::NewFromUtf8(isolate, "current"),
931 FunctionTemplate::New(isolate, RealmCurrent));
932 realm_template->Set(String::NewFromUtf8(isolate, "owner"),
933 FunctionTemplate::New(isolate, RealmOwner));
934 realm_template->Set(String::NewFromUtf8(isolate, "global"),
935 FunctionTemplate::New(isolate, RealmGlobal));
936 realm_template->Set(String::NewFromUtf8(isolate, "create"),
937 FunctionTemplate::New(isolate, RealmCreate));
938 realm_template->Set(String::NewFromUtf8(isolate, "dispose"),
939 FunctionTemplate::New(isolate, RealmDispose));
940 realm_template->Set(String::NewFromUtf8(isolate, "switch"),
941 FunctionTemplate::New(isolate, RealmSwitch));
942 realm_template->Set(String::NewFromUtf8(isolate, "eval"),
943 FunctionTemplate::New(isolate, RealmEval));
944 realm_template->SetAccessor(String::NewFromUtf8(isolate, "shared"),
945 RealmSharedGet, RealmSharedSet);
946 global_template->Set(String::NewFromUtf8(isolate, "Realm"), realm_template);
949 Handle<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
950 performance_template->Set(String::NewFromUtf8(isolate, "now"),
951 FunctionTemplate::New(isolate, PerformanceNow));
952 global_template->Set(String::NewFromUtf8(isolate, "performance"),
953 performance_template);
956 Handle<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
957 AddOSMethods(isolate, os_templ);
958 global_template->Set(String::NewFromUtf8(isolate, "os"), os_templ);
960 return global_template;
964 void Shell::Initialize(Isolate* isolate) {
966 Shell::counter_map_ = new CounterMap();
968 if (i::StrLength(i::FLAG_map_counters) != 0)
969 MapCounters(isolate, i::FLAG_map_counters);
970 if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
971 isolate->SetCounterFunction(LookupCounter);
972 isolate->SetCreateHistogramFunction(CreateHistogram);
973 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
979 void Shell::InitializeDebugger(Isolate* isolate) {
980 if (options.test_shell) return;
982 HandleScope scope(isolate);
983 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
984 utility_context_.Reset(isolate,
985 Context::New(isolate, NULL, global_template));
990 Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
992 // This needs to be a critical section since this is not thread-safe
993 base::LockGuard<base::Mutex> lock_guard(&context_mutex_);
995 // Initialize the global objects
996 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
997 EscapableHandleScope handle_scope(isolate);
998 Local<Context> context = Context::New(isolate, NULL, global_template);
999 DCHECK(!context.IsEmpty());
1000 Context::Scope scope(context);
1003 i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
1004 i::JSArguments js_args = i::FLAG_js_arguments;
1005 i::Handle<i::FixedArray> arguments_array =
1006 factory->NewFixedArray(js_args.argc);
1007 for (int j = 0; j < js_args.argc; j++) {
1008 i::Handle<i::String> arg =
1009 factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
1010 arguments_array->set(j, *arg);
1012 i::Handle<i::JSArray> arguments_jsarray =
1013 factory->NewJSArrayWithElements(arguments_array);
1014 context->Global()->Set(String::NewFromUtf8(isolate, "arguments"),
1015 Utils::ToLocal(arguments_jsarray));
1016 #endif // !V8_SHARED
1017 return handle_scope.Escape(context);
1021 void Shell::Exit(int exit_code) {
1022 // Use _exit instead of exit to avoid races between isolate
1023 // threads and static destructors.
1031 struct CounterAndKey {
1037 inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
1038 return strcmp(lhs.key, rhs.key) < 0;
1040 #endif // !V8_SHARED
1043 void Shell::OnExit(v8::Isolate* isolate) {
1044 LineEditor* line_editor = LineEditor::Get();
1045 if (line_editor) line_editor->Close();
1047 reinterpret_cast<i::Isolate*>(isolate)->DumpAndResetCompilationStats();
1048 if (i::FLAG_dump_counters) {
1049 int number_of_counters = 0;
1050 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1051 number_of_counters++;
1053 CounterAndKey* counters = new CounterAndKey[number_of_counters];
1055 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
1056 counters[j].counter = i.CurrentValue();
1057 counters[j].key = i.CurrentKey();
1059 std::sort(counters, counters + number_of_counters);
1060 printf("+----------------------------------------------------------------+"
1061 "-------------+\n");
1064 printf("+----------------------------------------------------------------+"
1065 "-------------+\n");
1066 for (j = 0; j < number_of_counters; j++) {
1067 Counter* counter = counters[j].counter;
1068 const char* key = counters[j].key;
1069 if (counter->is_histogram()) {
1070 printf("| c:%-60s | %11i |\n", key, counter->count());
1071 printf("| t:%-60s | %11i |\n", key, counter->sample_total());
1073 printf("| %-62s | %11i |\n", key, counter->count());
1076 printf("+----------------------------------------------------------------+"
1077 "-------------+\n");
1080 delete counters_file_;
1081 delete counter_map_;
1082 #endif // !V8_SHARED
1087 static FILE* FOpen(const char* path, const char* mode) {
1088 #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
1090 if (fopen_s(&result, path, mode) == 0) {
1096 FILE* file = fopen(path, mode);
1097 if (file == NULL) return NULL;
1098 struct stat file_stat;
1099 if (fstat(fileno(file), &file_stat) != 0) return NULL;
1100 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
1101 if (is_regular_file) return file;
1108 static char* ReadChars(Isolate* isolate, const char* name, int* size_out) {
1109 FILE* file = FOpen(name, "rb");
1110 if (file == NULL) return NULL;
1112 fseek(file, 0, SEEK_END);
1113 int size = ftell(file);
1116 char* chars = new char[size + 1];
1118 for (int i = 0; i < size;) {
1119 int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1128 struct DataAndPersistent {
1130 Persistent<ArrayBuffer> handle;
1134 static void ReadBufferWeakCallback(
1135 const v8::WeakCallbackData<ArrayBuffer, DataAndPersistent>& data) {
1136 size_t byte_length = data.GetValue()->ByteLength();
1137 data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
1138 -static_cast<intptr_t>(byte_length));
1140 delete[] data.GetParameter()->data;
1141 data.GetParameter()->handle.Reset();
1142 delete data.GetParameter();
1146 void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
1147 DCHECK(sizeof(char) == sizeof(uint8_t)); // NOLINT
1148 String::Utf8Value filename(args[0]);
1150 if (*filename == NULL) {
1151 Throw(args.GetIsolate(), "Error loading file");
1155 Isolate* isolate = args.GetIsolate();
1156 DataAndPersistent* data = new DataAndPersistent;
1157 data->data = reinterpret_cast<uint8_t*>(
1158 ReadChars(args.GetIsolate(), *filename, &length));
1159 if (data->data == NULL) {
1161 Throw(args.GetIsolate(), "Error reading file");
1164 Handle<v8::ArrayBuffer> buffer =
1165 ArrayBuffer::New(isolate, data->data, length);
1166 data->handle.Reset(isolate, buffer);
1167 data->handle.SetWeak(data, ReadBufferWeakCallback);
1168 data->handle.MarkIndependent();
1169 isolate->AdjustAmountOfExternalAllocatedMemory(length);
1171 args.GetReturnValue().Set(buffer);
1175 // Reads a file into a v8 string.
1176 Handle<String> Shell::ReadFile(Isolate* isolate, const char* name) {
1178 char* chars = ReadChars(isolate, name, &size);
1179 if (chars == NULL) return Handle<String>();
1180 Handle<String> result =
1181 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1187 void Shell::RunShell(Isolate* isolate) {
1188 HandleScope outer_scope(isolate);
1189 v8::Local<v8::Context> context =
1190 v8::Local<v8::Context>::New(isolate, evaluation_context_);
1191 v8::Context::Scope context_scope(context);
1192 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1193 Handle<String> name = String::NewFromUtf8(isolate, "(d8)");
1194 LineEditor* console = LineEditor::Get();
1195 printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
1196 console->Open(isolate);
1198 HandleScope inner_scope(isolate);
1199 Handle<String> input = console->Prompt(Shell::kPrompt);
1200 if (input.IsEmpty()) break;
1201 ExecuteString(isolate, input, name, true, true);
1207 SourceGroup::~SourceGroup() {
1211 #endif // !V8_SHARED
1215 void SourceGroup::Execute(Isolate* isolate) {
1216 bool exception_was_thrown = false;
1217 for (int i = begin_offset_; i < end_offset_; ++i) {
1218 const char* arg = argv_[i];
1219 Shell::SourceType source_type = Shell::SCRIPT;
1220 if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
1221 // Execute argument given to -e option directly.
1222 HandleScope handle_scope(isolate);
1223 Handle<String> file_name = String::NewFromUtf8(isolate, "unnamed");
1224 Handle<String> source = String::NewFromUtf8(isolate, argv_[i + 1]);
1225 if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1226 exception_was_thrown = true;
1231 } else if (strcmp(arg, "--module") == 0 && i + 1 < end_offset_) {
1232 // Treat the next file as a module.
1233 source_type = Shell::MODULE;
1235 } else if (arg[0] == '-') {
1236 // Ignore other options. They have been parsed already.
1240 // Use all other arguments as names of files to load and run.
1241 HandleScope handle_scope(isolate);
1242 Handle<String> file_name = String::NewFromUtf8(isolate, arg);
1243 Handle<String> source = ReadFile(isolate, arg);
1244 if (source.IsEmpty()) {
1245 printf("Error reading '%s'\n", arg);
1248 if (!Shell::ExecuteString(isolate, source, file_name, false, true,
1250 exception_was_thrown = true;
1254 if (exception_was_thrown != Shell::options.expected_to_throw) {
1260 Handle<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
1262 char* chars = ReadChars(isolate, name, &size);
1263 if (chars == NULL) return Handle<String>();
1264 Handle<String> result =
1265 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1272 base::Thread::Options SourceGroup::GetThreadOptions() {
1273 // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
1274 // which is not enough to parse the big literal expressions used in tests.
1275 // The stack size should be at least StackGuard::kLimitSize + some
1276 // OS-specific padding for thread startup code. 2Mbytes seems to be enough.
1277 return base::Thread::Options("IsolateThread", 2 * MB);
1281 void SourceGroup::ExecuteInThread() {
1282 Isolate* isolate = Isolate::New();
1284 next_semaphore_.Wait();
1286 Isolate::Scope iscope(isolate);
1288 HandleScope scope(isolate);
1289 PerIsolateData data(isolate);
1290 Local<Context> context = Shell::CreateEvaluationContext(isolate);
1292 Context::Scope cscope(context);
1293 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1297 if (Shell::options.send_idle_notification) {
1298 const int kLongIdlePauseInMs = 1000;
1299 isolate->ContextDisposedNotification();
1300 isolate->IdleNotification(kLongIdlePauseInMs);
1302 if (Shell::options.invoke_weak_callbacks) {
1303 // By sending a low memory notifications, we will try hard to collect
1304 // all garbage and will therefore also invoke all weak callbacks of
1305 // actually unreachable persistent handles.
1306 isolate->LowMemoryNotification();
1309 done_semaphore_.Signal();
1310 } while (!Shell::options.last_run);
1316 void SourceGroup::StartExecuteInThread() {
1317 if (thread_ == NULL) {
1318 thread_ = new IsolateThread(this);
1321 next_semaphore_.Signal();
1325 void SourceGroup::WaitForThread() {
1326 if (thread_ == NULL) return;
1327 if (Shell::options.last_run) {
1330 done_semaphore_.Wait();
1333 #endif // !V8_SHARED
1336 void SetFlagsFromString(const char* flags) {
1337 v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags)));
1341 bool Shell::SetOptions(int argc, char* argv[]) {
1342 bool logfile_per_isolate = false;
1343 for (int i = 0; i < argc; i++) {
1344 if (strcmp(argv[i], "--stress-opt") == 0) {
1345 options.stress_opt = true;
1347 } else if (strcmp(argv[i], "--nostress-opt") == 0) {
1348 options.stress_opt = false;
1350 } else if (strcmp(argv[i], "--stress-deopt") == 0) {
1351 options.stress_deopt = true;
1353 } else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) {
1354 options.mock_arraybuffer_allocator = true;
1356 } else if (strcmp(argv[i], "--noalways-opt") == 0) {
1357 // No support for stressing if we can't use --always-opt.
1358 options.stress_opt = false;
1359 options.stress_deopt = false;
1360 } else if (strcmp(argv[i], "--logfile-per-isolate") == 0) {
1361 logfile_per_isolate = true;
1363 } else if (strcmp(argv[i], "--shell") == 0) {
1364 options.interactive_shell = true;
1366 } else if (strcmp(argv[i], "--test") == 0) {
1367 options.test_shell = true;
1369 } else if (strcmp(argv[i], "--send-idle-notification") == 0) {
1370 options.send_idle_notification = true;
1372 } else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) {
1373 options.invoke_weak_callbacks = true;
1374 // TODO(jochen) See issue 3351
1375 options.send_idle_notification = true;
1377 } else if (strcmp(argv[i], "-f") == 0) {
1378 // Ignore any -f flags for compatibility with other stand-alone
1379 // JavaScript engines.
1381 } else if (strcmp(argv[i], "--isolate") == 0) {
1383 printf("D8 with shared library does not support multi-threading\n");
1386 options.num_isolates++;
1387 } else if (strcmp(argv[i], "--dump-heap-constants") == 0) {
1389 printf("D8 with shared library does not support constant dumping\n");
1392 options.dump_heap_constants = true;
1395 } else if (strcmp(argv[i], "--throws") == 0) {
1396 options.expected_to_throw = true;
1398 } else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) {
1399 options.icu_data_file = argv[i] + 16;
1402 } else if (strcmp(argv[i], "--dump-counters") == 0) {
1403 printf("D8 with shared library does not include counters\n");
1405 } else if (strcmp(argv[i], "--debugger") == 0) {
1406 printf("Javascript debugger not included\n");
1409 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1410 } else if (strncmp(argv[i], "--natives_blob=", 15) == 0) {
1411 options.natives_blob = argv[i] + 15;
1413 } else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) {
1414 options.snapshot_blob = argv[i] + 16;
1416 #endif // V8_USE_EXTERNAL_STARTUP_DATA
1417 } else if (strcmp(argv[i], "--cache") == 0 ||
1418 strncmp(argv[i], "--cache=", 8) == 0) {
1419 const char* value = argv[i] + 7;
1420 if (!*value || strncmp(value, "=code", 6) == 0) {
1421 options.compile_options = v8::ScriptCompiler::kProduceCodeCache;
1422 } else if (strncmp(value, "=parse", 7) == 0) {
1423 options.compile_options = v8::ScriptCompiler::kProduceParserCache;
1424 } else if (strncmp(value, "=none", 6) == 0) {
1425 options.compile_options = v8::ScriptCompiler::kNoCompileOptions;
1427 printf("Unknown option to --cache.\n");
1434 v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
1436 bool enable_harmony_modules = false;
1438 // Set up isolated source groups.
1439 options.isolate_sources = new SourceGroup[options.num_isolates];
1440 SourceGroup* current = options.isolate_sources;
1441 current->Begin(argv, 1);
1442 for (int i = 1; i < argc; i++) {
1443 const char* str = argv[i];
1444 if (strcmp(str, "--isolate") == 0) {
1447 current->Begin(argv, i + 1);
1448 } else if (strcmp(str, "--module") == 0) {
1449 // Pass on to SourceGroup, which understands this option.
1450 enable_harmony_modules = true;
1451 } else if (strncmp(argv[i], "--", 2) == 0) {
1452 printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
1457 if (!logfile_per_isolate && options.num_isolates) {
1458 SetFlagsFromString("--nologfile_per_isolate");
1461 if (enable_harmony_modules) {
1462 SetFlagsFromString("--harmony-modules");
1469 int Shell::RunMain(Isolate* isolate, int argc, char* argv[]) {
1471 for (int i = 1; i < options.num_isolates; ++i) {
1472 options.isolate_sources[i].StartExecuteInThread();
1474 #endif // !V8_SHARED
1476 HandleScope scope(isolate);
1477 Local<Context> context = CreateEvaluationContext(isolate);
1478 if (options.last_run && options.use_interactive_shell()) {
1479 // Keep using the same context in the interactive shell.
1480 evaluation_context_.Reset(isolate, context);
1482 // If the interactive debugger is enabled make sure to activate
1483 // it before running the files passed on the command line.
1484 if (i::FLAG_debugger) {
1485 InstallUtilityScript(isolate);
1487 #endif // !V8_SHARED
1490 Context::Scope cscope(context);
1491 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1492 options.isolate_sources[0].Execute(isolate);
1495 if (options.send_idle_notification) {
1496 const int kLongIdlePauseInMs = 1000;
1497 isolate->ContextDisposedNotification();
1498 isolate->IdleNotification(kLongIdlePauseInMs);
1500 if (options.invoke_weak_callbacks) {
1501 // By sending a low memory notifications, we will try hard to collect all
1502 // garbage and will therefore also invoke all weak callbacks of actually
1503 // unreachable persistent handles.
1504 isolate->LowMemoryNotification();
1508 for (int i = 1; i < options.num_isolates; ++i) {
1509 options.isolate_sources[i].WaitForThread();
1511 #endif // !V8_SHARED
1517 static void DumpHeapConstants(i::Isolate* isolate) {
1518 i::Heap* heap = isolate->heap();
1520 // Dump the INSTANCE_TYPES table to the console.
1521 printf("# List of known V8 instance types.\n");
1522 #define DUMP_TYPE(T) printf(" %d: \"%s\",\n", i::T, #T);
1523 printf("INSTANCE_TYPES = {\n");
1524 INSTANCE_TYPE_LIST(DUMP_TYPE)
1528 // Dump the KNOWN_MAP table to the console.
1529 printf("\n# List of known V8 maps.\n");
1530 #define ROOT_LIST_CASE(type, name, camel_name) \
1531 if (n == NULL && o == heap->name()) n = #camel_name;
1532 #define STRUCT_LIST_CASE(upper_name, camel_name, name) \
1533 if (n == NULL && o == heap->name##_map()) n = #camel_name "Map";
1534 i::HeapObjectIterator it(heap->map_space());
1535 printf("KNOWN_MAPS = {\n");
1536 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1537 i::Map* m = i::Map::cast(o);
1538 const char* n = NULL;
1539 intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff;
1540 int t = m->instance_type();
1541 ROOT_LIST(ROOT_LIST_CASE)
1542 STRUCT_LIST(STRUCT_LIST_CASE)
1543 if (n == NULL) continue;
1544 printf(" 0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n);
1547 #undef STRUCT_LIST_CASE
1548 #undef ROOT_LIST_CASE
1550 // Dump the KNOWN_OBJECTS table to the console.
1551 printf("\n# List of known V8 objects.\n");
1552 #define ROOT_LIST_CASE(type, name, camel_name) \
1553 if (n == NULL && o == heap->name()) n = #camel_name;
1554 i::OldSpaces spit(heap);
1555 printf("KNOWN_OBJECTS = {\n");
1556 for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) {
1557 i::HeapObjectIterator it(s);
1558 const char* sname = AllocationSpaceName(s->identity());
1559 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1560 const char* n = NULL;
1561 intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff;
1562 ROOT_LIST(ROOT_LIST_CASE)
1563 if (n == NULL) continue;
1564 printf(" (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n);
1568 #undef ROOT_LIST_CASE
1570 #endif // !V8_SHARED
1573 class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1575 virtual void* Allocate(size_t length) {
1576 void* data = AllocateUninitialized(length);
1577 return data == NULL ? data : memset(data, 0, length);
1579 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
1580 virtual void Free(void* data, size_t) { free(data); }
1584 class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1586 void* Allocate(size_t) OVERRIDE { return malloc(1); }
1587 void* AllocateUninitialized(size_t length) OVERRIDE { return malloc(1); }
1588 void Free(void* p, size_t) OVERRIDE { free(p); }
1592 int Shell::Main(int argc, char* argv[]) {
1593 #if (defined(_WIN32) || defined(_WIN64))
1595 SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
1596 UINT existing_flags = SetErrorMode(new_flags);
1597 SetErrorMode(existing_flags | new_flags);
1598 #if defined(_MSC_VER)
1599 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1600 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1601 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1602 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1603 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1604 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1605 _set_error_mode(_OUT_TO_STDERR);
1606 #endif // defined(_MSC_VER)
1607 #endif // defined(_WIN32) || defined(_WIN64)
1608 if (!SetOptions(argc, argv)) return 1;
1609 v8::V8::InitializeICU(options.icu_data_file);
1610 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
1611 v8::V8::InitializePlatform(platform);
1612 v8::V8::Initialize();
1613 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1614 v8::StartupDataHandler startup_data(argv[0], options.natives_blob,
1615 options.snapshot_blob);
1617 SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg");
1618 SetFlagsFromString("--trace-turbo-cfg-file=turbo.cfg");
1619 SetFlagsFromString("--redirect-code-traces-to=code.asm");
1620 ShellArrayBufferAllocator array_buffer_allocator;
1621 MockArrayBufferAllocator mock_arraybuffer_allocator;
1622 if (options.mock_arraybuffer_allocator) {
1623 v8::V8::SetArrayBufferAllocator(&mock_arraybuffer_allocator);
1625 v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
1628 Isolate::CreateParams create_params;
1629 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
1630 if (i::FLAG_gdbjit) {
1631 create_params.code_event_handler = i::GDBJITInterface::EventHandler;
1634 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1635 create_params.code_event_handler = vTune::GetVtuneCodeEventHandler();
1638 create_params.constraints.ConfigureDefaults(
1639 base::SysInfo::AmountOfPhysicalMemory(),
1640 base::SysInfo::AmountOfVirtualMemory(),
1641 base::SysInfo::NumberOfProcessors());
1643 Isolate* isolate = Isolate::New(create_params);
1644 DumbLineEditor dumb_line_editor(isolate);
1646 Isolate::Scope scope(isolate);
1647 Initialize(isolate);
1648 PerIsolateData data(isolate);
1649 InitializeDebugger(isolate);
1652 if (options.dump_heap_constants) {
1653 DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate));
1658 if (options.stress_opt || options.stress_deopt) {
1659 Testing::SetStressRunType(options.stress_opt
1660 ? Testing::kStressTypeOpt
1661 : Testing::kStressTypeDeopt);
1662 int stress_runs = Testing::GetStressRuns();
1663 for (int i = 0; i < stress_runs && result == 0; i++) {
1664 printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1665 Testing::PrepareStressRun(i);
1666 options.last_run = (i == stress_runs - 1);
1667 result = RunMain(isolate, argc, argv);
1669 printf("======== Full Deoptimization =======\n");
1670 Testing::DeoptimizeAll();
1671 #if !defined(V8_SHARED)
1672 } else if (i::FLAG_stress_runs > 0) {
1673 int stress_runs = i::FLAG_stress_runs;
1674 for (int i = 0; i < stress_runs && result == 0; i++) {
1675 printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1676 options.last_run = (i == stress_runs - 1);
1677 result = RunMain(isolate, argc, argv);
1681 result = RunMain(isolate, argc, argv);
1684 // Run interactive shell if explicitly requested or if no script has been
1685 // executed, but never on --test
1686 if (options.use_interactive_shell()) {
1688 if (!i::FLAG_debugger) {
1689 InstallUtilityScript(isolate);
1691 #endif // !V8_SHARED
1697 // Dump basic block profiling data.
1698 if (i::BasicBlockProfiler* profiler =
1699 reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) {
1700 i::OFStream os(stdout);
1703 #endif // !V8_SHARED
1706 V8::ShutdownPlatform();
1716 int main(int argc, char* argv[]) {
1717 return v8::Shell::Main(argc, argv);