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