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