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
39/**
40 * This sample program shows how to implement a simple javascript shell
41 * based on V8.  This includes initializing V8 with command line options,
42 * creating global functions, compiling and executing strings.
43 *
44 * For a more sophisticated shell, consider using the debug shell D8.
45 */
46
47
48v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate);
49void RunShell(v8::Handle<v8::Context> context);
50int RunMain(v8::Isolate* isolate, int argc, char* argv[]);
51bool ExecuteString(v8::Isolate* isolate,
52                   v8::Handle<v8::String> source,
53                   v8::Handle<v8::Value> name,
54                   bool print_result,
55                   bool report_exceptions);
56void Print(const v8::FunctionCallbackInfo<v8::Value>& args);
57void Read(const v8::FunctionCallbackInfo<v8::Value>& args);
58void Load(const v8::FunctionCallbackInfo<v8::Value>& args);
59void Quit(const v8::FunctionCallbackInfo<v8::Value>& args);
60void Version(const v8::FunctionCallbackInfo<v8::Value>& args);
61v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name);
62void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);
63
64
65static bool run_shell;
66
67
68class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
69 public:
70  virtual void* Allocate(size_t length) {
71    void* data = AllocateUninitialized(length);
72    return data == NULL ? data : memset(data, 0, length);
73  }
74  virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
75  virtual void Free(void* data, size_t) { free(data); }
76};
77
78
79int main(int argc, char* argv[]) {
80  v8::V8::InitializeICU();
81  v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
82  ShellArrayBufferAllocator array_buffer_allocator;
83  v8::V8::SetArrayBufferAllocator(&array_buffer_allocator);
84  v8::Isolate* isolate = v8::Isolate::New();
85  run_shell = (argc == 1);
86  int result;
87  {
88    v8::Isolate::Scope isolate_scope(isolate);
89    v8::HandleScope handle_scope(isolate);
90    v8::Handle<v8::Context> context = CreateShellContext(isolate);
91    if (context.IsEmpty()) {
92      fprintf(stderr, "Error creating context\n");
93      return 1;
94    }
95    v8::Context::Scope context_scope(context);
96    result = RunMain(isolate, argc, argv);
97    if (run_shell) RunShell(context);
98  }
99  v8::V8::Dispose();
100  return result;
101}
102
103
104// Extracts a C string from a V8 Utf8Value.
105const char* ToCString(const v8::String::Utf8Value& value) {
106  return *value ? *value : "<string conversion failed>";
107}
108
109
110// Creates a new execution environment containing the built-in
111// functions.
112v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate) {
113  // Create a template for the global object.
114  v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
115  // Bind the global 'print' function to the C++ Print callback.
116  global->Set(v8::String::NewFromUtf8(isolate, "print"),
117              v8::FunctionTemplate::New(isolate, Print));
118  // Bind the global 'read' function to the C++ Read callback.
119  global->Set(v8::String::NewFromUtf8(isolate, "read"),
120              v8::FunctionTemplate::New(isolate, Read));
121  // Bind the global 'load' function to the C++ Load callback.
122  global->Set(v8::String::NewFromUtf8(isolate, "load"),
123              v8::FunctionTemplate::New(isolate, Load));
124  // Bind the 'quit' function
125  global->Set(v8::String::NewFromUtf8(isolate, "quit"),
126              v8::FunctionTemplate::New(isolate, Quit));
127  // Bind the 'version' function
128  global->Set(v8::String::NewFromUtf8(isolate, "version"),
129              v8::FunctionTemplate::New(isolate, Version));
130
131  return v8::Context::New(isolate, NULL, global);
132}
133
134
135// The callback that is invoked by v8 whenever the JavaScript 'print'
136// function is called.  Prints its arguments on stdout separated by
137// spaces and ending with a newline.
138void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
139  bool first = true;
140  for (int i = 0; i < args.Length(); i++) {
141    v8::HandleScope handle_scope(args.GetIsolate());
142    if (first) {
143      first = false;
144    } else {
145      printf(" ");
146    }
147    v8::String::Utf8Value str(args[i]);
148    const char* cstr = ToCString(str);
149    printf("%s", cstr);
150  }
151  printf("\n");
152  fflush(stdout);
153}
154
155
156// The callback that is invoked by v8 whenever the JavaScript 'read'
157// function is called.  This function loads the content of the file named in
158// the argument into a JavaScript string.
159void Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
160  if (args.Length() != 1) {
161    args.GetIsolate()->ThrowException(
162        v8::String::NewFromUtf8(args.GetIsolate(), "Bad parameters"));
163    return;
164  }
165  v8::String::Utf8Value file(args[0]);
166  if (*file == NULL) {
167    args.GetIsolate()->ThrowException(
168        v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
169    return;
170  }
171  v8::Handle<v8::String> source = ReadFile(args.GetIsolate(), *file);
172  if (source.IsEmpty()) {
173    args.GetIsolate()->ThrowException(
174        v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
175    return;
176  }
177  args.GetReturnValue().Set(source);
178}
179
180
181// The callback that is invoked by v8 whenever the JavaScript 'load'
182// function is called.  Loads, compiles and executes its argument
183// JavaScript file.
184void Load(const v8::FunctionCallbackInfo<v8::Value>& args) {
185  for (int i = 0; i < args.Length(); i++) {
186    v8::HandleScope handle_scope(args.GetIsolate());
187    v8::String::Utf8Value file(args[i]);
188    if (*file == NULL) {
189      args.GetIsolate()->ThrowException(
190          v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
191      return;
192    }
193    v8::Handle<v8::String> source = ReadFile(args.GetIsolate(), *file);
194    if (source.IsEmpty()) {
195      args.GetIsolate()->ThrowException(
196           v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
197      return;
198    }
199    if (!ExecuteString(args.GetIsolate(),
200                       source,
201                       v8::String::NewFromUtf8(args.GetIsolate(), *file),
202                       false,
203                       false)) {
204      args.GetIsolate()->ThrowException(
205          v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file"));
206      return;
207    }
208  }
209}
210
211
212// The callback that is invoked by v8 whenever the JavaScript 'quit'
213// function is called.  Quits.
214void Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
215  // If not arguments are given args[0] will yield undefined which
216  // converts to the integer value 0.
217  int exit_code = args[0]->Int32Value();
218  fflush(stdout);
219  fflush(stderr);
220  exit(exit_code);
221}
222
223
224void Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
225  args.GetReturnValue().Set(
226      v8::String::NewFromUtf8(args.GetIsolate(), v8::V8::GetVersion()));
227}
228
229
230// Reads a file into a v8 string.
231v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name) {
232  FILE* file = fopen(name, "rb");
233  if (file == NULL) return v8::Handle<v8::String>();
234
235  fseek(file, 0, SEEK_END);
236  int size = ftell(file);
237  rewind(file);
238
239  char* chars = new char[size + 1];
240  chars[size] = '\0';
241  for (int i = 0; i < size;) {
242    int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
243    i += read;
244  }
245  fclose(file);
246  v8::Handle<v8::String> result =
247      v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size);
248  delete[] chars;
249  return result;
250}
251
252
253// Process remaining command line arguments and execute files
254int RunMain(v8::Isolate* isolate, int argc, char* argv[]) {
255  for (int i = 1; i < argc; i++) {
256    const char* str = argv[i];
257    if (strcmp(str, "--shell") == 0) {
258      run_shell = true;
259    } else if (strcmp(str, "-f") == 0) {
260      // Ignore any -f flags for compatibility with the other stand-
261      // alone JavaScript engines.
262      continue;
263    } else if (strncmp(str, "--", 2) == 0) {
264      fprintf(stderr,
265              "Warning: unknown flag %s.\nTry --help for options\n", str);
266    } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
267      // Execute argument given to -e option directly.
268      v8::Handle<v8::String> file_name =
269          v8::String::NewFromUtf8(isolate, "unnamed");
270      v8::Handle<v8::String> source =
271          v8::String::NewFromUtf8(isolate, argv[++i]);
272      if (!ExecuteString(isolate, source, file_name, false, true)) return 1;
273    } else {
274      // Use all other arguments as names of files to load and run.
275      v8::Handle<v8::String> file_name = v8::String::NewFromUtf8(isolate, str);
276      v8::Handle<v8::String> source = ReadFile(isolate, str);
277      if (source.IsEmpty()) {
278        fprintf(stderr, "Error reading '%s'\n", str);
279        continue;
280      }
281      if (!ExecuteString(isolate, source, file_name, false, true)) return 1;
282    }
283  }
284  return 0;
285}
286
287
288// The read-eval-execute loop of the shell.
289void RunShell(v8::Handle<v8::Context> context) {
290  fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion());
291  static const int kBufferSize = 256;
292  // Enter the execution environment before evaluating any code.
293  v8::Context::Scope context_scope(context);
294  v8::Local<v8::String> name(
295      v8::String::NewFromUtf8(context->GetIsolate(), "(shell)"));
296  while (true) {
297    char buffer[kBufferSize];
298    fprintf(stderr, "> ");
299    char* str = fgets(buffer, kBufferSize, stdin);
300    if (str == NULL) break;
301    v8::HandleScope handle_scope(context->GetIsolate());
302    ExecuteString(context->GetIsolate(),
303                  v8::String::NewFromUtf8(context->GetIsolate(), str),
304                  name,
305                  true,
306                  true);
307  }
308  fprintf(stderr, "\n");
309}
310
311
312// Executes a string within the current v8 context.
313bool ExecuteString(v8::Isolate* isolate,
314                   v8::Handle<v8::String> source,
315                   v8::Handle<v8::Value> name,
316                   bool print_result,
317                   bool report_exceptions) {
318  v8::HandleScope handle_scope(isolate);
319  v8::TryCatch try_catch;
320  v8::ScriptOrigin origin(name);
321  v8::Handle<v8::Script> script = v8::Script::Compile(source, &origin);
322  if (script.IsEmpty()) {
323    // Print errors that happened during compilation.
324    if (report_exceptions)
325      ReportException(isolate, &try_catch);
326    return false;
327  } else {
328    v8::Handle<v8::Value> result = script->Run();
329    if (result.IsEmpty()) {
330      assert(try_catch.HasCaught());
331      // Print errors that happened during execution.
332      if (report_exceptions)
333        ReportException(isolate, &try_catch);
334      return false;
335    } else {
336      assert(!try_catch.HasCaught());
337      if (print_result && !result->IsUndefined()) {
338        // If all went well and the result wasn't undefined then print
339        // the returned value.
340        v8::String::Utf8Value str(result);
341        const char* cstr = ToCString(str);
342        printf("%s\n", cstr);
343      }
344      return true;
345    }
346  }
347}
348
349
350void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
351  v8::HandleScope handle_scope(isolate);
352  v8::String::Utf8Value exception(try_catch->Exception());
353  const char* exception_string = ToCString(exception);
354  v8::Handle<v8::Message> message = try_catch->Message();
355  if (message.IsEmpty()) {
356    // V8 didn't provide any extra information about this error; just
357    // print the exception.
358    fprintf(stderr, "%s\n", exception_string);
359  } else {
360    // Print (filename):(line number): (message).
361    v8::String::Utf8Value filename(message->GetScriptResourceName());
362    const char* filename_string = ToCString(filename);
363    int linenum = message->GetLineNumber();
364    fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
365    // Print line of source code.
366    v8::String::Utf8Value sourceline(message->GetSourceLine());
367    const char* sourceline_string = ToCString(sourceline);
368    fprintf(stderr, "%s\n", sourceline_string);
369    // Print wavy underline (GetUnderline is deprecated).
370    int start = message->GetStartColumn();
371    for (int i = 0; i < start; i++) {
372      fprintf(stderr, " ");
373    }
374    int end = message->GetEndColumn();
375    for (int i = start; i < end; i++) {
376      fprintf(stderr, "^");
377    }
378    fprintf(stderr, "\n");
379    v8::String::Utf8Value stack_trace(try_catch->StackTrace());
380    if (stack_trace.length() > 0) {
381      const char* stack_trace_string = ToCString(stack_trace);
382      fprintf(stderr, "%s\n", stack_trace_string);
383    }
384  }
385}
386