7fa6f8c42e68a2cfd9de7f955da93229b94d1283
[platform/upstream/nodejs.git] / deps / v8 / src / d8.cc
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.
4
5
6 // Defined when linking against shared lib on Windows.
7 #if defined(USING_V8_SHARED) && !defined(V8_SHARED)
8 #define V8_SHARED
9 #endif
10
11 #include <errno.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/stat.h>
15
16 #ifdef V8_SHARED
17 #include <assert.h>
18 #endif  // V8_SHARED
19
20 #ifndef V8_SHARED
21 #include <algorithm>
22 #endif  // !V8_SHARED
23
24 #ifdef V8_SHARED
25 #include "include/v8-testing.h"
26 #endif  // V8_SHARED
27
28 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
29 #include "src/gdb-jit.h"
30 #endif
31
32 #ifdef ENABLE_VTUNE_JIT_INTERFACE
33 #include "src/third_party/vtune/v8-vtune.h"
34 #endif
35
36 #include "src/d8.h"
37
38 #include "include/libplatform/libplatform.h"
39 #ifndef V8_SHARED
40 #include "src/api.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"
49 #include "src/v8.h"
50 #endif  // !V8_SHARED
51
52 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
53 #include "src/startup-data-util.h"
54 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
55
56 #if !defined(_WIN32) && !defined(_WIN64)
57 #include <unistd.h>  // NOLINT
58 #else
59 #include <windows.h>  // NOLINT
60 #if defined(_MSC_VER)
61 #include <crtdbg.h>  // NOLINT
62 #endif               // defined(_MSC_VER)
63 #endif               // !defined(_WIN32) && !defined(_WIN64)
64
65 #ifndef DCHECK
66 #define DCHECK(condition) assert(condition)
67 #endif
68
69 #ifndef CHECK
70 #define CHECK(condition) assert(condition)
71 #endif
72
73 namespace v8 {
74
75
76 static Handle<Value> Throw(Isolate* isolate, const char* message) {
77   return isolate->ThrowException(String::NewFromUtf8(isolate, message));
78 }
79
80
81
82 class PerIsolateData {
83  public:
84   explicit PerIsolateData(Isolate* isolate) : isolate_(isolate), realms_(NULL) {
85     HandleScope scope(isolate);
86     isolate->SetData(0, this);
87   }
88
89   ~PerIsolateData() {
90     isolate_->SetData(0, NULL);  // Not really needed, just to be sure...
91   }
92
93   inline static PerIsolateData* Get(Isolate* isolate) {
94     return reinterpret_cast<PerIsolateData*>(isolate->GetData(0));
95   }
96
97   class RealmScope {
98    public:
99     explicit RealmScope(PerIsolateData* data);
100     ~RealmScope();
101    private:
102     PerIsolateData* data_;
103   };
104
105  private:
106   friend class Shell;
107   friend class RealmScope;
108   Isolate* isolate_;
109   int realm_count_;
110   int realm_current_;
111   int realm_switch_;
112   Persistent<Context>* realms_;
113   Persistent<Value> realm_shared_;
114
115   int RealmIndexOrThrow(const v8::FunctionCallbackInfo<v8::Value>& args,
116                         int arg_offset);
117   int RealmFind(Handle<Context> context);
118 };
119
120
121 LineEditor *LineEditor::current_ = NULL;
122
123
124 LineEditor::LineEditor(Type type, const char* name)
125     : type_(type), name_(name) {
126   if (current_ == NULL || current_->type_ < type) current_ = this;
127 }
128
129
130 class DumbLineEditor: public LineEditor {
131  public:
132   explicit DumbLineEditor(Isolate* isolate)
133       : LineEditor(LineEditor::DUMB, "dumb"), isolate_(isolate) { }
134   virtual Handle<String> Prompt(const char* prompt);
135  private:
136   Isolate* isolate_;
137 };
138
139
140 Handle<String> DumbLineEditor::Prompt(const char* prompt) {
141   printf("%s", prompt);
142 #if defined(__native_client__)
143   // Native Client libc is used to being embedded in Chrome and
144   // has trouble recognizing when to flush.
145   fflush(stdout);
146 #endif
147   return Shell::ReadFromStdin(isolate_);
148 }
149
150
151 #ifndef V8_SHARED
152 CounterMap* Shell::counter_map_;
153 base::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
154 CounterCollection Shell::local_counters_;
155 CounterCollection* Shell::counters_ = &local_counters_;
156 base::Mutex Shell::context_mutex_;
157 const base::TimeTicks Shell::kInitialTicks =
158     base::TimeTicks::HighResolutionNow();
159 Persistent<Context> Shell::utility_context_;
160 #endif  // !V8_SHARED
161
162 Persistent<Context> Shell::evaluation_context_;
163 ShellOptions Shell::options;
164 const char* Shell::kPrompt = "d8> ";
165
166
167 #ifndef V8_SHARED
168 const int MB = 1024 * 1024;
169
170 bool CounterMap::Match(void* key1, void* key2) {
171   const char* name1 = reinterpret_cast<const char*>(key1);
172   const char* name2 = reinterpret_cast<const char*>(key2);
173   return strcmp(name1, name2) == 0;
174 }
175 #endif  // !V8_SHARED
176
177
178 // Converts a V8 value to a C string.
179 const char* Shell::ToCString(const v8::String::Utf8Value& value) {
180   return *value ? *value : "<string conversion failed>";
181 }
182
183
184 ScriptCompiler::CachedData* CompileForCachedData(
185     Local<String> source, Local<Value> name,
186     ScriptCompiler::CompileOptions compile_options) {
187   int source_length = source->Length();
188   uint16_t* source_buffer = new uint16_t[source_length];
189   source->Write(source_buffer, 0, source_length);
190   int name_length = 0;
191   uint16_t* name_buffer = NULL;
192   if (name->IsString()) {
193     Local<String> name_string = Local<String>::Cast(name);
194     name_length = name_string->Length();
195     name_buffer = new uint16_t[name_length];
196     name_string->Write(name_buffer, 0, name_length);
197   }
198   Isolate* temp_isolate = Isolate::New();
199   ScriptCompiler::CachedData* result = NULL;
200   {
201     Isolate::Scope isolate_scope(temp_isolate);
202     HandleScope handle_scope(temp_isolate);
203     Context::Scope context_scope(Context::New(temp_isolate));
204     Local<String> source_copy = v8::String::NewFromTwoByte(
205         temp_isolate, source_buffer, v8::String::kNormalString, source_length);
206     Local<Value> name_copy;
207     if (name_buffer) {
208       name_copy = v8::String::NewFromTwoByte(
209           temp_isolate, name_buffer, v8::String::kNormalString, name_length);
210     } else {
211       name_copy = v8::Undefined(temp_isolate);
212     }
213     ScriptCompiler::Source script_source(source_copy, ScriptOrigin(name_copy));
214     ScriptCompiler::CompileUnbound(temp_isolate, &script_source,
215                                    compile_options);
216     if (script_source.GetCachedData()) {
217       int length = script_source.GetCachedData()->length;
218       uint8_t* cache = new uint8_t[length];
219       memcpy(cache, script_source.GetCachedData()->data, length);
220       result = new ScriptCompiler::CachedData(
221           cache, length, ScriptCompiler::CachedData::BufferOwned);
222     }
223   }
224   temp_isolate->Dispose();
225   delete[] source_buffer;
226   delete[] name_buffer;
227   return result;
228 }
229
230
231 // Compile a string within the current v8 context.
232 Local<Script> Shell::CompileString(
233     Isolate* isolate, Local<String> source, Local<Value> name,
234     ScriptCompiler::CompileOptions compile_options, SourceType source_type) {
235   ScriptOrigin origin(name);
236   if (compile_options == ScriptCompiler::kNoCompileOptions) {
237     ScriptCompiler::Source script_source(source, origin);
238     return source_type == SCRIPT
239                ? ScriptCompiler::Compile(isolate, &script_source,
240                                          compile_options)
241                : ScriptCompiler::CompileModule(isolate, &script_source,
242                                                compile_options);
243   }
244
245   ScriptCompiler::CachedData* data =
246       CompileForCachedData(source, name, compile_options);
247   ScriptCompiler::Source cached_source(source, origin, data);
248   if (compile_options == ScriptCompiler::kProduceCodeCache) {
249     compile_options = ScriptCompiler::kConsumeCodeCache;
250   } else if (compile_options == ScriptCompiler::kProduceParserCache) {
251     compile_options = ScriptCompiler::kConsumeParserCache;
252   } else {
253     DCHECK(false);  // A new compile option?
254   }
255   if (data == NULL) compile_options = ScriptCompiler::kNoCompileOptions;
256   Local<Script> result =
257       source_type == SCRIPT
258           ? ScriptCompiler::Compile(isolate, &cached_source, compile_options)
259           : ScriptCompiler::CompileModule(isolate, &cached_source,
260                                           compile_options);
261   CHECK(data == NULL || !data->rejected);
262   return result;
263 }
264
265
266 // Executes a string within the current v8 context.
267 bool Shell::ExecuteString(Isolate* isolate, Handle<String> source,
268                           Handle<Value> name, bool print_result,
269                           bool report_exceptions, SourceType source_type) {
270 #ifndef V8_SHARED
271   bool FLAG_debugger = i::FLAG_debugger;
272 #else
273   bool FLAG_debugger = false;
274 #endif  // !V8_SHARED
275   HandleScope handle_scope(isolate);
276   TryCatch try_catch;
277   options.script_executed = true;
278   if (FLAG_debugger) {
279     // When debugging make exceptions appear to be uncaught.
280     try_catch.SetVerbose(true);
281   }
282
283   Handle<Value> result;
284   {
285     PerIsolateData* data = PerIsolateData::Get(isolate);
286     Local<Context> realm =
287         Local<Context>::New(isolate, data->realms_[data->realm_current_]);
288     Context::Scope context_scope(realm);
289     Handle<Script> script = Shell::CompileString(
290         isolate, source, name, options.compile_options, source_type);
291     if (script.IsEmpty()) {
292       // Print errors that happened during compilation.
293       if (report_exceptions && !FLAG_debugger)
294         ReportException(isolate, &try_catch);
295       return false;
296     }
297     result = script->Run();
298     data->realm_current_ = data->realm_switch_;
299   }
300   if (result.IsEmpty()) {
301     DCHECK(try_catch.HasCaught());
302     // Print errors that happened during execution.
303     if (report_exceptions && !FLAG_debugger)
304       ReportException(isolate, &try_catch);
305     return false;
306   }
307   DCHECK(!try_catch.HasCaught());
308   if (print_result) {
309 #if !defined(V8_SHARED)
310     if (options.test_shell) {
311 #endif
312       if (!result->IsUndefined()) {
313         // If all went well and the result wasn't undefined then print
314         // the returned value.
315         v8::String::Utf8Value str(result);
316         fwrite(*str, sizeof(**str), str.length(), stdout);
317         printf("\n");
318       }
319 #if !defined(V8_SHARED)
320     } else {
321       v8::TryCatch try_catch;
322       v8::Local<v8::Context> context =
323           v8::Local<v8::Context>::New(isolate, utility_context_);
324       v8::Context::Scope context_scope(context);
325       Handle<Object> global = context->Global();
326       Handle<Value> fun =
327           global->Get(String::NewFromUtf8(isolate, "Stringify"));
328       Handle<Value> argv[1] = {result};
329       Handle<Value> s = Handle<Function>::Cast(fun)->Call(global, 1, argv);
330       if (try_catch.HasCaught()) return true;
331       v8::String::Utf8Value str(s);
332       fwrite(*str, sizeof(**str), str.length(), stdout);
333       printf("\n");
334     }
335 #endif
336   }
337   return true;
338 }
339
340
341 PerIsolateData::RealmScope::RealmScope(PerIsolateData* data) : data_(data) {
342   data_->realm_count_ = 1;
343   data_->realm_current_ = 0;
344   data_->realm_switch_ = 0;
345   data_->realms_ = new Persistent<Context>[1];
346   data_->realms_[0].Reset(data_->isolate_,
347                           data_->isolate_->GetEnteredContext());
348 }
349
350
351 PerIsolateData::RealmScope::~RealmScope() {
352   // Drop realms to avoid keeping them alive.
353   for (int i = 0; i < data_->realm_count_; ++i)
354     data_->realms_[i].Reset();
355   delete[] data_->realms_;
356   if (!data_->realm_shared_.IsEmpty())
357     data_->realm_shared_.Reset();
358 }
359
360
361 int PerIsolateData::RealmFind(Handle<Context> context) {
362   for (int i = 0; i < realm_count_; ++i) {
363     if (realms_[i] == context) return i;
364   }
365   return -1;
366 }
367
368
369 int PerIsolateData::RealmIndexOrThrow(
370     const v8::FunctionCallbackInfo<v8::Value>& args,
371     int arg_offset) {
372   if (args.Length() < arg_offset || !args[arg_offset]->IsNumber()) {
373     Throw(args.GetIsolate(), "Invalid argument");
374     return -1;
375   }
376   int index = args[arg_offset]->Int32Value();
377   if (index < 0 ||
378       index >= realm_count_ ||
379       realms_[index].IsEmpty()) {
380     Throw(args.GetIsolate(), "Invalid realm index");
381     return -1;
382   }
383   return index;
384 }
385
386
387 #ifndef V8_SHARED
388 // performance.now() returns a time stamp as double, measured in milliseconds.
389 // When FLAG_verify_predictable mode is enabled it returns current value
390 // of Heap::allocations_count().
391 void Shell::PerformanceNow(const v8::FunctionCallbackInfo<v8::Value>& args) {
392   if (i::FLAG_verify_predictable) {
393     Isolate* v8_isolate = args.GetIsolate();
394     i::Heap* heap = reinterpret_cast<i::Isolate*>(v8_isolate)->heap();
395     args.GetReturnValue().Set(heap->synthetic_time());
396   } else {
397     base::TimeDelta delta =
398         base::TimeTicks::HighResolutionNow() - kInitialTicks;
399     args.GetReturnValue().Set(delta.InMillisecondsF());
400   }
401 }
402 #endif  // !V8_SHARED
403
404
405 // Realm.current() returns the index of the currently active realm.
406 void Shell::RealmCurrent(const v8::FunctionCallbackInfo<v8::Value>& args) {
407   Isolate* isolate = args.GetIsolate();
408   PerIsolateData* data = PerIsolateData::Get(isolate);
409   int index = data->RealmFind(isolate->GetEnteredContext());
410   if (index == -1) return;
411   args.GetReturnValue().Set(index);
412 }
413
414
415 // Realm.owner(o) returns the index of the realm that created o.
416 void Shell::RealmOwner(const v8::FunctionCallbackInfo<v8::Value>& args) {
417   Isolate* isolate = args.GetIsolate();
418   PerIsolateData* data = PerIsolateData::Get(isolate);
419   if (args.Length() < 1 || !args[0]->IsObject()) {
420     Throw(args.GetIsolate(), "Invalid argument");
421     return;
422   }
423   int index = data->RealmFind(args[0]->ToObject(isolate)->CreationContext());
424   if (index == -1) return;
425   args.GetReturnValue().Set(index);
426 }
427
428
429 // Realm.global(i) returns the global object of realm i.
430 // (Note that properties of global objects cannot be read/written cross-realm.)
431 void Shell::RealmGlobal(const v8::FunctionCallbackInfo<v8::Value>& args) {
432   PerIsolateData* data = PerIsolateData::Get(args.GetIsolate());
433   int index = data->RealmIndexOrThrow(args, 0);
434   if (index == -1) return;
435   args.GetReturnValue().Set(
436       Local<Context>::New(args.GetIsolate(), data->realms_[index])->Global());
437 }
438
439
440 // Realm.create() creates a new realm and returns its index.
441 void Shell::RealmCreate(const v8::FunctionCallbackInfo<v8::Value>& args) {
442   Isolate* isolate = args.GetIsolate();
443   PerIsolateData* data = PerIsolateData::Get(isolate);
444   Persistent<Context>* old_realms = data->realms_;
445   int index = data->realm_count_;
446   data->realms_ = new Persistent<Context>[++data->realm_count_];
447   for (int i = 0; i < index; ++i) {
448     data->realms_[i].Reset(isolate, old_realms[i]);
449   }
450   delete[] old_realms;
451   Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
452   data->realms_[index].Reset(
453       isolate, Context::New(isolate, NULL, global_template));
454   args.GetReturnValue().Set(index);
455 }
456
457
458 // Realm.dispose(i) disposes the reference to the realm i.
459 void Shell::RealmDispose(const v8::FunctionCallbackInfo<v8::Value>& args) {
460   Isolate* isolate = args.GetIsolate();
461   PerIsolateData* data = PerIsolateData::Get(isolate);
462   int index = data->RealmIndexOrThrow(args, 0);
463   if (index == -1) return;
464   if (index == 0 ||
465       index == data->realm_current_ || index == data->realm_switch_) {
466     Throw(args.GetIsolate(), "Invalid realm index");
467     return;
468   }
469   data->realms_[index].Reset();
470 }
471
472
473 // Realm.switch(i) switches to the realm i for consecutive interactive inputs.
474 void Shell::RealmSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
475   Isolate* isolate = args.GetIsolate();
476   PerIsolateData* data = PerIsolateData::Get(isolate);
477   int index = data->RealmIndexOrThrow(args, 0);
478   if (index == -1) return;
479   data->realm_switch_ = index;
480 }
481
482
483 // Realm.eval(i, s) evaluates s in realm i and returns the result.
484 void Shell::RealmEval(const v8::FunctionCallbackInfo<v8::Value>& args) {
485   Isolate* isolate = args.GetIsolate();
486   PerIsolateData* data = PerIsolateData::Get(isolate);
487   int index = data->RealmIndexOrThrow(args, 0);
488   if (index == -1) return;
489   if (args.Length() < 2 || !args[1]->IsString()) {
490     Throw(args.GetIsolate(), "Invalid argument");
491     return;
492   }
493   ScriptCompiler::Source script_source(args[1]->ToString(isolate));
494   Handle<UnboundScript> script = ScriptCompiler::CompileUnbound(
495       isolate, &script_source);
496   if (script.IsEmpty()) return;
497   Local<Context> realm = Local<Context>::New(isolate, data->realms_[index]);
498   realm->Enter();
499   Handle<Value> result = script->BindToCurrentContext()->Run();
500   realm->Exit();
501   args.GetReturnValue().Set(result);
502 }
503
504
505 // Realm.shared is an accessor for a single shared value across realms.
506 void Shell::RealmSharedGet(Local<String> property,
507                            const PropertyCallbackInfo<Value>& info) {
508   Isolate* isolate = info.GetIsolate();
509   PerIsolateData* data = PerIsolateData::Get(isolate);
510   if (data->realm_shared_.IsEmpty()) return;
511   info.GetReturnValue().Set(data->realm_shared_);
512 }
513
514 void Shell::RealmSharedSet(Local<String> property,
515                            Local<Value> value,
516                            const PropertyCallbackInfo<void>& info) {
517   Isolate* isolate = info.GetIsolate();
518   PerIsolateData* data = PerIsolateData::Get(isolate);
519   data->realm_shared_.Reset(isolate, value);
520 }
521
522
523 void Shell::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
524   Write(args);
525   printf("\n");
526   fflush(stdout);
527 }
528
529
530 void Shell::Write(const v8::FunctionCallbackInfo<v8::Value>& args) {
531   for (int i = 0; i < args.Length(); i++) {
532     HandleScope handle_scope(args.GetIsolate());
533     if (i != 0) {
534       printf(" ");
535     }
536
537     // Explicitly catch potential exceptions in toString().
538     v8::TryCatch try_catch;
539     Handle<String> str_obj = args[i]->ToString(args.GetIsolate());
540     if (try_catch.HasCaught()) {
541       try_catch.ReThrow();
542       return;
543     }
544
545     v8::String::Utf8Value str(str_obj);
546     int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
547     if (n != str.length()) {
548       printf("Error in fwrite\n");
549       Exit(1);
550     }
551   }
552 }
553
554
555 void Shell::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
556   String::Utf8Value file(args[0]);
557   if (*file == NULL) {
558     Throw(args.GetIsolate(), "Error loading file");
559     return;
560   }
561   Handle<String> source = ReadFile(args.GetIsolate(), *file);
562   if (source.IsEmpty()) {
563     Throw(args.GetIsolate(), "Error loading file");
564     return;
565   }
566   args.GetReturnValue().Set(source);
567 }
568
569
570 Handle<String> Shell::ReadFromStdin(Isolate* isolate) {
571   static const int kBufferSize = 256;
572   char buffer[kBufferSize];
573   Handle<String> accumulator = String::NewFromUtf8(isolate, "");
574   int length;
575   while (true) {
576     // Continue reading if the line ends with an escape '\\' or the line has
577     // not been fully read into the buffer yet (does not end with '\n').
578     // If fgets gets an error, just give up.
579     char* input = NULL;
580     input = fgets(buffer, kBufferSize, stdin);
581     if (input == NULL) return Handle<String>();
582     length = static_cast<int>(strlen(buffer));
583     if (length == 0) {
584       return accumulator;
585     } else if (buffer[length-1] != '\n') {
586       accumulator = String::Concat(
587           accumulator,
588           String::NewFromUtf8(isolate, buffer, String::kNormalString, length));
589     } else if (length > 1 && buffer[length-2] == '\\') {
590       buffer[length-2] = '\n';
591       accumulator = String::Concat(
592           accumulator, String::NewFromUtf8(isolate, buffer,
593                                            String::kNormalString, length - 1));
594     } else {
595       return String::Concat(
596           accumulator, String::NewFromUtf8(isolate, buffer,
597                                            String::kNormalString, length - 1));
598     }
599   }
600 }
601
602
603 void Shell::Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
604   for (int i = 0; i < args.Length(); i++) {
605     HandleScope handle_scope(args.GetIsolate());
606     String::Utf8Value file(args[i]);
607     if (*file == NULL) {
608       Throw(args.GetIsolate(), "Error loading file");
609       return;
610     }
611     Handle<String> source = ReadFile(args.GetIsolate(), *file);
612     if (source.IsEmpty()) {
613       Throw(args.GetIsolate(), "Error loading file");
614       return;
615     }
616     if (!ExecuteString(args.GetIsolate(),
617                        source,
618                        String::NewFromUtf8(args.GetIsolate(), *file),
619                        false,
620                        true)) {
621       Throw(args.GetIsolate(), "Error executing file");
622       return;
623     }
624   }
625 }
626
627
628 void Shell::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
629   int exit_code = args[0]->Int32Value();
630   OnExit(args.GetIsolate());
631   exit(exit_code);
632 }
633
634
635 void Shell::Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
636   args.GetReturnValue().Set(
637       String::NewFromUtf8(args.GetIsolate(), V8::GetVersion()));
638 }
639
640
641 void Shell::ReportException(Isolate* isolate, v8::TryCatch* try_catch) {
642   HandleScope handle_scope(isolate);
643 #ifndef V8_SHARED
644   Handle<Context> utility_context;
645   bool enter_context = !isolate->InContext();
646   if (enter_context) {
647     utility_context = Local<Context>::New(isolate, utility_context_);
648     utility_context->Enter();
649   }
650 #endif  // !V8_SHARED
651   v8::String::Utf8Value exception(try_catch->Exception());
652   const char* exception_string = ToCString(exception);
653   Handle<Message> message = try_catch->Message();
654   if (message.IsEmpty()) {
655     // V8 didn't provide any extra information about this error; just
656     // print the exception.
657     printf("%s\n", exception_string);
658   } else {
659     // Print (filename):(line number): (message).
660     v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
661     const char* filename_string = ToCString(filename);
662     int linenum = message->GetLineNumber();
663     printf("%s:%i: %s\n", filename_string, linenum, exception_string);
664     // Print line of source code.
665     v8::String::Utf8Value sourceline(message->GetSourceLine());
666     const char* sourceline_string = ToCString(sourceline);
667     printf("%s\n", sourceline_string);
668     // Print wavy underline (GetUnderline is deprecated).
669     int start = message->GetStartColumn();
670     for (int i = 0; i < start; i++) {
671       printf(" ");
672     }
673     int end = message->GetEndColumn();
674     for (int i = start; i < end; i++) {
675       printf("^");
676     }
677     printf("\n");
678     v8::String::Utf8Value stack_trace(try_catch->StackTrace());
679     if (stack_trace.length() > 0) {
680       const char* stack_trace_string = ToCString(stack_trace);
681       printf("%s\n", stack_trace_string);
682     }
683   }
684   printf("\n");
685 #ifndef V8_SHARED
686   if (enter_context) utility_context->Exit();
687 #endif  // !V8_SHARED
688 }
689
690
691 #ifndef V8_SHARED
692 Handle<Array> Shell::GetCompletions(Isolate* isolate,
693                                     Handle<String> text,
694                                     Handle<String> full) {
695   EscapableHandleScope handle_scope(isolate);
696   v8::Local<v8::Context> utility_context =
697       v8::Local<v8::Context>::New(isolate, utility_context_);
698   v8::Context::Scope context_scope(utility_context);
699   Handle<Object> global = utility_context->Global();
700   Local<Value> fun =
701       global->Get(String::NewFromUtf8(isolate, "GetCompletions"));
702   static const int kArgc = 3;
703   v8::Local<v8::Context> evaluation_context =
704       v8::Local<v8::Context>::New(isolate, evaluation_context_);
705   Handle<Value> argv[kArgc] = { evaluation_context->Global(), text, full };
706   Local<Value> val = Local<Function>::Cast(fun)->Call(global, kArgc, argv);
707   return handle_scope.Escape(Local<Array>::Cast(val));
708 }
709
710
711 Local<Object> Shell::DebugMessageDetails(Isolate* isolate,
712                                          Handle<String> message) {
713   EscapableHandleScope handle_scope(isolate);
714   v8::Local<v8::Context> context =
715       v8::Local<v8::Context>::New(isolate, utility_context_);
716   v8::Context::Scope context_scope(context);
717   Handle<Object> global = context->Global();
718   Handle<Value> fun =
719       global->Get(String::NewFromUtf8(isolate, "DebugMessageDetails"));
720   static const int kArgc = 1;
721   Handle<Value> argv[kArgc] = { message };
722   Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
723   return handle_scope.Escape(Local<Object>(Handle<Object>::Cast(val)));
724 }
725
726
727 Local<Value> Shell::DebugCommandToJSONRequest(Isolate* isolate,
728                                               Handle<String> command) {
729   EscapableHandleScope handle_scope(isolate);
730   v8::Local<v8::Context> context =
731       v8::Local<v8::Context>::New(isolate, utility_context_);
732   v8::Context::Scope context_scope(context);
733   Handle<Object> global = context->Global();
734   Handle<Value> fun =
735       global->Get(String::NewFromUtf8(isolate, "DebugCommandToJSONRequest"));
736   static const int kArgc = 1;
737   Handle<Value> argv[kArgc] = { command };
738   Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
739   return handle_scope.Escape(Local<Value>(val));
740 }
741
742
743 int32_t* Counter::Bind(const char* name, bool is_histogram) {
744   int i;
745   for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
746     name_[i] = static_cast<char>(name[i]);
747   name_[i] = '\0';
748   is_histogram_ = is_histogram;
749   return ptr();
750 }
751
752
753 void Counter::AddSample(int32_t sample) {
754   count_++;
755   sample_total_ += sample;
756 }
757
758
759 CounterCollection::CounterCollection() {
760   magic_number_ = 0xDEADFACE;
761   max_counters_ = kMaxCounters;
762   max_name_size_ = Counter::kMaxNameSize;
763   counters_in_use_ = 0;
764 }
765
766
767 Counter* CounterCollection::GetNextCounter() {
768   if (counters_in_use_ == kMaxCounters) return NULL;
769   return &counters_[counters_in_use_++];
770 }
771
772
773 void Shell::MapCounters(v8::Isolate* isolate, const char* name) {
774   counters_file_ = base::OS::MemoryMappedFile::create(
775       name, sizeof(CounterCollection), &local_counters_);
776   void* memory = (counters_file_ == NULL) ?
777       NULL : counters_file_->memory();
778   if (memory == NULL) {
779     printf("Could not map counters file %s\n", name);
780     Exit(1);
781   }
782   counters_ = static_cast<CounterCollection*>(memory);
783   isolate->SetCounterFunction(LookupCounter);
784   isolate->SetCreateHistogramFunction(CreateHistogram);
785   isolate->SetAddHistogramSampleFunction(AddHistogramSample);
786 }
787
788
789 int CounterMap::Hash(const char* name) {
790   int h = 0;
791   int c;
792   while ((c = *name++) != 0) {
793     h += h << 5;
794     h += c;
795   }
796   return h;
797 }
798
799
800 Counter* Shell::GetCounter(const char* name, bool is_histogram) {
801   Counter* counter = counter_map_->Lookup(name);
802
803   if (counter == NULL) {
804     counter = counters_->GetNextCounter();
805     if (counter != NULL) {
806       counter_map_->Set(name, counter);
807       counter->Bind(name, is_histogram);
808     }
809   } else {
810     DCHECK(counter->is_histogram() == is_histogram);
811   }
812   return counter;
813 }
814
815
816 int* Shell::LookupCounter(const char* name) {
817   Counter* counter = GetCounter(name, false);
818
819   if (counter != NULL) {
820     return counter->ptr();
821   } else {
822     return NULL;
823   }
824 }
825
826
827 void* Shell::CreateHistogram(const char* name,
828                              int min,
829                              int max,
830                              size_t buckets) {
831   return GetCounter(name, true);
832 }
833
834
835 void Shell::AddHistogramSample(void* histogram, int sample) {
836   Counter* counter = reinterpret_cast<Counter*>(histogram);
837   counter->AddSample(sample);
838 }
839
840
841 class NoUseStrongForUtilityScriptScope {
842  public:
843   NoUseStrongForUtilityScriptScope() : flag_(i::FLAG_use_strong) {
844     i::FLAG_use_strong = false;
845   }
846   ~NoUseStrongForUtilityScriptScope() { i::FLAG_use_strong = flag_; }
847
848  private:
849   bool flag_;
850 };
851
852
853 void Shell::InstallUtilityScript(Isolate* isolate) {
854   NoUseStrongForUtilityScriptScope no_use_strong;
855   HandleScope scope(isolate);
856   // If we use the utility context, we have to set the security tokens so that
857   // utility, evaluation and debug context can all access each other.
858   v8::Local<v8::Context> utility_context =
859       v8::Local<v8::Context>::New(isolate, utility_context_);
860   v8::Local<v8::Context> evaluation_context =
861       v8::Local<v8::Context>::New(isolate, evaluation_context_);
862   utility_context->SetSecurityToken(Undefined(isolate));
863   evaluation_context->SetSecurityToken(Undefined(isolate));
864   v8::Context::Scope context_scope(utility_context);
865
866   if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
867   // Install the debugger object in the utility scope
868   i::Debug* debug = reinterpret_cast<i::Isolate*>(isolate)->debug();
869   debug->Load();
870   i::Handle<i::Context> debug_context = debug->debug_context();
871   i::Handle<i::JSObject> js_debug
872       = i::Handle<i::JSObject>(debug_context->global_object());
873   utility_context->Global()->Set(String::NewFromUtf8(isolate, "$debug"),
874                                  Utils::ToLocal(js_debug));
875   debug_context->set_security_token(
876       reinterpret_cast<i::Isolate*>(isolate)->heap()->undefined_value());
877
878   // Run the d8 shell utility script in the utility context
879   int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
880   i::Vector<const char> shell_source =
881       i::NativesCollection<i::D8>::GetScriptSource(source_index);
882   i::Vector<const char> shell_source_name =
883       i::NativesCollection<i::D8>::GetScriptName(source_index);
884   Handle<String> source =
885       String::NewFromUtf8(isolate, shell_source.start(), String::kNormalString,
886                           shell_source.length());
887   Handle<String> name =
888       String::NewFromUtf8(isolate, shell_source_name.start(),
889                           String::kNormalString, shell_source_name.length());
890   ScriptOrigin origin(name);
891   Handle<Script> script = Script::Compile(source, &origin);
892   script->Run();
893   // Mark the d8 shell script as native to avoid it showing up as normal source
894   // in the debugger.
895   i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
896   i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
897       ? i::Handle<i::Script>(i::Script::cast(
898           i::JSFunction::cast(*compiled_script)->shared()->script()))
899       : i::Handle<i::Script>(i::Script::cast(
900           i::SharedFunctionInfo::cast(*compiled_script)->script()));
901   script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
902
903   // Start the in-process debugger if requested.
904   if (i::FLAG_debugger) v8::Debug::SetDebugEventListener(HandleDebugEvent);
905 }
906 #endif  // !V8_SHARED
907
908
909 Handle<ObjectTemplate> Shell::CreateGlobalTemplate(Isolate* isolate) {
910   Handle<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
911   global_template->Set(String::NewFromUtf8(isolate, "print"),
912                        FunctionTemplate::New(isolate, Print));
913   global_template->Set(String::NewFromUtf8(isolate, "write"),
914                        FunctionTemplate::New(isolate, Write));
915   global_template->Set(String::NewFromUtf8(isolate, "read"),
916                        FunctionTemplate::New(isolate, Read));
917   global_template->Set(String::NewFromUtf8(isolate, "readbuffer"),
918                        FunctionTemplate::New(isolate, ReadBuffer));
919   global_template->Set(String::NewFromUtf8(isolate, "readline"),
920                        FunctionTemplate::New(isolate, ReadLine));
921   global_template->Set(String::NewFromUtf8(isolate, "load"),
922                        FunctionTemplate::New(isolate, Load));
923   global_template->Set(String::NewFromUtf8(isolate, "quit"),
924                        FunctionTemplate::New(isolate, Quit));
925   global_template->Set(String::NewFromUtf8(isolate, "version"),
926                        FunctionTemplate::New(isolate, Version));
927
928   // Bind the Realm object.
929   Handle<ObjectTemplate> realm_template = ObjectTemplate::New(isolate);
930   realm_template->Set(String::NewFromUtf8(isolate, "current"),
931                       FunctionTemplate::New(isolate, RealmCurrent));
932   realm_template->Set(String::NewFromUtf8(isolate, "owner"),
933                       FunctionTemplate::New(isolate, RealmOwner));
934   realm_template->Set(String::NewFromUtf8(isolate, "global"),
935                       FunctionTemplate::New(isolate, RealmGlobal));
936   realm_template->Set(String::NewFromUtf8(isolate, "create"),
937                       FunctionTemplate::New(isolate, RealmCreate));
938   realm_template->Set(String::NewFromUtf8(isolate, "dispose"),
939                       FunctionTemplate::New(isolate, RealmDispose));
940   realm_template->Set(String::NewFromUtf8(isolate, "switch"),
941                       FunctionTemplate::New(isolate, RealmSwitch));
942   realm_template->Set(String::NewFromUtf8(isolate, "eval"),
943                       FunctionTemplate::New(isolate, RealmEval));
944   realm_template->SetAccessor(String::NewFromUtf8(isolate, "shared"),
945                               RealmSharedGet, RealmSharedSet);
946   global_template->Set(String::NewFromUtf8(isolate, "Realm"), realm_template);
947
948 #ifndef V8_SHARED
949   Handle<ObjectTemplate> performance_template = ObjectTemplate::New(isolate);
950   performance_template->Set(String::NewFromUtf8(isolate, "now"),
951                             FunctionTemplate::New(isolate, PerformanceNow));
952   global_template->Set(String::NewFromUtf8(isolate, "performance"),
953                        performance_template);
954 #endif  // !V8_SHARED
955
956   Handle<ObjectTemplate> os_templ = ObjectTemplate::New(isolate);
957   AddOSMethods(isolate, os_templ);
958   global_template->Set(String::NewFromUtf8(isolate, "os"), os_templ);
959
960   return global_template;
961 }
962
963
964 void Shell::Initialize(Isolate* isolate) {
965 #ifndef V8_SHARED
966   Shell::counter_map_ = new CounterMap();
967   // Set up counters
968   if (i::StrLength(i::FLAG_map_counters) != 0)
969     MapCounters(isolate, i::FLAG_map_counters);
970   if (i::FLAG_dump_counters || i::FLAG_track_gc_object_stats) {
971     isolate->SetCounterFunction(LookupCounter);
972     isolate->SetCreateHistogramFunction(CreateHistogram);
973     isolate->SetAddHistogramSampleFunction(AddHistogramSample);
974   }
975 #endif  // !V8_SHARED
976 }
977
978
979 void Shell::InitializeDebugger(Isolate* isolate) {
980   if (options.test_shell) return;
981 #ifndef V8_SHARED
982   HandleScope scope(isolate);
983   Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
984   utility_context_.Reset(isolate,
985                          Context::New(isolate, NULL, global_template));
986 #endif  // !V8_SHARED
987 }
988
989
990 Local<Context> Shell::CreateEvaluationContext(Isolate* isolate) {
991 #ifndef V8_SHARED
992   // This needs to be a critical section since this is not thread-safe
993   base::LockGuard<base::Mutex> lock_guard(&context_mutex_);
994 #endif  // !V8_SHARED
995   // Initialize the global objects
996   Handle<ObjectTemplate> global_template = CreateGlobalTemplate(isolate);
997   EscapableHandleScope handle_scope(isolate);
998   Local<Context> context = Context::New(isolate, NULL, global_template);
999   DCHECK(!context.IsEmpty());
1000   Context::Scope scope(context);
1001
1002 #ifndef V8_SHARED
1003   i::Factory* factory = reinterpret_cast<i::Isolate*>(isolate)->factory();
1004   i::JSArguments js_args = i::FLAG_js_arguments;
1005   i::Handle<i::FixedArray> arguments_array =
1006       factory->NewFixedArray(js_args.argc);
1007   for (int j = 0; j < js_args.argc; j++) {
1008     i::Handle<i::String> arg =
1009         factory->NewStringFromUtf8(i::CStrVector(js_args[j])).ToHandleChecked();
1010     arguments_array->set(j, *arg);
1011   }
1012   i::Handle<i::JSArray> arguments_jsarray =
1013       factory->NewJSArrayWithElements(arguments_array);
1014   context->Global()->Set(String::NewFromUtf8(isolate, "arguments"),
1015                          Utils::ToLocal(arguments_jsarray));
1016 #endif  // !V8_SHARED
1017   return handle_scope.Escape(context);
1018 }
1019
1020
1021 void Shell::Exit(int exit_code) {
1022   // Use _exit instead of exit to avoid races between isolate
1023   // threads and static destructors.
1024   fflush(stdout);
1025   fflush(stderr);
1026   _exit(exit_code);
1027 }
1028
1029
1030 #ifndef V8_SHARED
1031 struct CounterAndKey {
1032   Counter* counter;
1033   const char* key;
1034 };
1035
1036
1037 inline bool operator<(const CounterAndKey& lhs, const CounterAndKey& rhs) {
1038   return strcmp(lhs.key, rhs.key) < 0;
1039 }
1040 #endif  // !V8_SHARED
1041
1042
1043 void Shell::OnExit(v8::Isolate* isolate) {
1044   LineEditor* line_editor = LineEditor::Get();
1045   if (line_editor) line_editor->Close();
1046 #ifndef V8_SHARED
1047   reinterpret_cast<i::Isolate*>(isolate)->DumpAndResetCompilationStats();
1048   if (i::FLAG_dump_counters) {
1049     int number_of_counters = 0;
1050     for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
1051       number_of_counters++;
1052     }
1053     CounterAndKey* counters = new CounterAndKey[number_of_counters];
1054     int j = 0;
1055     for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
1056       counters[j].counter = i.CurrentValue();
1057       counters[j].key = i.CurrentKey();
1058     }
1059     std::sort(counters, counters + number_of_counters);
1060     printf("+----------------------------------------------------------------+"
1061            "-------------+\n");
1062     printf("| Name                                                           |"
1063            " Value       |\n");
1064     printf("+----------------------------------------------------------------+"
1065            "-------------+\n");
1066     for (j = 0; j < number_of_counters; j++) {
1067       Counter* counter = counters[j].counter;
1068       const char* key = counters[j].key;
1069       if (counter->is_histogram()) {
1070         printf("| c:%-60s | %11i |\n", key, counter->count());
1071         printf("| t:%-60s | %11i |\n", key, counter->sample_total());
1072       } else {
1073         printf("| %-62s | %11i |\n", key, counter->count());
1074       }
1075     }
1076     printf("+----------------------------------------------------------------+"
1077            "-------------+\n");
1078     delete [] counters;
1079   }
1080   delete counters_file_;
1081   delete counter_map_;
1082 #endif  // !V8_SHARED
1083 }
1084
1085
1086
1087 static FILE* FOpen(const char* path, const char* mode) {
1088 #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
1089   FILE* result;
1090   if (fopen_s(&result, path, mode) == 0) {
1091     return result;
1092   } else {
1093     return NULL;
1094   }
1095 #else
1096   FILE* file = fopen(path, mode);
1097   if (file == NULL) return NULL;
1098   struct stat file_stat;
1099   if (fstat(fileno(file), &file_stat) != 0) return NULL;
1100   bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
1101   if (is_regular_file) return file;
1102   fclose(file);
1103   return NULL;
1104 #endif
1105 }
1106
1107
1108 static char* ReadChars(Isolate* isolate, const char* name, int* size_out) {
1109   FILE* file = FOpen(name, "rb");
1110   if (file == NULL) return NULL;
1111
1112   fseek(file, 0, SEEK_END);
1113   int size = ftell(file);
1114   rewind(file);
1115
1116   char* chars = new char[size + 1];
1117   chars[size] = '\0';
1118   for (int i = 0; i < size;) {
1119     int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1120     i += read;
1121   }
1122   fclose(file);
1123   *size_out = size;
1124   return chars;
1125 }
1126
1127
1128 struct DataAndPersistent {
1129   uint8_t* data;
1130   Persistent<ArrayBuffer> handle;
1131 };
1132
1133
1134 static void ReadBufferWeakCallback(
1135     const v8::WeakCallbackData<ArrayBuffer, DataAndPersistent>& data) {
1136   size_t byte_length = data.GetValue()->ByteLength();
1137   data.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(
1138       -static_cast<intptr_t>(byte_length));
1139
1140   delete[] data.GetParameter()->data;
1141   data.GetParameter()->handle.Reset();
1142   delete data.GetParameter();
1143 }
1144
1145
1146 void Shell::ReadBuffer(const v8::FunctionCallbackInfo<v8::Value>& args) {
1147   DCHECK(sizeof(char) == sizeof(uint8_t));  // NOLINT
1148   String::Utf8Value filename(args[0]);
1149   int length;
1150   if (*filename == NULL) {
1151     Throw(args.GetIsolate(), "Error loading file");
1152     return;
1153   }
1154
1155   Isolate* isolate = args.GetIsolate();
1156   DataAndPersistent* data = new DataAndPersistent;
1157   data->data = reinterpret_cast<uint8_t*>(
1158       ReadChars(args.GetIsolate(), *filename, &length));
1159   if (data->data == NULL) {
1160     delete data;
1161     Throw(args.GetIsolate(), "Error reading file");
1162     return;
1163   }
1164   Handle<v8::ArrayBuffer> buffer =
1165       ArrayBuffer::New(isolate, data->data, length);
1166   data->handle.Reset(isolate, buffer);
1167   data->handle.SetWeak(data, ReadBufferWeakCallback);
1168   data->handle.MarkIndependent();
1169   isolate->AdjustAmountOfExternalAllocatedMemory(length);
1170
1171   args.GetReturnValue().Set(buffer);
1172 }
1173
1174
1175 // Reads a file into a v8 string.
1176 Handle<String> Shell::ReadFile(Isolate* isolate, const char* name) {
1177   int size = 0;
1178   char* chars = ReadChars(isolate, name, &size);
1179   if (chars == NULL) return Handle<String>();
1180   Handle<String> result =
1181       String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1182   delete[] chars;
1183   return result;
1184 }
1185
1186
1187 void Shell::RunShell(Isolate* isolate) {
1188   HandleScope outer_scope(isolate);
1189   v8::Local<v8::Context> context =
1190       v8::Local<v8::Context>::New(isolate, evaluation_context_);
1191   v8::Context::Scope context_scope(context);
1192   PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1193   Handle<String> name = String::NewFromUtf8(isolate, "(d8)");
1194   LineEditor* console = LineEditor::Get();
1195   printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
1196   console->Open(isolate);
1197   while (true) {
1198     HandleScope inner_scope(isolate);
1199     Handle<String> input = console->Prompt(Shell::kPrompt);
1200     if (input.IsEmpty()) break;
1201     ExecuteString(isolate, input, name, true, true);
1202   }
1203   printf("\n");
1204 }
1205
1206
1207 SourceGroup::~SourceGroup() {
1208 #ifndef V8_SHARED
1209   delete thread_;
1210   thread_ = NULL;
1211 #endif  // !V8_SHARED
1212 }
1213
1214
1215 void SourceGroup::Execute(Isolate* isolate) {
1216   bool exception_was_thrown = false;
1217   for (int i = begin_offset_; i < end_offset_; ++i) {
1218     const char* arg = argv_[i];
1219     Shell::SourceType source_type = Shell::SCRIPT;
1220     if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
1221       // Execute argument given to -e option directly.
1222       HandleScope handle_scope(isolate);
1223       Handle<String> file_name = String::NewFromUtf8(isolate, "unnamed");
1224       Handle<String> source = String::NewFromUtf8(isolate, argv_[i + 1]);
1225       if (!Shell::ExecuteString(isolate, source, file_name, false, true)) {
1226         exception_was_thrown = true;
1227         break;
1228       }
1229       ++i;
1230       continue;
1231     } else if (strcmp(arg, "--module") == 0 && i + 1 < end_offset_) {
1232       // Treat the next file as a module.
1233       source_type = Shell::MODULE;
1234       arg = argv_[++i];
1235     } else if (arg[0] == '-') {
1236       // Ignore other options. They have been parsed already.
1237       continue;
1238     }
1239
1240     // Use all other arguments as names of files to load and run.
1241     HandleScope handle_scope(isolate);
1242     Handle<String> file_name = String::NewFromUtf8(isolate, arg);
1243     Handle<String> source = ReadFile(isolate, arg);
1244     if (source.IsEmpty()) {
1245       printf("Error reading '%s'\n", arg);
1246       Shell::Exit(1);
1247     }
1248     if (!Shell::ExecuteString(isolate, source, file_name, false, true,
1249                               source_type)) {
1250       exception_was_thrown = true;
1251       break;
1252     }
1253   }
1254   if (exception_was_thrown != Shell::options.expected_to_throw) {
1255     Shell::Exit(1);
1256   }
1257 }
1258
1259
1260 Handle<String> SourceGroup::ReadFile(Isolate* isolate, const char* name) {
1261   int size;
1262   char* chars = ReadChars(isolate, name, &size);
1263   if (chars == NULL) return Handle<String>();
1264   Handle<String> result =
1265       String::NewFromUtf8(isolate, chars, String::kNormalString, size);
1266   delete[] chars;
1267   return result;
1268 }
1269
1270
1271 #ifndef V8_SHARED
1272 base::Thread::Options SourceGroup::GetThreadOptions() {
1273   // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
1274   // which is not enough to parse the big literal expressions used in tests.
1275   // The stack size should be at least StackGuard::kLimitSize + some
1276   // OS-specific padding for thread startup code.  2Mbytes seems to be enough.
1277   return base::Thread::Options("IsolateThread", 2 * MB);
1278 }
1279
1280
1281 void SourceGroup::ExecuteInThread() {
1282   Isolate* isolate = Isolate::New();
1283   do {
1284     next_semaphore_.Wait();
1285     {
1286       Isolate::Scope iscope(isolate);
1287       {
1288         HandleScope scope(isolate);
1289         PerIsolateData data(isolate);
1290         Local<Context> context = Shell::CreateEvaluationContext(isolate);
1291         {
1292           Context::Scope cscope(context);
1293           PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1294           Execute(isolate);
1295         }
1296       }
1297       if (Shell::options.send_idle_notification) {
1298         const int kLongIdlePauseInMs = 1000;
1299         isolate->ContextDisposedNotification();
1300         isolate->IdleNotification(kLongIdlePauseInMs);
1301       }
1302       if (Shell::options.invoke_weak_callbacks) {
1303         // By sending a low memory notifications, we will try hard to collect
1304         // all garbage and will therefore also invoke all weak callbacks of
1305         // actually unreachable persistent handles.
1306         isolate->LowMemoryNotification();
1307       }
1308     }
1309     done_semaphore_.Signal();
1310   } while (!Shell::options.last_run);
1311
1312   isolate->Dispose();
1313 }
1314
1315
1316 void SourceGroup::StartExecuteInThread() {
1317   if (thread_ == NULL) {
1318     thread_ = new IsolateThread(this);
1319     thread_->Start();
1320   }
1321   next_semaphore_.Signal();
1322 }
1323
1324
1325 void SourceGroup::WaitForThread() {
1326   if (thread_ == NULL) return;
1327   if (Shell::options.last_run) {
1328     thread_->Join();
1329   } else {
1330     done_semaphore_.Wait();
1331   }
1332 }
1333 #endif  // !V8_SHARED
1334
1335
1336 void SetFlagsFromString(const char* flags) {
1337   v8::V8::SetFlagsFromString(flags, static_cast<int>(strlen(flags)));
1338 }
1339
1340
1341 bool Shell::SetOptions(int argc, char* argv[]) {
1342   bool logfile_per_isolate = false;
1343   for (int i = 0; i < argc; i++) {
1344     if (strcmp(argv[i], "--stress-opt") == 0) {
1345       options.stress_opt = true;
1346       argv[i] = NULL;
1347     } else if (strcmp(argv[i], "--nostress-opt") == 0) {
1348       options.stress_opt = false;
1349       argv[i] = NULL;
1350     } else if (strcmp(argv[i], "--stress-deopt") == 0) {
1351       options.stress_deopt = true;
1352       argv[i] = NULL;
1353     } else if (strcmp(argv[i], "--mock-arraybuffer-allocator") == 0) {
1354       options.mock_arraybuffer_allocator = true;
1355       argv[i] = NULL;
1356     } else if (strcmp(argv[i], "--noalways-opt") == 0) {
1357       // No support for stressing if we can't use --always-opt.
1358       options.stress_opt = false;
1359       options.stress_deopt = false;
1360     } else if (strcmp(argv[i], "--logfile-per-isolate") == 0) {
1361       logfile_per_isolate = true;
1362       argv[i] = NULL;
1363     } else if (strcmp(argv[i], "--shell") == 0) {
1364       options.interactive_shell = true;
1365       argv[i] = NULL;
1366     } else if (strcmp(argv[i], "--test") == 0) {
1367       options.test_shell = true;
1368       argv[i] = NULL;
1369     } else if (strcmp(argv[i], "--send-idle-notification") == 0) {
1370       options.send_idle_notification = true;
1371       argv[i] = NULL;
1372     } else if (strcmp(argv[i], "--invoke-weak-callbacks") == 0) {
1373       options.invoke_weak_callbacks = true;
1374       // TODO(jochen) See issue 3351
1375       options.send_idle_notification = true;
1376       argv[i] = NULL;
1377     } else if (strcmp(argv[i], "-f") == 0) {
1378       // Ignore any -f flags for compatibility with other stand-alone
1379       // JavaScript engines.
1380       continue;
1381     } else if (strcmp(argv[i], "--isolate") == 0) {
1382 #ifdef V8_SHARED
1383       printf("D8 with shared library does not support multi-threading\n");
1384       return false;
1385 #endif  // V8_SHARED
1386       options.num_isolates++;
1387     } else if (strcmp(argv[i], "--dump-heap-constants") == 0) {
1388 #ifdef V8_SHARED
1389       printf("D8 with shared library does not support constant dumping\n");
1390       return false;
1391 #else
1392       options.dump_heap_constants = true;
1393       argv[i] = NULL;
1394 #endif  // V8_SHARED
1395     } else if (strcmp(argv[i], "--throws") == 0) {
1396       options.expected_to_throw = true;
1397       argv[i] = NULL;
1398     } else if (strncmp(argv[i], "--icu-data-file=", 16) == 0) {
1399       options.icu_data_file = argv[i] + 16;
1400       argv[i] = NULL;
1401 #ifdef V8_SHARED
1402     } else if (strcmp(argv[i], "--dump-counters") == 0) {
1403       printf("D8 with shared library does not include counters\n");
1404       return false;
1405     } else if (strcmp(argv[i], "--debugger") == 0) {
1406       printf("Javascript debugger not included\n");
1407       return false;
1408 #endif  // V8_SHARED
1409 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1410     } else if (strncmp(argv[i], "--natives_blob=", 15) == 0) {
1411       options.natives_blob = argv[i] + 15;
1412       argv[i] = NULL;
1413     } else if (strncmp(argv[i], "--snapshot_blob=", 16) == 0) {
1414       options.snapshot_blob = argv[i] + 16;
1415       argv[i] = NULL;
1416 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
1417     } else if (strcmp(argv[i], "--cache") == 0 ||
1418                strncmp(argv[i], "--cache=", 8) == 0) {
1419       const char* value = argv[i] + 7;
1420       if (!*value || strncmp(value, "=code", 6) == 0) {
1421         options.compile_options = v8::ScriptCompiler::kProduceCodeCache;
1422       } else if (strncmp(value, "=parse", 7) == 0) {
1423         options.compile_options = v8::ScriptCompiler::kProduceParserCache;
1424       } else if (strncmp(value, "=none", 6) == 0) {
1425         options.compile_options = v8::ScriptCompiler::kNoCompileOptions;
1426       } else {
1427         printf("Unknown option to --cache.\n");
1428         return false;
1429       }
1430       argv[i] = NULL;
1431     }
1432   }
1433
1434   v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
1435
1436   bool enable_harmony_modules = false;
1437
1438   // Set up isolated source groups.
1439   options.isolate_sources = new SourceGroup[options.num_isolates];
1440   SourceGroup* current = options.isolate_sources;
1441   current->Begin(argv, 1);
1442   for (int i = 1; i < argc; i++) {
1443     const char* str = argv[i];
1444     if (strcmp(str, "--isolate") == 0) {
1445       current->End(i);
1446       current++;
1447       current->Begin(argv, i + 1);
1448     } else if (strcmp(str, "--module") == 0) {
1449       // Pass on to SourceGroup, which understands this option.
1450       enable_harmony_modules = true;
1451     } else if (strncmp(argv[i], "--", 2) == 0) {
1452       printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
1453     }
1454   }
1455   current->End(argc);
1456
1457   if (!logfile_per_isolate && options.num_isolates) {
1458     SetFlagsFromString("--nologfile_per_isolate");
1459   }
1460
1461   if (enable_harmony_modules) {
1462     SetFlagsFromString("--harmony-modules");
1463   }
1464
1465   return true;
1466 }
1467
1468
1469 int Shell::RunMain(Isolate* isolate, int argc, char* argv[]) {
1470 #ifndef V8_SHARED
1471   for (int i = 1; i < options.num_isolates; ++i) {
1472     options.isolate_sources[i].StartExecuteInThread();
1473   }
1474 #endif  // !V8_SHARED
1475   {
1476     HandleScope scope(isolate);
1477     Local<Context> context = CreateEvaluationContext(isolate);
1478     if (options.last_run && options.use_interactive_shell()) {
1479       // Keep using the same context in the interactive shell.
1480       evaluation_context_.Reset(isolate, context);
1481 #ifndef V8_SHARED
1482       // If the interactive debugger is enabled make sure to activate
1483       // it before running the files passed on the command line.
1484       if (i::FLAG_debugger) {
1485         InstallUtilityScript(isolate);
1486       }
1487 #endif  // !V8_SHARED
1488     }
1489     {
1490       Context::Scope cscope(context);
1491       PerIsolateData::RealmScope realm_scope(PerIsolateData::Get(isolate));
1492       options.isolate_sources[0].Execute(isolate);
1493     }
1494   }
1495   if (options.send_idle_notification) {
1496     const int kLongIdlePauseInMs = 1000;
1497     isolate->ContextDisposedNotification();
1498     isolate->IdleNotification(kLongIdlePauseInMs);
1499   }
1500   if (options.invoke_weak_callbacks) {
1501     // By sending a low memory notifications, we will try hard to collect all
1502     // garbage and will therefore also invoke all weak callbacks of actually
1503     // unreachable persistent handles.
1504     isolate->LowMemoryNotification();
1505   }
1506
1507 #ifndef V8_SHARED
1508   for (int i = 1; i < options.num_isolates; ++i) {
1509     options.isolate_sources[i].WaitForThread();
1510   }
1511 #endif  // !V8_SHARED
1512   return 0;
1513 }
1514
1515
1516 #ifndef V8_SHARED
1517 static void DumpHeapConstants(i::Isolate* isolate) {
1518   i::Heap* heap = isolate->heap();
1519
1520   // Dump the INSTANCE_TYPES table to the console.
1521   printf("# List of known V8 instance types.\n");
1522 #define DUMP_TYPE(T) printf("  %d: \"%s\",\n", i::T, #T);
1523   printf("INSTANCE_TYPES = {\n");
1524   INSTANCE_TYPE_LIST(DUMP_TYPE)
1525   printf("}\n");
1526 #undef DUMP_TYPE
1527
1528   // Dump the KNOWN_MAP table to the console.
1529   printf("\n# List of known V8 maps.\n");
1530 #define ROOT_LIST_CASE(type, name, camel_name) \
1531   if (n == NULL && o == heap->name()) n = #camel_name;
1532 #define STRUCT_LIST_CASE(upper_name, camel_name, name) \
1533   if (n == NULL && o == heap->name##_map()) n = #camel_name "Map";
1534   i::HeapObjectIterator it(heap->map_space());
1535   printf("KNOWN_MAPS = {\n");
1536   for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1537     i::Map* m = i::Map::cast(o);
1538     const char* n = NULL;
1539     intptr_t p = reinterpret_cast<intptr_t>(m) & 0xfffff;
1540     int t = m->instance_type();
1541     ROOT_LIST(ROOT_LIST_CASE)
1542     STRUCT_LIST(STRUCT_LIST_CASE)
1543     if (n == NULL) continue;
1544     printf("  0x%05" V8PRIxPTR ": (%d, \"%s\"),\n", p, t, n);
1545   }
1546   printf("}\n");
1547 #undef STRUCT_LIST_CASE
1548 #undef ROOT_LIST_CASE
1549
1550   // Dump the KNOWN_OBJECTS table to the console.
1551   printf("\n# List of known V8 objects.\n");
1552 #define ROOT_LIST_CASE(type, name, camel_name) \
1553   if (n == NULL && o == heap->name()) n = #camel_name;
1554   i::OldSpaces spit(heap);
1555   printf("KNOWN_OBJECTS = {\n");
1556   for (i::PagedSpace* s = spit.next(); s != NULL; s = spit.next()) {
1557     i::HeapObjectIterator it(s);
1558     const char* sname = AllocationSpaceName(s->identity());
1559     for (i::Object* o = it.Next(); o != NULL; o = it.Next()) {
1560       const char* n = NULL;
1561       intptr_t p = reinterpret_cast<intptr_t>(o) & 0xfffff;
1562       ROOT_LIST(ROOT_LIST_CASE)
1563       if (n == NULL) continue;
1564       printf("  (\"%s\", 0x%05" V8PRIxPTR "): \"%s\",\n", sname, p, n);
1565     }
1566   }
1567   printf("}\n");
1568 #undef ROOT_LIST_CASE
1569 }
1570 #endif  // !V8_SHARED
1571
1572
1573 class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1574  public:
1575   virtual void* Allocate(size_t length) {
1576     void* data = AllocateUninitialized(length);
1577     return data == NULL ? data : memset(data, 0, length);
1578   }
1579   virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
1580   virtual void Free(void* data, size_t) { free(data); }
1581 };
1582
1583
1584 class MockArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
1585  public:
1586   void* Allocate(size_t) OVERRIDE { return malloc(1); }
1587   void* AllocateUninitialized(size_t length) OVERRIDE { return malloc(1); }
1588   void Free(void* p, size_t) OVERRIDE { free(p); }
1589 };
1590
1591
1592 int Shell::Main(int argc, char* argv[]) {
1593 #if (defined(_WIN32) || defined(_WIN64))
1594   UINT new_flags =
1595       SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
1596   UINT existing_flags = SetErrorMode(new_flags);
1597   SetErrorMode(existing_flags | new_flags);
1598 #if defined(_MSC_VER)
1599   _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1600   _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1601   _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1602   _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1603   _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
1604   _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1605   _set_error_mode(_OUT_TO_STDERR);
1606 #endif  // defined(_MSC_VER)
1607 #endif  // defined(_WIN32) || defined(_WIN64)
1608   if (!SetOptions(argc, argv)) return 1;
1609   v8::V8::InitializeICU(options.icu_data_file);
1610   v8::Platform* platform = v8::platform::CreateDefaultPlatform();
1611   v8::V8::InitializePlatform(platform);
1612   v8::V8::Initialize();
1613 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1614   v8::StartupDataHandler startup_data(argv[0], options.natives_blob,
1615                                       options.snapshot_blob);
1616 #endif
1617   SetFlagsFromString("--trace-hydrogen-file=hydrogen.cfg");
1618   SetFlagsFromString("--trace-turbo-cfg-file=turbo.cfg");
1619   SetFlagsFromString("--redirect-code-traces-to=code.asm");
1620   ShellArrayBufferAllocator array_buffer_allocator;
1621   MockArrayBufferAllocator mock_arraybuffer_allocator;
1622   if (options.mock_arraybuffer_allocator) {
1623     v8::V8::SetArrayBufferAllocator(&mock_arraybuffer_allocator);
1624   } else {
1625     v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
1626   }
1627   int result = 0;
1628   Isolate::CreateParams create_params;
1629 #if !defined(V8_SHARED) && defined(ENABLE_GDB_JIT_INTERFACE)
1630   if (i::FLAG_gdbjit) {
1631     create_params.code_event_handler = i::GDBJITInterface::EventHandler;
1632   }
1633 #endif
1634 #ifdef ENABLE_VTUNE_JIT_INTERFACE
1635   create_params.code_event_handler = vTune::GetVtuneCodeEventHandler();
1636 #endif
1637 #ifndef V8_SHARED
1638   create_params.constraints.ConfigureDefaults(
1639       base::SysInfo::AmountOfPhysicalMemory(),
1640       base::SysInfo::AmountOfVirtualMemory(),
1641       base::SysInfo::NumberOfProcessors());
1642 #endif
1643   Isolate* isolate = Isolate::New(create_params);
1644   DumbLineEditor dumb_line_editor(isolate);
1645   {
1646     Isolate::Scope scope(isolate);
1647     Initialize(isolate);
1648     PerIsolateData data(isolate);
1649     InitializeDebugger(isolate);
1650
1651 #ifndef V8_SHARED
1652     if (options.dump_heap_constants) {
1653       DumpHeapConstants(reinterpret_cast<i::Isolate*>(isolate));
1654       return 0;
1655     }
1656 #endif
1657
1658     if (options.stress_opt || options.stress_deopt) {
1659       Testing::SetStressRunType(options.stress_opt
1660                                 ? Testing::kStressTypeOpt
1661                                 : Testing::kStressTypeDeopt);
1662       int stress_runs = Testing::GetStressRuns();
1663       for (int i = 0; i < stress_runs && result == 0; i++) {
1664         printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1665         Testing::PrepareStressRun(i);
1666         options.last_run = (i == stress_runs - 1);
1667         result = RunMain(isolate, argc, argv);
1668       }
1669       printf("======== Full Deoptimization =======\n");
1670       Testing::DeoptimizeAll();
1671 #if !defined(V8_SHARED)
1672     } else if (i::FLAG_stress_runs > 0) {
1673       int stress_runs = i::FLAG_stress_runs;
1674       for (int i = 0; i < stress_runs && result == 0; i++) {
1675         printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1676         options.last_run = (i == stress_runs - 1);
1677         result = RunMain(isolate, argc, argv);
1678       }
1679 #endif
1680     } else {
1681       result = RunMain(isolate, argc, argv);
1682     }
1683
1684     // Run interactive shell if explicitly requested or if no script has been
1685     // executed, but never on --test
1686     if (options.use_interactive_shell()) {
1687 #ifndef V8_SHARED
1688       if (!i::FLAG_debugger) {
1689         InstallUtilityScript(isolate);
1690       }
1691 #endif  // !V8_SHARED
1692       RunShell(isolate);
1693     }
1694   }
1695   OnExit(isolate);
1696 #ifndef V8_SHARED
1697   // Dump basic block profiling data.
1698   if (i::BasicBlockProfiler* profiler =
1699           reinterpret_cast<i::Isolate*>(isolate)->basic_block_profiler()) {
1700     i::OFStream os(stdout);
1701     os << *profiler;
1702   }
1703 #endif  // !V8_SHARED
1704   isolate->Dispose();
1705   V8::Dispose();
1706   V8::ShutdownPlatform();
1707   delete platform;
1708
1709   return result;
1710 }
1711
1712 }  // namespace v8
1713
1714
1715 #ifndef GOOGLE3
1716 int main(int argc, char* argv[]) {
1717   return v8::Shell::Main(argc, argv);
1718 }
1719 #endif