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