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/snapshot/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 v8::Platform* g_platform = NULL;
80 static Handle<Value> Throw(Isolate* isolate, const char* message) {
81 return isolate->ThrowException(String::NewFromUtf8(isolate, message));
86 class PerIsolateData {
88 explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
89 HandleScope scope(isolate);
90 isolate->SetData(0, this);
94 isolate_->SetData(0, NULL); // Not really needed, just to be sure...
97 inline static PerIsolateData* Get(Isolate* isolate) {
98 return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
103 explicit RealmScope(PerIsolateData* data);
106 PerIsolateData* data_;
111 friend class RealmScope;
116 Persistent<Context>* realms_;
117 Persistent<Value> realm_shared_;
119 int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
121 int RealmFind(Handle<Context> context);
125 LineEditor *LineEditor::current_ = NULL;
128 LineEditor::LineEditor(Type type, const char* name)
129 : type_(type), name_(name) {
130 if (current_ == NULL || current_->type_ < type) current_ = this;
134 class DumbLineEditor: public LineEditor {
136 explicit DumbLineEditor(Isolate* isolate)
137 : LineEditor(LineEditor::DUMB, "dumb"), isolate_(isolate) { }
138 virtual Handle<String> Prompt(const char* prompt);
144 Handle<String> DumbLineEditor::Prompt(const char* prompt) {
145 printf("%s", prompt);
146 #if defined(__native_client__)
147 // Native Client libc is used to being embedded in Chrome and
148 // has trouble recognizing when to flush.
151 return Shell::ReadFromStdin(isolate_);
156 CounterMap* Shell::counter_map_;
157 base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
158 CounterCollection Shell::local_counters_;
159 CounterCollection* Shell::counters_ = &local_counters_;
160 base::Mutex Shell::context_mutex_;
161 const base::TimeTicks Shell::kInitialTicks =
162 base::TimeTicks::HighResolutionNow();
163 Persistent<Context> Shell::utility_context_;
166 Persistent<Context> Shell::evaluation_context_;
167 ShellOptions Shell::options;
168 const char* Shell::kPrompt = "d8> ";
172 const int MB = 1024 * 1024;
174 bool CounterMap::Match(void* key1, void* key2) {
175 const char* name1 = reinterpret_cast<const char*>(key1);
176 const char* name2 = reinterpret_cast<const char*>(key2);
177 return strcmp(name1, name2) == 0;
182 // Converts a V8 value to a C string.
183 const char* Shell::ToCString(const v8::String::Utf8Value& value) {
184 return *value ? *value : "<string conversion failed>";
188 ScriptCompiler::CachedData* CompileForCachedData(
189 Local<String> source, Local<Value> name,
190 ScriptCompiler::CompileOptions compile_options) {
191 int source_length = source->Length();
192 uint16_t* source_buffer = new uint16_t[source_length];
193 source->Write(source_buffer, 0, source_length);
195 uint16_t* name_buffer = NULL;
196 if (name->IsString()) {
197 Local<String> name_string = Local<String>::Cast(name);
198 name_length = name_string->Length();
199 name_buffer = new uint16_t[name_length];
200 name_string->Write(name_buffer, 0, name_length);
202 Isolate* temp_isolate = Isolate::New();
203 ScriptCompiler::CachedData* result = NULL;
205 Isolate::Scope isolate_scope(temp_isolate);
206 HandleScope handle_scope(temp_isolate);
207 Context::Scope context_scope(Context::New(temp_isolate));
208 Local<String> source_copy = v8::String::NewFromTwoByte(
209 temp_isolate, source_buffer, v8::String::kNormalString, source_length);
210 Local<Value> name_copy;
212 name_copy = v8::String::NewFromTwoByte(
213 temp_isolate, name_buffer, v8::String::kNormalString, name_length);
215 name_copy = v8::Undefined(temp_isolate);
217 ScriptCompiler::Source script_source(source_copy, ScriptOrigin(name_copy));
218 ScriptCompiler::CompileUnbound(temp_isolate, &script_source,
220 if (script_source.GetCachedData()) {
221 int length = script_source.GetCachedData()->length;
222 uint8_t* cache = new uint8_t[length];
223 memcpy(cache, script_source.GetCachedData()->data, length);
224 result = new ScriptCompiler::CachedData(
225 cache, length, ScriptCompiler::CachedData::BufferOwned);
228 temp_isolate->Dispose();
229 delete[] source_buffer;
230 delete[] name_buffer;
235 // Compile a string within the current v8 context.
236 Local<Script> Shell::CompileString(
237 Isolate* isolate, Local<String> source, Local<Value> name,
238 ScriptCompiler::CompileOptions compile_options, SourceType source_type) {
239 ScriptOrigin origin(name);
240 if (compile_options == ScriptCompiler::kNoCompileOptions) {
241 ScriptCompiler::Source script_source(source, origin);
242 return source_type == SCRIPT
243 ? ScriptCompiler::Compile(isolate, &script_source,
245 : ScriptCompiler::CompileModule(isolate, &script_source,
249 ScriptCompiler::CachedData* data =
250 CompileForCachedData(source, name, compile_options);
251 ScriptCompiler::Source cached_source(source, origin, data);
252 if (compile_options == ScriptCompiler::kProduceCodeCache) {
253 compile_options = ScriptCompiler::kConsumeCodeCache;
254 } else if (compile_options == ScriptCompiler::kProduceParserCache) {
255 compile_options = ScriptCompiler::kConsumeParserCache;
257 DCHECK(false); // A new compile option?
259 if (data == NULL) compile_options = ScriptCompiler::kNoCompileOptions;
260 Local<Script> result =
261 source_type == SCRIPT
262 ? ScriptCompiler::Compile(isolate, &cached_source, compile_options)
263 : ScriptCompiler::CompileModule(isolate, &cached_source,
265 CHECK(data == NULL || !data->rejected);
270 // Executes a string within the current v8 context.
271 bool Shell::ExecuteString(Isolate* isolate, Handle<String> source,
272 Handle<Value> name, bool print_result,
273 bool report_exceptions, SourceType source_type) {
275 bool FLAG_debugger = i::FLAG_debugger;
277 bool FLAG_debugger = false;
279 HandleScope handle_scope(isolate);
281 options.script_executed = true;
283 // When debugging make exceptions appear to be uncaught.
284 try_catch.SetVerbose(true);
287 Handle<Value> result;
289 PerIsolateData* data = PerIsolateData::Get(isolate);
290 Local<Context> realm =
291 Local<Context>::New(isolate, data->realms_[data->realm_current_]);
292 Context::Scope context_scope(realm);
293 Handle<Script> script = Shell::CompileString(
294 isolate, source, name, options.compile_options, source_type);
295 if (script.IsEmpty()) {
296 // Print errors that happened during compilation.
297 if (report_exceptions && !FLAG_debugger)
298 ReportException(isolate, &try_catch);
301 result = script->Run();
302 data->realm_current_ = data->realm_switch_;
304 if (result.IsEmpty()) {
305 DCHECK(try_catch.HasCaught());
306 // Print errors that happened during execution.
307 if (report_exceptions && !FLAG_debugger)
308 ReportException(isolate, &try_catch);
311 DCHECK(!try_catch.HasCaught());
313 #if !defined(V8_SHARED)
314 if (options.test_shell) {
316 if (!result->IsUndefined()) {
317 // If all went well and the result wasn't undefined then print
318 // the returned value.
319 v8::String::Utf8Value str(result);
320 fwrite(*str, sizeof(**str), str.length(), stdout);
323 #if !defined(V8_SHARED)
325 v8::TryCatch try_catch;
326 v8::Local<v8::Context> context =
327 v8::Local<v8::Context>::New(isolate, utility_context_);
328 v8::Context::Scope context_scope(context);
329 Handle<Object> global = context->Global();
331 global->Get(String::NewFromUtf8(isolate, "Stringify"));
332 Handle<Value> argv[1] = {result};
333 Handle<Value> s = Handle<Function>::Cast(fun)->Call(global, 1, argv);
334 if (try_catch.HasCaught()) return true;
335 v8::String::Utf8Value str(s);
336 fwrite(*str, sizeof(**str), str.length(), stdout);
345 PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
346 data_->realm_count_ = 1;
347 data_->realm_current_ = 0;
348 data_->realm_switch_ = 0;
349 data_->realms_ = new Persistent<Context>[1];
350 data_->realms_[0].Reset(data_->isolate_,
351 data_->isolate_->GetEnteredContext());
355 PerIsolateData::RealmScope::~RealmScope() {
356 // Drop realms to avoid keeping them alive.
357 for (int i = 0; i < data_->realm_count_; ++i)
358 data_->realms_[i].Reset();
359 delete[] data_->realms_;
360 if (!data_->realm_shared_.IsEmpty())
361 data_->realm_shared_.Reset();
365 int PerIsolateData::RealmFind(Handle<Context> context) {
366 for (int i = 0; i < realm_count_; ++i) {
367 if (realms_[i] == context) return i;
373 int PerIsolateData::RealmIndexOrThrow(
374 const v8::FunctionCallbackInfo<v8::Value>& args,
376 if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
377 Throw(args.GetIsolate(), "Invalid argument");
380 int index = args[arg_offset]->Int32Value();
382 index >= realm_count_ ||
383 realms_[index].IsEmpty()) {
384 Throw(args.GetIsolate(), "Invalid realm index");
392 // performance.now() returns a time stamp as double, measured in milliseconds.
393 // When FLAG_verify_predictable mode is enabled it returns current value
394 // of Heap::allocations_count().
395 void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
396 if (i::FLAG_verify_predictable) {
397 Isolate* v8_isolate = args.GetIsolate();
398 i::Heap* heap = reinterpret_cast<i::Isolate*>(v8_isolate)->heap();
399 args.GetReturnValue().Set(heap->synthetic_time());
401 base::TimeDelta delta =
402 base::TimeTicks::HighResolutionNow() - kInitialTicks;
403 args.GetReturnValue().Set(delta.InMillisecondsF());
409 // Realm.current() returns the index of the currently active realm.
410 void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
411 Isolate* isolate = args.GetIsolate();
412 PerIsolateData* data = PerIsolateData::Get(isolate);
413 int index = data->RealmFind(isolate->GetEnteredContext());
414 if (index == -1) return;
415 args.GetReturnValue().Set(index);
419 // Realm.owner(o) returns the index of the realm that created o.
420 void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
421 Isolate* isolate = args.GetIsolate();
422 PerIsolateData* data = PerIsolateData::Get(isolate);
423 if (args.Length() < 1 || !args[0]->IsObject()) {
424 Throw(args.GetIsolate(), "Invalid argument");
427 int index = data->RealmFind(args[0]->ToObject(isolate)->CreationContext());
428 if (index == -1) return;
429 args.GetReturnValue().Set(index);
433 // Realm.global(i) returns the global object of realm i.
434 // (Note that properties of global objects cannot be read/written cross-realm.)
435 void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
436 PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
437 int index = data->RealmIndexOrThrow(args, 0);
438 if (index == -1) return;
439 args.GetReturnValue().Set(
440 Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
444 // Realm.create() creates a new realm and returns its index.
445 void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
446 Isolate* isolate = args.GetIsolate();
447 PerIsolateData* data = PerIsolateData::Get(isolate);
448 Persistent<Context>* old_realms = data->realms_;
449 int index = data->realm_count_;
450 data->realms_ = new Persistent<Context>[++data->realm_count_];
451 for (int i = 0; i < index; ++i) {
452 data->realms_[i].Reset(isolate, old_realms[i]);
455 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
456 data->realms_[index].Reset(
457 isolate, Context::New(isolate, NULL, global_template));
458 args.GetReturnValue().Set(index);
462 // Realm.dispose(i) disposes the reference to the realm i.
463 void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
464 Isolate* isolate = args.GetIsolate();
465 PerIsolateData* data = PerIsolateData::Get(isolate);
466 int index = data->RealmIndexOrThrow(args, 0);
467 if (index == -1) return;
469 index == data->realm_current_ || index == data->realm_switch_) {
470 Throw(args.GetIsolate(), "Invalid realm index");
473 data->realms_[index].Reset();
477 // Realm.switch(i) switches to the realm i for consecutive interactive inputs.
478 void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
479 Isolate* isolate = args.GetIsolate();
480 PerIsolateData* data = PerIsolateData::Get(isolate);
481 int index = data->RealmIndexOrThrow(args, 0);
482 if (index == -1) return;
483 data->realm_switch_ = index;
487 // Realm.eval(i, s) evaluates s in realm i and returns the result.
488 void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
489 Isolate* isolate = args.GetIsolate();
490 PerIsolateData* data = PerIsolateData::Get(isolate);
491 int index = data->RealmIndexOrThrow(args, 0);
492 if (index == -1) return;
493 if (args.Length() < 2 || !args[1]->IsString()) {
494 Throw(args.GetIsolate(), "Invalid argument");
497 ScriptCompiler::Source script_source(args[1]->ToString(isolate));
498 Handle<UnboundScript> script = ScriptCompiler::CompileUnbound(
499 isolate, &script_source);
500 if (script.IsEmpty()) return;
501 Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
503 Handle<Value> result = script->BindToCurrentContext()->Run();
505 args.GetReturnValue().Set(result);
509 // Realm.shared is an accessor for a single shared value across realms.
510 void Shell::RealmSharedGet(Local<String> property,
511 const PropertyCallbackInfo<Value>& info) {
512 Isolate* isolate = info.GetIsolate();
513 PerIsolateData* data = PerIsolateData::Get(isolate);
514 if (data->realm_shared_.IsEmpty()) return;
515 info.GetReturnValue().Set(data->realm_shared_);
518 void Shell::RealmSharedSet(Local<String> property,
520 const PropertyCallbackInfo<void>& info) {
521 Isolate* isolate = info.GetIsolate();
522 PerIsolateData* data = PerIsolateData::Get(isolate);
523 data->realm_shared_.Reset(isolate, value);
527 void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
534 void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
535 for (int i = 0; i < args.Length(); i++) {
536 HandleScope handle_scope(args.GetIsolate());
541 // Explicitly catch potential exceptions in toString().
542 v8::TryCatch try_catch;
543 Handle<String> str_obj = args[i]->ToString(args.GetIsolate());
544 if (try_catch.HasCaught()) {
549 v8::String::Utf8Value str(str_obj);
550 int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
551 if (n != str.length()) {
552 printf("Error in fwrite\n");
559 void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
560 String::Utf8Value file(args[0]);
562 Throw(args.GetIsolate(), "Error loading file");
565 Handle<String> source = ReadFile(args.GetIsolate(), *file);
566 if (source.IsEmpty()) {
567 Throw(args.GetIsolate(), "Error loading file");
570 args.GetReturnValue().Set(source);
574 Handle<String> Shell::ReadFromStdin(Isolate* isolate) {
575 static const int kBufferSize = 256;
576 char buffer[kBufferSize];
577 Handle<String> accumulator = String::NewFromUtf8(isolate, "");
580 // Continue reading if the line ends with an escape '\\' or the line has
581 // not been fully read into the buffer yet (does not end with '\n').
582 // If fgets gets an error, just give up.
584 input = fgets(buffer, kBufferSize, stdin);
585 if (input == NULL) return Handle<String>();
586 length = static_cast<int>(strlen(buffer));
589 } else if (buffer[length-1] != '\n') {
590 accumulator = String::Concat(
592 String::NewFromUtf8(isolate, buffer, String::kNormalString, length));
593 } else if (length > 1 && buffer[length-2] == '\\') {
594 buffer[length-2] = '\n';
595 accumulator = String::Concat(
596 accumulator, String::NewFromUtf8(isolate, buffer,
597 String::kNormalString, length - 1));
599 return String::Concat(
600 accumulator, String::NewFromUtf8(isolate, buffer,
601 String::kNormalString, length - 1));
607 void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
608 for (int i = 0; i < args.Length(); i++) {
609 HandleScope handle_scope(args.GetIsolate());
610 String::Utf8Value file(args[i]);
612 Throw(args.GetIsolate(), "Error loading file");
615 Handle<String> source = ReadFile(args.GetIsolate(), *file);
616 if (source.IsEmpty()) {
617 Throw(args.GetIsolate(), "Error loading file");
620 if (!ExecuteString(args.GetIsolate(),
622 String::NewFromUtf8(args.GetIsolate(), *file),
625 Throw(args.GetIsolate(), "Error executing file");
632 void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
633 int exit_code = args[0]->Int32Value();
634 OnExit(args.GetIsolate());
639 void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
640 args.GetReturnValue().Set(
641 String::NewFromUtf8(args.GetIsolate(), V8::GetVersion()));
645 void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
646 HandleScope handle_scope(isolate);
648 Handle<Context> utility_context;
649 bool enter_context = !isolate->InContext();
651 utility_context = Local<Context>::New(isolate, utility_context_);
652 utility_context->Enter();
655 v8::String::Utf8Value exception(try_catch->Exception());
656 const char* exception_string = ToCString(exception);
657 Handle<Message> message = try_catch->Message();
658 if (message.IsEmpty()) {
659 // V8 didn't provide any extra information about this error; just
660 // print the exception.
661 printf("%s\n", exception_string);
663 // Print (filename):(line number): (message).
664 v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
665 const char* filename_string = ToCString(filename);
666 int linenum = message->GetLineNumber();
667 printf("%s:%i: %s\n", filename_string, linenum, exception_string);
668 // Print line of source code.
669 v8::String::Utf8Value sourceline(message->GetSourceLine());
670 const char* sourceline_string = ToCString(sourceline);
671 printf("%s\n", sourceline_string);
672 // Print wavy underline (GetUnderline is deprecated).
673 int start = message->GetStartColumn();
674 for (int i = 0; i < start; i++) {
677 int end = message->GetEndColumn();
678 for (int i = start; i < end; i++) {
682 v8::String::Utf8Value stack_trace(try_catch->StackTrace());
683 if (stack_trace.length() > 0) {
684 const char* stack_trace_string = ToCString(stack_trace);
685 printf("%s\n", stack_trace_string);
690 if (enter_context) utility_context->Exit();
696 Handle<Array> Shell::GetCompletions(Isolate* isolate,
698 Handle<String> full) {
699 EscapableHandleScope handle_scope(isolate);
700 v8::Local<v8::Context> utility_context =
701 v8::Local<v8::Context>::New(isolate, utility_context_);
702 v8::Context::Scope context_scope(utility_context);
703 Handle<Object> global = utility_context->Global();
705 global->Get(String::NewFromUtf8(isolate, "GetCompletions"));
706 static const int kArgc = 3;
707 v8::Local<v8::Context> evaluation_context =
708 v8::Local<v8::Context>::New(isolate, evaluation_context_);
709 Handle<Value> argv[kArgc] = { evaluation_context->Global(), text, full };
710 Local<Value> val = Local<Function>::Cast(fun)->Call(global, kArgc, argv);
711 return handle_scope.Escape(Local<Array>::Cast(val));
715 Local<Object> Shell::DebugMessageDetails(Isolate* isolate,
716 Handle<String> message) {
717 EscapableHandleScope handle_scope(isolate);
718 v8::Local<v8::Context> context =
719 v8::Local<v8::Context>::New(isolate, utility_context_);
720 v8::Context::Scope context_scope(context);
721 Handle<Object> global = context->Global();
723 global->Get(String::NewFromUtf8(isolate, "DebugMessageDetails"));
724 static const int kArgc = 1;
725 Handle<Value> argv[kArgc] = { message };
726 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
727 return handle_scope.Escape(Local<Object>(Handle<Object>::Cast(val)));
731 Local<Value> Shell::DebugCommandToJSONRequest(Isolate* isolate,
732 Handle<String> command) {
733 EscapableHandleScope handle_scope(isolate);
734 v8::Local<v8::Context> context =
735 v8::Local<v8::Context>::New(isolate, utility_context_);
736 v8::Context::Scope context_scope(context);
737 Handle<Object> global = context->Global();
739 global->Get(String::NewFromUtf8(isolate, "DebugCommandToJSONRequest"));
740 static const int kArgc = 1;
741 Handle<Value> argv[kArgc] = { command };
742 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
743 return handle_scope.Escape(Local<Value>(val));
747 int32_t* Counter::Bind(const char* name, bool is_histogram) {
749 for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
750 name_[i] = static_cast<char>(name[i]);
752 is_histogram_ = is_histogram;
757 void Counter::AddSample(int32_t sample) {
759 sample_total_ += sample;
763 CounterCollection::CounterCollection() {
764 magic_number_ = 0xDEADFACE;
765 max_counters_ = kMaxCounters;
766 max_name_size_ = Counter::kMaxNameSize;
767 counters_in_use_ = 0;
771 Counter* CounterCollection::GetNextCounter() {
772 if (counters_in_use_ == kMaxCounters) return NULL;
773 return &counters_[counters_in_use_++];
777 void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
778 counters_file_ = base::OS::MemoryMappedFile::create(
779 name, sizeof(CounterCollection), &local_counters_);
780 void* memory = (counters_file_ == NULL) ?
781 NULL : counters_file_->memory();
782 if (memory == NULL) {
783 printf("Could not map counters file %s\n", name);
786 counters_ = static_cast<CounterCollection*>(memory);
787 isolate->SetCounterFunction(LookupCounter);
788 isolate->SetCreateHistogramFunction(CreateHistogram);
789 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
793 int CounterMap::Hash(const char* name) {
796 while ((c = *name++) != 0) {
804 Counter* Shell::GetCounter(const char* name, bool is_histogram) {
805 Counter* counter = counter_map_->Lookup(name);
807 if (counter == NULL) {
808 counter = counters_->GetNextCounter();
809 if (counter != NULL) {
810 counter_map_->Set(name, counter);
811 counter->Bind(name, is_histogram);
814 DCHECK(counter->is_histogram() == is_histogram);
820 int* Shell::LookupCounter(const char* name) {
821 Counter* counter = GetCounter(name, false);
823 if (counter != NULL) {
824 return counter->ptr();
831 void* Shell::CreateHistogram(const char* name,
835 return GetCounter(name, true);
839 void Shell::AddHistogramSample(void* histogram, int sample) {
840 Counter* counter = reinterpret_cast<Counter*>(histogram);
841 counter->AddSample(sample);
845 class NoUseStrongForUtilityScriptScope {
847 NoUseStrongForUtilityScriptScope() : flag_(i::FLAG_use_strong) {
848 i::FLAG_use_strong = false;
850 ~NoUseStrongForUtilityScriptScope() { i::FLAG_use_strong = flag_; }
857 void Shell::InstallUtilityScript(Isolate* isolate) {
858 NoUseStrongForUtilityScriptScope no_use_strong;
859 HandleScope scope(isolate);
860 // If we use the utility context, we have to set the security tokens so that
861 // utility, evaluation and debug context can all access each other.
862 v8::Local<v8::Context> utility_context =
863 v8::Local<v8::Context>::New(isolate, utility_context_);
864 v8::Local<v8::Context> evaluation_context =
865 v8::Local<v8::Context>::New(isolate, evaluation_context_);
866 utility_context->SetSecurityToken(Undefined(isolate));
867 evaluation_context->SetSecurityToken(Undefined(isolate));
868 v8::Context::Scope context_scope(utility_context);
870 if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
871 // Install the debugger object in the utility scope
872 i::Debug* debug = reinterpret_cast<i::Isolate*>(isolate)->debug();
874 i::Handle<i::Context> debug_context = debug->debug_context();
875 i::Handle<i::JSObject> js_debug
876 = i::Handle<i::JSObject>(debug_context->global_object());
877 utility_context->Global()->Set(String::NewFromUtf8(isolate, "$debug"),
878 Utils::ToLocal(js_debug));
879 debug_context->set_security_token(
880 reinterpret_cast<i::Isolate*>(isolate)->heap()->undefined_value());
882 // Run the d8 shell utility script in the utility context
883 int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
884 i::Vector<const char> shell_source =
885 i::NativesCollection<i::D8>::GetScriptSource(source_index);
886 i::Vector<const char> shell_source_name =
887 i::NativesCollection<i::D8>::GetScriptName(source_index);
888 Handle<String> source =
889 String::NewFromUtf8(isolate, shell_source.start(), String::kNormalString,
890 shell_source.length());
891 Handle<String> name =
892 String::NewFromUtf8(isolate, shell_source_name.start(),
893 String::kNormalString, shell_source_name.length());
894 ScriptOrigin origin(name);
895 Handle<Script> script = Script::Compile(source, &origin);
897 // Mark the d8 shell script as native to avoid it showing up as normal source
899 i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
900 i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
901 ? i::Handle<i::Script>(i::Script::cast(
902 i::JSFunction::cast(*compiled_script)->shared()->script()))
903 : i::Handle<i::Script>(i::Script::cast(
904 i::SharedFunctionInfo::cast(*compiled_script)->script()));
905 script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
907 // Start the in-process debugger if requested.
908 if (i::FLAG_debugger) v8::Debug::SetDebugEventListener(HandleDebugEvent);
913 Handle<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
914 Handle<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
915 global_template->Set(String::NewFromUtf8(isolate, "print"),
916 FunctionTemplate::New(isolate, Print));
917 global_template->Set(String::NewFromUtf8(isolate, "write"),
918 FunctionTemplate::New(isolate, Write));
919 global_template->Set(String::NewFromUtf8(isolate, "read"),
920 FunctionTemplate::New(isolate, Read));
921 global_template->Set(String::NewFromUtf8(isolate, "readbuffer"),
922 FunctionTemplate::New(isolate, ReadBuffer));
923 global_template->Set(String::NewFromUtf8(isolate, "readline"),
924 FunctionTemplate::New(isolate, ReadLine));
925 global_template->Set(String::NewFromUtf8(isolate, "load"),
926 FunctionTemplate::New(isolate, Load));
927 global_template->Set(String::NewFromUtf8(isolate, "quit"),
928 FunctionTemplate::New(isolate, Quit));
929 global_template->Set(String::NewFromUtf8(isolate, "version"),
930 FunctionTemplate::New(isolate, Version));
932 // Bind the Realm object.
933 Handle<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
934 realm_template->Set(String::NewFromUtf8(isolate, "current"),
935 FunctionTemplate::New(isolate, RealmCurrent));
936 realm_template->Set(String::NewFromUtf8(isolate, "owner"),
937 FunctionTemplate::New(isolate, RealmOwner));
938 realm_template->Set(String::NewFromUtf8(isolate, "global"),
939 FunctionTemplate::New(isolate, RealmGlobal));
940 realm_template->Set(String::NewFromUtf8(isolate, "create"),
941 FunctionTemplate::New(isolate, RealmCreate));
942 realm_template->Set(String::NewFromUtf8(isolate, "dispose"),
943 FunctionTemplate::New(isolate, RealmDispose));
944 realm_template->Set(String::NewFromUtf8(isolate, "switch"),
945 FunctionTemplate::New(isolate, RealmSwitch));
946 realm_template->Set(String::NewFromUtf8(isolate, "eval"),
947 FunctionTemplate::New(isolate, RealmEval));
948 realm_template->SetAccessor(String::NewFromUtf8(isolate, "shared"),
949 RealmSharedGet, RealmSharedSet);
950 global_template->Set(String::NewFromUtf8(isolate, "Realm"), realm_template);
953 Handle<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
954 performance_template->Set(String::NewFromUtf8(isolate, "now"),
955 FunctionTemplate::New(isolate, PerformanceNow));
956 global_template->Set(String::NewFromUtf8(isolate, "performance"),
957 performance_template);
960 Handle<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
961 AddOSMethods(isolate, os_templ);
962 global_template->Set(String::NewFromUtf8(isolate, "os"), os_templ);
964 return global_template;
968 void Shell::Initialize(Isolate* isolate) {
971 if (i::StrLength(i::FLAG_map_counters) != 0)
972 MapCounters(isolate, i::FLAG_map_counters);
977 void Shell::InitializeDebugger(Isolate* isolate) {
978 if (options.test_shell) return;
980 HandleScope scope(isolate);
981 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
982 utility_context_.Reset(isolate,
983 Context::New(isolate, NULL, global_template));
988 Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
990 // This needs to be a critical section since this is not thread-safe
991 base::LockGuard<base::Mutex> lock_guard(&context_mutex_);
993 // Initialize the global objects
994 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
995 EscapableHandleScope handle_scope(isolate);
996 Local<Context> context = Context::New(isolate, NULL, global_template);
997 DCHECK(!context.IsEmpty());
998 Context::Scope scope(context);
1001 i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
1002 i::JSArguments js_args = i::FLAG_js_arguments;
1003 i::Handle<i::FixedArray> arguments_array =
1004 factory->NewFixedArray(js_args.argc);
1005 for (int j = 0; j < js_args.argc; j++) {
1006 i::Handle<i::String> arg =
1007 factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
1008 arguments_array->set(j, *arg);
1010 i::Handle<i::JSArray> arguments_jsarray =
1011 factory->NewJSArrayWithElements(arguments_array);
1012 context->Global()->Set(String::NewFromUtf8(isolate, "arguments"),
1013 Utils::ToLocal(arguments_jsarray));
1014 #endif // !V8_SHARED
1015 return handle_scope.Escape(context);
1019 void Shell::Exit(int exit_code) {
1020 // Use _exit instead of exit to avoid races between isolate
1021 // threads and static destructors.
1029 struct CounterAndKey {
1035 inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
1036 return strcmp(lhs.key, rhs.key) < 0;
1038 #endif // !V8_SHARED
1041 void Shell::OnExit(v8::Isolate* isolate) {
1042 LineEditor* line_editor = LineEditor::Get();
1043 if (line_editor) line_editor->Close();
1045 reinterpret_cast<i::Isolate*>(isolate)->DumpAndResetCompilationStats();
1046 if (i::FLAG_dump_counters) {
1047 int number_of_counters = 0;
1048 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1049 number_of_counters++;
1051 CounterAndKey* counters = new CounterAndKey[number_of_counters];
1053 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
1054 counters[j].counter = i.CurrentValue();
1055 counters[j].key = i.CurrentKey();
1057 std::sort(counters, counters + number_of_counters);
1058 printf("+----------------------------------------------------------------+"
1059 "-------------+\n");
1062 printf("+----------------------------------------------------------------+"
1063 "-------------+\n");
1064 for (j = 0; j < number_of_counters; j++) {
1065 Counter* counter = counters[j].counter;
1066 const char* key = counters[j].key;
1067 if (counter->is_histogram()) {
1068 printf("| c:%-60s | %11i |\n", key, counter->count());
1069 printf("| t:%-60s | %11i |\n", key, counter->sample_total());
1071 printf("| %-62s | %11i |\n", key, counter->count());
1074 printf("+----------------------------------------------------------------+"
1075 "-------------+\n");
1078 delete counters_file_;
1079 delete counter_map_;
1080 #endif // !V8_SHARED
1085 static FILE* FOpen(const char* path, const char* mode) {
1086 #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
1088 if (fopen_s(&result, path, mode) == 0) {
1094 FILE* file = fopen(path, mode);
1095 if (file == NULL) return NULL;
1096 struct stat file_stat;
1097 if (fstat(fileno(file), &file_stat) != 0) return NULL;
1098 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
1099 if (is_regular_file) return file;
1106 static char* ReadChars(Isolate* isolate, const char* name, int* size_out) {
1107 FILE* file = FOpen(name, "rb");
1108 if (file == NULL) return NULL;
1110 fseek(file, 0, SEEK_END);
1111 int size = ftell(file);
1114 char* chars = new char[size + 1];
1116 for (int i = 0; i < size;) {
1117 int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1126 struct DataAndPersistent {
1128 Persistent<ArrayBuffer> handle;
1132 static void ReadBufferWeakCallback(
1133 const v8::WeakCallbackData<ArrayBuffer, DataAndPersistent>& data) {
1134 size_t byte_length = data.GetValue()->ByteLength();
1135 data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
1136 -static_cast<intptr_t>(byte_length));
1138 delete[] data.GetParameter()->data;
1139 data.GetParameter()->handle.Reset();
1140 delete data.GetParameter();
1144 void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
1145 DCHECK(sizeof(char) == sizeof(uint8_t)); // NOLINT
1146 String::Utf8Value filename(args[0]);
1148 if (*filename == NULL) {
1149 Throw(args.GetIsolate(), "Error loading file");
1153 Isolate* isolate = args.GetIsolate();
1154 DataAndPersistent* data = new DataAndPersistent;
1155 data->data = reinterpret_cast<uint8_t*>(
1156 ReadChars(args.GetIsolate(), *filename, &length));
1157 if (data->data == NULL) {
1159 Throw(args.GetIsolate(), "Error reading file");
1162 Handle<v8::ArrayBuffer> buffer =
1163 ArrayBuffer::New(isolate, data->data, length);
1164 data->handle.Reset(isolate, buffer);
1165 data->handle.SetWeak(data, ReadBufferWeakCallback);
1166 data->handle.MarkIndependent();
1167 isolate->AdjustAmountOfExternalAllocatedMemory(length);
1169 args.GetReturnValue().Set(buffer);
1173 // Reads a file into a v8 string.
1174 Handle<String> Shell::ReadFile(Isolate* isolate, const char* name) {
1176 char* chars = ReadChars(isolate, name, &size);
1177 if (chars == NULL) return Handle<String>();
1178 Handle<String> result =
1179 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1185 void Shell::RunShell(Isolate* isolate) {
1186 HandleScope outer_scope(isolate);
1187 v8::Local<v8::Context> context =
1188 v8::Local<v8::Context>::New(isolate, evaluation_context_);
1189 v8::Context::Scope context_scope(context);
1190 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1191 Handle<String> name = String::NewFromUtf8(isolate, "(d8)");
1192 LineEditor* console = LineEditor::Get();
1193 printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
1194 console->Open(isolate);
1196 HandleScope inner_scope(isolate);
1197 Handle<String> input = console->Prompt(Shell::kPrompt);
1198 if (input.IsEmpty()) break;
1199 ExecuteString(isolate, input, name, true, true);
1205 SourceGroup::~SourceGroup() {
1209 #endif // !V8_SHARED
1213 void SourceGroup::Execute(Isolate* isolate) {
1214 bool exception_was_thrown = false;
1215 for (int i = begin_offset_; i < end_offset_; ++i) {
1216 const char* arg = argv_[i];
1217 Shell::SourceType source_type = Shell::SCRIPT;
1218 if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
1219 // Execute argument given to -e option directly.
1220 HandleScope handle_scope(isolate);
1221 Handle<String> file_name = String::NewFromUtf8(isolate, "unnamed");
1222 Handle<String> source = String::NewFromUtf8(isolate, argv_[i + 1]);
1223 if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1224 exception_was_thrown = true;
1229 } else if (strcmp(arg, "--module") == 0 && i + 1 < end_offset_) {
1230 // Treat the next file as a module.
1231 source_type = Shell::MODULE;
1233 } else if (arg[0] == '-') {
1234 // Ignore other options. They have been parsed already.
1238 // Use all other arguments as names of files to load and run.
1239 HandleScope handle_scope(isolate);
1240 Handle<String> file_name = String::NewFromUtf8(isolate, arg);
1241 Handle<String> source = ReadFile(isolate, arg);
1242 if (source.IsEmpty()) {
1243 printf("Error reading '%s'\n", arg);
1246 if (!Shell::ExecuteString(isolate, source, file_name, false, true,
1248 exception_was_thrown = true;
1252 if (exception_was_thrown != Shell::options.expected_to_throw) {
1258 Handle<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
1260 char* chars = ReadChars(isolate, name, &size);
1261 if (chars == NULL) return Handle<String>();
1262 Handle<String> result =
1263 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1270 base::Thread::Options SourceGroup::GetThreadOptions() {
1271 // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
1272 // which is not enough to parse the big literal expressions used in tests.
1273 // The stack size should be at least StackGuard::kLimitSize + some
1274 // OS-specific padding for thread startup code. 2Mbytes seems to be enough.
1275 return base::Thread::Options("IsolateThread", 2 * MB);
1279 void SourceGroup::ExecuteInThread() {
1280 Isolate* isolate = Isolate::New();
1282 next_semaphore_.Wait();
1284 Isolate::Scope iscope(isolate);
1286 HandleScope scope(isolate);
1287 PerIsolateData data(isolate);
1288 Local<Context> context = Shell::CreateEvaluationContext(isolate);
1290 Context::Scope cscope(context);
1291 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1295 if (Shell::options.send_idle_notification) {
1296 const double kLongIdlePauseInSeconds = 1.0;
1297 isolate->ContextDisposedNotification();
1298 isolate->IdleNotificationDeadline(
1299 g_platform->MonotonicallyIncreasingTime() +
1300 kLongIdlePauseInSeconds);
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 double kLongIdlePauseInSeconds = 1.0;
1497 isolate->ContextDisposedNotification();
1498 isolate->IdleNotificationDeadline(
1499 g_platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds);
1501 if (options.invoke_weak_callbacks) {
1502 // By sending a low memory notifications, we will try hard to collect all
1503 // garbage and will therefore also invoke all weak callbacks of actually
1504 // unreachable persistent handles.
1505 isolate->LowMemoryNotification();
1509 for (int i = 1; i < options.num_isolates; ++i) {
1510 options.isolate_sources[i].WaitForThread();
1512 #endif // !V8_SHARED
1518 static void DumpHeapConstants(i::Isolate* isolate) {
1519 i::Heap* heap = isolate->heap();
1521 // Dump the INSTANCE_TYPES table to the console.
1522 printf("# List of known V8 instance types.\n");
1523 #define DUMP_TYPE(T) printf(" %d: \"%s\",\n", i::T, #T);
1524 printf("INSTANCE_TYPES = {\n");
1525 INSTANCE_TYPE_LIST(DUMP_TYPE)
1529 // Dump the KNOWN_MAP table to the console.
1530 printf("\n# List of known V8 maps.\n");
1531 #define ROOT_LIST_CASE(type, name, camel_name) \
1532 if (n == NULL && o == heap->name()) n = #camel_name;
1533 #define STRUCT_LIST_CASE(upper_name, camel_name, name) \
1534 if (n == NULL && o == heap->name##_map()) n = #camel_name "Map";
1535 i::HeapObjectIterator it(heap->map_space());
1536 printf("KNOWN_MAPS = {\n");
1537 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1538 i::Map* m = i::Map::cast(o);
1539 const char* n = NULL;
1540 intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff;
1541 int t = m->instance_type();
1542 ROOT_LIST(ROOT_LIST_CASE)
1543 STRUCT_LIST(STRUCT_LIST_CASE)
1544 if (n == NULL) continue;
1545 printf(" 0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n);
1548 #undef STRUCT_LIST_CASE
1549 #undef ROOT_LIST_CASE
1551 // Dump the KNOWN_OBJECTS table to the console.
1552 printf("\n# List of known V8 objects.\n");
1553 #define ROOT_LIST_CASE(type, name, camel_name) \
1554 if (n == NULL && o == heap->name()) n = #camel_name;
1555 i::OldSpaces spit(heap);
1556 printf("KNOWN_OBJECTS = {\n");
1557 for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) {
1558 i::HeapObjectIterator it(s);
1559 const char* sname = AllocationSpaceName(s->identity());
1560 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1561 const char* n = NULL;
1562 intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff;
1563 ROOT_LIST(ROOT_LIST_CASE)
1564 if (n == NULL) continue;
1565 printf(" (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n);
1569 #undef ROOT_LIST_CASE
1571 #endif // !V8_SHARED
1574 class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1576 virtual void* Allocate(size_t length) {
1577 void* data = AllocateUninitialized(length);
1578 return data == NULL ? data : memset(data, 0, length);
1580 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
1581 virtual void Free(void* data, size_t) { free(data); }
1585 class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1587 void* Allocate(size_t) OVERRIDE { return malloc(1); }
1588 void* AllocateUninitialized(size_t length) OVERRIDE { return malloc(1); }
1589 void Free(void* p, size_t) OVERRIDE { free(p); }
1593 int Shell::Main(int argc, char* argv[]) {
1594 #if (defined(_WIN32) || defined(_WIN64))
1596 SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
1597 UINT existing_flags = SetErrorMode(new_flags);
1598 SetErrorMode(existing_flags | new_flags);
1599 #if defined(_MSC_VER)
1600 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1601 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1602 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1603 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1604 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1605 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1606 _set_error_mode(_OUT_TO_STDERR);
1607 #endif // defined(_MSC_VER)
1608 #endif // defined(_WIN32) || defined(_WIN64)
1609 if (!SetOptions(argc, argv)) return 1;
1610 v8::V8::InitializeICU(options.icu_data_file);
1611 g_platform = v8::platform::CreateDefaultPlatform();
1612 v8::V8::InitializePlatform(g_platform);
1613 v8::V8::Initialize();
1614 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1615 v8::StartupDataHandler startup_data(argv[0], options.natives_blob,
1616 options.snapshot_blob);
1618 SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg");
1619 SetFlagsFromString("--trace-turbo-cfg-file=turbo.cfg");
1620 SetFlagsFromString("--redirect-code-traces-to=code.asm");
1621 ShellArrayBufferAllocator array_buffer_allocator;
1622 MockArrayBufferAllocator mock_arraybuffer_allocator;
1623 if (options.mock_arraybuffer_allocator) {
1624 v8::V8::SetArrayBufferAllocator(&mock_arraybuffer_allocator);
1626 v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
1629 Isolate::CreateParams create_params;
1630 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
1631 if (i::FLAG_gdbjit) {
1632 create_params.code_event_handler = i::GDBJITInterface::EventHandler;
1635 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1636 create_params.code_event_handler = vTune::GetVtuneCodeEventHandler();
1639 create_params.constraints.ConfigureDefaults(
1640 base::SysInfo::AmountOfPhysicalMemory(),
1641 base::SysInfo::AmountOfVirtualMemory(),
1642 base::SysInfo::NumberOfProcessors());
1644 Shell::counter_map_ = new CounterMap();
1645 if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
1646 create_params.counter_lookup_callback = LookupCounter;
1647 create_params.create_histogram_callback = CreateHistogram;
1648 create_params.add_histogram_sample_callback = AddHistogramSample;
1651 Isolate* isolate = Isolate::New(create_params);
1652 DumbLineEditor dumb_line_editor(isolate);
1654 Isolate::Scope scope(isolate);
1655 Initialize(isolate);
1656 PerIsolateData data(isolate);
1657 InitializeDebugger(isolate);
1660 if (options.dump_heap_constants) {
1661 DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate));
1666 if (options.stress_opt || options.stress_deopt) {
1667 Testing::SetStressRunType(options.stress_opt
1668 ? Testing::kStressTypeOpt
1669 : Testing::kStressTypeDeopt);
1670 int stress_runs = Testing::GetStressRuns();
1671 for (int i = 0; i < stress_runs && result == 0; i++) {
1672 printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1673 Testing::PrepareStressRun(i);
1674 options.last_run = (i == stress_runs - 1);
1675 result = RunMain(isolate, argc, argv);
1677 printf("======== Full Deoptimization =======\n");
1678 Testing::DeoptimizeAll();
1679 #if !defined(V8_SHARED)
1680 } else if (i::FLAG_stress_runs > 0) {
1681 int stress_runs = i::FLAG_stress_runs;
1682 for (int i = 0; i < stress_runs && result == 0; i++) {
1683 printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1684 options.last_run = (i == stress_runs - 1);
1685 result = RunMain(isolate, argc, argv);
1689 result = RunMain(isolate, argc, argv);
1692 // Run interactive shell if explicitly requested or if no script has been
1693 // executed, but never on --test
1694 if (options.use_interactive_shell()) {
1696 if (!i::FLAG_debugger) {
1697 InstallUtilityScript(isolate);
1699 #endif // !V8_SHARED
1705 // Dump basic block profiling data.
1706 if (i::BasicBlockProfiler* profiler =
1707 reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) {
1708 i::OFStream os(stdout);
1711 #endif // !V8_SHARED
1714 V8::ShutdownPlatform();
1724 int main(int argc, char* argv[]) {
1725 return v8::Shell::Main(argc, argv);