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)
11 #ifdef COMPRESS_STARTUP_DATA_BZ2
29 #include "include/v8-testing.h"
32 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
33 #include "src/gdb-jit.h"
36 #ifdef ENABLE_VTUNE_JIT_INTERFACE
37 #include "src/third_party/vtune/v8-vtune.h"
42 #include "include/libplatform/libplatform.h"
45 #include "src/base/cpu.h"
46 #include "src/base/logging.h"
47 #include "src/base/platform/platform.h"
48 #include "src/d8-debug.h"
49 #include "src/debug.h"
50 #include "src/natives.h"
54 #if !defined(_WIN32) && !defined(_WIN64)
55 #include <unistd.h> // NOLINT
59 #define DCHECK(condition) assert(condition)
65 static Handle<Value> Throw(Isolate* isolate, const char* message) {
66 return isolate->ThrowException(String::NewFromUtf8(isolate, message));
71 class PerIsolateData {
73 explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
74 HandleScope scope(isolate);
75 isolate->SetData(0, this);
79 isolate_->SetData(0, NULL); // Not really needed, just to be sure...
82 inline static PerIsolateData* Get(Isolate* isolate) {
83 return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
88 explicit RealmScope(PerIsolateData* data);
91 PerIsolateData* data_;
96 friend class RealmScope;
101 Persistent<Context>* realms_;
102 Persistent<Value> realm_shared_;
104 int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
106 int RealmFind(Handle<Context> context);
110 LineEditor *LineEditor::current_ = NULL;
113 LineEditor::LineEditor(Type type, const char* name)
114 : type_(type), name_(name) {
115 if (current_ == NULL || current_->type_ < type) current_ = this;
119 class DumbLineEditor: public LineEditor {
121 explicit DumbLineEditor(Isolate* isolate)
122 : LineEditor(LineEditor::DUMB, "dumb"), isolate_(isolate) { }
123 virtual Handle<String> Prompt(const char* prompt);
129 Handle<String> DumbLineEditor::Prompt(const char* prompt) {
130 printf("%s", prompt);
131 #if defined(__native_client__)
132 // Native Client libc is used to being embedded in Chrome and
133 // has trouble recognizing when to flush.
136 return Shell::ReadFromStdin(isolate_);
141 CounterMap* Shell::counter_map_;
142 base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
143 CounterCollection Shell::local_counters_;
144 CounterCollection* Shell::counters_ = &local_counters_;
145 base::Mutex Shell::context_mutex_;
146 const base::TimeTicks Shell::kInitialTicks =
147 base::TimeTicks::HighResolutionNow();
148 Persistent<Context> Shell::utility_context_;
151 Persistent<Context> Shell::evaluation_context_;
152 ShellOptions Shell::options;
153 const char* Shell::kPrompt = "d8> ";
157 const int MB = 1024 * 1024;
159 bool CounterMap::Match(void* key1, void* key2) {
160 const char* name1 = reinterpret_cast<const char*>(key1);
161 const char* name2 = reinterpret_cast<const char*>(key2);
162 return strcmp(name1, name2) == 0;
167 // Converts a V8 value to a C string.
168 const char* Shell::ToCString(const v8::String::Utf8Value& value) {
169 return *value ? *value : "<string conversion failed>";
173 // Compile a string within the current v8 context.
174 Local<UnboundScript> Shell::CompileString(
175 Isolate* isolate, Local<String> source, Local<Value> name,
176 v8::ScriptCompiler::CompileOptions compile_options) {
177 ScriptOrigin origin(name);
178 ScriptCompiler::Source script_source(source, origin);
179 Local<UnboundScript> script =
180 ScriptCompiler::CompileUnbound(isolate, &script_source, compile_options);
182 // Was caching requested & successful? Then compile again, now with cache.
183 if (script_source.GetCachedData()) {
184 if (compile_options == ScriptCompiler::kProduceCodeCache) {
185 compile_options = ScriptCompiler::kConsumeCodeCache;
186 } else if (compile_options == ScriptCompiler::kProduceParserCache) {
187 compile_options = ScriptCompiler::kConsumeParserCache;
189 DCHECK(false); // A new compile option?
191 ScriptCompiler::Source cached_source(
192 source, origin, new v8::ScriptCompiler::CachedData(
193 script_source.GetCachedData()->data,
194 script_source.GetCachedData()->length,
195 v8::ScriptCompiler::CachedData::BufferNotOwned));
196 script = ScriptCompiler::CompileUnbound(isolate, &cached_source,
203 // Executes a string within the current v8 context.
204 bool Shell::ExecuteString(Isolate* isolate,
205 Handle<String> source,
208 bool report_exceptions) {
210 bool FLAG_debugger = i::FLAG_debugger;
212 bool FLAG_debugger = false;
214 HandleScope handle_scope(isolate);
216 options.script_executed = true;
218 // When debugging make exceptions appear to be uncaught.
219 try_catch.SetVerbose(true);
222 Handle<UnboundScript> script =
223 Shell::CompileString(isolate, source, name, options.compile_options);
224 if (script.IsEmpty()) {
225 // Print errors that happened during compilation.
226 if (report_exceptions && !FLAG_debugger)
227 ReportException(isolate, &try_catch);
230 PerIsolateData* data = PerIsolateData::Get(isolate);
231 Local<Context> realm =
232 Local<Context>::New(isolate, data->realms_[data->realm_current_]);
234 Handle<Value> result = script->BindToCurrentContext()->Run();
236 data->realm_current_ = data->realm_switch_;
237 if (result.IsEmpty()) {
238 DCHECK(try_catch.HasCaught());
239 // Print errors that happened during execution.
240 if (report_exceptions && !FLAG_debugger)
241 ReportException(isolate, &try_catch);
244 DCHECK(!try_catch.HasCaught());
246 #if !defined(V8_SHARED)
247 if (options.test_shell) {
249 if (!result->IsUndefined()) {
250 // If all went well and the result wasn't undefined then print
251 // the returned value.
252 v8::String::Utf8Value str(result);
253 fwrite(*str, sizeof(**str), str.length(), stdout);
256 #if !defined(V8_SHARED)
258 v8::TryCatch try_catch;
259 v8::Local<v8::Context> context =
260 v8::Local<v8::Context>::New(isolate, utility_context_);
261 v8::Context::Scope context_scope(context);
262 Handle<Object> global = context->Global();
264 global->Get(String::NewFromUtf8(isolate, "Stringify"));
265 Handle<Value> argv[1] = { result };
266 Handle<Value> s = Handle<Function>::Cast(fun)->Call(global, 1, argv);
267 if (try_catch.HasCaught()) return true;
268 v8::String::Utf8Value str(s);
269 fwrite(*str, sizeof(**str), str.length(), stdout);
280 PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
281 data_->realm_count_ = 1;
282 data_->realm_current_ = 0;
283 data_->realm_switch_ = 0;
284 data_->realms_ = new Persistent<Context>[1];
285 data_->realms_[0].Reset(data_->isolate_,
286 data_->isolate_->GetEnteredContext());
290 PerIsolateData::RealmScope::~RealmScope() {
291 // Drop realms to avoid keeping them alive.
292 for (int i = 0; i < data_->realm_count_; ++i)
293 data_->realms_[i].Reset();
294 delete[] data_->realms_;
295 if (!data_->realm_shared_.IsEmpty())
296 data_->realm_shared_.Reset();
300 int PerIsolateData::RealmFind(Handle<Context> context) {
301 for (int i = 0; i < realm_count_; ++i) {
302 if (realms_[i] == context) return i;
308 int PerIsolateData::RealmIndexOrThrow(
309 const v8::FunctionCallbackInfo<v8::Value>& args,
311 if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
312 Throw(args.GetIsolate(), "Invalid argument");
315 int index = args[arg_offset]->Int32Value();
317 index >= realm_count_ ||
318 realms_[index].IsEmpty()) {
319 Throw(args.GetIsolate(), "Invalid realm index");
327 // performance.now() returns a time stamp as double, measured in milliseconds.
328 // When FLAG_verify_predictable mode is enabled it returns current value
329 // of Heap::allocations_count().
330 void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
331 if (i::FLAG_verify_predictable) {
332 Isolate* v8_isolate = args.GetIsolate();
333 i::Heap* heap = reinterpret_cast<i::Isolate*>(v8_isolate)->heap();
334 args.GetReturnValue().Set(heap->synthetic_time());
337 base::TimeDelta delta =
338 base::TimeTicks::HighResolutionNow() - kInitialTicks;
339 args.GetReturnValue().Set(delta.InMillisecondsF());
345 // Realm.current() returns the index of the currently active realm.
346 void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
347 Isolate* isolate = args.GetIsolate();
348 PerIsolateData* data = PerIsolateData::Get(isolate);
349 int index = data->RealmFind(isolate->GetEnteredContext());
350 if (index == -1) return;
351 args.GetReturnValue().Set(index);
355 // Realm.owner(o) returns the index of the realm that created o.
356 void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
357 Isolate* isolate = args.GetIsolate();
358 PerIsolateData* data = PerIsolateData::Get(isolate);
359 if (args.Length() < 1 || !args[0]->IsObject()) {
360 Throw(args.GetIsolate(), "Invalid argument");
363 int index = data->RealmFind(args[0]->ToObject()->CreationContext());
364 if (index == -1) return;
365 args.GetReturnValue().Set(index);
369 // Realm.global(i) returns the global object of realm i.
370 // (Note that properties of global objects cannot be read/written cross-realm.)
371 void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
372 PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
373 int index = data->RealmIndexOrThrow(args, 0);
374 if (index == -1) return;
375 args.GetReturnValue().Set(
376 Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
380 // Realm.create() creates a new realm and returns its index.
381 void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
382 Isolate* isolate = args.GetIsolate();
383 PerIsolateData* data = PerIsolateData::Get(isolate);
384 Persistent<Context>* old_realms = data->realms_;
385 int index = data->realm_count_;
386 data->realms_ = new Persistent<Context>[++data->realm_count_];
387 for (int i = 0; i < index; ++i) {
388 data->realms_[i].Reset(isolate, old_realms[i]);
391 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
392 data->realms_[index].Reset(
393 isolate, Context::New(isolate, NULL, global_template));
394 args.GetReturnValue().Set(index);
398 // Realm.dispose(i) disposes the reference to the realm i.
399 void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
400 Isolate* isolate = args.GetIsolate();
401 PerIsolateData* data = PerIsolateData::Get(isolate);
402 int index = data->RealmIndexOrThrow(args, 0);
403 if (index == -1) return;
405 index == data->realm_current_ || index == data->realm_switch_) {
406 Throw(args.GetIsolate(), "Invalid realm index");
409 data->realms_[index].Reset();
413 // Realm.switch(i) switches to the realm i for consecutive interactive inputs.
414 void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
415 Isolate* isolate = args.GetIsolate();
416 PerIsolateData* data = PerIsolateData::Get(isolate);
417 int index = data->RealmIndexOrThrow(args, 0);
418 if (index == -1) return;
419 data->realm_switch_ = index;
423 // Realm.eval(i, s) evaluates s in realm i and returns the result.
424 void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
425 Isolate* isolate = args.GetIsolate();
426 PerIsolateData* data = PerIsolateData::Get(isolate);
427 int index = data->RealmIndexOrThrow(args, 0);
428 if (index == -1) return;
429 if (args.Length() < 2 || !args[1]->IsString()) {
430 Throw(args.GetIsolate(), "Invalid argument");
433 ScriptCompiler::Source script_source(args[1]->ToString());
434 Handle<UnboundScript> script = ScriptCompiler::CompileUnbound(
435 isolate, &script_source);
436 if (script.IsEmpty()) return;
437 Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
439 Handle<Value> result = script->BindToCurrentContext()->Run();
441 args.GetReturnValue().Set(result);
445 // Realm.shared is an accessor for a single shared value across realms.
446 void Shell::RealmSharedGet(Local<String> property,
447 const PropertyCallbackInfo<Value>& info) {
448 Isolate* isolate = info.GetIsolate();
449 PerIsolateData* data = PerIsolateData::Get(isolate);
450 if (data->realm_shared_.IsEmpty()) return;
451 info.GetReturnValue().Set(data->realm_shared_);
454 void Shell::RealmSharedSet(Local<String> property,
456 const PropertyCallbackInfo<void>& info) {
457 Isolate* isolate = info.GetIsolate();
458 PerIsolateData* data = PerIsolateData::Get(isolate);
459 data->realm_shared_.Reset(isolate, value);
463 void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
470 void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
471 for (int i = 0; i < args.Length(); i++) {
472 HandleScope handle_scope(args.GetIsolate());
477 // Explicitly catch potential exceptions in toString().
478 v8::TryCatch try_catch;
479 Handle<String> str_obj = args[i]->ToString();
480 if (try_catch.HasCaught()) {
485 v8::String::Utf8Value str(str_obj);
486 int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
487 if (n != str.length()) {
488 printf("Error in fwrite\n");
495 void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
496 String::Utf8Value file(args[0]);
498 Throw(args.GetIsolate(), "Error loading file");
501 Handle<String> source = ReadFile(args.GetIsolate(), *file);
502 if (source.IsEmpty()) {
503 Throw(args.GetIsolate(), "Error loading file");
506 args.GetReturnValue().Set(source);
510 Handle<String> Shell::ReadFromStdin(Isolate* isolate) {
511 static const int kBufferSize = 256;
512 char buffer[kBufferSize];
513 Handle<String> accumulator = String::NewFromUtf8(isolate, "");
516 // Continue reading if the line ends with an escape '\\' or the line has
517 // not been fully read into the buffer yet (does not end with '\n').
518 // If fgets gets an error, just give up.
520 input = fgets(buffer, kBufferSize, stdin);
521 if (input == NULL) return Handle<String>();
522 length = static_cast<int>(strlen(buffer));
525 } else if (buffer[length-1] != '\n') {
526 accumulator = String::Concat(
528 String::NewFromUtf8(isolate, buffer, String::kNormalString, length));
529 } else if (length > 1 && buffer[length-2] == '\\') {
530 buffer[length-2] = '\n';
531 accumulator = String::Concat(
532 accumulator, String::NewFromUtf8(isolate, buffer,
533 String::kNormalString, length - 1));
535 return String::Concat(
536 accumulator, String::NewFromUtf8(isolate, buffer,
537 String::kNormalString, length - 1));
543 void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
544 for (int i = 0; i < args.Length(); i++) {
545 HandleScope handle_scope(args.GetIsolate());
546 String::Utf8Value file(args[i]);
548 Throw(args.GetIsolate(), "Error loading file");
551 Handle<String> source = ReadFile(args.GetIsolate(), *file);
552 if (source.IsEmpty()) {
553 Throw(args.GetIsolate(), "Error loading file");
556 if (!ExecuteString(args.GetIsolate(),
558 String::NewFromUtf8(args.GetIsolate(), *file),
561 Throw(args.GetIsolate(), "Error executing file");
568 void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
569 int exit_code = args[0]->Int32Value();
575 void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
576 args.GetReturnValue().Set(
577 String::NewFromUtf8(args.GetIsolate(), V8::GetVersion()));
581 void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
582 HandleScope handle_scope(isolate);
584 Handle<Context> utility_context;
585 bool enter_context = !isolate->InContext();
587 utility_context = Local<Context>::New(isolate, utility_context_);
588 utility_context->Enter();
591 v8::String::Utf8Value exception(try_catch->Exception());
592 const char* exception_string = ToCString(exception);
593 Handle<Message> message = try_catch->Message();
594 if (message.IsEmpty()) {
595 // V8 didn't provide any extra information about this error; just
596 // print the exception.
597 printf("%s\n", exception_string);
599 // Print (filename):(line number): (message).
600 v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
601 const char* filename_string = ToCString(filename);
602 int linenum = message->GetLineNumber();
603 printf("%s:%i: %s\n", filename_string, linenum, exception_string);
604 // Print line of source code.
605 v8::String::Utf8Value sourceline(message->GetSourceLine());
606 const char* sourceline_string = ToCString(sourceline);
607 printf("%s\n", sourceline_string);
608 // Print wavy underline (GetUnderline is deprecated).
609 int start = message->GetStartColumn();
610 for (int i = 0; i < start; i++) {
613 int end = message->GetEndColumn();
614 for (int i = start; i < end; i++) {
618 v8::String::Utf8Value stack_trace(try_catch->StackTrace());
619 if (stack_trace.length() > 0) {
620 const char* stack_trace_string = ToCString(stack_trace);
621 printf("%s\n", stack_trace_string);
626 if (enter_context) utility_context->Exit();
632 Handle<Array> Shell::GetCompletions(Isolate* isolate,
634 Handle<String> full) {
635 EscapableHandleScope handle_scope(isolate);
636 v8::Local<v8::Context> utility_context =
637 v8::Local<v8::Context>::New(isolate, utility_context_);
638 v8::Context::Scope context_scope(utility_context);
639 Handle<Object> global = utility_context->Global();
641 global->Get(String::NewFromUtf8(isolate, "GetCompletions"));
642 static const int kArgc = 3;
643 v8::Local<v8::Context> evaluation_context =
644 v8::Local<v8::Context>::New(isolate, evaluation_context_);
645 Handle<Value> argv[kArgc] = { evaluation_context->Global(), text, full };
646 Local<Value> val = Local<Function>::Cast(fun)->Call(global, kArgc, argv);
647 return handle_scope.Escape(Local<Array>::Cast(val));
651 Local<Object> Shell::DebugMessageDetails(Isolate* isolate,
652 Handle<String> message) {
653 EscapableHandleScope handle_scope(isolate);
654 v8::Local<v8::Context> context =
655 v8::Local<v8::Context>::New(isolate, utility_context_);
656 v8::Context::Scope context_scope(context);
657 Handle<Object> global = context->Global();
659 global->Get(String::NewFromUtf8(isolate, "DebugMessageDetails"));
660 static const int kArgc = 1;
661 Handle<Value> argv[kArgc] = { message };
662 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
663 return handle_scope.Escape(Local<Object>(Handle<Object>::Cast(val)));
667 Local<Value> Shell::DebugCommandToJSONRequest(Isolate* isolate,
668 Handle<String> command) {
669 EscapableHandleScope handle_scope(isolate);
670 v8::Local<v8::Context> context =
671 v8::Local<v8::Context>::New(isolate, utility_context_);
672 v8::Context::Scope context_scope(context);
673 Handle<Object> global = context->Global();
675 global->Get(String::NewFromUtf8(isolate, "DebugCommandToJSONRequest"));
676 static const int kArgc = 1;
677 Handle<Value> argv[kArgc] = { command };
678 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
679 return handle_scope.Escape(Local<Value>(val));
683 int32_t* Counter::Bind(const char* name, bool is_histogram) {
685 for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
686 name_[i] = static_cast<char>(name[i]);
688 is_histogram_ = is_histogram;
693 void Counter::AddSample(int32_t sample) {
695 sample_total_ += sample;
699 CounterCollection::CounterCollection() {
700 magic_number_ = 0xDEADFACE;
701 max_counters_ = kMaxCounters;
702 max_name_size_ = Counter::kMaxNameSize;
703 counters_in_use_ = 0;
707 Counter* CounterCollection::GetNextCounter() {
708 if (counters_in_use_ == kMaxCounters) return NULL;
709 return &counters_[counters_in_use_++];
713 void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
714 counters_file_ = base::OS::MemoryMappedFile::create(
715 name, sizeof(CounterCollection), &local_counters_);
716 void* memory = (counters_file_ == NULL) ?
717 NULL : counters_file_->memory();
718 if (memory == NULL) {
719 printf("Could not map counters file %s\n", name);
722 counters_ = static_cast<CounterCollection*>(memory);
723 isolate->SetCounterFunction(LookupCounter);
724 isolate->SetCreateHistogramFunction(CreateHistogram);
725 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
729 int CounterMap::Hash(const char* name) {
732 while ((c = *name++) != 0) {
740 Counter* Shell::GetCounter(const char* name, bool is_histogram) {
741 Counter* counter = counter_map_->Lookup(name);
743 if (counter == NULL) {
744 counter = counters_->GetNextCounter();
745 if (counter != NULL) {
746 counter_map_->Set(name, counter);
747 counter->Bind(name, is_histogram);
750 DCHECK(counter->is_histogram() == is_histogram);
756 int* Shell::LookupCounter(const char* name) {
757 Counter* counter = GetCounter(name, false);
759 if (counter != NULL) {
760 return counter->ptr();
767 void* Shell::CreateHistogram(const char* name,
771 return GetCounter(name, true);
775 void Shell::AddHistogramSample(void* histogram, int sample) {
776 Counter* counter = reinterpret_cast<Counter*>(histogram);
777 counter->AddSample(sample);
781 void Shell::InstallUtilityScript(Isolate* isolate) {
782 HandleScope scope(isolate);
783 // If we use the utility context, we have to set the security tokens so that
784 // utility, evaluation and debug context can all access each other.
785 v8::Local<v8::Context> utility_context =
786 v8::Local<v8::Context>::New(isolate, utility_context_);
787 v8::Local<v8::Context> evaluation_context =
788 v8::Local<v8::Context>::New(isolate, evaluation_context_);
789 utility_context->SetSecurityToken(Undefined(isolate));
790 evaluation_context->SetSecurityToken(Undefined(isolate));
791 v8::Context::Scope context_scope(utility_context);
793 if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
794 // Install the debugger object in the utility scope
795 i::Debug* debug = reinterpret_cast<i::Isolate*>(isolate)->debug();
797 i::Handle<i::Context> debug_context = debug->debug_context();
798 i::Handle<i::JSObject> js_debug
799 = i::Handle<i::JSObject>(debug_context->global_object());
800 utility_context->Global()->Set(String::NewFromUtf8(isolate, "$debug"),
801 Utils::ToLocal(js_debug));
802 debug_context->set_security_token(
803 reinterpret_cast<i::Isolate*>(isolate)->heap()->undefined_value());
805 // Run the d8 shell utility script in the utility context
806 int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
807 i::Vector<const char> shell_source =
808 i::NativesCollection<i::D8>::GetRawScriptSource(source_index);
809 i::Vector<const char> shell_source_name =
810 i::NativesCollection<i::D8>::GetScriptName(source_index);
811 Handle<String> source =
812 String::NewFromUtf8(isolate, shell_source.start(), String::kNormalString,
813 shell_source.length());
814 Handle<String> name =
815 String::NewFromUtf8(isolate, shell_source_name.start(),
816 String::kNormalString, shell_source_name.length());
817 ScriptOrigin origin(name);
818 Handle<Script> script = Script::Compile(source, &origin);
820 // Mark the d8 shell script as native to avoid it showing up as normal source
822 i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
823 i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
824 ? i::Handle<i::Script>(i::Script::cast(
825 i::JSFunction::cast(*compiled_script)->shared()->script()))
826 : i::Handle<i::Script>(i::Script::cast(
827 i::SharedFunctionInfo::cast(*compiled_script)->script()));
828 script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
830 // Start the in-process debugger if requested.
831 if (i::FLAG_debugger) v8::Debug::SetDebugEventListener(HandleDebugEvent);
836 #ifdef COMPRESS_STARTUP_DATA_BZ2
837 class BZip2Decompressor : public v8::StartupDataDecompressor {
839 virtual ~BZip2Decompressor() { }
842 virtual int DecompressData(char* raw_data,
844 const char* compressed_data,
845 int compressed_data_size) {
846 DCHECK_EQ(v8::StartupData::kBZip2,
847 v8::V8::GetCompressedStartupDataAlgorithm());
848 unsigned int decompressed_size = *raw_data_size;
850 BZ2_bzBuffToBuffDecompress(raw_data,
852 const_cast<char*>(compressed_data),
853 compressed_data_size,
855 if (result == BZ_OK) {
856 *raw_data_size = decompressed_size;
864 Handle<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
865 Handle<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
866 global_template->Set(String::NewFromUtf8(isolate, "print"),
867 FunctionTemplate::New(isolate, Print));
868 global_template->Set(String::NewFromUtf8(isolate, "write"),
869 FunctionTemplate::New(isolate, Write));
870 global_template->Set(String::NewFromUtf8(isolate, "read"),
871 FunctionTemplate::New(isolate, Read));
872 global_template->Set(String::NewFromUtf8(isolate, "readbuffer"),
873 FunctionTemplate::New(isolate, ReadBuffer));
874 global_template->Set(String::NewFromUtf8(isolate, "readline"),
875 FunctionTemplate::New(isolate, ReadLine));
876 global_template->Set(String::NewFromUtf8(isolate, "load"),
877 FunctionTemplate::New(isolate, Load));
878 global_template->Set(String::NewFromUtf8(isolate, "quit"),
879 FunctionTemplate::New(isolate, Quit));
880 global_template->Set(String::NewFromUtf8(isolate, "version"),
881 FunctionTemplate::New(isolate, Version));
883 // Bind the Realm object.
884 Handle<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
885 realm_template->Set(String::NewFromUtf8(isolate, "current"),
886 FunctionTemplate::New(isolate, RealmCurrent));
887 realm_template->Set(String::NewFromUtf8(isolate, "owner"),
888 FunctionTemplate::New(isolate, RealmOwner));
889 realm_template->Set(String::NewFromUtf8(isolate, "global"),
890 FunctionTemplate::New(isolate, RealmGlobal));
891 realm_template->Set(String::NewFromUtf8(isolate, "create"),
892 FunctionTemplate::New(isolate, RealmCreate));
893 realm_template->Set(String::NewFromUtf8(isolate, "dispose"),
894 FunctionTemplate::New(isolate, RealmDispose));
895 realm_template->Set(String::NewFromUtf8(isolate, "switch"),
896 FunctionTemplate::New(isolate, RealmSwitch));
897 realm_template->Set(String::NewFromUtf8(isolate, "eval"),
898 FunctionTemplate::New(isolate, RealmEval));
899 realm_template->SetAccessor(String::NewFromUtf8(isolate, "shared"),
900 RealmSharedGet, RealmSharedSet);
901 global_template->Set(String::NewFromUtf8(isolate, "Realm"), realm_template);
904 Handle<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
905 performance_template->Set(String::NewFromUtf8(isolate, "now"),
906 FunctionTemplate::New(isolate, PerformanceNow));
907 global_template->Set(String::NewFromUtf8(isolate, "performance"),
908 performance_template);
911 Handle<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
912 AddOSMethods(isolate, os_templ);
913 global_template->Set(String::NewFromUtf8(isolate, "os"), os_templ);
915 return global_template;
919 void Shell::Initialize(Isolate* isolate) {
920 #ifdef COMPRESS_STARTUP_DATA_BZ2
921 BZip2Decompressor startup_data_decompressor;
922 int bz2_result = startup_data_decompressor.Decompress();
923 if (bz2_result != BZ_OK) {
924 fprintf(stderr, "bzip error code: %d\n", bz2_result);
930 Shell::counter_map_ = new CounterMap();
932 if (i::StrLength(i::FLAG_map_counters) != 0)
933 MapCounters(isolate, i::FLAG_map_counters);
934 if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
935 isolate->SetCounterFunction(LookupCounter);
936 isolate->SetCreateHistogramFunction(CreateHistogram);
937 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
943 void Shell::InitializeDebugger(Isolate* isolate) {
944 if (options.test_shell) return;
946 HandleScope scope(isolate);
947 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
948 utility_context_.Reset(isolate,
949 Context::New(isolate, NULL, global_template));
954 Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
956 // This needs to be a critical section since this is not thread-safe
957 base::LockGuard<base::Mutex> lock_guard(&context_mutex_);
959 // Initialize the global objects
960 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
961 EscapableHandleScope handle_scope(isolate);
962 Local<Context> context = Context::New(isolate, NULL, global_template);
963 DCHECK(!context.IsEmpty());
964 Context::Scope scope(context);
967 i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
968 i::JSArguments js_args = i::FLAG_js_arguments;
969 i::Handle<i::FixedArray> arguments_array =
970 factory->NewFixedArray(js_args.argc);
971 for (int j = 0; j < js_args.argc; j++) {
972 i::Handle<i::String> arg =
973 factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
974 arguments_array->set(j, *arg);
976 i::Handle<i::JSArray> arguments_jsarray =
977 factory->NewJSArrayWithElements(arguments_array);
978 context->Global()->Set(String::NewFromUtf8(isolate, "arguments"),
979 Utils::ToLocal(arguments_jsarray));
981 return handle_scope.Escape(context);
985 void Shell::Exit(int exit_code) {
986 // Use _exit instead of exit to avoid races between isolate
987 // threads and static destructors.
995 struct CounterAndKey {
1001 inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
1002 return strcmp(lhs.key, rhs.key) < 0;
1004 #endif // !V8_SHARED
1007 void Shell::OnExit() {
1008 LineEditor* line_editor = LineEditor::Get();
1009 if (line_editor) line_editor->Close();
1011 if (i::FLAG_dump_counters) {
1012 int number_of_counters = 0;
1013 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1014 number_of_counters++;
1016 CounterAndKey* counters = new CounterAndKey[number_of_counters];
1018 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
1019 counters[j].counter = i.CurrentValue();
1020 counters[j].key = i.CurrentKey();
1022 std::sort(counters, counters + number_of_counters);
1023 printf("+----------------------------------------------------------------+"
1024 "-------------+\n");
1027 printf("+----------------------------------------------------------------+"
1028 "-------------+\n");
1029 for (j = 0; j < number_of_counters; j++) {
1030 Counter* counter = counters[j].counter;
1031 const char* key = counters[j].key;
1032 if (counter->is_histogram()) {
1033 printf("| c:%-60s | %11i |\n", key, counter->count());
1034 printf("| t:%-60s | %11i |\n", key, counter->sample_total());
1036 printf("| %-62s | %11i |\n", key, counter->count());
1039 printf("+----------------------------------------------------------------+"
1040 "-------------+\n");
1043 delete counters_file_;
1044 delete counter_map_;
1045 #endif // !V8_SHARED
1050 static FILE* FOpen(const char* path, const char* mode) {
1051 #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
1053 if (fopen_s(&result, path, mode) == 0) {
1059 FILE* file = fopen(path, mode);
1060 if (file == NULL) return NULL;
1061 struct stat file_stat;
1062 if (fstat(fileno(file), &file_stat) != 0) return NULL;
1063 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
1064 if (is_regular_file) return file;
1071 static char* ReadChars(Isolate* isolate, const char* name, int* size_out) {
1072 FILE* file = FOpen(name, "rb");
1073 if (file == NULL) return NULL;
1075 fseek(file, 0, SEEK_END);
1076 int size = ftell(file);
1079 char* chars = new char[size + 1];
1081 for (int i = 0; i < size;) {
1082 int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1091 struct DataAndPersistent {
1093 Persistent<ArrayBuffer> handle;
1097 static void ReadBufferWeakCallback(
1098 const v8::WeakCallbackData<ArrayBuffer, DataAndPersistent>& data) {
1099 size_t byte_length = data.GetValue()->ByteLength();
1100 data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
1101 -static_cast<intptr_t>(byte_length));
1103 delete[] data.GetParameter()->data;
1104 data.GetParameter()->handle.Reset();
1105 delete data.GetParameter();
1109 void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
1110 DCHECK(sizeof(char) == sizeof(uint8_t)); // NOLINT
1111 String::Utf8Value filename(args[0]);
1113 if (*filename == NULL) {
1114 Throw(args.GetIsolate(), "Error loading file");
1118 Isolate* isolate = args.GetIsolate();
1119 DataAndPersistent* data = new DataAndPersistent;
1120 data->data = reinterpret_cast<uint8_t*>(
1121 ReadChars(args.GetIsolate(), *filename, &length));
1122 if (data->data == NULL) {
1124 Throw(args.GetIsolate(), "Error reading file");
1127 Handle<v8::ArrayBuffer> buffer =
1128 ArrayBuffer::New(isolate, data->data, length);
1129 data->handle.Reset(isolate, buffer);
1130 data->handle.SetWeak(data, ReadBufferWeakCallback);
1131 data->handle.MarkIndependent();
1132 isolate->AdjustAmountOfExternalAllocatedMemory(length);
1134 args.GetReturnValue().Set(buffer);
1138 // Reads a file into a v8 string.
1139 Handle<String> Shell::ReadFile(Isolate* isolate, const char* name) {
1141 char* chars = ReadChars(isolate, name, &size);
1142 if (chars == NULL) return Handle<String>();
1143 Handle<String> result =
1144 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1150 void Shell::RunShell(Isolate* isolate) {
1151 HandleScope outer_scope(isolate);
1152 v8::Local<v8::Context> context =
1153 v8::Local<v8::Context>::New(isolate, evaluation_context_);
1154 v8::Context::Scope context_scope(context);
1155 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1156 Handle<String> name = String::NewFromUtf8(isolate, "(d8)");
1157 LineEditor* console = LineEditor::Get();
1158 printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
1159 console->Open(isolate);
1161 HandleScope inner_scope(isolate);
1162 Handle<String> input = console->Prompt(Shell::kPrompt);
1163 if (input.IsEmpty()) break;
1164 ExecuteString(isolate, input, name, true, true);
1170 SourceGroup::~SourceGroup() {
1174 #endif // !V8_SHARED
1178 void SourceGroup::Execute(Isolate* isolate) {
1179 bool exception_was_thrown = false;
1180 for (int i = begin_offset_; i < end_offset_; ++i) {
1181 const char* arg = argv_[i];
1182 if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
1183 // Execute argument given to -e option directly.
1184 HandleScope handle_scope(isolate);
1185 Handle<String> file_name = String::NewFromUtf8(isolate, "unnamed");
1186 Handle<String> source = String::NewFromUtf8(isolate, argv_[i + 1]);
1187 if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1188 exception_was_thrown = true;
1192 } else if (arg[0] == '-') {
1193 // Ignore other options. They have been parsed already.
1195 // Use all other arguments as names of files to load and run.
1196 HandleScope handle_scope(isolate);
1197 Handle<String> file_name = String::NewFromUtf8(isolate, arg);
1198 Handle<String> source = ReadFile(isolate, arg);
1199 if (source.IsEmpty()) {
1200 printf("Error reading '%s'\n", arg);
1203 if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1204 exception_was_thrown = true;
1209 if (exception_was_thrown != Shell::options.expected_to_throw) {
1215 Handle<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
1217 char* chars = ReadChars(isolate, name, &size);
1218 if (chars == NULL) return Handle<String>();
1219 Handle<String> result =
1220 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1227 base::Thread::Options SourceGroup::GetThreadOptions() {
1228 // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
1229 // which is not enough to parse the big literal expressions used in tests.
1230 // The stack size should be at least StackGuard::kLimitSize + some
1231 // OS-specific padding for thread startup code. 2Mbytes seems to be enough.
1232 return base::Thread::Options("IsolateThread", 2 * MB);
1236 void SourceGroup::ExecuteInThread() {
1237 Isolate* isolate = Isolate::New();
1239 next_semaphore_.Wait();
1241 Isolate::Scope iscope(isolate);
1243 HandleScope scope(isolate);
1244 PerIsolateData data(isolate);
1245 Local<Context> context = Shell::CreateEvaluationContext(isolate);
1247 Context::Scope cscope(context);
1248 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1252 if (Shell::options.send_idle_notification) {
1253 const int kLongIdlePauseInMs = 1000;
1254 isolate->ContextDisposedNotification();
1255 isolate->IdleNotification(kLongIdlePauseInMs);
1257 if (Shell::options.invoke_weak_callbacks) {
1258 // By sending a low memory notifications, we will try hard to collect
1259 // all garbage and will therefore also invoke all weak callbacks of
1260 // actually unreachable persistent handles.
1261 isolate->LowMemoryNotification();
1264 done_semaphore_.Signal();
1265 } while (!Shell::options.last_run);
1271 void SourceGroup::StartExecuteInThread() {
1272 if (thread_ == NULL) {
1273 thread_ = new IsolateThread(this);
1276 next_semaphore_.Signal();
1280 void SourceGroup::WaitForThread() {
1281 if (thread_ == NULL) return;
1282 if (Shell::options.last_run) {
1285 done_semaphore_.Wait();
1288 #endif // !V8_SHARED
1291 void SetFlagsFromString(const char* flags) {
1292 v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags)));
1296 bool Shell::SetOptions(int argc, char* argv[]) {
1297 bool logfile_per_isolate = false;
1298 for (int i = 0; i < argc; i++) {
1299 if (strcmp(argv[i], "--stress-opt") == 0) {
1300 options.stress_opt = true;
1302 } else if (strcmp(argv[i], "--nostress-opt") == 0) {
1303 options.stress_opt = false;
1305 } else if (strcmp(argv[i], "--stress-deopt") == 0) {
1306 options.stress_deopt = true;
1308 } else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) {
1309 options.mock_arraybuffer_allocator = true;
1311 } else if (strcmp(argv[i], "--noalways-opt") == 0) {
1312 // No support for stressing if we can't use --always-opt.
1313 options.stress_opt = false;
1314 options.stress_deopt = false;
1315 } else if (strcmp(argv[i], "--logfile-per-isolate") == 0) {
1316 logfile_per_isolate = true;
1318 } else if (strcmp(argv[i], "--shell") == 0) {
1319 options.interactive_shell = true;
1321 } else if (strcmp(argv[i], "--test") == 0) {
1322 options.test_shell = true;
1324 } else if (strcmp(argv[i], "--send-idle-notification") == 0) {
1325 options.send_idle_notification = true;
1327 } else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) {
1328 options.invoke_weak_callbacks = true;
1329 // TODO(jochen) See issue 3351
1330 options.send_idle_notification = true;
1332 } else if (strcmp(argv[i], "-f") == 0) {
1333 // Ignore any -f flags for compatibility with other stand-alone
1334 // JavaScript engines.
1336 } else if (strcmp(argv[i], "--isolate") == 0) {
1338 printf("D8 with shared library does not support multi-threading\n");
1341 options.num_isolates++;
1342 } else if (strcmp(argv[i], "--dump-heap-constants") == 0) {
1344 printf("D8 with shared library does not support constant dumping\n");
1347 options.dump_heap_constants = true;
1350 } else if (strcmp(argv[i], "--throws") == 0) {
1351 options.expected_to_throw = true;
1353 } else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) {
1354 options.icu_data_file = argv[i] + 16;
1357 } else if (strcmp(argv[i], "--dump-counters") == 0) {
1358 printf("D8 with shared library does not include counters\n");
1360 } else if (strcmp(argv[i], "--debugger") == 0) {
1361 printf("Javascript debugger not included\n");
1364 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1365 } else if (strncmp(argv[i], "--natives_blob=", 15) == 0) {
1366 options.natives_blob = argv[i] + 15;
1368 } else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) {
1369 options.snapshot_blob = argv[i] + 16;
1371 #endif // V8_USE_EXTERNAL_STARTUP_DATA
1372 } else if (strcmp(argv[i], "--cache") == 0 ||
1373 strncmp(argv[i], "--cache=", 8) == 0) {
1374 const char* value = argv[i] + 7;
1375 if (!*value || strncmp(value, "=code", 6) == 0) {
1376 options.compile_options = v8::ScriptCompiler::kProduceCodeCache;
1377 } else if (strncmp(value, "=parse", 7) == 0) {
1378 options.compile_options = v8::ScriptCompiler::kProduceParserCache;
1379 } else if (strncmp(value, "=none", 6) == 0) {
1380 options.compile_options = v8::ScriptCompiler::kNoCompileOptions;
1382 printf("Unknown option to --cache.\n");
1389 v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
1391 // Set up isolated source groups.
1392 options.isolate_sources = new SourceGroup[options.num_isolates];
1393 SourceGroup* current = options.isolate_sources;
1394 current->Begin(argv, 1);
1395 for (int i = 1; i < argc; i++) {
1396 const char* str = argv[i];
1397 if (strcmp(str, "--isolate") == 0) {
1400 current->Begin(argv, i + 1);
1401 } else if (strncmp(argv[i], "--", 2) == 0) {
1402 printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
1407 if (!logfile_per_isolate && options.num_isolates) {
1408 SetFlagsFromString("--nologfile_per_isolate");
1415 int Shell::RunMain(Isolate* isolate, int argc, char* argv[]) {
1417 for (int i = 1; i < options.num_isolates; ++i) {
1418 options.isolate_sources[i].StartExecuteInThread();
1420 #endif // !V8_SHARED
1422 HandleScope scope(isolate);
1423 Local<Context> context = CreateEvaluationContext(isolate);
1424 if (options.last_run && options.use_interactive_shell()) {
1425 // Keep using the same context in the interactive shell.
1426 evaluation_context_.Reset(isolate, context);
1428 // If the interactive debugger is enabled make sure to activate
1429 // it before running the files passed on the command line.
1430 if (i::FLAG_debugger) {
1431 InstallUtilityScript(isolate);
1433 #endif // !V8_SHARED
1436 Context::Scope cscope(context);
1437 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1438 options.isolate_sources[0].Execute(isolate);
1441 if (options.send_idle_notification) {
1442 const int kLongIdlePauseInMs = 1000;
1443 isolate->ContextDisposedNotification();
1444 isolate->IdleNotification(kLongIdlePauseInMs);
1446 if (options.invoke_weak_callbacks) {
1447 // By sending a low memory notifications, we will try hard to collect all
1448 // garbage and will therefore also invoke all weak callbacks of actually
1449 // unreachable persistent handles.
1450 isolate->LowMemoryNotification();
1454 for (int i = 1; i < options.num_isolates; ++i) {
1455 options.isolate_sources[i].WaitForThread();
1457 #endif // !V8_SHARED
1463 static void DumpHeapConstants(i::Isolate* isolate) {
1464 i::Heap* heap = isolate->heap();
1466 // Dump the INSTANCE_TYPES table to the console.
1467 printf("# List of known V8 instance types.\n");
1468 #define DUMP_TYPE(T) printf(" %d: \"%s\",\n", i::T, #T);
1469 printf("INSTANCE_TYPES = {\n");
1470 INSTANCE_TYPE_LIST(DUMP_TYPE)
1474 // Dump the KNOWN_MAP table to the console.
1475 printf("\n# List of known V8 maps.\n");
1476 #define ROOT_LIST_CASE(type, name, camel_name) \
1477 if (n == NULL && o == heap->name()) n = #camel_name;
1478 #define STRUCT_LIST_CASE(upper_name, camel_name, name) \
1479 if (n == NULL && o == heap->name##_map()) n = #camel_name "Map";
1480 i::HeapObjectIterator it(heap->map_space());
1481 printf("KNOWN_MAPS = {\n");
1482 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1483 i::Map* m = i::Map::cast(o);
1484 const char* n = NULL;
1485 intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff;
1486 int t = m->instance_type();
1487 ROOT_LIST(ROOT_LIST_CASE)
1488 STRUCT_LIST(STRUCT_LIST_CASE)
1489 if (n == NULL) continue;
1490 printf(" 0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n);
1493 #undef STRUCT_LIST_CASE
1494 #undef ROOT_LIST_CASE
1496 // Dump the KNOWN_OBJECTS table to the console.
1497 printf("\n# List of known V8 objects.\n");
1498 #define ROOT_LIST_CASE(type, name, camel_name) \
1499 if (n == NULL && o == heap->name()) n = #camel_name;
1500 i::OldSpaces spit(heap);
1501 printf("KNOWN_OBJECTS = {\n");
1502 for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) {
1503 i::HeapObjectIterator it(s);
1504 const char* sname = AllocationSpaceName(s->identity());
1505 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1506 const char* n = NULL;
1507 intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff;
1508 ROOT_LIST(ROOT_LIST_CASE)
1509 if (n == NULL) continue;
1510 printf(" (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n);
1514 #undef ROOT_LIST_CASE
1516 #endif // !V8_SHARED
1519 class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1521 virtual void* Allocate(size_t length) {
1522 void* data = AllocateUninitialized(length);
1523 return data == NULL ? data : memset(data, 0, length);
1525 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
1526 virtual void Free(void* data, size_t) { free(data); }
1530 class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1532 virtual void* Allocate(size_t) V8_OVERRIDE {
1535 virtual void* AllocateUninitialized(size_t length) V8_OVERRIDE {
1538 virtual void Free(void* p, size_t) V8_OVERRIDE {
1544 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1545 class StartupDataHandler {
1547 StartupDataHandler(const char* natives_blob,
1548 const char* snapshot_blob) {
1549 Load(natives_blob, &natives_, v8::V8::SetNativesDataBlob);
1550 Load(snapshot_blob, &snapshot_, v8::V8::SetSnapshotDataBlob);
1553 ~StartupDataHandler() {
1554 delete[] natives_.data;
1555 delete[] snapshot_.data;
1559 void Load(const char* blob_file,
1560 v8::StartupData* startup_data,
1561 void (*setter_fn)(v8::StartupData*)) {
1562 startup_data->data = NULL;
1563 startup_data->compressed_size = 0;
1564 startup_data->raw_size = 0;
1569 FILE* file = fopen(blob_file, "rb");
1573 fseek(file, 0, SEEK_END);
1574 startup_data->raw_size = ftell(file);
1577 startup_data->data = new char[startup_data->raw_size];
1578 startup_data->compressed_size = fread(
1579 const_cast<char*>(startup_data->data), 1, startup_data->raw_size,
1583 if (startup_data->raw_size == startup_data->compressed_size)
1584 (*setter_fn)(startup_data);
1587 v8::StartupData natives_;
1588 v8::StartupData snapshot_;
1590 // Disallow copy & assign.
1591 StartupDataHandler(const StartupDataHandler& other);
1592 void operator=(const StartupDataHandler& other);
1594 #endif // V8_USE_EXTERNAL_STARTUP_DATA
1597 int Shell::Main(int argc, char* argv[]) {
1598 if (!SetOptions(argc, argv)) return 1;
1599 v8::V8::InitializeICU(options.icu_data_file);
1600 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
1601 v8::V8::InitializePlatform(platform);
1602 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1603 StartupDataHandler startup_data(options.natives_blob, options.snapshot_blob);
1605 SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg");
1606 SetFlagsFromString("--redirect-code-traces-to=code.asm");
1607 ShellArrayBufferAllocator array_buffer_allocator;
1608 MockArrayBufferAllocator mock_arraybuffer_allocator;
1609 if (options.mock_arraybuffer_allocator) {
1610 v8::V8::SetArrayBufferAllocator(&mock_arraybuffer_allocator);
1612 v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
1615 Isolate* isolate = Isolate::New();
1617 v8::ResourceConstraints constraints;
1618 constraints.ConfigureDefaults(base::OS::TotalPhysicalMemory(),
1619 base::OS::MaxVirtualMemory(),
1620 base::OS::NumberOfProcessorsOnline());
1621 v8::SetResourceConstraints(isolate, &constraints);
1623 DumbLineEditor dumb_line_editor(isolate);
1625 Isolate::Scope scope(isolate);
1626 Initialize(isolate);
1627 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
1628 if (i::FLAG_gdbjit) {
1629 v8::V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault,
1630 i::GDBJITInterface::EventHandler);
1633 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1634 vTune::InitializeVtuneForV8();
1636 PerIsolateData data(isolate);
1637 InitializeDebugger(isolate);
1640 if (options.dump_heap_constants) {
1641 DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate));
1646 if (options.stress_opt || options.stress_deopt) {
1647 Testing::SetStressRunType(options.stress_opt
1648 ? Testing::kStressTypeOpt
1649 : Testing::kStressTypeDeopt);
1650 int stress_runs = Testing::GetStressRuns();
1651 for (int i = 0; i < stress_runs && result == 0; i++) {
1652 printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1653 Testing::PrepareStressRun(i);
1654 options.last_run = (i == stress_runs - 1);
1655 result = RunMain(isolate, argc, argv);
1657 printf("======== Full Deoptimization =======\n");
1658 Testing::DeoptimizeAll();
1659 #if !defined(V8_SHARED)
1660 } else if (i::FLAG_stress_runs > 0) {
1661 int stress_runs = i::FLAG_stress_runs;
1662 for (int i = 0; i < stress_runs && result == 0; i++) {
1663 printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1664 options.last_run = (i == stress_runs - 1);
1665 result = RunMain(isolate, argc, argv);
1669 result = RunMain(isolate, argc, argv);
1672 // Run interactive shell if explicitly requested or if no script has been
1673 // executed, but never on --test
1674 if (options.use_interactive_shell()) {
1676 if (!i::FLAG_debugger) {
1677 InstallUtilityScript(isolate);
1679 #endif // !V8_SHARED
1685 V8::ShutdownPlatform();
1697 int main(int argc, char* argv[]) {
1698 return v8::Shell::Main(argc, argv);