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