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