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
lineprocessor.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 
30 #ifdef ENABLE_DEBUGGER_SUPPORT
31 #include <v8-debug.h>
32 #endif // ENABLE_DEBUGGER_SUPPORT
33 
34 #include <fcntl.h>
35 #include <string.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 
98 };
99 
100 const char* ToCString(const v8::String::Utf8Value& value);
101 void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);
102 v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name);
104 
108  v8::Local<v8::Context> context,
109  bool report_exceptions);
110 
111 
112 #ifdef ENABLE_DEBUGGER_SUPPORT
113 v8::Persistent<v8::Context> debug_message_context;
114 
115 void DispatchDebugMessages() {
116  // We are in some random thread. We should already have v8::Locker acquired
117  // (we requested this when registered this callback). We was called
118  // because new debug messages arrived; they may have already been processed,
119  // but we shouldn't worry about this.
120  //
121  // All we have to do is to set context and call ProcessDebugMessages.
122  //
123  // We should decide which V8 context to use here. This is important for
124  // "evaluate" command, because it must be executed some context.
125  // In our sample we have only one context, so there is nothing really to
126  // think about.
128  v8::HandleScope handle_scope(isolate);
129  v8::Local<v8::Context> context =
130  v8::Local<v8::Context>::New(isolate, debug_message_context);
131  v8::Context::Scope scope(context);
132 
134 }
135 #endif // ENABLE_DEBUGGER_SUPPORT
136 
137 
138 int RunMain(int argc, char* argv[]) {
139  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
141  v8::HandleScope handle_scope(isolate);
142 
143  v8::Handle<v8::String> script_source;
144  v8::Handle<v8::Value> script_name;
145  int script_param_counter = 0;
146 
147 #ifdef ENABLE_DEBUGGER_SUPPORT
148  int port_number = -1;
149  bool wait_for_connection = false;
150  bool support_callback = false;
151 #endif // ENABLE_DEBUGGER_SUPPORT
152 
153  MainCycleType cycle_type = CycleInCpp;
154 
155  for (int i = 1; i < argc; i++) {
156  const char* str = argv[i];
157  if (strcmp(str, "-f") == 0) {
158  // Ignore any -f flags for compatibility with the other stand-
159  // alone JavaScript engines.
160  continue;
161  } else if (strcmp(str, "--main-cycle-in-cpp") == 0) {
162  cycle_type = CycleInCpp;
163  } else if (strcmp(str, "--main-cycle-in-js") == 0) {
164  cycle_type = CycleInJs;
165 #ifdef ENABLE_DEBUGGER_SUPPORT
166  } else if (strcmp(str, "--callback") == 0) {
167  support_callback = true;
168  } else if (strcmp(str, "--wait-for-connection") == 0) {
169  wait_for_connection = true;
170  } else if (strcmp(str, "-p") == 0 && i + 1 < argc) {
171  port_number = atoi(argv[i + 1]); // NOLINT
172  i++;
173 #endif // ENABLE_DEBUGGER_SUPPORT
174  } else if (strncmp(str, "--", 2) == 0) {
175  printf("Warning: unknown flag %s.\nTry --help for options\n", str);
176  } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
177  script_source = v8::String::NewFromUtf8(isolate, argv[i + 1]);
178  script_name = v8::String::NewFromUtf8(isolate, "unnamed");
179  i++;
180  script_param_counter++;
181  } else {
182  // Use argument as a name of file to load.
183  script_source = ReadFile(isolate, str);
184  script_name = v8::String::NewFromUtf8(isolate, str);
185  if (script_source.IsEmpty()) {
186  printf("Error reading '%s'\n", str);
187  return 1;
188  }
189  script_param_counter++;
190  }
191  }
192 
193  if (script_param_counter == 0) {
194  printf("Script is not specified\n");
195  return 1;
196  }
197  if (script_param_counter != 1) {
198  printf("Only one script may be specified\n");
199  return 1;
200  }
201 
202  // Create a template for the global object.
204 
205  // Bind the global 'print' function to the C++ Print callback.
206  global->Set(v8::String::NewFromUtf8(isolate, "print"),
207  v8::FunctionTemplate::New(isolate, Print));
208 
209  if (cycle_type == CycleInJs) {
210  // Bind the global 'read_line' function to the C++ Print callback.
211  global->Set(v8::String::NewFromUtf8(isolate, "read_line"),
213  }
214 
215  // Create a new execution environment containing the built-in
216  // functions
217  v8::Handle<v8::Context> context = v8::Context::New(isolate, NULL, global);
218  // Enter the newly created execution environment.
219  v8::Context::Scope context_scope(context);
220 
221 #ifdef ENABLE_DEBUGGER_SUPPORT
222  debug_message_context.Reset(isolate, context);
223 
224  v8::Locker locker(isolate);
225 
226  if (support_callback) {
227  v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true);
228  }
229 
230  if (port_number != -1) {
231  v8::Debug::EnableAgent("lineprocessor", port_number, wait_for_connection);
232  }
233 #endif // ENABLE_DEBUGGER_SUPPORT
234 
235  bool report_exceptions = true;
236 
237  v8::Handle<v8::Script> script;
238  {
239  // Compile script in try/catch context.
240  v8::TryCatch try_catch;
241  v8::ScriptOrigin origin(script_name);
242  script = v8::Script::Compile(script_source, &origin);
243  if (script.IsEmpty()) {
244  // Print errors that happened during compilation.
245  if (report_exceptions)
246  ReportException(isolate, &try_catch);
247  return 1;
248  }
249  }
250 
251  {
252  v8::TryCatch try_catch;
253 
254  script->Run();
255  if (try_catch.HasCaught()) {
256  if (report_exceptions)
257  ReportException(isolate, &try_catch);
258  return 1;
259  }
260  }
261 
262  if (cycle_type == CycleInCpp) {
263  bool res = RunCppCycle(script,
264  isolate->GetCurrentContext(),
265  report_exceptions);
266  return !res;
267  } else {
268  // All is already done.
269  }
270  return 0;
271 }
272 
273 
275  v8::Local<v8::Context> context,
276  bool report_exceptions) {
277  v8::Isolate* isolate = context->GetIsolate();
278 #ifdef ENABLE_DEBUGGER_SUPPORT
279  v8::Locker lock(isolate);
280 #endif // ENABLE_DEBUGGER_SUPPORT
281 
282  v8::Handle<v8::String> fun_name =
283  v8::String::NewFromUtf8(isolate, "ProcessLine");
284  v8::Handle<v8::Value> process_val = context->Global()->Get(fun_name);
285 
286  // If there is no Process function, or if it is not a function,
287  // bail out
288  if (!process_val->IsFunction()) {
289  printf("Error: Script does not declare 'ProcessLine' global function.\n");
290  return 1;
291  }
292 
293  // It is a function; cast it to a Function
294  v8::Handle<v8::Function> process_fun =
295  v8::Handle<v8::Function>::Cast(process_val);
296 
297 
298  while (!feof(stdin)) {
299  v8::HandleScope handle_scope(isolate);
300 
301  v8::Handle<v8::String> input_line = ReadLine();
302  if (input_line == v8::Undefined(isolate)) {
303  continue;
304  }
305 
306  const int argc = 1;
307  v8::Handle<v8::Value> argv[argc] = { input_line };
308 
309  v8::Handle<v8::Value> result;
310  {
311  v8::TryCatch try_catch;
312  result = process_fun->Call(isolate->GetCurrentContext()->Global(),
313  argc, argv);
314  if (try_catch.HasCaught()) {
315  if (report_exceptions)
316  ReportException(isolate, &try_catch);
317  return false;
318  }
319  }
320  v8::String::Utf8Value str(result);
321  const char* cstr = ToCString(str);
322  printf("%s\n", cstr);
323  }
324 
325  return true;
326 }
327 
328 
329 int main(int argc, char* argv[]) {
331  int result = RunMain(argc, argv);
332  v8::V8::Dispose();
333  return result;
334 }
335 
336 
337 // Extracts a C string from a V8 Utf8Value.
338 const char* ToCString(const v8::String::Utf8Value& value) {
339  return *value ? *value : "<string conversion failed>";
340 }
341 
342 
343 // Reads a file into a v8 string.
345  FILE* file = fopen(name, "rb");
346  if (file == NULL) return v8::Handle<v8::String>();
347 
348  fseek(file, 0, SEEK_END);
349  int size = ftell(file);
350  rewind(file);
351 
352  char* chars = new char[size + 1];
353  chars[size] = '\0';
354  for (int i = 0; i < size;) {
355  int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
356  i += read;
357  }
358  fclose(file);
359  v8::Handle<v8::String> result =
360  v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size);
361  delete[] chars;
362  return result;
363 }
364 
365 
366 void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
367  v8::HandleScope handle_scope(isolate);
368  v8::String::Utf8Value exception(try_catch->Exception());
369  const char* exception_string = ToCString(exception);
370  v8::Handle<v8::Message> message = try_catch->Message();
371  if (message.IsEmpty()) {
372  // V8 didn't provide any extra information about this error; just
373  // print the exception.
374  printf("%s\n", exception_string);
375  } else {
376  // Print (filename):(line number): (message).
377  v8::String::Utf8Value filename(message->GetScriptResourceName());
378  const char* filename_string = ToCString(filename);
379  int linenum = message->GetLineNumber();
380  printf("%s:%i: %s\n", filename_string, linenum, exception_string);
381  // Print line of source code.
382  v8::String::Utf8Value sourceline(message->GetSourceLine());
383  const char* sourceline_string = ToCString(sourceline);
384  printf("%s\n", sourceline_string);
385  // Print wavy underline (GetUnderline is deprecated).
386  int start = message->GetStartColumn();
387  for (int i = 0; i < start; i++) {
388  printf(" ");
389  }
390  int end = message->GetEndColumn();
391  for (int i = start; i < end; i++) {
392  printf("^");
393  }
394  printf("\n");
395  }
396 }
397 
398 
399 // The callback that is invoked by v8 whenever the JavaScript 'print'
400 // function is called. Prints its arguments on stdout separated by
401 // spaces and ending with a newline.
403  bool first = true;
404  for (int i = 0; i < args.Length(); i++) {
405  v8::HandleScope handle_scope(args.GetIsolate());
406  if (first) {
407  first = false;
408  } else {
409  printf(" ");
410  }
411  v8::String::Utf8Value str(args[i]);
412  const char* cstr = ToCString(str);
413  printf("%s", cstr);
414  }
415  printf("\n");
416  fflush(stdout);
417 }
418 
419 
420 // The callback that is invoked by v8 whenever the JavaScript 'read_line'
421 // function is called. Reads a string from standard input and returns.
423  if (args.Length() > 0) {
424  args.GetIsolate()->ThrowException(
425  v8::String::NewFromUtf8(args.GetIsolate(), "Unexpected arguments"));
426  return;
427  }
428  args.GetReturnValue().Set(ReadLine());
429 }
430 
431 
433  const int kBufferSize = 1024 + 1;
434  char buffer[kBufferSize];
435 
436  char* res;
437  {
438 #ifdef ENABLE_DEBUGGER_SUPPORT
440 #endif // ENABLE_DEBUGGER_SUPPORT
441  res = fgets(buffer, kBufferSize, stdin);
442  }
444  if (res == NULL) {
447  }
448  // Remove newline char
449  for (char* pos = buffer; *pos != '\0'; pos++) {
450  if (*pos == '\n') {
451  *pos = '\0';
452  break;
453  }
454  }
455  return v8::String::NewFromUtf8(isolate, buffer);
456 }
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
static V8_INLINE Local< T > New(Isolate *isolate, Handle< T > that)
Definition: v8.h:5713
MainCycleType
Local< Value > Call(Handle< Value > recv, int argc, Handle< Value > argv[])
Definition: api.cc:3996
const char * ToCString(const v8::String::Utf8Value &value)
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
Local< Context > GetCurrentContext()
Definition: api.cc:6359
v8::Handle< v8::String > ReadLine()
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 Local< ObjectTemplate > New()
Definition: api.cc:1286
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
static V8_INLINE Handle< T > Cast(Handle< S > that)
Definition: v8.h:297
Local< Object > Global()
Definition: api.cc:5239
static bool EnableAgent(const char *name, int port, bool wait_for_connection=false)
int GetLineNumber() const
Definition: api.cc:2061
bool IsFunction() const
Definition: api.cc:2357
V8_INLINE Handle< Primitive > Undefined(Isolate *isolate)
Definition: v8.h:6541
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
bool RunCppCycle(v8::Handle< v8::Script > script, v8::Local< v8::Context > context, bool report_exceptions)
static void SetDebugMessageDispatchHandler(DebugMessageDispatchHandler handler, bool provide_locker=false)
V8_INLINE bool IsEmpty() const
Definition: v8.h:248
v8::Handle< v8::String > ReadFile(v8::Isolate *isolate, const char *name)
V8_INLINE void Reset()
Definition: v8.h:5808
static bool InitializeICU(const char *icu_data_file=NULL)
Definition: api.cc:5115
int RunMain(int argc, char *argv[])
void Print(const v8::FunctionCallbackInfo< v8::Value > &args)
Local< Value > Run()
Definition: api.cc:1686
static void SetFlagsFromCommandLine(int *argc, char **argv, bool remove_flags)
Definition: api.cc:411
void ReportException(v8::Isolate *isolate, v8::TryCatch *handler)
int GetStartColumn() const
Definition: api.cc:2096
int main(int argc, char *argv[])
static void ProcessDebugMessages()
Definition: v8.h:124
Local< v8::Message > Message() const
Definition: api.cc:1953
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