v8  3.11.10(node0.8.26)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
d8.cc
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 
29 // Defined when linking against shared lib on Windows.
30 #if defined(USING_V8_SHARED) && !defined(V8_SHARED)
31 #define V8_SHARED
32 #endif
33 
34 #ifdef COMPRESS_STARTUP_DATA_BZ2
35 #include <bzlib.h>
36 #endif
37 
38 #include <errno.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 
43 #ifdef V8_SHARED
44 #include <assert.h>
45 #include "../include/v8-testing.h"
46 #endif // V8_SHARED
47 
48 #include "d8.h"
49 
50 #ifndef V8_SHARED
51 #include "api.h"
52 #include "checks.h"
53 #include "d8-debug.h"
54 #include "debug.h"
55 #include "natives.h"
56 #include "platform.h"
57 #include "v8.h"
58 #endif // V8_SHARED
59 
60 #if !defined(_WIN32) && !defined(_WIN64)
61 #include <unistd.h> // NOLINT
62 #endif
63 
64 #ifndef ASSERT
65 #define ASSERT(condition) assert(condition)
66 #endif
67 
68 namespace v8 {
69 
70 LineEditor *LineEditor::first_ = NULL;
71 
72 
74  : type_(type),
75  name_(name),
76  next_(first_) {
77  first_ = this;
78 }
79 
80 
82  LineEditor* current = first_;
83  LineEditor* best = current;
84  while (current != NULL) {
85  if (current->type_ > best->type_)
86  best = current;
87  current = current->next_;
88  }
89  return best;
90 }
91 
92 
93 class DumbLineEditor: public LineEditor {
94  public:
96  virtual Handle<String> Prompt(const char* prompt);
97 };
98 
99 
100 static DumbLineEditor dumb_line_editor;
101 
102 
104  printf("%s", prompt);
105  return Shell::ReadFromStdin();
106 }
107 
108 
109 #ifndef V8_SHARED
110 CounterMap* Shell::counter_map_;
111 i::OS::MemoryMappedFile* Shell::counters_file_ = NULL;
112 CounterCollection Shell::local_counters_;
113 CounterCollection* Shell::counters_ = &local_counters_;
114 i::Mutex* Shell::context_mutex_(i::OS::CreateMutex());
115 Persistent<Context> Shell::utility_context_;
116 #endif // V8_SHARED
117 
119 Persistent<Context> Shell::evaluation_context_;
121 const char* Shell::kPrompt = "d8> ";
122 
123 
124 const int MB = 1024 * 1024;
125 
126 
127 #ifndef V8_SHARED
128 bool CounterMap::Match(void* key1, void* key2) {
129  const char* name1 = reinterpret_cast<const char*>(key1);
130  const char* name2 = reinterpret_cast<const char*>(key2);
131  return strcmp(name1, name2) == 0;
132 }
133 #endif // V8_SHARED
134 
135 
136 // Converts a V8 value to a C string.
137 const char* Shell::ToCString(const v8::String::Utf8Value& value) {
138  return *value ? *value : "<string conversion failed>";
139 }
140 
141 
142 // Executes a string within the current v8 context.
145  bool print_result,
146  bool report_exceptions) {
147 #if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
148  bool FLAG_debugger = i::FLAG_debugger;
149 #else
150  bool FLAG_debugger = false;
151 #endif // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
152  HandleScope handle_scope;
153  TryCatch try_catch;
154  options.script_executed = true;
155  if (FLAG_debugger) {
156  // When debugging make exceptions appear to be uncaught.
157  try_catch.SetVerbose(true);
158  }
159  Handle<Script> script = Script::Compile(source, name);
160  if (script.IsEmpty()) {
161  // Print errors that happened during compilation.
162  if (report_exceptions && !FLAG_debugger)
163  ReportException(&try_catch);
164  return false;
165  } else {
166  Handle<Value> result = script->Run();
167  if (result.IsEmpty()) {
168  ASSERT(try_catch.HasCaught());
169  // Print errors that happened during execution.
170  if (report_exceptions && !FLAG_debugger)
171  ReportException(&try_catch);
172  return false;
173  } else {
174  ASSERT(!try_catch.HasCaught());
175  if (print_result && !result->IsUndefined()) {
176  // If all went well and the result wasn't undefined then print
177  // the returned value.
178  v8::String::Utf8Value str(result);
179  size_t count = fwrite(*str, sizeof(**str), str.length(), stdout);
180  (void) count; // Silence GCC-4.5.x "unused result" warning.
181  printf("\n");
182  }
183  return true;
184  }
185  }
186 }
187 
188 
190  Handle<Value> val = Write(args);
191  printf("\n");
192  fflush(stdout);
193  return val;
194 }
195 
196 
198  for (int i = 0; i < args.Length(); i++) {
199  HandleScope handle_scope;
200  if (i != 0) {
201  printf(" ");
202  }
203  v8::String::Utf8Value str(args[i]);
204  int n = static_cast<int>(fwrite(*str, sizeof(**str), str.length(), stdout));
205  if (n != str.length()) {
206  printf("Error in fwrite\n");
207  Exit(1);
208  }
209  }
210  return Undefined();
211 }
212 
213 
216  return Undefined();
217 }
218 
219 
222  return Undefined();
223 }
224 
225 
227  String::Utf8Value file(args[0]);
228  if (*file == NULL) {
229  return ThrowException(String::New("Error loading file"));
230  }
231  Handle<String> source = ReadFile(*file);
232  if (source.IsEmpty()) {
233  return ThrowException(String::New("Error loading file"));
234  }
235  return source;
236 }
237 
238 
240  static const int kBufferSize = 256;
241  char buffer[kBufferSize];
242  Handle<String> accumulator = String::New("");
243  int length;
244  while (true) {
245  // Continue reading if the line ends with an escape '\\' or the line has
246  // not been fully read into the buffer yet (does not end with '\n').
247  // If fgets gets an error, just give up.
248  char* input = NULL;
249  { // Release lock for blocking input.
250  Unlocker unlock(Isolate::GetCurrent());
251  input = fgets(buffer, kBufferSize, stdin);
252  }
253  if (input == NULL) return Handle<String>();
254  length = static_cast<int>(strlen(buffer));
255  if (length == 0) {
256  return accumulator;
257  } else if (buffer[length-1] != '\n') {
258  accumulator = String::Concat(accumulator, String::New(buffer, length));
259  } else if (length > 1 && buffer[length-2] == '\\') {
260  buffer[length-2] = '\n';
261  accumulator = String::Concat(accumulator, String::New(buffer, length-1));
262  } else {
263  return String::Concat(accumulator, String::New(buffer, length-1));
264  }
265  }
266 }
267 
268 
270  for (int i = 0; i < args.Length(); i++) {
271  HandleScope handle_scope;
272  String::Utf8Value file(args[i]);
273  if (*file == NULL) {
274  return ThrowException(String::New("Error loading file"));
275  }
276  Handle<String> source = ReadFile(*file);
277  if (source.IsEmpty()) {
278  return ThrowException(String::New("Error loading file"));
279  }
280  if (!ExecuteString(source, String::New(*file), false, true)) {
281  return ThrowException(String::New("Error executing file"));
282  }
283  }
284  return Undefined();
285 }
286 
287 static size_t convertToUint(Local<Value> value_in, TryCatch* try_catch) {
288  if (value_in->IsUint32()) {
289  return value_in->Uint32Value();
290  }
291 
292  Local<Value> number = value_in->ToNumber();
293  if (try_catch->HasCaught()) return 0;
294 
295  ASSERT(number->IsNumber());
296  Local<Int32> int32 = number->ToInt32();
297  if (try_catch->HasCaught() || int32.IsEmpty()) return 0;
298 
299  int32_t raw_value = int32->Int32Value();
300  if (try_catch->HasCaught()) return 0;
301 
302  if (raw_value < 0) {
303  ThrowException(String::New("Array length must not be negative."));
304  return 0;
305  }
306 
307  static const int kMaxLength = 0x3fffffff;
308 #ifndef V8_SHARED
309  ASSERT(kMaxLength == i::ExternalArray::kMaxLength);
310 #endif // V8_SHARED
311  if (raw_value > static_cast<int32_t>(kMaxLength)) {
313  String::New("Array length exceeds maximum length."));
314  }
315  return static_cast<size_t>(raw_value);
316 }
317 
318 
319 const char kArrayBufferMarkerPropName[] = "d8::_is_array_buffer_";
320 
321 
322 Handle<Value> Shell::CreateExternalArrayBuffer(int32_t length) {
323  static const int32_t kMaxSize = 0x7fffffff;
324  // Make sure the total size fits into a (signed) int.
325  if (length < 0 || length > kMaxSize) {
326  return ThrowException(String::New("ArrayBuffer exceeds maximum size (2G)"));
327  }
328  uint8_t* data = new uint8_t[length];
329  if (data == NULL) {
330  return ThrowException(String::New("Memory allocation failed."));
331  }
332  memset(data, 0, length);
333 
334  Handle<Object> buffer = Object::New();
336  Persistent<Object> persistent_array = Persistent<Object>::New(buffer);
337  persistent_array.MakeWeak(data, ExternalArrayWeakCallback);
338  persistent_array.MarkIndependent();
340 
342  data, v8::kExternalByteArray, length);
343  buffer->Set(String::New("byteLength"), Int32::New(length), ReadOnly);
344 
345  return buffer;
346 }
347 
348 
349 Handle<Value> Shell::CreateExternalArrayBuffer(const Arguments& args) {
350  if (args.Length() == 0) {
351  return ThrowException(
352  String::New("ArrayBuffer constructor must have one parameter."));
353  }
354  TryCatch try_catch;
355  int32_t length = convertToUint(args[0], &try_catch);
356  if (try_catch.HasCaught()) return try_catch.Exception();
357 
358  return CreateExternalArrayBuffer(length);
359 }
360 
361 
362 Handle<Value> Shell::CreateExternalArray(const Arguments& args,
364  int32_t element_size) {
365  TryCatch try_catch;
366  ASSERT(element_size == 1 || element_size == 2 ||
367  element_size == 4 || element_size == 8);
368 
369  // Currently, only the following constructors are supported:
370  // TypedArray(unsigned long length)
371  // TypedArray(ArrayBuffer buffer,
372  // optional unsigned long byteOffset,
373  // optional unsigned long length)
374  Handle<Object> buffer;
375  int32_t length;
376  int32_t byteLength;
377  int32_t byteOffset;
378  if (args.Length() == 0) {
379  return ThrowException(
380  String::New("Array constructor must have at least one parameter."));
381  }
382  if (args[0]->IsObject() &&
383  !args[0]->ToObject()->GetHiddenValue(
385  buffer = args[0]->ToObject();
386  int32_t bufferLength =
387  convertToUint(buffer->Get(String::New("byteLength")), &try_catch);
388  if (try_catch.HasCaught()) return try_catch.Exception();
389 
390  if (args.Length() < 2 || args[1]->IsUndefined()) {
391  byteOffset = 0;
392  } else {
393  byteOffset = convertToUint(args[1], &try_catch);
394  if (try_catch.HasCaught()) return try_catch.Exception();
395  if (byteOffset > bufferLength) {
396  return ThrowException(String::New("byteOffset out of bounds"));
397  }
398  if (byteOffset % element_size != 0) {
399  return ThrowException(
400  String::New("byteOffset must be multiple of element_size"));
401  }
402  }
403 
404  if (args.Length() < 3 || args[2]->IsUndefined()) {
405  byteLength = bufferLength - byteOffset;
406  length = byteLength / element_size;
407  if (byteLength % element_size != 0) {
408  return ThrowException(
409  String::New("buffer size must be multiple of element_size"));
410  }
411  } else {
412  length = convertToUint(args[2], &try_catch);
413  if (try_catch.HasCaught()) return try_catch.Exception();
414  byteLength = length * element_size;
415  if (byteOffset + byteLength > bufferLength) {
416  return ThrowException(String::New("length out of bounds"));
417  }
418  }
419  } else {
420  length = convertToUint(args[0], &try_catch);
421  byteLength = length * element_size;
422  byteOffset = 0;
423  Handle<Value> result = CreateExternalArrayBuffer(byteLength);
424  if (!result->IsObject()) return result;
425  buffer = result->ToObject();
426  }
427 
428  void* data = buffer->GetIndexedPropertiesExternalArrayData();
429  ASSERT(data != NULL);
430 
431  Handle<Object> array = Object::New();
432  array->SetIndexedPropertiesToExternalArrayData(
433  static_cast<uint8_t*>(data) + byteOffset, type, length);
434  array->Set(String::New("byteLength"), Int32::New(byteLength), ReadOnly);
435  array->Set(String::New("byteOffset"), Int32::New(byteOffset), ReadOnly);
436  array->Set(String::New("length"), Int32::New(length), ReadOnly);
437  array->Set(String::New("BYTES_PER_ELEMENT"), Int32::New(element_size));
438  array->Set(String::New("buffer"), buffer, ReadOnly);
439 
440  return array;
441 }
442 
443 
444 void Shell::ExternalArrayWeakCallback(Persistent<Value> object, void* data) {
445  HandleScope scope;
446  int32_t length =
447  object->ToObject()->Get(String::New("byteLength"))->Uint32Value();
449  delete[] static_cast<uint8_t*>(data);
450  object.Dispose();
451 }
452 
453 
455  return CreateExternalArrayBuffer(args);
456 }
457 
458 
460  return CreateExternalArray(args, v8::kExternalByteArray, sizeof(int8_t));
461 }
462 
463 
465  return CreateExternalArray(args, kExternalUnsignedByteArray, sizeof(uint8_t));
466 }
467 
468 
470  return CreateExternalArray(args, kExternalShortArray, sizeof(int16_t));
471 }
472 
473 
475  return CreateExternalArray(args, kExternalUnsignedShortArray,
476  sizeof(uint16_t));
477 }
478 
479 
481  return CreateExternalArray(args, kExternalIntArray, sizeof(int32_t));
482 }
483 
484 
486  return CreateExternalArray(args, kExternalUnsignedIntArray, sizeof(uint32_t));
487 }
488 
489 
491  return CreateExternalArray(args, kExternalFloatArray,
492  sizeof(float)); // NOLINT
493 }
494 
495 
497  return CreateExternalArray(args, kExternalDoubleArray,
498  sizeof(double)); // NOLINT
499 }
500 
501 
503  return CreateExternalArray(args, kExternalPixelArray, sizeof(uint8_t));
504 }
505 
506 
508  v8::Unlocker unlocker;
509  return Undefined();
510 }
511 
512 
514  int exit_code = args[0]->Int32Value();
515 #ifndef V8_SHARED
516  OnExit();
517 #endif // V8_SHARED
518  exit(exit_code);
519  return Undefined();
520 }
521 
522 
524  return String::New(V8::GetVersion());
525 }
526 
527 
529  HandleScope handle_scope;
530 #if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
531  bool enter_context = !Context::InContext();
532  if (enter_context) utility_context_->Enter();
533 #endif // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
534  v8::String::Utf8Value exception(try_catch->Exception());
535  const char* exception_string = ToCString(exception);
536  Handle<Message> message = try_catch->Message();
537  if (message.IsEmpty()) {
538  // V8 didn't provide any extra information about this error; just
539  // print the exception.
540  printf("%s\n", exception_string);
541  } else {
542  // Print (filename):(line number): (message).
543  v8::String::Utf8Value filename(message->GetScriptResourceName());
544  const char* filename_string = ToCString(filename);
545  int linenum = message->GetLineNumber();
546  printf("%s:%i: %s\n", filename_string, linenum, exception_string);
547  // Print line of source code.
548  v8::String::Utf8Value sourceline(message->GetSourceLine());
549  const char* sourceline_string = ToCString(sourceline);
550  printf("%s\n", sourceline_string);
551  // Print wavy underline (GetUnderline is deprecated).
552  int start = message->GetStartColumn();
553  for (int i = 0; i < start; i++) {
554  printf(" ");
555  }
556  int end = message->GetEndColumn();
557  for (int i = start; i < end; i++) {
558  printf("^");
559  }
560  printf("\n");
561  v8::String::Utf8Value stack_trace(try_catch->StackTrace());
562  if (stack_trace.length() > 0) {
563  const char* stack_trace_string = ToCString(stack_trace);
564  printf("%s\n", stack_trace_string);
565  }
566  }
567  printf("\n");
568 #if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
569  if (enter_context) utility_context_->Exit();
570 #endif // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
571 }
572 
573 
574 #ifndef V8_SHARED
576  HandleScope handle_scope;
577  Context::Scope context_scope(utility_context_);
578  Handle<Object> global = utility_context_->Global();
579  Handle<Value> fun = global->Get(String::New("GetCompletions"));
580  static const int kArgc = 3;
581  Handle<Value> argv[kArgc] = { evaluation_context_->Global(), text, full };
582  Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
583  return handle_scope.Close(Handle<Array>::Cast(val));
584 }
585 
586 
587 #ifdef ENABLE_DEBUGGER_SUPPORT
588 Handle<Object> Shell::DebugMessageDetails(Handle<String> message) {
589  Context::Scope context_scope(utility_context_);
590  Handle<Object> global = utility_context_->Global();
591  Handle<Value> fun = global->Get(String::New("DebugMessageDetails"));
592  static const int kArgc = 1;
593  Handle<Value> argv[kArgc] = { message };
594  Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
595  return Handle<Object>::Cast(val);
596 }
597 
598 
599 Handle<Value> Shell::DebugCommandToJSONRequest(Handle<String> command) {
600  Context::Scope context_scope(utility_context_);
601  Handle<Object> global = utility_context_->Global();
602  Handle<Value> fun = global->Get(String::New("DebugCommandToJSONRequest"));
603  static const int kArgc = 1;
604  Handle<Value> argv[kArgc] = { command };
605  Handle<Value> val = Handle<Function>::Cast(fun)->Call(global, kArgc, argv);
606  return val;
607 }
608 
609 
611  v8::Context::Scope scope(Shell::evaluation_context_);
613 }
614 #endif // ENABLE_DEBUGGER_SUPPORT
615 #endif // V8_SHARED
616 
617 
618 #ifndef V8_SHARED
619 int32_t* Counter::Bind(const char* name, bool is_histogram) {
620  int i;
621  for (i = 0; i < kMaxNameSize - 1 && name[i]; i++)
622  name_[i] = static_cast<char>(name[i]);
623  name_[i] = '\0';
624  is_histogram_ = is_histogram;
625  return ptr();
626 }
627 
628 
630  count_++;
631  sample_total_ += sample;
632 }
633 
634 
636  magic_number_ = 0xDEADFACE;
637  max_counters_ = kMaxCounters;
638  max_name_size_ = Counter::kMaxNameSize;
639  counters_in_use_ = 0;
640 }
641 
642 
644  if (counters_in_use_ == kMaxCounters) return NULL;
645  return &counters_[counters_in_use_++];
646 }
647 
648 
649 void Shell::MapCounters(const char* name) {
650  counters_file_ = i::OS::MemoryMappedFile::create(
651  name, sizeof(CounterCollection), &local_counters_);
652  void* memory = (counters_file_ == NULL) ?
653  NULL : counters_file_->memory();
654  if (memory == NULL) {
655  printf("Could not map counters file %s\n", name);
656  Exit(1);
657  }
658  counters_ = static_cast<CounterCollection*>(memory);
662 }
663 
664 
665 int CounterMap::Hash(const char* name) {
666  int h = 0;
667  int c;
668  while ((c = *name++) != 0) {
669  h += h << 5;
670  h += c;
671  }
672  return h;
673 }
674 
675 
676 Counter* Shell::GetCounter(const char* name, bool is_histogram) {
677  Counter* counter = counter_map_->Lookup(name);
678 
679  if (counter == NULL) {
680  counter = counters_->GetNextCounter();
681  if (counter != NULL) {
682  counter_map_->Set(name, counter);
683  counter->Bind(name, is_histogram);
684  }
685  } else {
686  ASSERT(counter->is_histogram() == is_histogram);
687  }
688  return counter;
689 }
690 
691 
692 int* Shell::LookupCounter(const char* name) {
693  Counter* counter = GetCounter(name, false);
694 
695  if (counter != NULL) {
696  return counter->ptr();
697  } else {
698  return NULL;
699  }
700 }
701 
702 
703 void* Shell::CreateHistogram(const char* name,
704  int min,
705  int max,
706  size_t buckets) {
707  return GetCounter(name, true);
708 }
709 
710 
711 void Shell::AddHistogramSample(void* histogram, int sample) {
712  Counter* counter = reinterpret_cast<Counter*>(histogram);
713  counter->AddSample(sample);
714 }
715 
716 
717 void Shell::InstallUtilityScript() {
718  Locker lock;
719  HandleScope scope;
720  // If we use the utility context, we have to set the security tokens so that
721  // utility, evaluation and debug context can all access each other.
722  utility_context_->SetSecurityToken(Undefined());
723  evaluation_context_->SetSecurityToken(Undefined());
724  Context::Scope utility_scope(utility_context_);
725 
726 #ifdef ENABLE_DEBUGGER_SUPPORT
727  if (i::FLAG_debugger) printf("JavaScript debugger enabled\n");
728  // Install the debugger object in the utility scope
729  i::Debug* debug = i::Isolate::Current()->debug();
730  debug->Load();
731  i::Handle<i::JSObject> js_debug
732  = i::Handle<i::JSObject>(debug->debug_context()->global());
733  utility_context_->Global()->Set(String::New("$debug"),
734  Utils::ToLocal(js_debug));
735  debug->debug_context()->set_security_token(HEAP->undefined_value());
736 #endif // ENABLE_DEBUGGER_SUPPORT
737 
738  // Run the d8 shell utility script in the utility context
739  int source_index = i::NativesCollection<i::D8>::GetIndex("d8");
740  i::Vector<const char> shell_source =
742  i::Vector<const char> shell_source_name =
744  Handle<String> source = String::New(shell_source.start(),
745  shell_source.length());
746  Handle<String> name = String::New(shell_source_name.start(),
747  shell_source_name.length());
748  Handle<Script> script = Script::Compile(source, name);
749  script->Run();
750  // Mark the d8 shell script as native to avoid it showing up as normal source
751  // in the debugger.
752  i::Handle<i::Object> compiled_script = Utils::OpenHandle(*script);
753  i::Handle<i::Script> script_object = compiled_script->IsJSFunction()
755  i::JSFunction::cast(*compiled_script)->shared()->script()))
756  : i::Handle<i::Script>(i::Script::cast(
757  i::SharedFunctionInfo::cast(*compiled_script)->script()));
758  script_object->set_type(i::Smi::FromInt(i::Script::TYPE_NATIVE));
759 
760 #ifdef ENABLE_DEBUGGER_SUPPORT
761  // Start the in-process debugger if requested.
762  if (i::FLAG_debugger && !i::FLAG_debugger_agent) {
764  }
765 #endif // ENABLE_DEBUGGER_SUPPORT
766 }
767 #endif // V8_SHARED
768 
769 
770 #ifdef COMPRESS_STARTUP_DATA_BZ2
771 class BZip2Decompressor : public v8::StartupDataDecompressor {
772  public:
773  virtual ~BZip2Decompressor() { }
774 
775  protected:
776  virtual int DecompressData(char* raw_data,
777  int* raw_data_size,
778  const char* compressed_data,
779  int compressed_data_size) {
782  unsigned int decompressed_size = *raw_data_size;
783  int result =
784  BZ2_bzBuffToBuffDecompress(raw_data,
785  &decompressed_size,
786  const_cast<char*>(compressed_data),
787  compressed_data_size,
788  0, 1);
789  if (result == BZ_OK) {
790  *raw_data_size = decompressed_size;
791  }
792  return result;
793  }
794 };
795 #endif
796 
797 Handle<ObjectTemplate> Shell::CreateGlobalTemplate() {
798  Handle<ObjectTemplate> global_template = ObjectTemplate::New();
799  global_template->Set(String::New("print"), FunctionTemplate::New(Print));
800  global_template->Set(String::New("write"), FunctionTemplate::New(Write));
801  global_template->Set(String::New("read"), FunctionTemplate::New(Read));
802  global_template->Set(String::New("readbuffer"),
804  global_template->Set(String::New("readline"),
806  global_template->Set(String::New("load"), FunctionTemplate::New(Load));
807  global_template->Set(String::New("quit"), FunctionTemplate::New(Quit));
808  global_template->Set(String::New("version"), FunctionTemplate::New(Version));
809  global_template->Set(String::New("enableProfiler"),
811  global_template->Set(String::New("disableProfiler"),
813 
814  // Bind the handlers for external arrays.
815  global_template->Set(String::New("ArrayBuffer"),
817  global_template->Set(String::New("Int8Array"),
819  global_template->Set(String::New("Uint8Array"),
821  global_template->Set(String::New("Int16Array"),
823  global_template->Set(String::New("Uint16Array"),
825  global_template->Set(String::New("Int32Array"),
827  global_template->Set(String::New("Uint32Array"),
829  global_template->Set(String::New("Float32Array"),
831  global_template->Set(String::New("Float64Array"),
833  global_template->Set(String::New("PixelArray"),
835 
836 #ifdef LIVE_OBJECT_LIST
837  global_template->Set(String::New("lol_is_enabled"), True());
838 #else
839  global_template->Set(String::New("lol_is_enabled"), False());
840 #endif
841 
842 #if !defined(V8_SHARED) && !defined(_WIN32) && !defined(_WIN64)
843  Handle<ObjectTemplate> os_templ = ObjectTemplate::New();
844  AddOSMethods(os_templ);
845  global_template->Set(String::New("os"), os_templ);
846 #endif // V8_SHARED
847 
848  return global_template;
849 }
850 
851 
852 void Shell::Initialize() {
853 #ifdef COMPRESS_STARTUP_DATA_BZ2
854  BZip2Decompressor startup_data_decompressor;
855  int bz2_result = startup_data_decompressor.Decompress();
856  if (bz2_result != BZ_OK) {
857  fprintf(stderr, "bzip error code: %d\n", bz2_result);
858  Exit(1);
859  }
860 #endif
861 
862 #ifndef V8_SHARED
863  Shell::counter_map_ = new CounterMap();
864  // Set up counters
865  if (i::StrLength(i::FLAG_map_counters) != 0)
866  MapCounters(i::FLAG_map_counters);
867  if (i::FLAG_dump_counters) {
871  }
872 #endif // V8_SHARED
873  if (options.test_shell) return;
874 
875 #ifndef V8_SHARED
876  Locker lock;
877  HandleScope scope;
878  Handle<ObjectTemplate> global_template = CreateGlobalTemplate();
879  utility_context_ = Context::New(NULL, global_template);
880 
881 #ifdef ENABLE_DEBUGGER_SUPPORT
882  // Start the debugger agent if requested.
883  if (i::FLAG_debugger_agent) {
884  v8::Debug::EnableAgent("d8 shell", i::FLAG_debugger_port, true);
886  }
887 #endif // ENABLE_DEBUGGER_SUPPORT
888 #endif // V8_SHARED
889 }
890 
891 
893 #ifndef V8_SHARED
894  // This needs to be a critical section since this is not thread-safe
895  i::ScopedLock lock(context_mutex_);
896 #endif // V8_SHARED
897  // Initialize the global objects
898  Handle<ObjectTemplate> global_template = CreateGlobalTemplate();
899  Persistent<Context> context = Context::New(NULL, global_template);
900  ASSERT(!context.IsEmpty());
901  Context::Scope scope(context);
902 
903 #ifndef V8_SHARED
904  i::JSArguments js_args = i::FLAG_js_arguments;
905  i::Handle<i::FixedArray> arguments_array =
906  FACTORY->NewFixedArray(js_args.argc());
907  for (int j = 0; j < js_args.argc(); j++) {
909  FACTORY->NewStringFromUtf8(i::CStrVector(js_args[j]));
910  arguments_array->set(j, *arg);
911  }
912  i::Handle<i::JSArray> arguments_jsarray =
913  FACTORY->NewJSArrayWithElements(arguments_array);
914  context->Global()->Set(String::New("arguments"),
915  Utils::ToLocal(arguments_jsarray));
916 #endif // V8_SHARED
917  return context;
918 }
919 
920 
921 void Shell::Exit(int exit_code) {
922  // Use _exit instead of exit to avoid races between isolate
923  // threads and static destructors.
924  fflush(stdout);
925  fflush(stderr);
926  _exit(exit_code);
927 }
928 
929 
930 #ifndef V8_SHARED
933  const char* key;
934 };
935 
936 
937 int CompareKeys(const void* a, const void* b) {
938  return strcmp(static_cast<const CounterAndKey*>(a)->key,
939  static_cast<const CounterAndKey*>(b)->key);
940 }
941 
942 
944  if (console != NULL) console->Close();
945  if (i::FLAG_dump_counters) {
946  int number_of_counters = 0;
947  for (CounterMap::Iterator i(counter_map_); i.More(); i.Next()) {
948  number_of_counters++;
949  }
950  CounterAndKey* counters = new CounterAndKey[number_of_counters];
951  int j = 0;
952  for (CounterMap::Iterator i(counter_map_); i.More(); i.Next(), j++) {
953  counters[j].counter = i.CurrentValue();
954  counters[j].key = i.CurrentKey();
955  }
956  qsort(counters, number_of_counters, sizeof(counters[0]), CompareKeys);
957  printf("+--------------------------------------------+-------------+\n");
958  printf("| Name | Value |\n");
959  printf("+--------------------------------------------+-------------+\n");
960  for (j = 0; j < number_of_counters; j++) {
961  Counter* counter = counters[j].counter;
962  const char* key = counters[j].key;
963  if (counter->is_histogram()) {
964  printf("| c:%-40s | %11i |\n", key, counter->count());
965  printf("| t:%-40s | %11i |\n", key, counter->sample_total());
966  } else {
967  printf("| %-42s | %11i |\n", key, counter->count());
968  }
969  }
970  printf("+--------------------------------------------+-------------+\n");
971  delete [] counters;
972  }
973  delete counters_file_;
974  delete counter_map_;
975 }
976 #endif // V8_SHARED
977 
978 
979 static FILE* FOpen(const char* path, const char* mode) {
980 #if defined(_MSC_VER) && (defined(_WIN32) || defined(_WIN64))
981  FILE* result;
982  if (fopen_s(&result, path, mode) == 0) {
983  return result;
984  } else {
985  return NULL;
986  }
987 #else
988  FILE* file = fopen(path, mode);
989  if (file == NULL) return NULL;
990  struct stat file_stat;
991  if (fstat(fileno(file), &file_stat) != 0) return NULL;
992  bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
993  if (is_regular_file) return file;
994  fclose(file);
995  return NULL;
996 #endif
997 }
998 
999 
1000 static char* ReadChars(const char* name, int* size_out) {
1001  // Release the V8 lock while reading files.
1002  v8::Unlocker unlocker(Isolate::GetCurrent());
1003  FILE* file = FOpen(name, "rb");
1004  if (file == NULL) return NULL;
1005 
1006  fseek(file, 0, SEEK_END);
1007  int size = ftell(file);
1008  rewind(file);
1009 
1010  char* chars = new char[size + 1];
1011  chars[size] = '\0';
1012  for (int i = 0; i < size;) {
1013  int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
1014  i += read;
1015  }
1016  fclose(file);
1017  *size_out = size;
1018  return chars;
1019 }
1020 
1021 
1023  ASSERT(sizeof(char) == sizeof(uint8_t)); // NOLINT
1024  String::Utf8Value filename(args[0]);
1025  int length;
1026  if (*filename == NULL) {
1027  return ThrowException(String::New("Error loading file"));
1028  }
1029 
1030  uint8_t* data = reinterpret_cast<uint8_t*>(ReadChars(*filename, &length));
1031  if (data == NULL) {
1032  return ThrowException(String::New("Error reading file"));
1033  }
1034  Handle<Object> buffer = Object::New();
1036  Persistent<Object> persistent_buffer = Persistent<Object>::New(buffer);
1037  persistent_buffer.MakeWeak(data, ExternalArrayWeakCallback);
1038  persistent_buffer.MarkIndependent();
1040 
1042  data, kExternalUnsignedByteArray, length);
1043  buffer->Set(String::New("byteLength"),
1044  Int32::New(static_cast<int32_t>(length)), ReadOnly);
1045  return buffer;
1046 }
1047 
1048 
1049 #ifndef V8_SHARED
1050 static char* ReadToken(char* data, char token) {
1051  char* next = i::OS::StrChr(data, token);
1052  if (next != NULL) {
1053  *next = '\0';
1054  return (next + 1);
1055  }
1056 
1057  return NULL;
1058 }
1059 
1060 
1061 static char* ReadLine(char* data) {
1062  return ReadToken(data, '\n');
1063 }
1064 
1065 
1066 static char* ReadWord(char* data) {
1067  return ReadToken(data, ' ');
1068 }
1069 #endif // V8_SHARED
1070 
1071 
1072 // Reads a file into a v8 string.
1073 Handle<String> Shell::ReadFile(const char* name) {
1074  int size = 0;
1075  char* chars = ReadChars(name, &size);
1076  if (chars == NULL) return Handle<String>();
1077  Handle<String> result = String::New(chars);
1078  delete[] chars;
1079  return result;
1080 }
1081 
1082 
1083 void Shell::RunShell() {
1084  Locker locker;
1085  Context::Scope context_scope(evaluation_context_);
1086  HandleScope outer_scope;
1087  Handle<String> name = String::New("(d8)");
1089  printf("V8 version %s [console: %s]\n", V8::GetVersion(), console->name());
1090  console->Open();
1091  while (true) {
1092  HandleScope inner_scope;
1094  if (input.IsEmpty()) break;
1095  ExecuteString(input, name, true, true);
1096  }
1097  printf("\n");
1098 }
1099 
1100 
1101 #ifndef V8_SHARED
1102 class ShellThread : public i::Thread {
1103  public:
1104  // Takes ownership of the underlying char array of |files|.
1105  ShellThread(int no, char* files)
1106  : Thread("d8:ShellThread"),
1107  no_(no), files_(files) { }
1108 
1110  delete[] files_;
1111  }
1112 
1113  virtual void Run();
1114  private:
1115  int no_;
1116  char* files_;
1117 };
1118 
1119 
1121  char* ptr = files_;
1122  while ((ptr != NULL) && (*ptr != '\0')) {
1123  // For each newline-separated line.
1124  char* next_line = ReadLine(ptr);
1125 
1126  if (*ptr == '#') {
1127  // Skip comment lines.
1128  ptr = next_line;
1129  continue;
1130  }
1131 
1132  // Prepare the context for this thread.
1133  Locker locker;
1134  HandleScope outer_scope;
1136  Context::Scope context_scope(thread_context);
1137 
1138  while ((ptr != NULL) && (*ptr != '\0')) {
1139  HandleScope inner_scope;
1140  char* filename = ptr;
1141  ptr = ReadWord(ptr);
1142 
1143  // Skip empty strings.
1144  if (strlen(filename) == 0) {
1145  continue;
1146  }
1147 
1148  Handle<String> str = Shell::ReadFile(filename);
1149  if (str.IsEmpty()) {
1150  printf("File '%s' not found\n", filename);
1151  Shell::Exit(1);
1152  }
1153 
1154  Shell::ExecuteString(str, String::New(filename), false, false);
1155  }
1156 
1157  thread_context.Dispose();
1158  ptr = next_line;
1159  }
1160 }
1161 #endif // V8_SHARED
1162 
1163 
1165 #ifndef V8_SHARED
1166  delete next_semaphore_;
1167  next_semaphore_ = NULL;
1168  delete done_semaphore_;
1169  done_semaphore_ = NULL;
1170  delete thread_;
1171  thread_ = NULL;
1172 #endif // V8_SHARED
1173 }
1174 
1175 
1177  for (int i = begin_offset_; i < end_offset_; ++i) {
1178  const char* arg = argv_[i];
1179  if (strcmp(arg, "-e") == 0 && i + 1 < end_offset_) {
1180  // Execute argument given to -e option directly.
1181  HandleScope handle_scope;
1182  Handle<String> file_name = String::New("unnamed");
1183  Handle<String> source = String::New(argv_[i + 1]);
1184  if (!Shell::ExecuteString(source, file_name, false, true)) {
1185  Shell::Exit(1);
1186  }
1187  ++i;
1188  } else if (arg[0] == '-') {
1189  // Ignore other options. They have been parsed already.
1190  } else {
1191  // Use all other arguments as names of files to load and run.
1192  HandleScope handle_scope;
1193  Handle<String> file_name = String::New(arg);
1194  Handle<String> source = ReadFile(arg);
1195  if (source.IsEmpty()) {
1196  printf("Error reading '%s'\n", arg);
1197  Shell::Exit(1);
1198  }
1199  if (!Shell::ExecuteString(source, file_name, false, true)) {
1200  Shell::Exit(1);
1201  }
1202  }
1203  }
1204 }
1205 
1206 
1207 Handle<String> SourceGroup::ReadFile(const char* name) {
1208  int size;
1209  char* chars = ReadChars(name, &size);
1210  if (chars == NULL) return Handle<String>();
1211  Handle<String> result = String::New(chars, size);
1212  delete[] chars;
1213  return result;
1214 }
1215 
1216 
1217 #ifndef V8_SHARED
1218 i::Thread::Options SourceGroup::GetThreadOptions() {
1219  // On some systems (OSX 10.6) the stack size default is 0.5Mb or less
1220  // which is not enough to parse the big literal expressions used in tests.
1221  // The stack size should be at least StackGuard::kLimitSize + some
1222  // OS-specific padding for thread startup code. 2Mbytes seems to be enough.
1223  return i::Thread::Options("IsolateThread", 2 * MB);
1224 }
1225 
1226 
1227 void SourceGroup::ExecuteInThread() {
1228  Isolate* isolate = Isolate::New();
1229  do {
1230  if (next_semaphore_ != NULL) next_semaphore_->Wait();
1231  {
1232  Isolate::Scope iscope(isolate);
1233  Locker lock(isolate);
1234  HandleScope scope;
1235  Persistent<Context> context = Shell::CreateEvaluationContext();
1236  {
1237  Context::Scope cscope(context);
1238  Execute();
1239  }
1240  context.Dispose();
1241  }
1242  if (done_semaphore_ != NULL) done_semaphore_->Signal();
1243  } while (!Shell::options.last_run);
1244  isolate->Dispose();
1245 }
1246 
1247 
1249  if (thread_ == NULL) {
1250  thread_ = new IsolateThread(this);
1251  thread_->Start();
1252  }
1253  next_semaphore_->Signal();
1254 }
1255 
1256 
1258  if (thread_ == NULL) return;
1259  if (Shell::options.last_run) {
1260  thread_->Join();
1261  } else {
1262  done_semaphore_->Wait();
1263  }
1264 }
1265 #endif // V8_SHARED
1266 
1267 
1268 bool Shell::SetOptions(int argc, char* argv[]) {
1269  for (int i = 0; i < argc; i++) {
1270  if (strcmp(argv[i], "--stress-opt") == 0) {
1271  options.stress_opt = true;
1272  argv[i] = NULL;
1273  } else if (strcmp(argv[i], "--stress-deopt") == 0) {
1274  options.stress_deopt = true;
1275  argv[i] = NULL;
1276  } else if (strcmp(argv[i], "--noalways-opt") == 0) {
1277  // No support for stressing if we can't use --always-opt.
1278  options.stress_opt = false;
1279  options.stress_deopt = false;
1280  } else if (strcmp(argv[i], "--shell") == 0) {
1281  options.interactive_shell = true;
1282  argv[i] = NULL;
1283  } else if (strcmp(argv[i], "--test") == 0) {
1284  options.test_shell = true;
1285  argv[i] = NULL;
1286  } else if (strcmp(argv[i], "--preemption") == 0) {
1287 #ifdef V8_SHARED
1288  printf("D8 with shared library does not support multi-threading\n");
1289  return false;
1290 #else
1291  options.use_preemption = true;
1292  argv[i] = NULL;
1293 #endif // V8_SHARED
1294  } else if (strcmp(argv[i], "--nopreemption") == 0) {
1295 #ifdef V8_SHARED
1296  printf("D8 with shared library does not support multi-threading\n");
1297  return false;
1298 #else
1299  options.use_preemption = false;
1300  argv[i] = NULL;
1301 #endif // V8_SHARED
1302  } else if (strcmp(argv[i], "--preemption-interval") == 0) {
1303 #ifdef V8_SHARED
1304  printf("D8 with shared library does not support multi-threading\n");
1305  return false;
1306 #else
1307  if (++i < argc) {
1308  argv[i-1] = NULL;
1309  char* end = NULL;
1310  options.preemption_interval = strtol(argv[i], &end, 10); // NOLINT
1311  if (options.preemption_interval <= 0
1312  || *end != '\0'
1313  || errno == ERANGE) {
1314  printf("Invalid value for --preemption-interval '%s'\n", argv[i]);
1315  return false;
1316  }
1317  argv[i] = NULL;
1318  } else {
1319  printf("Missing value for --preemption-interval\n");
1320  return false;
1321  }
1322 #endif // V8_SHARED
1323  } else if (strcmp(argv[i], "-f") == 0) {
1324  // Ignore any -f flags for compatibility with other stand-alone
1325  // JavaScript engines.
1326  continue;
1327  } else if (strcmp(argv[i], "--isolate") == 0) {
1328 #ifdef V8_SHARED
1329  printf("D8 with shared library does not support multi-threading\n");
1330  return false;
1331 #endif // V8_SHARED
1333  } else if (strcmp(argv[i], "-p") == 0) {
1334 #ifdef V8_SHARED
1335  printf("D8 with shared library does not support multi-threading\n");
1336  return false;
1337 #else
1339 #endif // V8_SHARED
1340  }
1341 #ifdef V8_SHARED
1342  else if (strcmp(argv[i], "--dump-counters") == 0) {
1343  printf("D8 with shared library does not include counters\n");
1344  return false;
1345  } else if (strcmp(argv[i], "--debugger") == 0) {
1346  printf("Javascript debugger not included\n");
1347  return false;
1348  }
1349 #endif // V8_SHARED
1350  }
1351 
1352 #ifndef V8_SHARED
1353  // Run parallel threads if we are not using --isolate
1355  int parallel_files_set = 0;
1356  for (int i = 1; i < argc; i++) {
1357  if (argv[i] == NULL) continue;
1358  if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) {
1359  if (options.num_isolates > 1) {
1360  printf("-p is not compatible with --isolate\n");
1361  return false;
1362  }
1363  argv[i] = NULL;
1364  i++;
1365  options.parallel_files[parallel_files_set] = argv[i];
1366  parallel_files_set++;
1367  argv[i] = NULL;
1368  }
1369  }
1370  if (parallel_files_set != options.num_parallel_files) {
1371  printf("-p requires a file containing a list of files as parameter\n");
1372  return false;
1373  }
1374 #endif // V8_SHARED
1375 
1376  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
1377 
1378  // Set up isolated source groups.
1379  options.isolate_sources = new SourceGroup[options.num_isolates];
1380  SourceGroup* current = options.isolate_sources;
1381  current->Begin(argv, 1);
1382  for (int i = 1; i < argc; i++) {
1383  const char* str = argv[i];
1384  if (strcmp(str, "--isolate") == 0) {
1385  current->End(i);
1386  current++;
1387  current->Begin(argv, i + 1);
1388  } else if (strncmp(argv[i], "--", 2) == 0) {
1389  printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
1390  }
1391  }
1392  current->End(argc);
1393 
1394  return true;
1395 }
1396 
1397 
1398 int Shell::RunMain(int argc, char* argv[]) {
1399 #ifndef V8_SHARED
1400  i::List<i::Thread*> threads(1);
1401  if (options.parallel_files != NULL) {
1402  for (int i = 0; i < options.num_parallel_files; i++) {
1403  char* files = NULL;
1404  { Locker lock(Isolate::GetCurrent());
1405  int size = 0;
1406  files = ReadChars(options.parallel_files[i], &size);
1407  }
1408  if (files == NULL) {
1409  printf("File list '%s' not found\n", options.parallel_files[i]);
1410  Exit(1);
1411  }
1412  ShellThread* thread = new ShellThread(threads.length(), files);
1413  thread->Start();
1414  threads.Add(thread);
1415  }
1416  }
1417  for (int i = 1; i < options.num_isolates; ++i) {
1419  }
1420 #endif // V8_SHARED
1421  { // NOLINT
1422  Locker lock;
1423  HandleScope scope;
1425  if (options.last_run) {
1426  // Keep using the same context in the interactive shell.
1427  evaluation_context_ = context;
1428 #if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
1429  // If the interactive debugger is enabled make sure to activate
1430  // it before running the files passed on the command line.
1431  if (i::FLAG_debugger) {
1432  InstallUtilityScript();
1433  }
1434 #endif // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
1435  }
1436  {
1437  Context::Scope cscope(context);
1439  }
1440  if (!options.last_run) {
1441  context.Dispose();
1442 #if !defined(V8_SHARED)
1443  if (i::FLAG_send_idle_notification) {
1444  const int kLongIdlePauseInMs = 1000;
1446  V8::IdleNotification(kLongIdlePauseInMs);
1447  }
1448 #endif // !V8_SHARED
1449  }
1450 
1451 #ifndef V8_SHARED
1452  // Start preemption if threads have been created and preemption is enabled.
1453  if (threads.length() > 0
1454  && options.use_preemption) {
1456  }
1457 #endif // V8_SHARED
1458  }
1459 
1460 #ifndef V8_SHARED
1461  for (int i = 1; i < options.num_isolates; ++i) {
1463  }
1464 
1465  for (int i = 0; i < threads.length(); i++) {
1466  i::Thread* thread = threads[i];
1467  thread->Join();
1468  delete thread;
1469  }
1470 
1471  if (threads.length() > 0 && options.use_preemption) {
1472  Locker lock;
1474  }
1475 #endif // V8_SHARED
1476  return 0;
1477 }
1478 
1479 
1480 int Shell::Main(int argc, char* argv[]) {
1481  if (!SetOptions(argc, argv)) return 1;
1482  Initialize();
1483 
1484  int result = 0;
1489  int stress_runs = Testing::GetStressRuns();
1490  for (int i = 0; i < stress_runs && result == 0; i++) {
1491  printf("============ Stress %d/%d ============\n", i + 1, stress_runs);
1493  options.last_run = (i == stress_runs - 1);
1494  result = RunMain(argc, argv);
1495  }
1496  printf("======== Full Deoptimization =======\n");
1498 #if !defined(V8_SHARED)
1499  } else if (i::FLAG_stress_runs > 0) {
1500  int stress_runs = i::FLAG_stress_runs;
1501  for (int i = 0; i < stress_runs && result == 0; i++) {
1502  printf("============ Run %d/%d ============\n", i + 1, stress_runs);
1503  options.last_run = (i == stress_runs - 1);
1504  result = RunMain(argc, argv);
1505  }
1506 #endif
1507  } else {
1508  result = RunMain(argc, argv);
1509  }
1510 
1511 
1512 #if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
1513  // Run remote debugger if requested, but never on --test
1514  if (i::FLAG_remote_debugger && !options.test_shell) {
1515  InstallUtilityScript();
1516  RunRemoteDebugger(i::FLAG_debugger_port);
1517  return 0;
1518  }
1519 #endif // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
1520 
1521  // Run interactive shell if explicitly requested or if no script has been
1522  // executed, but never on --test
1523 
1525  || !options.script_executed )
1526  && !options.test_shell ) {
1527 #if !defined(V8_SHARED) && defined(ENABLE_DEBUGGER_SUPPORT)
1528  if (!i::FLAG_debugger) {
1529  InstallUtilityScript();
1530  }
1531 #endif // !V8_SHARED && ENABLE_DEBUGGER_SUPPORT
1532  RunShell();
1533  }
1534 
1535  V8::Dispose();
1536 
1537 #ifndef V8_SHARED
1538  OnExit();
1539 #endif // V8_SHARED
1540 
1541  return result;
1542 }
1543 
1544 } // namespace v8
1545 
1546 
1547 #ifndef GOOGLE3
1548 int main(int argc, char* argv[]) {
1549  return v8::Shell::Main(argc, argv);
1550 }
1551 #endif
static Isolate * GetCurrent()
Definition: api.cc:5380
static void Exit(int exit_code)
Definition: d8.cc:921
void MakeWeak(void *parameters, WeakReferenceCallback callback)
Definition: v8.h:4075
static Handle< Array > GetCompletions(Handle< String > text, Handle< String > full)
Definition: d8.cc:575
void Set(const char *name, Counter *value)
Definition: d8.h:90
static Local< Script > Compile(Handle< String > source, ScriptOrigin *origin=NULL, ScriptData *pre_data=NULL, Handle< String > script_data=Handle< String >())
Definition: api.cc:1560
Counter * counter
Definition: d8.cc:932
int num_parallel_files
Definition: d8.h:247
bool use_preemption
Definition: d8.h:245
void RunRemoteDebugger(int port)
static const int kMaxLength
Definition: objects.h:3717
static Local< FunctionTemplate > New(InvocationCallback callback=0, Handle< Value > data=Handle< Value >(), Handle< Signature > signature=Handle< Signature >())
Definition: api.cc:943
Handle< Boolean > V8EXPORT True()
Definition: api.cc:566
static int GetStressRuns()
Definition: api.cc:6286
void Dispose()
Definition: v8.h:4065
char ** parallel_files
Definition: d8.h:248
Thread(const Options &options)
Local< Value > Exception() const
Definition: api.cc:1712
static void SetAddHistogramSampleFunction(AddHistogramSampleCallback)
Definition: api.cc:5189
V8EXPORT Local< Value > Get(Handle< Value > key)
Definition: api.cc:2845
static Handle< Value > Version(const Arguments &args)
Definition: d8.cc:523
static Smi * FromInt(int value)
Definition: objects-inl.h:973
static int Main(int argc, char *argv[])
Definition: d8.cc:1480
static int GetIndex(const char *name)
void WaitForThread()
Definition: d8.cc:1257
bool HasCaught() const
Definition: api.cc:1695
static void AddHistogramSample(void *histogram, int sample)
Definition: d8.cc:711
void AddSample(int32_t sample)
Definition: d8.cc:629
bool interactive_shell
Definition: d8.h:254
static Handle< Value > Int32Array(const Arguments &args)
Definition: d8.cc:480
static Handle< Value > Float32Array(const Arguments &args)
Definition: d8.cc:490
static Vector< const char > GetRawScriptSource(int index)
value format" "after each garbage collection") DEFINE_bool(print_cumulative_gc_stat, false, "print cumulative GC statistics in name=value format on exit") DEFINE_bool(trace_gc_verbose, false, "print more details following each garbage collection") DEFINE_bool(trace_fragmentation, false, "report fragmentation for old pointer and data pages") DEFINE_bool(collect_maps, true, "garbage collect maps from which no objects can be reached") DEFINE_bool(flush_code, true, "flush code that we expect not to use again before full gc") DEFINE_bool(incremental_marking, true, "use incremental marking") DEFINE_bool(incremental_marking_steps, true, "do incremental marking steps") DEFINE_bool(trace_incremental_marking, false, "trace progress of the incremental marking") DEFINE_bool(use_idle_notification, true, "Use idle notification to reduce memory footprint.") DEFINE_bool(send_idle_notification, false, "Send idle notifcation between stress runs.") DEFINE_bool(use_ic, true, "use inline caching") DEFINE_bool(native_code_counters, false, "generate extra code for manipulating stats counters") DEFINE_bool(always_compact, false, "Perform compaction on every full GC") DEFINE_bool(lazy_sweeping, true, "Use lazy sweeping for old pointer and data spaces") DEFINE_bool(never_compact, false, "Never perform compaction on full GC-testing only") DEFINE_bool(compact_code_space, true, "Compact code space on full non-incremental collections") DEFINE_bool(cleanup_code_caches_at_gc, true, "Flush inline caches prior to mark compact collection and" "flush code caches in maps during mark compact cycle.") DEFINE_int(random_seed, 0, "Default seed for initializing random generator" "(0, the default, means to use system random).") DEFINE_bool(use_verbose_printer, true, "allows verbose printing") DEFINE_bool(allow_natives_syntax, false, "allow natives syntax") DEFINE_bool(trace_sim, false, "Trace simulator execution") DEFINE_bool(check_icache, false, "Check icache flushes in ARM and MIPS simulator") DEFINE_int(stop_sim_at, 0, "Simulator stop after x number of instructions") DEFINE_int(sim_stack_alignment, 8, "Stack alingment in bytes in simulator(4 or 8, 8 is default)") DEFINE_bool(trace_exception, false, "print stack trace when throwing exceptions") DEFINE_bool(preallocate_message_memory, false, "preallocate some memory to build stack traces.") DEFINE_bool(randomize_hashes, true, "randomize hashes to avoid predictable hash collisions" "(with snapshots this option cannot override the baked-in seed)") DEFINE_int(hash_seed, 0, "Fixed seed to use to hash property keys(0 means random)" "(with snapshots this option cannot override the baked-in seed)") DEFINE_bool(preemption, false, "activate a 100ms timer that switches between V8 threads") DEFINE_bool(regexp_optimization, true, "generate optimized regexp code") DEFINE_bool(testing_bool_flag, true, "testing_bool_flag") DEFINE_int(testing_int_flag, 13, "testing_int_flag") DEFINE_float(testing_float_flag, 2.5, "float-flag") DEFINE_string(testing_string_flag, "Hello, world!", "string-flag") DEFINE_int(testing_prng_seed, 42, "Seed used for threading test randomness") DEFINE_string(testing_serialization_file, "/tmp/serdes", "file in which to serialize heap") DEFINE_bool(help, false, "Print usage message, including flags, on console") DEFINE_bool(dump_counters, false, "Dump counters on exit") DEFINE_string(map_counters, "", "Map counters to a file") DEFINE_args(js_arguments, JSARGUMENTS_INIT, "Pass all remaining arguments to the script.Alias for\"--\".") DEFINE_bool(debug_compile_events, true,"Enable debugger compile events") DEFINE_bool(debug_script_collected_events, true,"Enable debugger script collected events") DEFINE_bool(gdbjit, false,"enable GDBJIT interface (disables compacting GC)") DEFINE_bool(gdbjit_full, false,"enable GDBJIT interface for all code objects") DEFINE_bool(gdbjit_dump, false,"dump elf objects with debug info to disk") DEFINE_string(gdbjit_dump_filter,"","dump only objects containing this substring") DEFINE_bool(force_marking_deque_overflows, false,"force overflows of marking deque by reducing it's size ""to 64 words") DEFINE_bool(stress_compaction, false,"stress the GC compactor to flush out bugs (implies ""--force_marking_deque_overflows)")#define FLAG DEFINE_bool(enable_slow_asserts, false,"enable asserts that are slow to execute") DEFINE_bool(trace_codegen, false,"print name of functions for which code is generated") DEFINE_bool(print_source, false,"pretty print source code") DEFINE_bool(print_builtin_source, false,"pretty print source code for builtins") DEFINE_bool(print_ast, false,"print source AST") DEFINE_bool(print_builtin_ast, false,"print source AST for builtins") DEFINE_string(stop_at,"","function name where to insert a breakpoint") DEFINE_bool(print_builtin_scopes, false,"print scopes for builtins") DEFINE_bool(print_scopes, false,"print scopes") DEFINE_bool(trace_contexts, false,"trace contexts operations") DEFINE_bool(gc_greedy, false,"perform GC prior to some allocations") DEFINE_bool(gc_verbose, false,"print stuff during garbage collection") DEFINE_bool(heap_stats, false,"report heap statistics before and after GC") DEFINE_bool(code_stats, false,"report code statistics after GC") DEFINE_bool(verify_heap, false,"verify heap pointers before and after GC") DEFINE_bool(print_handles, false,"report handles after GC") DEFINE_bool(print_global_handles, false,"report global handles after GC") DEFINE_bool(trace_ic, false,"trace inline cache state transitions") DEFINE_bool(print_interfaces, false,"print interfaces") DEFINE_bool(print_interface_details, false,"print interface inference details") DEFINE_int(print_interface_depth, 5,"depth for printing interfaces") DEFINE_bool(trace_normalization, false,"prints when objects are turned into dictionaries.") DEFINE_bool(trace_lazy, false,"trace lazy compilation") DEFINE_bool(collect_heap_spill_statistics, false,"report heap spill statistics along with heap_stats ""(requires heap_stats)") DEFINE_bool(trace_isolates, false,"trace isolate state changes") DEFINE_bool(log_state_changes, false,"Log state changes.") DEFINE_bool(regexp_possessive_quantifier, false,"enable possessive quantifier syntax for testing") DEFINE_bool(trace_regexp_bytecodes, false,"trace regexp bytecode execution") DEFINE_bool(trace_regexp_assembler, false,"trace regexp macro assembler calls.")#define FLAG DEFINE_bool(log, false,"Minimal logging (no API, code, GC, suspect, or handles samples).") DEFINE_bool(log_all, false,"Log all events to the log file.") DEFINE_bool(log_runtime, false,"Activate runtime system %Log call.") DEFINE_bool(log_api, false,"Log API events to the log file.") DEFINE_bool(log_code, false,"Log code events to the log file without profiling.") DEFINE_bool(log_gc, false,"Log heap samples on garbage collection for the hp2ps tool.") DEFINE_bool(log_handles, false,"Log global handle events.") DEFINE_bool(log_snapshot_positions, false,"log positions of (de)serialized objects in the snapshot.") DEFINE_bool(log_suspect, false,"Log suspect operations.") DEFINE_bool(prof, false,"Log statistical profiling information (implies --log-code).") DEFINE_bool(prof_auto, true,"Used with --prof, starts profiling automatically") DEFINE_bool(prof_lazy, false,"Used with --prof, only does sampling and logging"" when profiler is active (implies --noprof_auto).") DEFINE_bool(prof_browser_mode, true,"Used with --prof, turns on browser-compatible mode for profiling.") DEFINE_bool(log_regexp, false,"Log regular expression execution.") DEFINE_bool(sliding_state_window, false,"Update sliding state window counters.") DEFINE_string(logfile,"v8.log","Specify the name of the log file.") DEFINE_bool(ll_prof, false,"Enable low-level linux profiler.")#define FLAG DEFINE_bool(trace_elements_transitions, false,"trace elements transitions") DEFINE_bool(print_code_stubs, false,"print code stubs") DEFINE_bool(test_secondary_stub_cache, false,"test secondary stub cache by disabling the primary one") DEFINE_bool(test_primary_stub_cache, false,"test primary stub cache by disabling the secondary one") DEFINE_bool(print_code, false,"print generated code") DEFINE_bool(print_opt_code, false,"print optimized code") DEFINE_bool(print_unopt_code, false,"print unoptimized code before ""printing optimized code based on it") DEFINE_bool(print_code_verbose, false,"print more information for code") DEFINE_bool(print_builtin_code, false,"print generated code for builtins")#43"/Users/thlorenz/dev/dx/v8-perf/build/v8/src/flags.cc"2#define FLAG_MODE_DEFINE_DEFAULTS#1"/Users/thlorenz/dev/dx/v8-perf/build/v8/src/flag-definitions.h"1#define FLAG_FULL(ftype, ctype, nam, def, cmt)#define FLAG_READONLY(ftype, ctype, nam, def, cmt)#define DEFINE_implication(whenflag, thenflag)#define DEFINE_bool(nam, def, cmt)#define DEFINE_int(nam, def, cmt)#define DEFINE_float(nam, def, cmt)#define DEFINE_string(nam, def, cmt)#define DEFINE_args(nam, def, cmt)#define FLAG DEFINE_bool(use_strict, false,"enforce strict mode") DEFINE_bool(es5_readonly, false,"activate correct semantics for inheriting readonliness") DEFINE_bool(es52_globals, false,"activate new semantics for global var declarations") DEFINE_bool(harmony_typeof, false,"enable harmony semantics for typeof") DEFINE_bool(harmony_scoping, false,"enable harmony block scoping") DEFINE_bool(harmony_modules, false,"enable harmony modules (implies block scoping)") DEFINE_bool(harmony_proxies, false,"enable harmony proxies") DEFINE_bool(harmony_collections, false,"enable harmony collections (sets, maps, and weak maps)") DEFINE_bool(harmony, false,"enable all harmony features (except typeof)") DEFINE_implication(harmony, harmony_scoping) DEFINE_implication(harmony, harmony_modules) DEFINE_implication(harmony, harmony_proxies) DEFINE_implication(harmony, harmony_collections) DEFINE_implication(harmony_modules, harmony_scoping) DEFINE_bool(packed_arrays, false,"optimizes arrays that have no holes") DEFINE_bool(smi_only_arrays, true,"tracks arrays with only smi values") DEFINE_bool(clever_optimizations, true,"Optimize object size, Array shift, DOM strings and string +") DEFINE_bool(unbox_double_arrays, true,"automatically unbox arrays of doubles") DEFINE_bool(string_slices, true,"use string slices") DEFINE_bool(crankshaft, true,"use crankshaft") DEFINE_string(hydrogen_filter,"","optimization filter") DEFINE_bool(use_range, true,"use hydrogen range analysis") DEFINE_bool(eliminate_dead_phis, true,"eliminate dead phis") DEFINE_bool(use_gvn, true,"use hydrogen global value numbering") DEFINE_bool(use_canonicalizing, true,"use hydrogen instruction canonicalizing") DEFINE_bool(use_inlining, true,"use function inlining") DEFINE_int(max_inlined_source_size, 600,"maximum source size in bytes considered for a single inlining") DEFINE_int(max_inlined_nodes, 196,"maximum number of AST nodes considered for a single inlining") DEFINE_int(max_inlined_nodes_cumulative, 196,"maximum cumulative number of AST nodes considered for inlining") DEFINE_bool(loop_invariant_code_motion, true,"loop invariant code motion") DEFINE_bool(collect_megamorphic_maps_from_stub_cache, true,"crankshaft harvests type feedback from stub cache") DEFINE_bool(hydrogen_stats, false,"print statistics for hydrogen") DEFINE_bool(trace_hydrogen, false,"trace generated hydrogen to file") DEFINE_string(trace_phase,"Z","trace generated IR for specified phases") DEFINE_bool(trace_inlining, false,"trace inlining decisions") DEFINE_bool(trace_alloc, false,"trace register allocator") DEFINE_bool(trace_all_uses, false,"trace all use positions") DEFINE_bool(trace_range, false,"trace range analysis") DEFINE_bool(trace_gvn, false,"trace global value numbering") DEFINE_bool(trace_representation, false,"trace representation types") DEFINE_bool(stress_pointer_maps, false,"pointer map for every instruction") DEFINE_bool(stress_environments, false,"environment for every instruction") DEFINE_int(deopt_every_n_times, 0,"deoptimize every n times a deopt point is passed") DEFINE_bool(trap_on_deopt, false,"put a break point before deoptimizing") DEFINE_bool(deoptimize_uncommon_cases, true,"deoptimize uncommon cases") DEFINE_bool(polymorphic_inlining, true,"polymorphic inlining") DEFINE_bool(use_osr, true,"use on-stack replacement") DEFINE_bool(array_bounds_checks_elimination, false,"perform array bounds checks elimination") DEFINE_bool(array_index_dehoisting, false,"perform array index dehoisting") DEFINE_bool(trace_osr, false,"trace on-stack replacement") DEFINE_int(stress_runs, 0,"number of stress runs") DEFINE_bool(optimize_closures, true,"optimize closures") DEFINE_bool(inline_construct, true,"inline constructor calls") DEFINE_bool(inline_arguments, true,"inline functions with arguments object") DEFINE_int(loop_weight, 1,"loop weight for representation inference") DEFINE_bool(optimize_for_in, true,"optimize functions containing for-in loops") DEFINE_bool(experimental_profiler, true,"enable all profiler experiments") DEFINE_bool(watch_ic_patching, false,"profiler considers IC stability") DEFINE_int(frame_count, 1,"number of stack frames inspected by the profiler") DEFINE_bool(self_optimization, false,"primitive functions trigger their own optimization") DEFINE_bool(direct_self_opt, false,"call recompile stub directly when self-optimizing") DEFINE_bool(retry_self_opt, false,"re-try self-optimization if it failed") DEFINE_bool(count_based_interrupts, false,"trigger profiler ticks based on counting instead of timing") DEFINE_bool(interrupt_at_exit, false,"insert an interrupt check at function exit") DEFINE_bool(weighted_back_edges, false,"weight back edges by jump distance for interrupt triggering") DEFINE_int(interrupt_budget, 5900,"execution budget before interrupt is triggered") DEFINE_int(type_info_threshold, 15,"percentage of ICs that must have type info to allow optimization") DEFINE_int(self_opt_count, 130,"call count before self-optimization") DEFINE_implication(experimental_profiler, watch_ic_patching) DEFINE_implication(experimental_profiler, self_optimization) DEFINE_implication(experimental_profiler, retry_self_opt) DEFINE_implication(experimental_profiler, count_based_interrupts) DEFINE_implication(experimental_profiler, interrupt_at_exit) DEFINE_implication(experimental_profiler, weighted_back_edges) DEFINE_bool(trace_opt_verbose, false,"extra verbose compilation tracing") DEFINE_implication(trace_opt_verbose, trace_opt) DEFINE_bool(debug_code, false,"generate extra code (assertions) for debugging") DEFINE_bool(code_comments, false,"emit comments in code disassembly") DEFINE_bool(enable_sse2, true,"enable use of SSE2 instructions if available") DEFINE_bool(enable_sse3, true,"enable use of SSE3 instructions if available") DEFINE_bool(enable_sse4_1, true,"enable use of SSE4.1 instructions if available") DEFINE_bool(enable_cmov, true,"enable use of CMOV instruction if available") DEFINE_bool(enable_rdtsc, true,"enable use of RDTSC instruction if available") DEFINE_bool(enable_sahf, true,"enable use of SAHF instruction if available (X64 only)") DEFINE_bool(enable_vfp3, true,"enable use of VFP3 instructions if available - this implies ""enabling ARMv7 instructions (ARM only)") DEFINE_bool(enable_armv7, true,"enable use of ARMv7 instructions if available (ARM only)") DEFINE_bool(enable_fpu, true,"enable use of MIPS FPU instructions if available (MIPS only)") DEFINE_string(expose_natives_as, NULL,"expose natives in global object") DEFINE_string(expose_debug_as, NULL,"expose debug in global object") DEFINE_bool(expose_gc, false,"expose gc extension") DEFINE_bool(expose_externalize_string, false,"expose externalize string extension") DEFINE_int(stack_trace_limit, 10,"number of stack frames to capture") DEFINE_bool(builtins_in_stack_traces, false,"show built-in functions in stack traces") DEFINE_bool(disable_native_files, false,"disable builtin natives files") DEFINE_bool(inline_new, true,"use fast inline allocation") DEFINE_bool(stack_trace_on_abort, true,"print a stack trace if an assertion failure occurs") DEFINE_bool(trace, false,"trace function calls") DEFINE_bool(mask_constants_with_cookie, true,"use random jit cookie to mask large constants") DEFINE_bool(lazy, true,"use lazy compilation") DEFINE_bool(trace_opt, false,"trace lazy optimization") DEFINE_bool(trace_opt_stats, false,"trace lazy optimization statistics") DEFINE_bool(opt, true,"use adaptive optimizations") DEFINE_bool(always_opt, false,"always try to optimize functions") DEFINE_bool(prepare_always_opt, false,"prepare for turning on always opt") DEFINE_bool(trace_deopt, false,"trace deoptimization") DEFINE_int(min_preparse_length, 1024,"minimum length for automatic enable preparsing") DEFINE_bool(always_full_compiler, false,"try to use the dedicated run-once backend for all code") DEFINE_bool(trace_bailout, false,"print reasons for falling back to using the classic V8 backend") DEFINE_bool(compilation_cache, true,"enable compilation cache") DEFINE_bool(cache_prototype_transitions, true,"cache prototype transitions") DEFINE_bool(trace_debug_json, false,"trace debugging JSON request/response") DEFINE_bool(debugger_auto_break, true,"automatically set the debug break flag when debugger commands are ""in the queue") DEFINE_bool(enable_liveedit, true,"enable liveedit experimental feature") DEFINE_bool(break_on_abort, true,"always cause a debug break before aborting") DEFINE_int(stack_size, kPointerSize *123,"default size of stack region v8 is allowed to use (in kBytes)") DEFINE_int(max_stack_trace_source_length, 300,"maximum length of function source code printed in a stack trace.") DEFINE_bool(always_inline_smi_code, false,"always inline smi code in non-opt code") DEFINE_int(max_new_space_size, 0,"max size of the new generation (in kBytes)") DEFINE_int(max_old_space_size, 0,"max size of the old generation (in Mbytes)") DEFINE_int(max_executable_size, 0,"max size of executable memory (in Mbytes)") DEFINE_bool(gc_global, false,"always perform global GCs") DEFINE_int(gc_interval,-1,"garbage collect after <n> allocations") DEFINE_bool(trace_gc, false,"print one trace line following each garbage collection") DEFINE_bool(trace_gc_nvp, false,"print one detailed trace line in name=value format ""after each garbage collection") DEFINE_bool(print_cumulative_gc_stat, false,"print cumulative GC statistics in name=value format on exit") DEFINE_bool(trace_gc_verbose, false,"print more details following each garbage collection") DEFINE_bool(trace_fragmentation, false,"report fragmentation for old pointer and data pages") DEFINE_bool(collect_maps, true,"garbage collect maps from which no objects can be reached") DEFINE_bool(flush_code, true,"flush code that we expect not to use again before full gc") DEFINE_bool(incremental_marking, true,"use incremental marking") DEFINE_bool(incremental_marking_steps, true,"do incremental marking steps") DEFINE_bool(trace_incremental_marking, false,"trace progress of the incremental marking") DEFINE_bool(use_idle_notification, true,"Use idle notification to reduce memory footprint.") DEFINE_bool(send_idle_notification, false,"Send idle notifcation between stress runs.") DEFINE_bool(use_ic, true,"use inline caching") DEFINE_bool(native_code_counters, false,"generate extra code for manipulating stats counters") DEFINE_bool(always_compact, false,"Perform compaction on every full GC") DEFINE_bool(lazy_sweeping, true,"Use lazy sweeping for old pointer and data spaces") DEFINE_bool(never_compact, false,"Never perform compaction on full GC - testing only") DEFINE_bool(compact_code_space, true,"Compact code space on full non-incremental collections") DEFINE_bool(cleanup_code_caches_at_gc, true,"Flush inline caches prior to mark compact collection and ""flush code caches in maps during mark compact cycle.") DEFINE_int(random_seed, 0,"Default seed for initializing random generator ""(0, the default, means to use system random).") DEFINE_bool(use_verbose_printer, true,"allows verbose printing") DEFINE_bool(allow_natives_syntax, false,"allow natives syntax") DEFINE_bool(trace_sim, false,"Trace simulator execution") DEFINE_bool(check_icache, false,"Check icache flushes in ARM and MIPS simulator") DEFINE_int(stop_sim_at, 0,"Simulator stop after x number of instructions") DEFINE_int(sim_stack_alignment, 8,"Stack alingment in bytes in simulator (4 or 8, 8 is default)") DEFINE_bool(trace_exception, false,"print stack trace when throwing exceptions") DEFINE_bool(preallocate_message_memory, false,"preallocate some memory to build stack traces.") DEFINE_bool(randomize_hashes, true,"randomize hashes to avoid predictable hash collisions ""(with snapshots this option cannot override the baked-in seed)") DEFINE_int(hash_seed, 0,"Fixed seed to use to hash property keys (0 means random)""(with snapshots this option cannot override the baked-in seed)") DEFINE_bool(preemption, false,"activate a 100ms timer that switches between V8 threads") DEFINE_bool(regexp_optimization, true,"generate optimized regexp code") DEFINE_bool(testing_bool_flag, true,"testing_bool_flag") DEFINE_int(testing_int_flag, 13,"testing_int_flag") DEFINE_float(testing_float_flag, 2.5,"float-flag") DEFINE_string(testing_string_flag,"Hello, world!","string-flag") DEFINE_int(testing_prng_seed, 42,"Seed used for threading test randomness") DEFINE_string(testing_serialization_file,"/tmp/serdes","file in which to serialize heap") DEFINE_bool(help, false,"Print usage message, including flags, on console") DEFINE_bool(dump_counters, false,"Dump counters on exit") DEFINE_string(map_counters,"","Map counters to a file") DEFINE_args(js_arguments, JSARGUMENTS_INIT,"Pass all remaining arguments to the script. Alias for \"--\".") DEFINE_bool(debug_compile_events, true,"Enable debugger compile events") DEFINE_bool(debug_script_collected_events, true,"Enable debugger script collected events") DEFINE_bool(gdbjit, false,"enable GDBJIT interface (disables compacting GC)") DEFINE_bool(gdbjit_full, false,"enable GDBJIT interface for all code objects") DEFINE_bool(gdbjit_dump, false,"dump elf objects with debug info to disk") DEFINE_string(gdbjit_dump_filter,"","dump only objects containing this substring") DEFINE_bool(force_marking_deque_overflows, false,"force overflows of marking deque by reducing it's size ""to 64 words") DEFINE_bool(stress_compaction, false,"stress the GC compactor to flush out bugs (implies ""--force_marking_deque_overflows)")#define FLAG DEFINE_bool(enable_slow_asserts, false,"enable asserts that are slow to execute") DEFINE_bool(trace_codegen, false,"print name of functions for which code is generated") DEFINE_bool(print_source, false,"pretty print source code") DEFINE_bool(print_builtin_source, false,"pretty print source code for builtins") DEFINE_bool(print_ast, false,"print source AST") DEFINE_bool(print_builtin_ast, false,"print source AST for builtins") DEFINE_string(stop_at,"","function name where to insert a breakpoint") DEFINE_bool(print_builtin_scopes, false,"print scopes for builtins") DEFINE_bool(print_scopes, false,"print scopes") DEFINE_bool(trace_contexts, false,"trace contexts operations") DEFINE_bool(gc_greedy, false,"perform GC prior to some allocations") DEFINE_bool(gc_verbose, false,"print stuff during garbage collection") DEFINE_bool(heap_stats, false,"report heap statistics before and after GC") DEFINE_bool(code_stats, false,"report code statistics after GC") DEFINE_bool(verify_heap, false,"verify heap pointers before and after GC") DEFINE_bool(print_handles, false,"report handles after GC") DEFINE_bool(print_global_handles, false,"report global handles after GC") DEFINE_bool(trace_ic, false,"trace inline cache state transitions") DEFINE_bool(print_interfaces, false,"print interfaces") DEFINE_bool(print_interface_details, false,"print interface inference details") DEFINE_int(print_interface_depth, 5,"depth for printing interfaces") DEFINE_bool(trace_normalization, false,"prints when objects are turned into dictionaries.") DEFINE_bool(trace_lazy, false,"trace lazy compilation") DEFINE_bool(collect_heap_spill_statistics, false,"report heap spill statistics along with heap_stats ""(requires heap_stats)") DEFINE_bool(trace_isolates, false,"trace isolate state changes") DEFINE_bool(log_state_changes, false,"Log state changes.") DEFINE_bool(regexp_possessive_quantifier, false,"enable possessive quantifier syntax for testing") DEFINE_bool(trace_regexp_bytecodes, false,"trace regexp bytecode execution") DEFINE_bool(trace_regexp_assembler, false,"trace regexp macro assembler calls.")#define FLAG DEFINE_bool(log, false,"Minimal logging (no API, code, GC, suspect, or handles samples).") DEFINE_bool(log_all, false,"Log all events to the log file.") DEFINE_bool(log_runtime, false,"Activate runtime system %Log call.") DEFINE_bool(log_api, false,"Log API events to the log file.") DEFINE_bool(log_code, false,"Log code events to the log file without profiling.") DEFINE_bool(log_gc, false,"Log heap samples on garbage collection for the hp2ps tool.") DEFINE_bool(log_handles, false,"Log global handle events.") DEFINE_bool(log_snapshot_positions, false,"log positions of (de)serialized objects in the snapshot.") DEFINE_bool(log_suspect, false,"Log suspect operations.") DEFINE_bool(prof, false,"Log statistical profiling information (implies --log-code).") DEFINE_bool(prof_auto, true,"Used with --prof, starts profiling automatically") DEFINE_bool(prof_lazy, false,"Used with --prof, only does sampling and logging"" when profiler is active (implies --noprof_auto).") DEFINE_bool(prof_browser_mode, true,"Used with --prof, turns on browser-compatible mode for profiling.") DEFINE_bool(log_regexp, false,"Log regular expression execution.") DEFINE_bool(sliding_state_window, false,"Update sliding state window counters.") DEFINE_string(logfile,"v8.log","Specify the name of the log file.") DEFINE_bool(ll_prof, false,"Enable low-level linux profiler.")#define FLAG DEFINE_bool(trace_elements_transitions, false,"trace elements transitions") DEFINE_bool(print_code_stubs, false,"print code stubs") DEFINE_bool(test_secondary_stub_cache, false,"test secondary stub cache by disabling the primary one") DEFINE_bool(test_primary_stub_cache, false,"test primary stub cache by disabling the secondary one") DEFINE_bool(print_code, false,"print generated code") DEFINE_bool(print_opt_code, false,"print optimized code") DEFINE_bool(print_unopt_code, false,"print unoptimized code before ""printing optimized code based on it") DEFINE_bool(print_code_verbose, false,"print more information for code") DEFINE_bool(print_builtin_code, false,"print generated code for builtins")#47"/Users/thlorenz/dev/dx/v8-perf/build/v8/src/flags.cc"2 namespace{struct Flag{enum FlagType{TYPE_BOOL, TYPE_INT, TYPE_FLOAT, TYPE_STRING, TYPE_ARGS} name
Definition: flags.cc:1349
static Vector< const char > GetScriptName(int index)
static V8EXPORT Local< String > New(const char *data, int length=-1)
Definition: api.cc:4655
void DispatchDebugMessages()
static Handle< Value > ReadLine(const Arguments &args)
Definition: d8.h:312
static void AddOSMethods(Handle< ObjectTemplate > os_template)
Definition: d8-posix.cc:677
int int32_t
Definition: unicode.cc:47
virtual bool Open()
Definition: d8.h:126
static LineEditor * Get()
Definition: d8.cc:81
int32_t * ptr()
Definition: d8.h:49
static Handle< T > Cast(Handle< S > that)
Definition: v8.h:243
int preemption_interval
Definition: d8.h:246
TickSample * sample
static Handle< Value > PixelArray(const Arguments &args)
Definition: d8.cc:502
Counter * GetNextCounter()
Definition: d8.cc:643
int32_t * Bind(const char *name, bool histogram)
Definition: d8.cc:619
~ShellThread()
Definition: d8.cc:1109
FlagType type_
Definition: flags.cc:1351
#define ASSERT(condition)
Definition: checks.h:270
V8EXPORT Local< Number > ToNumber() const
Definition: api.cc:2382
static Handle< Value > Int16Array(const Arguments &args)
Definition: d8.cc:469
static Script * cast(Object *obj)
ExternalArrayType
Definition: v8.h:1407
unsigned short uint16_t
Definition: unicode.cc:46
DumbLineEditor()
Definition: d8.cc:95
int main(int argc, char *argv[])
Definition: d8.cc:1548
static const int kMaxNameSize
Definition: d8.h:47
static bool InContext()
Definition: api.cc:4424
static intptr_t AdjustAmountOfExternalAllocatedMemory(intptr_t change_in_bytes)
Definition: api.cc:5235
void SetVerbose(bool value)
Definition: api.cc:1760
int32_t * Bind(const char *name)
Definition: mksnapshot.cc:49
static bool Dispose()
Definition: api.cc:4224
V8EXPORT void SetIndexedPropertiesToExternalArrayData(void *data, ExternalArrayType array_type, int number_of_elements)
Definition: api.cc:3437
static Handle< Value > Uint16Array(const Arguments &args)
Definition: d8.cc:474
ShellThread(int no, char *files)
Definition: d8.cc:1105
static LineEditor * console
Definition: d8.h:363
static const char * GetVersion()
Definition: api.cc:4291
static ShellOptions options
Definition: d8.h:365
V8EXPORT bool IsUint32() const
Definition: api.cc:2214
const int MB
Definition: d8.cc:124
LineEditor(Type type, const char *name)
Definition: d8.cc:73
static bool SetDebugEventListener(EventCallback that, Handle< Value > data=Handle< Value >())
bool is_histogram()
Definition: d8.h:52
T * start() const
Definition: utils.h:389
static Local< ObjectTemplate > New()
Definition: api.cc:1246
static Handle< Value > ArrayBuffer(const Arguments &args)
Definition: d8.cc:454
static Handle< Value > EnableProfiler(const Arguments &args)
Definition: d8.cc:214
static const char * ToCString(const v8::String::Utf8Value &value)
Definition: d8.cc:137
static Handle< Value > DisableProfiler(const Arguments &args)
Definition: d8.cc:220
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination trace on stack replacement optimize closures functions with arguments object optimize functions containing for in loops profiler considers IC stability primitive functions trigger their own optimization re try self optimization if it failed insert an interrupt check at function exit execution budget before interrupt is triggered call count before self optimization self_optimization count_based_interrupts weighted_back_edges trace_opt emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 enable use of ARMv7 instructions if enable use of MIPS FPU instructions if NULL
static void ResumeProfiler()
Definition: api.cc:5328
int32_t sample_total()
Definition: d8.h:51
static Isolate * New()
Definition: api.cc:5386
static int ContextDisposedNotification()
Definition: api.cc:4284
int Length() const
Definition: v8.h:4143
static Handle< Value > Read(const Arguments &args)
Definition: d8.cc:226
SourceGroup * isolate_sources
Definition: d8.h:257
~SourceGroup()
Definition: d8.cc:1164
int num_isolates
Definition: d8.h:256
int length() const
Definition: utils.h:383
static void SetStressRunType(StressType type)
Definition: api.cc:6282
static Mutex * CreateMutex()
static const char * kPrompt
Definition: d8.h:364
bool stress_opt
Definition: d8.h:252
V8EXPORT bool SetHiddenValue(Handle< String > key, Handle< Value > value)
Definition: api.cc:3286
static Persistent< T > New(Handle< T > that)
Definition: v8.h:4043
int CompareKeys(const void *a, const void *b)
Definition: d8.cc:937
static bool EnableAgent(const char *name, int port, bool wait_for_connection=false)
static void * CreateHistogram(const char *name, int min, int max, size_t buckets)
Definition: d8.cc:703
const char * name()
Definition: d8.h:130
bool IsUndefined() const
Definition: v8.h:4277
Handle< Boolean > V8EXPORT False()
Definition: api.cc:576
static Handle< Value > Int8Array(const Arguments &args)
Definition: d8.cc:459
Definition: v8.h:592
bool stress_deopt
Definition: d8.h:253
Vector< const char > CStrVector(const char *data)
Definition: utils.h:525
int argc() const
Definition: flags.h:88
int StrLength(const char *string)
Definition: utils.h:234
static Local< Context > ToLocal(v8::internal::Handle< v8::internal::Context > obj)
static Handle< Value > Write(const Arguments &args)
Definition: d8.cc:197
Local< Value > StackTrace() const
Definition: api.cc:1724
virtual bool Close()
Definition: d8.h:127
static Handle< Value > Load(const Arguments &args)
Definition: d8.cc:269
Counter * Lookup(const char *name)
Definition: d8.h:82
V8EXPORT uint32_t Uint32Value() const
Definition: api.cc:2735
virtual Handle< String > Prompt(const char *prompt)=0
static void SetDebugMessageDispatchHandler(DebugMessageDispatchHandler handler, bool provide_locker=false)
static Handle< Value > ReadBuffer(const Arguments &args)
Definition: d8.cc:1022
const char * key
Definition: d8.cc:933
static Handle< Value > Print(const Arguments &args)
Definition: d8.cc:189
int length() const
Definition: v8.h:1288
void Execute()
Definition: d8.cc:1176
static bool ExecuteString(Handle< String > source, Handle< Value > name, bool print_result, bool report_exceptions)
Definition: d8.cc:143
static Handle< Value > Float64Array(const Arguments &args)
Definition: d8.cc:496
virtual void Signal()=0
#define HEAP
Definition: isolate.h:1408
static Persistent< Context > CreateEvaluationContext()
Definition: d8.cc:892
static Handle< String > ReadFile(const char *name)
Definition: d8.cc:1073
#define ASSERT_EQ(v1, v2)
Definition: checks.h:271
static V8EXPORT Local< Integer > New(int32_t value)
Definition: api.cc:5100
void Begin(char **argv, int offset)
Definition: d8.h:154
static void MapCounters(const char *name)
Definition: d8.cc:649
static void PrepareStressRun(int run)
Definition: api.cc:6303
static void StartPreemption(int every_n_ms)
Definition: v8threads.cc:142
static void SetCreateHistogramFunction(CreateHistogramCallback)
Definition: api.cc:5183
Local< T > Close(Handle< T > value)
Definition: v8.h:4149
static void ReportException(TryCatch *try_catch)
Definition: d8.cc:528
static Handle< Value > Uint8Array(const Arguments &args)
Definition: d8.cc:464
Handle< Primitive > V8EXPORT Undefined()
Definition: api.cc:546
virtual void Wait()=0
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
Definition: list-inl.h:38
bool IsEmpty() const
Definition: v8.h:208
Local< Value > Run()
Definition: api.cc:1590
#define FACTORY
Definition: isolate.h:1409
static V8EXPORT Local< String > Concat(Handle< String > left, Handle< String > right)
Definition: api.cc:4669
static Handle< String > ReadFromStdin()
Definition: d8.cc:239
int32_t count()
Definition: d8.h:50
static Persistent< Context > New(ExtensionConfiguration *extensions=NULL, Handle< ObjectTemplate > global_template=Handle< ObjectTemplate >(), Handle< Value > global_object=Handle< Value >())
Definition: api.cc:4308
const char * name_
Definition: flags.cc:1352
static Handle< Value > Quit(const Arguments &args)
Definition: d8.cc:513
static Handle< Value > Uint32Array(const Arguments &args)
Definition: d8.cc:485
bool test_shell
Definition: d8.h:255
static void SetFlagsFromCommandLine(int *argc, char **argv, bool remove_flags)
Definition: api.cc:480
static int * LookupCounter(const char *name)
Definition: d8.cc:692
static Handle< Value > Yield(const Arguments &args)
Definition: d8.cc:507
signed short int16_t
Definition: unicode.cc:45
void MarkIndependent()
Definition: v8.h:4087
static void StopPreemption()
Definition: v8threads.cc:147
Handle< Value > V8EXPORT ThrowException(Handle< Value > exception)
Definition: api.cc:485
static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm()
Definition: api.cc:368
bool script_executed
Definition: d8.h:250
static void DeoptimizeAll()
Definition: api.cc:6338
const char kArrayBufferMarkerPropName[]
Definition: d8.cc:319
static void ProcessDebugMessages()
Definition: v8.h:105
void RunShell(v8::Handle< v8::Context > context)
Definition: shell.cc:251
static void PauseProfiler()
Definition: api.cc:5322
Local< v8::Message > Message() const
Definition: api.cc:1742
Definition: d8.h:45
void StartExecuteInThread()
Definition: d8.cc:1248
static void OnExit()
Definition: d8.cc:943
FlagType type() const
Definition: flags.cc:1358
static int RunMain(int argc, char *argv[])
Definition: d8.cc:1398
virtual Handle< String > Prompt(const char *prompt)
Definition: d8.cc:103
void HandleDebugEvent(DebugEvent event, Handle< Object > exec_state, Handle< Object > event_data, Handle< Value > data)
static V8EXPORT Local< Object > New()
Definition: api.cc:4829
static char * StrChr(char *str, int c)
static void SetCounterFunction(CounterLookupCallback)
Definition: api.cc:5177
static v8::internal::Handle< v8::internal::TemplateInfo > OpenHandle(const Template *that)
virtual void Run()
Definition: d8.cc:1120
V8EXPORT bool Set(Handle< Value > key, Handle< Value > value, PropertyAttribute attribs=None)
Definition: api.cc:2757
static bool IdleNotification(int hint=1000)
Definition: api.cc:4268
bool last_run
Definition: d8.h:251
static JSFunction * cast(Object *obj)