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