1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 // Defined when linking against shared lib on Windows.
7 #if defined(USING_V8_SHARED) && !defined(V8_SHARED)
25 #include "include/v8-testing.h"
28 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
29 #include "src/gdb-jit.h"
32 #ifdef ENABLE_VTUNE_JIT_INTERFACE
33 #include "src/third_party/vtune/v8-vtune.h"
38 #include "include/libplatform/libplatform.h"
41 #include "src/base/cpu.h"
42 #include "src/base/logging.h"
43 #include "src/base/platform/platform.h"
44 #include "src/base/sys-info.h"
45 #include "src/basic-block-profiler.h"
46 #include "src/d8-debug.h"
47 #include "src/debug.h"
48 #include "src/natives.h"
52 #if !defined(_WIN32) && !defined(_WIN64)
53 #include <unistd.h> // NOLINT
55 #include <windows.h> // NOLINT
57 #include <crtdbg.h> // NOLINT
58 #endif // defined(_MSC_VER)
59 #endif // !defined(_WIN32) && !defined(_WIN64)
62 #define DCHECK(condition) assert(condition)
68 static Handle<Value> Throw(Isolate* isolate, const char* message) {
69 return isolate->ThrowException(String::NewFromUtf8(isolate, message));
74 class PerIsolateData {
76 explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
77 HandleScope scope(isolate);
78 isolate->SetData(0, this);
82 isolate_->SetData(0, NULL); // Not really needed, just to be sure...
85 inline static PerIsolateData* Get(Isolate* isolate) {
86 return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
91 explicit RealmScope(PerIsolateData* data);
94 PerIsolateData* data_;
99 friend class RealmScope;
104 Persistent<Context>* realms_;
105 Persistent<Value> realm_shared_;
107 int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
109 int RealmFind(Handle<Context> context);
113 LineEditor *LineEditor::current_ = NULL;
116 LineEditor::LineEditor(Type type, const char* name)
117 : type_(type), name_(name) {
118 if (current_ == NULL || current_->type_ < type) current_ = this;
122 class DumbLineEditor: public LineEditor {
124 explicit DumbLineEditor(Isolate* isolate)
125 : LineEditor(LineEditor::DUMB, "dumb"), isolate_(isolate) { }
126 virtual Handle<String> Prompt(const char* prompt);
132 Handle<String> DumbLineEditor::Prompt(const char* prompt) {
133 printf("%s", prompt);
134 #if defined(__native_client__)
135 // Native Client libc is used to being embedded in Chrome and
136 // has trouble recognizing when to flush.
139 return Shell::ReadFromStdin(isolate_);
144 CounterMap* Shell::counter_map_;
145 base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
146 CounterCollection Shell::local_counters_;
147 CounterCollection* Shell::counters_ = &local_counters_;
148 base::Mutex Shell::context_mutex_;
149 const base::TimeTicks Shell::kInitialTicks =
150 base::TimeTicks::HighResolutionNow();
151 Persistent<Context> Shell::utility_context_;
154 Persistent<Context> Shell::evaluation_context_;
155 ShellOptions Shell::options;
156 const char* Shell::kPrompt = "d8> ";
160 const int MB = 1024 * 1024;
162 bool CounterMap::Match(void* key1, void* key2) {
163 const char* name1 = reinterpret_cast<const char*>(key1);
164 const char* name2 = reinterpret_cast<const char*>(key2);
165 return strcmp(name1, name2) == 0;
170 // Converts a V8 value to a C string.
171 const char* Shell::ToCString(const v8::String::Utf8Value& value) {
172 return *value ? *value : "<string conversion failed>";
176 ScriptCompiler::CachedData* CompileForCachedData(
177 Local<String> source, Local<Value> name,
178 ScriptCompiler::CompileOptions compile_options) {
179 int source_length = source->Length();
180 uint16_t* source_buffer = new uint16_t[source_length];
181 source->Write(source_buffer, 0, source_length);
183 uint16_t* name_buffer = NULL;
184 if (name->IsString()) {
185 Local<String> name_string = Local<String>::Cast(name);
186 name_length = name_string->Length();
187 name_buffer = new uint16_t[name_length];
188 name_string->Write(name_buffer, 0, name_length);
190 Isolate* temp_isolate = Isolate::New();
191 ScriptCompiler::CachedData* result = NULL;
193 Isolate::Scope isolate_scope(temp_isolate);
194 HandleScope handle_scope(temp_isolate);
195 Context::Scope context_scope(Context::New(temp_isolate));
196 Local<String> source_copy = v8::String::NewFromTwoByte(
197 temp_isolate, source_buffer, v8::String::kNormalString, source_length);
198 Local<Value> name_copy;
200 name_copy = v8::String::NewFromTwoByte(
201 temp_isolate, name_buffer, v8::String::kNormalString, name_length);
203 name_copy = v8::Undefined(temp_isolate);
205 ScriptCompiler::Source script_source(source_copy, ScriptOrigin(name_copy));
206 ScriptCompiler::CompileUnbound(temp_isolate, &script_source,
208 if (script_source.GetCachedData()) {
209 int length = script_source.GetCachedData()->length;
210 uint8_t* cache = new uint8_t[length];
211 memcpy(cache, script_source.GetCachedData()->data, length);
212 result = new ScriptCompiler::CachedData(
213 cache, length, ScriptCompiler::CachedData::BufferOwned);
216 temp_isolate->Dispose();
217 delete[] source_buffer;
218 delete[] name_buffer;
223 // Compile a string within the current v8 context.
224 Local<UnboundScript> Shell::CompileString(
225 Isolate* isolate, Local<String> source, Local<Value> name,
226 ScriptCompiler::CompileOptions compile_options) {
227 ScriptOrigin origin(name);
228 if (compile_options == ScriptCompiler::kNoCompileOptions) {
229 ScriptCompiler::Source script_source(source, origin);
230 return ScriptCompiler::CompileUnbound(isolate, &script_source,
234 ScriptCompiler::CachedData* data =
235 CompileForCachedData(source, name, compile_options);
236 ScriptCompiler::Source cached_source(source, origin, data);
237 if (compile_options == ScriptCompiler::kProduceCodeCache) {
238 compile_options = ScriptCompiler::kConsumeCodeCache;
239 } else if (compile_options == ScriptCompiler::kProduceParserCache) {
240 compile_options = ScriptCompiler::kConsumeParserCache;
242 DCHECK(false); // A new compile option?
244 if (data == NULL) compile_options = ScriptCompiler::kNoCompileOptions;
245 return ScriptCompiler::CompileUnbound(isolate, &cached_source,
250 // Executes a string within the current v8 context.
251 bool Shell::ExecuteString(Isolate* isolate,
252 Handle<String> source,
255 bool report_exceptions) {
257 bool FLAG_debugger = i::FLAG_debugger;
259 bool FLAG_debugger = false;
261 HandleScope handle_scope(isolate);
263 options.script_executed = true;
265 // When debugging make exceptions appear to be uncaught.
266 try_catch.SetVerbose(true);
269 Handle<UnboundScript> script =
270 Shell::CompileString(isolate, source, name, options.compile_options);
271 if (script.IsEmpty()) {
272 // Print errors that happened during compilation.
273 if (report_exceptions && !FLAG_debugger)
274 ReportException(isolate, &try_catch);
277 PerIsolateData* data = PerIsolateData::Get(isolate);
278 Local<Context> realm =
279 Local<Context>::New(isolate, data->realms_[data->realm_current_]);
281 Handle<Value> result = script->BindToCurrentContext()->Run();
283 data->realm_current_ = data->realm_switch_;
284 if (result.IsEmpty()) {
285 DCHECK(try_catch.HasCaught());
286 // Print errors that happened during execution.
287 if (report_exceptions && !FLAG_debugger)
288 ReportException(isolate, &try_catch);
291 DCHECK(!try_catch.HasCaught());
293 #if !defined(V8_SHARED)
294 if (options.test_shell) {
296 if (!result->IsUndefined()) {
297 // If all went well and the result wasn't undefined then print
298 // the returned value.
299 v8::String::Utf8Value str(result);
300 fwrite(*str, sizeof(**str), str.length(), stdout);
303 #if !defined(V8_SHARED)
305 v8::TryCatch try_catch;
306 v8::Local<v8::Context> context =
307 v8::Local<v8::Context>::New(isolate, utility_context_);
308 v8::Context::Scope context_scope(context);
309 Handle<Object> global = context->Global();
311 global->Get(String::NewFromUtf8(isolate, "Stringify"));
312 Handle<Value> argv[1] = { result };
313 Handle<Value> s = Handle<Function>::Cast(fun)->Call(global, 1, argv);
314 if (try_catch.HasCaught()) return true;
315 v8::String::Utf8Value str(s);
316 fwrite(*str, sizeof(**str), str.length(), stdout);
327 PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
328 data_->realm_count_ = 1;
329 data_->realm_current_ = 0;
330 data_->realm_switch_ = 0;
331 data_->realms_ = new Persistent<Context>[1];
332 data_->realms_[0].Reset(data_->isolate_,
333 data_->isolate_->GetEnteredContext());
337 PerIsolateData::RealmScope::~RealmScope() {
338 // Drop realms to avoid keeping them alive.
339 for (int i = 0; i < data_->realm_count_; ++i)
340 data_->realms_[i].Reset();
341 delete[] data_->realms_;
342 if (!data_->realm_shared_.IsEmpty())
343 data_->realm_shared_.Reset();
347 int PerIsolateData::RealmFind(Handle<Context> context) {
348 for (int i = 0; i < realm_count_; ++i) {
349 if (realms_[i] == context) return i;
355 int PerIsolateData::RealmIndexOrThrow(
356 const v8::FunctionCallbackInfo<v8::Value>& args,
358 if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
359 Throw(args.GetIsolate(), "Invalid argument");
362 int index = args[arg_offset]->Int32Value();
364 index >= realm_count_ ||
365 realms_[index].IsEmpty()) {
366 Throw(args.GetIsolate(), "Invalid realm index");
374 // performance.now() returns a time stamp as double, measured in milliseconds.
375 // When FLAG_verify_predictable mode is enabled it returns current value
376 // of Heap::allocations_count().
377 void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
378 if (i::FLAG_verify_predictable) {
379 Isolate* v8_isolate = args.GetIsolate();
380 i::Heap* heap = reinterpret_cast<i::Isolate*>(v8_isolate)->heap();
381 args.GetReturnValue().Set(heap->synthetic_time());
383 base::TimeDelta delta =
384 base::TimeTicks::HighResolutionNow() - kInitialTicks;
385 args.GetReturnValue().Set(delta.InMillisecondsF());
391 // Realm.current() returns the index of the currently active realm.
392 void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
393 Isolate* isolate = args.GetIsolate();
394 PerIsolateData* data = PerIsolateData::Get(isolate);
395 int index = data->RealmFind(isolate->GetEnteredContext());
396 if (index == -1) return;
397 args.GetReturnValue().Set(index);
401 // Realm.owner(o) returns the index of the realm that created o.
402 void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
403 Isolate* isolate = args.GetIsolate();
404 PerIsolateData* data = PerIsolateData::Get(isolate);
405 if (args.Length() < 1 || !args[0]->IsObject()) {
406 Throw(args.GetIsolate(), "Invalid argument");
409 int index = data->RealmFind(args[0]->ToObject(isolate)->CreationContext());
410 if (index == -1) return;
411 args.GetReturnValue().Set(index);
415 // Realm.global(i) returns the global object of realm i.
416 // (Note that properties of global objects cannot be read/written cross-realm.)
417 void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
418 PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
419 int index = data->RealmIndexOrThrow(args, 0);
420 if (index == -1) return;
421 args.GetReturnValue().Set(
422 Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
426 // Realm.create() creates a new realm and returns its index.
427 void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
428 Isolate* isolate = args.GetIsolate();
429 PerIsolateData* data = PerIsolateData::Get(isolate);
430 Persistent<Context>* old_realms = data->realms_;
431 int index = data->realm_count_;
432 data->realms_ = new Persistent<Context>[++data->realm_count_];
433 for (int i = 0; i < index; ++i) {
434 data->realms_[i].Reset(isolate, old_realms[i]);
437 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
438 data->realms_[index].Reset(
439 isolate, Context::New(isolate, NULL, global_template));
440 args.GetReturnValue().Set(index);
444 // Realm.dispose(i) disposes the reference to the realm i.
445 void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
446 Isolate* isolate = args.GetIsolate();
447 PerIsolateData* data = PerIsolateData::Get(isolate);
448 int index = data->RealmIndexOrThrow(args, 0);
449 if (index == -1) return;
451 index == data->realm_current_ || index == data->realm_switch_) {
452 Throw(args.GetIsolate(), "Invalid realm index");
455 data->realms_[index].Reset();
459 // Realm.switch(i) switches to the realm i for consecutive interactive inputs.
460 void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
461 Isolate* isolate = args.GetIsolate();
462 PerIsolateData* data = PerIsolateData::Get(isolate);
463 int index = data->RealmIndexOrThrow(args, 0);
464 if (index == -1) return;
465 data->realm_switch_ = index;
469 // Realm.eval(i, s) evaluates s in realm i and returns the result.
470 void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
471 Isolate* isolate = args.GetIsolate();
472 PerIsolateData* data = PerIsolateData::Get(isolate);
473 int index = data->RealmIndexOrThrow(args, 0);
474 if (index == -1) return;
475 if (args.Length() < 2 || !args[1]->IsString()) {
476 Throw(args.GetIsolate(), "Invalid argument");
479 ScriptCompiler::Source script_source(args[1]->ToString(isolate));
480 Handle<UnboundScript> script = ScriptCompiler::CompileUnbound(
481 isolate, &script_source);
482 if (script.IsEmpty()) return;
483 Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
485 Handle<Value> result = script->BindToCurrentContext()->Run();
487 args.GetReturnValue().Set(result);
491 // Realm.shared is an accessor for a single shared value across realms.
492 void Shell::RealmSharedGet(Local<String> property,
493 const PropertyCallbackInfo<Value>& info) {
494 Isolate* isolate = info.GetIsolate();
495 PerIsolateData* data = PerIsolateData::Get(isolate);
496 if (data->realm_shared_.IsEmpty()) return;
497 info.GetReturnValue().Set(data->realm_shared_);
500 void Shell::RealmSharedSet(Local<String> property,
502 const PropertyCallbackInfo<void>& info) {
503 Isolate* isolate = info.GetIsolate();
504 PerIsolateData* data = PerIsolateData::Get(isolate);
505 data->realm_shared_.Reset(isolate, value);
509 void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
516 void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
517 for (int i = 0; i < args.Length(); i++) {
518 HandleScope handle_scope(args.GetIsolate());
523 // Explicitly catch potential exceptions in toString().
524 v8::TryCatch try_catch;
525 Handle<String> str_obj = args[i]->ToString(args.GetIsolate());
526 if (try_catch.HasCaught()) {
531 v8::String::Utf8Value str(str_obj);
532 int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
533 if (n != str.length()) {
534 printf("Error in fwrite\n");
541 void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
542 String::Utf8Value file(args[0]);
544 Throw(args.GetIsolate(), "Error loading file");
547 Handle<String> source = ReadFile(args.GetIsolate(), *file);
548 if (source.IsEmpty()) {
549 Throw(args.GetIsolate(), "Error loading file");
552 args.GetReturnValue().Set(source);
556 Handle<String> Shell::ReadFromStdin(Isolate* isolate) {
557 static const int kBufferSize = 256;
558 char buffer[kBufferSize];
559 Handle<String> accumulator = String::NewFromUtf8(isolate, "");
562 // Continue reading if the line ends with an escape '\\' or the line has
563 // not been fully read into the buffer yet (does not end with '\n').
564 // If fgets gets an error, just give up.
566 input = fgets(buffer, kBufferSize, stdin);
567 if (input == NULL) return Handle<String>();
568 length = static_cast<int>(strlen(buffer));
571 } else if (buffer[length-1] != '\n') {
572 accumulator = String::Concat(
574 String::NewFromUtf8(isolate, buffer, String::kNormalString, length));
575 } else if (length > 1 && buffer[length-2] == '\\') {
576 buffer[length-2] = '\n';
577 accumulator = String::Concat(
578 accumulator, String::NewFromUtf8(isolate, buffer,
579 String::kNormalString, length - 1));
581 return String::Concat(
582 accumulator, String::NewFromUtf8(isolate, buffer,
583 String::kNormalString, length - 1));
589 void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
590 for (int i = 0; i < args.Length(); i++) {
591 HandleScope handle_scope(args.GetIsolate());
592 String::Utf8Value file(args[i]);
594 Throw(args.GetIsolate(), "Error loading file");
597 Handle<String> source = ReadFile(args.GetIsolate(), *file);
598 if (source.IsEmpty()) {
599 Throw(args.GetIsolate(), "Error loading file");
602 if (!ExecuteString(args.GetIsolate(),
604 String::NewFromUtf8(args.GetIsolate(), *file),
607 Throw(args.GetIsolate(), "Error executing file");
614 void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
615 int exit_code = args[0]->Int32Value();
616 OnExit(args.GetIsolate());
621 void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
622 args.GetReturnValue().Set(
623 String::NewFromUtf8(args.GetIsolate(), V8::GetVersion()));
627 void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
628 HandleScope handle_scope(isolate);
630 Handle<Context> utility_context;
631 bool enter_context = !isolate->InContext();
633 utility_context = Local<Context>::New(isolate, utility_context_);
634 utility_context->Enter();
637 v8::String::Utf8Value exception(try_catch->Exception());
638 const char* exception_string = ToCString(exception);
639 Handle<Message> message = try_catch->Message();
640 if (message.IsEmpty()) {
641 // V8 didn't provide any extra information about this error; just
642 // print the exception.
643 printf("%s\n", exception_string);
645 // Print (filename):(line number): (message).
646 v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
647 const char* filename_string = ToCString(filename);
648 int linenum = message->GetLineNumber();
649 printf("%s:%i: %s\n", filename_string, linenum, exception_string);
650 // Print line of source code.
651 v8::String::Utf8Value sourceline(message->GetSourceLine());
652 const char* sourceline_string = ToCString(sourceline);
653 printf("%s\n", sourceline_string);
654 // Print wavy underline (GetUnderline is deprecated).
655 int start = message->GetStartColumn();
656 for (int i = 0; i < start; i++) {
659 int end = message->GetEndColumn();
660 for (int i = start; i < end; i++) {
664 v8::String::Utf8Value stack_trace(try_catch->StackTrace());
665 if (stack_trace.length() > 0) {
666 const char* stack_trace_string = ToCString(stack_trace);
667 printf("%s\n", stack_trace_string);
672 if (enter_context) utility_context->Exit();
678 Handle<Array> Shell::GetCompletions(Isolate* isolate,
680 Handle<String> full) {
681 EscapableHandleScope handle_scope(isolate);
682 v8::Local<v8::Context> utility_context =
683 v8::Local<v8::Context>::New(isolate, utility_context_);
684 v8::Context::Scope context_scope(utility_context);
685 Handle<Object> global = utility_context->Global();
687 global->Get(String::NewFromUtf8(isolate, "GetCompletions"));
688 static const int kArgc = 3;
689 v8::Local<v8::Context> evaluation_context =
690 v8::Local<v8::Context>::New(isolate, evaluation_context_);
691 Handle<Value> argv[kArgc] = { evaluation_context->Global(), text, full };
692 Local<Value> val = Local<Function>::Cast(fun)->Call(global, kArgc, argv);
693 return handle_scope.Escape(Local<Array>::Cast(val));
697 Local<Object> Shell::DebugMessageDetails(Isolate* isolate,
698 Handle<String> message) {
699 EscapableHandleScope handle_scope(isolate);
700 v8::Local<v8::Context> context =
701 v8::Local<v8::Context>::New(isolate, utility_context_);
702 v8::Context::Scope context_scope(context);
703 Handle<Object> global = context->Global();
705 global->Get(String::NewFromUtf8(isolate, "DebugMessageDetails"));
706 static const int kArgc = 1;
707 Handle<Value> argv[kArgc] = { message };
708 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
709 return handle_scope.Escape(Local<Object>(Handle<Object>::Cast(val)));
713 Local<Value> Shell::DebugCommandToJSONRequest(Isolate* isolate,
714 Handle<String> command) {
715 EscapableHandleScope handle_scope(isolate);
716 v8::Local<v8::Context> context =
717 v8::Local<v8::Context>::New(isolate, utility_context_);
718 v8::Context::Scope context_scope(context);
719 Handle<Object> global = context->Global();
721 global->Get(String::NewFromUtf8(isolate, "DebugCommandToJSONRequest"));
722 static const int kArgc = 1;
723 Handle<Value> argv[kArgc] = { command };
724 Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
725 return handle_scope.Escape(Local<Value>(val));
729 int32_t* Counter::Bind(const char* name, bool is_histogram) {
731 for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
732 name_[i] = static_cast<char>(name[i]);
734 is_histogram_ = is_histogram;
739 void Counter::AddSample(int32_t sample) {
741 sample_total_ += sample;
745 CounterCollection::CounterCollection() {
746 magic_number_ = 0xDEADFACE;
747 max_counters_ = kMaxCounters;
748 max_name_size_ = Counter::kMaxNameSize;
749 counters_in_use_ = 0;
753 Counter* CounterCollection::GetNextCounter() {
754 if (counters_in_use_ == kMaxCounters) return NULL;
755 return &counters_[counters_in_use_++];
759 void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
760 counters_file_ = base::OS::MemoryMappedFile::create(
761 name, sizeof(CounterCollection), &local_counters_);
762 void* memory = (counters_file_ == NULL) ?
763 NULL : counters_file_->memory();
764 if (memory == NULL) {
765 printf("Could not map counters file %s\n", name);
768 counters_ = static_cast<CounterCollection*>(memory);
769 isolate->SetCounterFunction(LookupCounter);
770 isolate->SetCreateHistogramFunction(CreateHistogram);
771 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
775 int CounterMap::Hash(const char* name) {
778 while ((c = *name++) != 0) {
786 Counter* Shell::GetCounter(const char* name, bool is_histogram) {
787 Counter* counter = counter_map_->Lookup(name);
789 if (counter == NULL) {
790 counter = counters_->GetNextCounter();
791 if (counter != NULL) {
792 counter_map_->Set(name, counter);
793 counter->Bind(name, is_histogram);
796 DCHECK(counter->is_histogram() == is_histogram);
802 int* Shell::LookupCounter(const char* name) {
803 Counter* counter = GetCounter(name, false);
805 if (counter != NULL) {
806 return counter->ptr();
813 void* Shell::CreateHistogram(const char* name,
817 return GetCounter(name, true);
821 void Shell::AddHistogramSample(void* histogram, int sample) {
822 Counter* counter = reinterpret_cast<Counter*>(histogram);
823 counter->AddSample(sample);
827 void Shell::InstallUtilityScript(Isolate* isolate) {
828 HandleScope scope(isolate);
829 // If we use the utility context, we have to set the security tokens so that
830 // utility, evaluation and debug context can all access each other.
831 v8::Local<v8::Context> utility_context =
832 v8::Local<v8::Context>::New(isolate, utility_context_);
833 v8::Local<v8::Context> evaluation_context =
834 v8::Local<v8::Context>::New(isolate, evaluation_context_);
835 utility_context->SetSecurityToken(Undefined(isolate));
836 evaluation_context->SetSecurityToken(Undefined(isolate));
837 v8::Context::Scope context_scope(utility_context);
839 if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
840 // Install the debugger object in the utility scope
841 i::Debug* debug = reinterpret_cast<i::Isolate*>(isolate)->debug();
843 i::Handle<i::Context> debug_context = debug->debug_context();
844 i::Handle<i::JSObject> js_debug
845 = i::Handle<i::JSObject>(debug_context->global_object());
846 utility_context->Global()->Set(String::NewFromUtf8(isolate, "$debug"),
847 Utils::ToLocal(js_debug));
848 debug_context->set_security_token(
849 reinterpret_cast<i::Isolate*>(isolate)->heap()->undefined_value());
851 // Run the d8 shell utility script in the utility context
852 int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
853 i::Vector<const char> shell_source =
854 i::NativesCollection<i::D8>::GetScriptSource(source_index);
855 i::Vector<const char> shell_source_name =
856 i::NativesCollection<i::D8>::GetScriptName(source_index);
857 Handle<String> source =
858 String::NewFromUtf8(isolate, shell_source.start(), String::kNormalString,
859 shell_source.length());
860 Handle<String> name =
861 String::NewFromUtf8(isolate, shell_source_name.start(),
862 String::kNormalString, shell_source_name.length());
863 ScriptOrigin origin(name);
864 Handle<Script> script = Script::Compile(source, &origin);
866 // Mark the d8 shell script as native to avoid it showing up as normal source
868 i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
869 i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
870 ? i::Handle<i::Script>(i::Script::cast(
871 i::JSFunction::cast(*compiled_script)->shared()->script()))
872 : i::Handle<i::Script>(i::Script::cast(
873 i::SharedFunctionInfo::cast(*compiled_script)->script()));
874 script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
876 // Start the in-process debugger if requested.
877 if (i::FLAG_debugger) v8::Debug::SetDebugEventListener(HandleDebugEvent);
882 Handle<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
883 Handle<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
884 global_template->Set(String::NewFromUtf8(isolate, "print"),
885 FunctionTemplate::New(isolate, Print));
886 global_template->Set(String::NewFromUtf8(isolate, "write"),
887 FunctionTemplate::New(isolate, Write));
888 global_template->Set(String::NewFromUtf8(isolate, "read"),
889 FunctionTemplate::New(isolate, Read));
890 global_template->Set(String::NewFromUtf8(isolate, "readbuffer"),
891 FunctionTemplate::New(isolate, ReadBuffer));
892 global_template->Set(String::NewFromUtf8(isolate, "readline"),
893 FunctionTemplate::New(isolate, ReadLine));
894 global_template->Set(String::NewFromUtf8(isolate, "load"),
895 FunctionTemplate::New(isolate, Load));
896 global_template->Set(String::NewFromUtf8(isolate, "quit"),
897 FunctionTemplate::New(isolate, Quit));
898 global_template->Set(String::NewFromUtf8(isolate, "version"),
899 FunctionTemplate::New(isolate, Version));
901 // Bind the Realm object.
902 Handle<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
903 realm_template->Set(String::NewFromUtf8(isolate, "current"),
904 FunctionTemplate::New(isolate, RealmCurrent));
905 realm_template->Set(String::NewFromUtf8(isolate, "owner"),
906 FunctionTemplate::New(isolate, RealmOwner));
907 realm_template->Set(String::NewFromUtf8(isolate, "global"),
908 FunctionTemplate::New(isolate, RealmGlobal));
909 realm_template->Set(String::NewFromUtf8(isolate, "create"),
910 FunctionTemplate::New(isolate, RealmCreate));
911 realm_template->Set(String::NewFromUtf8(isolate, "dispose"),
912 FunctionTemplate::New(isolate, RealmDispose));
913 realm_template->Set(String::NewFromUtf8(isolate, "switch"),
914 FunctionTemplate::New(isolate, RealmSwitch));
915 realm_template->Set(String::NewFromUtf8(isolate, "eval"),
916 FunctionTemplate::New(isolate, RealmEval));
917 realm_template->SetAccessor(String::NewFromUtf8(isolate, "shared"),
918 RealmSharedGet, RealmSharedSet);
919 global_template->Set(String::NewFromUtf8(isolate, "Realm"), realm_template);
922 Handle<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
923 performance_template->Set(String::NewFromUtf8(isolate, "now"),
924 FunctionTemplate::New(isolate, PerformanceNow));
925 global_template->Set(String::NewFromUtf8(isolate, "performance"),
926 performance_template);
929 Handle<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
930 AddOSMethods(isolate, os_templ);
931 global_template->Set(String::NewFromUtf8(isolate, "os"), os_templ);
933 return global_template;
937 void Shell::Initialize(Isolate* isolate) {
939 Shell::counter_map_ = new CounterMap();
941 if (i::StrLength(i::FLAG_map_counters) != 0)
942 MapCounters(isolate, i::FLAG_map_counters);
943 if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
944 isolate->SetCounterFunction(LookupCounter);
945 isolate->SetCreateHistogramFunction(CreateHistogram);
946 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
952 void Shell::InitializeDebugger(Isolate* isolate) {
953 if (options.test_shell) return;
955 HandleScope scope(isolate);
956 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
957 utility_context_.Reset(isolate,
958 Context::New(isolate, NULL, global_template));
963 Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
965 // This needs to be a critical section since this is not thread-safe
966 base::LockGuard<base::Mutex> lock_guard(&context_mutex_);
968 // Initialize the global objects
969 Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
970 EscapableHandleScope handle_scope(isolate);
971 Local<Context> context = Context::New(isolate, NULL, global_template);
972 DCHECK(!context.IsEmpty());
973 Context::Scope scope(context);
976 i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
977 i::JSArguments js_args = i::FLAG_js_arguments;
978 i::Handle<i::FixedArray> arguments_array =
979 factory->NewFixedArray(js_args.argc);
980 for (int j = 0; j < js_args.argc; j++) {
981 i::Handle<i::String> arg =
982 factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
983 arguments_array->set(j, *arg);
985 i::Handle<i::JSArray> arguments_jsarray =
986 factory->NewJSArrayWithElements(arguments_array);
987 context->Global()->Set(String::NewFromUtf8(isolate, "arguments"),
988 Utils::ToLocal(arguments_jsarray));
990 return handle_scope.Escape(context);
994 void Shell::Exit(int exit_code) {
995 // Use _exit instead of exit to avoid races between isolate
996 // threads and static destructors.
1004 struct CounterAndKey {
1010 inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
1011 return strcmp(lhs.key, rhs.key) < 0;
1013 #endif // !V8_SHARED
1016 void Shell::OnExit(v8::Isolate* isolate) {
1017 LineEditor* line_editor = LineEditor::Get();
1018 if (line_editor) line_editor->Close();
1020 reinterpret_cast<i::Isolate*>(isolate)->DumpAndResetCompilationStats();
1021 if (i::FLAG_dump_counters) {
1022 int number_of_counters = 0;
1023 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1024 number_of_counters++;
1026 CounterAndKey* counters = new CounterAndKey[number_of_counters];
1028 for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
1029 counters[j].counter = i.CurrentValue();
1030 counters[j].key = i.CurrentKey();
1032 std::sort(counters, counters + number_of_counters);
1033 printf("+----------------------------------------------------------------+"
1034 "-------------+\n");
1037 printf("+----------------------------------------------------------------+"
1038 "-------------+\n");
1039 for (j = 0; j < number_of_counters; j++) {
1040 Counter* counter = counters[j].counter;
1041 const char* key = counters[j].key;
1042 if (counter->is_histogram()) {
1043 printf("| c:%-60s | %11i |\n", key, counter->count());
1044 printf("| t:%-60s | %11i |\n", key, counter->sample_total());
1046 printf("| %-62s | %11i |\n", key, counter->count());
1049 printf("+----------------------------------------------------------------+"
1050 "-------------+\n");
1053 delete counters_file_;
1054 delete counter_map_;
1055 #endif // !V8_SHARED
1060 static FILE* FOpen(const char* path, const char* mode) {
1061 #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
1063 if (fopen_s(&result, path, mode) == 0) {
1069 FILE* file = fopen(path, mode);
1070 if (file == NULL) return NULL;
1071 struct stat file_stat;
1072 if (fstat(fileno(file), &file_stat) != 0) return NULL;
1073 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
1074 if (is_regular_file) return file;
1081 static char* ReadChars(Isolate* isolate, const char* name, int* size_out) {
1082 FILE* file = FOpen(name, "rb");
1083 if (file == NULL) return NULL;
1085 fseek(file, 0, SEEK_END);
1086 int size = ftell(file);
1089 char* chars = new char[size + 1];
1091 for (int i = 0; i < size;) {
1092 int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1101 struct DataAndPersistent {
1103 Persistent<ArrayBuffer> handle;
1107 static void ReadBufferWeakCallback(
1108 const v8::WeakCallbackData<ArrayBuffer, DataAndPersistent>& data) {
1109 size_t byte_length = data.GetValue()->ByteLength();
1110 data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
1111 -static_cast<intptr_t>(byte_length));
1113 delete[] data.GetParameter()->data;
1114 data.GetParameter()->handle.Reset();
1115 delete data.GetParameter();
1119 void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
1120 DCHECK(sizeof(char) == sizeof(uint8_t)); // NOLINT
1121 String::Utf8Value filename(args[0]);
1123 if (*filename == NULL) {
1124 Throw(args.GetIsolate(), "Error loading file");
1128 Isolate* isolate = args.GetIsolate();
1129 DataAndPersistent* data = new DataAndPersistent;
1130 data->data = reinterpret_cast<uint8_t*>(
1131 ReadChars(args.GetIsolate(), *filename, &length));
1132 if (data->data == NULL) {
1134 Throw(args.GetIsolate(), "Error reading file");
1137 Handle<v8::ArrayBuffer> buffer =
1138 ArrayBuffer::New(isolate, data->data, length);
1139 data->handle.Reset(isolate, buffer);
1140 data->handle.SetWeak(data, ReadBufferWeakCallback);
1141 data->handle.MarkIndependent();
1142 isolate->AdjustAmountOfExternalAllocatedMemory(length);
1144 args.GetReturnValue().Set(buffer);
1148 // Reads a file into a v8 string.
1149 Handle<String> Shell::ReadFile(Isolate* isolate, const char* name) {
1151 char* chars = ReadChars(isolate, name, &size);
1152 if (chars == NULL) return Handle<String>();
1153 Handle<String> result =
1154 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1160 void Shell::RunShell(Isolate* isolate) {
1161 HandleScope outer_scope(isolate);
1162 v8::Local<v8::Context> context =
1163 v8::Local<v8::Context>::New(isolate, evaluation_context_);
1164 v8::Context::Scope context_scope(context);
1165 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1166 Handle<String> name = String::NewFromUtf8(isolate, "(d8)");
1167 LineEditor* console = LineEditor::Get();
1168 printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
1169 console->Open(isolate);
1171 HandleScope inner_scope(isolate);
1172 Handle<String> input = console->Prompt(Shell::kPrompt);
1173 if (input.IsEmpty()) break;
1174 ExecuteString(isolate, input, name, true, true);
1180 SourceGroup::~SourceGroup() {
1184 #endif // !V8_SHARED
1188 void SourceGroup::Execute(Isolate* isolate) {
1189 bool exception_was_thrown = false;
1190 for (int i = begin_offset_; i < end_offset_; ++i) {
1191 const char* arg = argv_[i];
1192 if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
1193 // Execute argument given to -e option directly.
1194 HandleScope handle_scope(isolate);
1195 Handle<String> file_name = String::NewFromUtf8(isolate, "unnamed");
1196 Handle<String> source = String::NewFromUtf8(isolate, argv_[i + 1]);
1197 if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1198 exception_was_thrown = true;
1202 } else if (arg[0] == '-') {
1203 // Ignore other options. They have been parsed already.
1205 // Use all other arguments as names of files to load and run.
1206 HandleScope handle_scope(isolate);
1207 Handle<String> file_name = String::NewFromUtf8(isolate, arg);
1208 Handle<String> source = ReadFile(isolate, arg);
1209 if (source.IsEmpty()) {
1210 printf("Error reading '%s'\n", arg);
1213 if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1214 exception_was_thrown = true;
1219 if (exception_was_thrown != Shell::options.expected_to_throw) {
1225 Handle<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
1227 char* chars = ReadChars(isolate, name, &size);
1228 if (chars == NULL) return Handle<String>();
1229 Handle<String> result =
1230 String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1237 base::Thread::Options SourceGroup::GetThreadOptions() {
1238 // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
1239 // which is not enough to parse the big literal expressions used in tests.
1240 // The stack size should be at least StackGuard::kLimitSize + some
1241 // OS-specific padding for thread startup code. 2Mbytes seems to be enough.
1242 return base::Thread::Options("IsolateThread", 2 * MB);
1246 void SourceGroup::ExecuteInThread() {
1247 Isolate* isolate = Isolate::New();
1249 next_semaphore_.Wait();
1251 Isolate::Scope iscope(isolate);
1253 HandleScope scope(isolate);
1254 PerIsolateData data(isolate);
1255 Local<Context> context = Shell::CreateEvaluationContext(isolate);
1257 Context::Scope cscope(context);
1258 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1262 if (Shell::options.send_idle_notification) {
1263 const int kLongIdlePauseInMs = 1000;
1264 isolate->ContextDisposedNotification();
1265 isolate->IdleNotification(kLongIdlePauseInMs);
1267 if (Shell::options.invoke_weak_callbacks) {
1268 // By sending a low memory notifications, we will try hard to collect
1269 // all garbage and will therefore also invoke all weak callbacks of
1270 // actually unreachable persistent handles.
1271 isolate->LowMemoryNotification();
1274 done_semaphore_.Signal();
1275 } while (!Shell::options.last_run);
1281 void SourceGroup::StartExecuteInThread() {
1282 if (thread_ == NULL) {
1283 thread_ = new IsolateThread(this);
1286 next_semaphore_.Signal();
1290 void SourceGroup::WaitForThread() {
1291 if (thread_ == NULL) return;
1292 if (Shell::options.last_run) {
1295 done_semaphore_.Wait();
1298 #endif // !V8_SHARED
1301 void SetFlagsFromString(const char* flags) {
1302 v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags)));
1306 bool Shell::SetOptions(int argc, char* argv[]) {
1307 bool logfile_per_isolate = false;
1308 for (int i = 0; i < argc; i++) {
1309 if (strcmp(argv[i], "--stress-opt") == 0) {
1310 options.stress_opt = true;
1312 } else if (strcmp(argv[i], "--nostress-opt") == 0) {
1313 options.stress_opt = false;
1315 } else if (strcmp(argv[i], "--stress-deopt") == 0) {
1316 options.stress_deopt = true;
1318 } else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) {
1319 options.mock_arraybuffer_allocator = true;
1321 } else if (strcmp(argv[i], "--noalways-opt") == 0) {
1322 // No support for stressing if we can't use --always-opt.
1323 options.stress_opt = false;
1324 options.stress_deopt = false;
1325 } else if (strcmp(argv[i], "--logfile-per-isolate") == 0) {
1326 logfile_per_isolate = true;
1328 } else if (strcmp(argv[i], "--shell") == 0) {
1329 options.interactive_shell = true;
1331 } else if (strcmp(argv[i], "--test") == 0) {
1332 options.test_shell = true;
1334 } else if (strcmp(argv[i], "--send-idle-notification") == 0) {
1335 options.send_idle_notification = true;
1337 } else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) {
1338 options.invoke_weak_callbacks = true;
1339 // TODO(jochen) See issue 3351
1340 options.send_idle_notification = true;
1342 } else if (strcmp(argv[i], "-f") == 0) {
1343 // Ignore any -f flags for compatibility with other stand-alone
1344 // JavaScript engines.
1346 } else if (strcmp(argv[i], "--isolate") == 0) {
1348 printf("D8 with shared library does not support multi-threading\n");
1351 options.num_isolates++;
1352 } else if (strcmp(argv[i], "--dump-heap-constants") == 0) {
1354 printf("D8 with shared library does not support constant dumping\n");
1357 options.dump_heap_constants = true;
1360 } else if (strcmp(argv[i], "--throws") == 0) {
1361 options.expected_to_throw = true;
1363 } else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) {
1364 options.icu_data_file = argv[i] + 16;
1367 } else if (strcmp(argv[i], "--dump-counters") == 0) {
1368 printf("D8 with shared library does not include counters\n");
1370 } else if (strcmp(argv[i], "--debugger") == 0) {
1371 printf("Javascript debugger not included\n");
1374 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1375 } else if (strncmp(argv[i], "--natives_blob=", 15) == 0) {
1376 options.natives_blob = argv[i] + 15;
1378 } else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) {
1379 options.snapshot_blob = argv[i] + 16;
1381 #endif // V8_USE_EXTERNAL_STARTUP_DATA
1382 } else if (strcmp(argv[i], "--cache") == 0 ||
1383 strncmp(argv[i], "--cache=", 8) == 0) {
1384 const char* value = argv[i] + 7;
1385 if (!*value || strncmp(value, "=code", 6) == 0) {
1386 options.compile_options = v8::ScriptCompiler::kProduceCodeCache;
1387 } else if (strncmp(value, "=parse", 7) == 0) {
1388 options.compile_options = v8::ScriptCompiler::kProduceParserCache;
1389 } else if (strncmp(value, "=none", 6) == 0) {
1390 options.compile_options = v8::ScriptCompiler::kNoCompileOptions;
1392 printf("Unknown option to --cache.\n");
1399 v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
1401 // Set up isolated source groups.
1402 options.isolate_sources = new SourceGroup[options.num_isolates];
1403 SourceGroup* current = options.isolate_sources;
1404 current->Begin(argv, 1);
1405 for (int i = 1; i < argc; i++) {
1406 const char* str = argv[i];
1407 if (strcmp(str, "--isolate") == 0) {
1410 current->Begin(argv, i + 1);
1411 } else if (strncmp(argv[i], "--", 2) == 0) {
1412 printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
1417 if (!logfile_per_isolate && options.num_isolates) {
1418 SetFlagsFromString("--nologfile_per_isolate");
1425 int Shell::RunMain(Isolate* isolate, int argc, char* argv[]) {
1427 for (int i = 1; i < options.num_isolates; ++i) {
1428 options.isolate_sources[i].StartExecuteInThread();
1430 #endif // !V8_SHARED
1432 HandleScope scope(isolate);
1433 Local<Context> context = CreateEvaluationContext(isolate);
1434 if (options.last_run && options.use_interactive_shell()) {
1435 // Keep using the same context in the interactive shell.
1436 evaluation_context_.Reset(isolate, context);
1438 // If the interactive debugger is enabled make sure to activate
1439 // it before running the files passed on the command line.
1440 if (i::FLAG_debugger) {
1441 InstallUtilityScript(isolate);
1443 #endif // !V8_SHARED
1446 Context::Scope cscope(context);
1447 PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1448 options.isolate_sources[0].Execute(isolate);
1451 if (options.send_idle_notification) {
1452 const int kLongIdlePauseInMs = 1000;
1453 isolate->ContextDisposedNotification();
1454 isolate->IdleNotification(kLongIdlePauseInMs);
1456 if (options.invoke_weak_callbacks) {
1457 // By sending a low memory notifications, we will try hard to collect all
1458 // garbage and will therefore also invoke all weak callbacks of actually
1459 // unreachable persistent handles.
1460 isolate->LowMemoryNotification();
1464 for (int i = 1; i < options.num_isolates; ++i) {
1465 options.isolate_sources[i].WaitForThread();
1467 #endif // !V8_SHARED
1473 static void DumpHeapConstants(i::Isolate* isolate) {
1474 i::Heap* heap = isolate->heap();
1476 // Dump the INSTANCE_TYPES table to the console.
1477 printf("# List of known V8 instance types.\n");
1478 #define DUMP_TYPE(T) printf(" %d: \"%s\",\n", i::T, #T);
1479 printf("INSTANCE_TYPES = {\n");
1480 INSTANCE_TYPE_LIST(DUMP_TYPE)
1484 // Dump the KNOWN_MAP table to the console.
1485 printf("\n# List of known V8 maps.\n");
1486 #define ROOT_LIST_CASE(type, name, camel_name) \
1487 if (n == NULL && o == heap->name()) n = #camel_name;
1488 #define STRUCT_LIST_CASE(upper_name, camel_name, name) \
1489 if (n == NULL && o == heap->name##_map()) n = #camel_name "Map";
1490 i::HeapObjectIterator it(heap->map_space());
1491 printf("KNOWN_MAPS = {\n");
1492 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1493 i::Map* m = i::Map::cast(o);
1494 const char* n = NULL;
1495 intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff;
1496 int t = m->instance_type();
1497 ROOT_LIST(ROOT_LIST_CASE)
1498 STRUCT_LIST(STRUCT_LIST_CASE)
1499 if (n == NULL) continue;
1500 printf(" 0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n);
1503 #undef STRUCT_LIST_CASE
1504 #undef ROOT_LIST_CASE
1506 // Dump the KNOWN_OBJECTS table to the console.
1507 printf("\n# List of known V8 objects.\n");
1508 #define ROOT_LIST_CASE(type, name, camel_name) \
1509 if (n == NULL && o == heap->name()) n = #camel_name;
1510 i::OldSpaces spit(heap);
1511 printf("KNOWN_OBJECTS = {\n");
1512 for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) {
1513 i::HeapObjectIterator it(s);
1514 const char* sname = AllocationSpaceName(s->identity());
1515 for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1516 const char* n = NULL;
1517 intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff;
1518 ROOT_LIST(ROOT_LIST_CASE)
1519 if (n == NULL) continue;
1520 printf(" (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n);
1524 #undef ROOT_LIST_CASE
1526 #endif // !V8_SHARED
1529 class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1531 virtual void* Allocate(size_t length) {
1532 void* data = AllocateUninitialized(length);
1533 return data == NULL ? data : memset(data, 0, length);
1535 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
1536 virtual void Free(void* data, size_t) { free(data); }
1540 class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1542 void* Allocate(size_t) OVERRIDE { return malloc(0); }
1543 void* AllocateUninitialized(size_t length) OVERRIDE { return malloc(0); }
1544 void Free(void* p, size_t) OVERRIDE { free(p); }
1548 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1549 class StartupDataHandler {
1551 StartupDataHandler(const char* exec_path, const char* natives_blob,
1552 const char* snapshot_blob) {
1553 // If we have (at least one) explicitly given blob, use those.
1554 // If not, use the default blob locations next to the d8 binary.
1555 if (natives_blob || snapshot_blob) {
1556 LoadFromFiles(natives_blob, snapshot_blob);
1560 LoadFromFiles(RelativePath(&natives, exec_path, "natives_blob.bin"),
1561 RelativePath(&snapshot, exec_path, "snapshot_blob.bin"));
1568 ~StartupDataHandler() {
1569 delete[] natives_.data;
1570 delete[] snapshot_.data;
1574 static char* RelativePath(char** buffer, const char* exec_path,
1577 const char* last_slash = strrchr(exec_path, '/');
1579 int after_slash = last_slash - exec_path + 1;
1580 int name_length = strlen(name);
1582 reinterpret_cast<char*>(calloc(after_slash + name_length + 1, 1));
1583 strncpy(*buffer, exec_path, after_slash);
1584 strncat(*buffer, name, name_length);
1586 *buffer = strdup(name);
1591 void LoadFromFiles(const char* natives_blob, const char* snapshot_blob) {
1592 Load(natives_blob, &natives_, v8::V8::SetNativesDataBlob);
1593 Load(snapshot_blob, &snapshot_, v8::V8::SetSnapshotDataBlob);
1596 void Load(const char* blob_file,
1597 v8::StartupData* startup_data,
1598 void (*setter_fn)(v8::StartupData*)) {
1599 startup_data->data = NULL;
1600 startup_data->raw_size = 0;
1605 FILE* file = fopen(blob_file, "rb");
1609 fseek(file, 0, SEEK_END);
1610 startup_data->raw_size = ftell(file);
1613 startup_data->data = new char[startup_data->raw_size];
1615 static_cast<int>(fread(const_cast<char*>(startup_data->data), 1,
1616 startup_data->raw_size, file));
1619 if (startup_data->raw_size == read_size) (*setter_fn)(startup_data);
1622 v8::StartupData natives_;
1623 v8::StartupData snapshot_;
1625 // Disallow copy & assign.
1626 StartupDataHandler(const StartupDataHandler& other);
1627 void operator=(const StartupDataHandler& other);
1629 #endif // V8_USE_EXTERNAL_STARTUP_DATA
1632 int Shell::Main(int argc, char* argv[]) {
1633 #if (defined(_WIN32) || defined(_WIN64))
1635 SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
1636 UINT existing_flags = SetErrorMode(new_flags);
1637 SetErrorMode(existing_flags | new_flags);
1638 #if defined(_MSC_VER)
1639 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1640 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1641 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1642 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1643 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1644 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1645 _set_error_mode(_OUT_TO_STDERR);
1646 #endif // defined(_MSC_VER)
1647 #endif // defined(_WIN32) || defined(_WIN64)
1648 if (!SetOptions(argc, argv)) return 1;
1649 v8::V8::InitializeICU(options.icu_data_file);
1650 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
1651 v8::V8::InitializePlatform(platform);
1652 v8::V8::Initialize();
1653 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1654 StartupDataHandler startup_data(argv[0], options.natives_blob,
1655 options.snapshot_blob);
1657 SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg");
1658 SetFlagsFromString("--trace-turbo-cfg-file=turbo.cfg");
1659 SetFlagsFromString("--redirect-code-traces-to=code.asm");
1660 ShellArrayBufferAllocator array_buffer_allocator;
1661 MockArrayBufferAllocator mock_arraybuffer_allocator;
1662 if (options.mock_arraybuffer_allocator) {
1663 v8::V8::SetArrayBufferAllocator(&mock_arraybuffer_allocator);
1665 v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
1668 Isolate::CreateParams create_params;
1669 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
1670 if (i::FLAG_gdbjit) {
1671 create_params.code_event_handler = i::GDBJITInterface::EventHandler;
1674 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1675 create_params.code_event_handler = vTune::GetVtuneCodeEventHandler();
1678 create_params.constraints.ConfigureDefaults(
1679 base::SysInfo::AmountOfPhysicalMemory(),
1680 base::SysInfo::AmountOfVirtualMemory(),
1681 base::SysInfo::NumberOfProcessors());
1683 Isolate* isolate = Isolate::New(create_params);
1684 DumbLineEditor dumb_line_editor(isolate);
1686 Isolate::Scope scope(isolate);
1687 Initialize(isolate);
1688 PerIsolateData data(isolate);
1689 InitializeDebugger(isolate);
1692 if (options.dump_heap_constants) {
1693 DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate));
1698 if (options.stress_opt || options.stress_deopt) {
1699 Testing::SetStressRunType(options.stress_opt
1700 ? Testing::kStressTypeOpt
1701 : Testing::kStressTypeDeopt);
1702 int stress_runs = Testing::GetStressRuns();
1703 for (int i = 0; i < stress_runs && result == 0; i++) {
1704 printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1705 Testing::PrepareStressRun(i);
1706 options.last_run = (i == stress_runs - 1);
1707 result = RunMain(isolate, argc, argv);
1709 printf("======== Full Deoptimization =======\n");
1710 Testing::DeoptimizeAll();
1711 #if !defined(V8_SHARED)
1712 } else if (i::FLAG_stress_runs > 0) {
1713 int stress_runs = i::FLAG_stress_runs;
1714 for (int i = 0; i < stress_runs && result == 0; i++) {
1715 printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1716 options.last_run = (i == stress_runs - 1);
1717 result = RunMain(isolate, argc, argv);
1721 result = RunMain(isolate, argc, argv);
1724 // Run interactive shell if explicitly requested or if no script has been
1725 // executed, but never on --test
1726 if (options.use_interactive_shell()) {
1728 if (!i::FLAG_debugger) {
1729 InstallUtilityScript(isolate);
1731 #endif // !V8_SHARED
1737 // Dump basic block profiling data.
1738 if (i::BasicBlockProfiler* profiler =
1739 reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) {
1740 i::OFStream os(stdout);
1743 #endif // !V8_SHARED
1746 V8::ShutdownPlatform();
1756 int main(int argc, char* argv[]) {
1757 return v8::Shell::Main(argc, argv);