v8  3.25.30(node0.11.13)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
shell.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 #include <v8.h>
29 #include <assert.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 
35 #ifdef COMPRESS_STARTUP_DATA_BZ2
36 #error Using compressed startup data is not supported for this sample
37 #endif
38 
49 void RunShell(v8::Handle<v8::Context> context);
50 int RunMain(v8::Isolate* isolate, int argc, char* argv[]);
51 bool ExecuteString(v8::Isolate* isolate,
54  bool print_result,
55  bool report_exceptions);
61 v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name);
62 void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);
63 
64 
65 static bool run_shell;
66 
67 
68 int main(int argc, char* argv[]) {
70  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
72  run_shell = (argc == 1);
73  int result;
74  {
75  v8::HandleScope handle_scope(isolate);
77  if (context.IsEmpty()) {
78  fprintf(stderr, "Error creating context\n");
79  return 1;
80  }
81  context->Enter();
82  result = RunMain(isolate, argc, argv);
83  if (run_shell) RunShell(context);
84  context->Exit();
85  }
87  return result;
88 }
89 
90 
91 // Extracts a C string from a V8 Utf8Value.
92 const char* ToCString(const v8::String::Utf8Value& value) {
93  return *value ? *value : "<string conversion failed>";
94 }
95 
96 
97 // Creates a new execution environment containing the built-in
98 // functions.
100  // Create a template for the global object.
102  // Bind the global 'print' function to the C++ Print callback.
103  global->Set(v8::String::NewFromUtf8(isolate, "print"),
104  v8::FunctionTemplate::New(isolate, Print));
105  // Bind the global 'read' function to the C++ Read callback.
106  global->Set(v8::String::NewFromUtf8(isolate, "read"),
107  v8::FunctionTemplate::New(isolate, Read));
108  // Bind the global 'load' function to the C++ Load callback.
109  global->Set(v8::String::NewFromUtf8(isolate, "load"),
110  v8::FunctionTemplate::New(isolate, Load));
111  // Bind the 'quit' function
112  global->Set(v8::String::NewFromUtf8(isolate, "quit"),
113  v8::FunctionTemplate::New(isolate, Quit));
114  // Bind the 'version' function
115  global->Set(v8::String::NewFromUtf8(isolate, "version"),
117 
118  return v8::Context::New(isolate, NULL, global);
119 }
120 
121 
122 // The callback that is invoked by v8 whenever the JavaScript 'print'
123 // function is called. Prints its arguments on stdout separated by
124 // spaces and ending with a newline.
126  bool first = true;
127  for (int i = 0; i < args.Length(); i++) {
128  v8::HandleScope handle_scope(args.GetIsolate());
129  if (first) {
130  first = false;
131  } else {
132  printf(" ");
133  }
134  v8::String::Utf8Value str(args[i]);
135  const char* cstr = ToCString(str);
136  printf("%s", cstr);
137  }
138  printf("\n");
139  fflush(stdout);
140 }
141 
142 
143 // The callback that is invoked by v8 whenever the JavaScript 'read'
144 // function is called. This function loads the content of the file named in
145 // the argument into a JavaScript string.
147  if (args.Length() != 1) {
148  args.GetIsolate()->ThrowException(
149  v8::String::NewFromUtf8(args.GetIsolate(), "Bad parameters"));
150  return;
151  }
152  v8::String::Utf8Value file(args[0]);
153  if (*file == NULL) {
154  args.GetIsolate()->ThrowException(
155  v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
156  return;
157  }
158  v8::Handle<v8::String> source = ReadFile(args.GetIsolate(), *file);
159  if (source.IsEmpty()) {
160  args.GetIsolate()->ThrowException(
161  v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
162  return;
163  }
164  args.GetReturnValue().Set(source);
165 }
166 
167 
168 // The callback that is invoked by v8 whenever the JavaScript 'load'
169 // function is called. Loads, compiles and executes its argument
170 // JavaScript file.
172  for (int i = 0; i < args.Length(); i++) {
173  v8::HandleScope handle_scope(args.GetIsolate());
174  v8::String::Utf8Value file(args[i]);
175  if (*file == NULL) {
176  args.GetIsolate()->ThrowException(
177  v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
178  return;
179  }
180  v8::Handle<v8::String> source = ReadFile(args.GetIsolate(), *file);
181  if (source.IsEmpty()) {
182  args.GetIsolate()->ThrowException(
183  v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
184  return;
185  }
186  if (!ExecuteString(args.GetIsolate(),
187  source,
188  v8::String::NewFromUtf8(args.GetIsolate(), *file),
189  false,
190  false)) {
191  args.GetIsolate()->ThrowException(
192  v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file"));
193  return;
194  }
195  }
196 }
197 
198 
199 // The callback that is invoked by v8 whenever the JavaScript 'quit'
200 // function is called. Quits.
202  // If not arguments are given args[0] will yield undefined which
203  // converts to the integer value 0.
204  int exit_code = args[0]->Int32Value();
205  fflush(stdout);
206  fflush(stderr);
207  exit(exit_code);
208 }
209 
210 
212  args.GetReturnValue().Set(
214 }
215 
216 
217 // Reads a file into a v8 string.
219  FILE* file = fopen(name, "rb");
220  if (file == NULL) return v8::Handle<v8::String>();
221 
222  fseek(file, 0, SEEK_END);
223  int size = ftell(file);
224  rewind(file);
225 
226  char* chars = new char[size + 1];
227  chars[size] = '\0';
228  for (int i = 0; i < size;) {
229  int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
230  i += read;
231  }
232  fclose(file);
233  v8::Handle<v8::String> result =
234  v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size);
235  delete[] chars;
236  return result;
237 }
238 
239 
240 // Process remaining command line arguments and execute files
241 int RunMain(v8::Isolate* isolate, int argc, char* argv[]) {
242  for (int i = 1; i < argc; i++) {
243  const char* str = argv[i];
244  if (strcmp(str, "--shell") == 0) {
245  run_shell = true;
246  } else if (strcmp(str, "-f") == 0) {
247  // Ignore any -f flags for compatibility with the other stand-
248  // alone JavaScript engines.
249  continue;
250  } else if (strncmp(str, "--", 2) == 0) {
251  fprintf(stderr,
252  "Warning: unknown flag %s.\nTry --help for options\n", str);
253  } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
254  // Execute argument given to -e option directly.
255  v8::Handle<v8::String> file_name =
256  v8::String::NewFromUtf8(isolate, "unnamed");
257  v8::Handle<v8::String> source =
258  v8::String::NewFromUtf8(isolate, argv[++i]);
259  if (!ExecuteString(isolate, source, file_name, false, true)) return 1;
260  } else {
261  // Use all other arguments as names of files to load and run.
262  v8::Handle<v8::String> file_name = v8::String::NewFromUtf8(isolate, str);
263  v8::Handle<v8::String> source = ReadFile(isolate, str);
264  if (source.IsEmpty()) {
265  fprintf(stderr, "Error reading '%s'\n", str);
266  continue;
267  }
268  if (!ExecuteString(isolate, source, file_name, false, true)) return 1;
269  }
270  }
271  return 0;
272 }
273 
274 
275 // The read-eval-execute loop of the shell.
277  fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion());
278  static const int kBufferSize = 256;
279  // Enter the execution environment before evaluating any code.
280  v8::Context::Scope context_scope(context);
282  v8::String::NewFromUtf8(context->GetIsolate(), "(shell)"));
283  while (true) {
284  char buffer[kBufferSize];
285  fprintf(stderr, "> ");
286  char* str = fgets(buffer, kBufferSize, stdin);
287  if (str == NULL) break;
288  v8::HandleScope handle_scope(context->GetIsolate());
289  ExecuteString(context->GetIsolate(),
290  v8::String::NewFromUtf8(context->GetIsolate(), str),
291  name,
292  true,
293  true);
294  }
295  fprintf(stderr, "\n");
296 }
297 
298 
299 // Executes a string within the current v8 context.
301  v8::Handle<v8::String> source,
303  bool print_result,
304  bool report_exceptions) {
305  v8::HandleScope handle_scope(isolate);
306  v8::TryCatch try_catch;
307  v8::ScriptOrigin origin(name);
308  v8::Handle<v8::Script> script = v8::Script::Compile(source, &origin);
309  if (script.IsEmpty()) {
310  // Print errors that happened during compilation.
311  if (report_exceptions)
312  ReportException(isolate, &try_catch);
313  return false;
314  } else {
315  v8::Handle<v8::Value> result = script->Run();
316  if (result.IsEmpty()) {
317  assert(try_catch.HasCaught());
318  // Print errors that happened during execution.
319  if (report_exceptions)
320  ReportException(isolate, &try_catch);
321  return false;
322  } else {
323  assert(!try_catch.HasCaught());
324  if (print_result && !result->IsUndefined()) {
325  // If all went well and the result wasn't undefined then print
326  // the returned value.
327  v8::String::Utf8Value str(result);
328  const char* cstr = ToCString(str);
329  printf("%s\n", cstr);
330  }
331  return true;
332  }
333  }
334 }
335 
336 
337 void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
338  v8::HandleScope handle_scope(isolate);
339  v8::String::Utf8Value exception(try_catch->Exception());
340  const char* exception_string = ToCString(exception);
341  v8::Handle<v8::Message> message = try_catch->Message();
342  if (message.IsEmpty()) {
343  // V8 didn't provide any extra information about this error; just
344  // print the exception.
345  fprintf(stderr, "%s\n", exception_string);
346  } else {
347  // Print (filename):(line number): (message).
348  v8::String::Utf8Value filename(message->GetScriptResourceName());
349  const char* filename_string = ToCString(filename);
350  int linenum = message->GetLineNumber();
351  fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
352  // Print line of source code.
353  v8::String::Utf8Value sourceline(message->GetSourceLine());
354  const char* sourceline_string = ToCString(sourceline);
355  fprintf(stderr, "%s\n", sourceline_string);
356  // Print wavy underline (GetUnderline is deprecated).
357  int start = message->GetStartColumn();
358  for (int i = 0; i < start; i++) {
359  fprintf(stderr, " ");
360  }
361  int end = message->GetEndColumn();
362  for (int i = start; i < end; i++) {
363  fprintf(stderr, "^");
364  }
365  fprintf(stderr, "\n");
366  v8::String::Utf8Value stack_trace(try_catch->StackTrace());
367  if (stack_trace.length() > 0) {
368  const char* stack_trace_string = ToCString(stack_trace);
369  fprintf(stderr, "%s\n", stack_trace_string);
370  }
371  }
372 }
void Enter()
Definition: api.cc:650
int main(int argc, char *argv[])
Definition: shell.cc:68
static Isolate * GetCurrent()
Definition: api.cc:6580
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter NULL
Local< Value > Exception() const
Definition: api.cc:1923
V8_INLINE Isolate * GetIsolate() const
Definition: v8.h:6061
bool HasCaught() const
Definition: api.cc:1901
V8_INLINE ReturnValue< T > GetReturnValue() const
Definition: v8.h:6067
V8_INLINE int Length() const
Definition: v8.h:6079
void Quit(const v8::FunctionCallbackInfo< v8::Value > &args)
Definition: shell.cc:201
void Read(const v8::FunctionCallbackInfo< v8::Value > &args)
Definition: shell.cc:146
const char * ToCString(const v8::String::Utf8Value &value)
Definition: shell.cc:92
void Set(Handle< String > name, Handle< Data > value, PropertyAttribute attributes=None)
Definition: api.cc:841
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in only print modified registers Don t break for ASM_UNIMPLEMENTED_BREAK macros print stack trace when an illegal exception is thrown randomize hashes to avoid predictable hash Fixed seed to use to hash property Print the time it takes to deserialize the snapshot testing_bool_flag testing_int_flag string flag tmp file in which to serialize heap Print the time it takes to lazily compile hydrogen code stubs concurrent_recompilation concurrent_sweeping Print usage message
static bool Dispose()
Definition: api.cc:5028
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in name
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object size
Handle< Value > GetScriptResourceName() const
Definition: api.cc:2001
v8::Isolate * GetIsolate()
Definition: api.cc:5233
int GetEndColumn() const
Definition: api.cc:2111
static const char * GetVersion()
Definition: api.cc:5120
v8::Handle< v8::Context > CreateShellContext(v8::Isolate *isolate)
Definition: shell.cc:99
static Local< ObjectTemplate > New()
Definition: api.cc:1286
void Print(const v8::FunctionCallbackInfo< v8::Value > &args)
Definition: shell.cc:125
static Local< FunctionTemplate > New(Isolate *isolate, FunctionCallback callback=0, Handle< Value > data=Handle< Value >(), Handle< Signature > signature=Handle< Signature >(), int length=0)
Definition: api.cc:942
static Local< Script > Compile(Handle< String > source, ScriptOrigin *origin=NULL, ScriptData *script_data=NULL)
Definition: api.cc:1832
void Version(const v8::FunctionCallbackInfo< v8::Value > &args)
Definition: shell.cc:211
v8::Handle< v8::String > ReadFile(v8::Isolate *isolate, const char *name)
Definition: shell.cc:218
V8_INLINE bool IsUndefined() const
Definition: v8.h:6229
int GetLineNumber() const
Definition: api.cc:2061
static Local< Context > New(Isolate *isolate, ExtensionConfiguration *extensions=NULL, Handle< ObjectTemplate > global_template=Handle< ObjectTemplate >(), Handle< Value > global_object=Handle< Value >())
Definition: api.cc:5188
Local< Value > StackTrace() const
Definition: api.cc:1935
void Load(const v8::FunctionCallbackInfo< v8::Value > &args)
Definition: shell.cc:171
void Exit()
Definition: api.cc:661
V8_INLINE bool IsEmpty() const
Definition: v8.h:248
void ReportException(v8::Isolate *isolate, v8::TryCatch *handler)
Definition: shell.cc:337
static bool InitializeICU(const char *icu_data_file=NULL)
Definition: api.cc:5115
Local< Value > Run()
Definition: api.cc:1686
bool ExecuteString(v8::Isolate *isolate, v8::Handle< v8::String > source, v8::Handle< v8::Value > name, bool print_result, bool report_exceptions)
Definition: shell.cc:300
static void SetFlagsFromCommandLine(int *argc, char **argv, bool remove_flags)
Definition: api.cc:411
int GetStartColumn() const
Definition: api.cc:2096
void RunShell(v8::Handle< v8::Context > context)
Definition: shell.cc:276
Local< v8::Message > Message() const
Definition: api.cc:1953
int RunMain(v8::Isolate *isolate, int argc, char *argv[])
Definition: shell.cc:241
Local< String > GetSourceLine() const
Definition: api.cc:2143
static Local< String > NewFromUtf8(Isolate *isolate, const char *data, NewStringType type=kNormalString, int length=-1)
Definition: api.cc:5417