blob: b40eca2f7c0b696411e0db9b4d4101100d0baf50 [file] [log] [blame]
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +00001// Copyright 2011 the V8 project authors. All rights reserved.
kasper.lund7276f142008-07-30 08:49:36 +00002// 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>
kmillikin@chromium.org49edbdf2011-02-16 12:32:18 +000029#include <assert.h>
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000030#include <fcntl.h>
31#include <string.h>
32#include <stdio.h>
33#include <stdlib.h>
kasper.lund7276f142008-07-30 08:49:36 +000034
rossberg@chromium.org28a37082011-08-22 11:03:23 +000035#ifdef COMPRESS_STARTUP_DATA_BZ2
36#error Using compressed startup data is not supported for this sample
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000037#endif
38
rossberg@chromium.org28a37082011-08-22 11:03:23 +000039/**
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
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000047
48v8::Persistent<v8::Context> CreateShellContext();
kasper.lund7276f142008-07-30 08:49:36 +000049void RunShell(v8::Handle<v8::Context> context);
rossberg@chromium.org28a37082011-08-22 11:03:23 +000050int RunMain(int argc, char* argv[]);
mads.s.agercbaa0602008-08-14 13:41:48 +000051bool ExecuteString(v8::Handle<v8::String> source,
52 v8::Handle<v8::Value> name,
ager@chromium.org9258b6b2008-09-11 09:11:10 +000053 bool print_result,
54 bool report_exceptions);
kasper.lund7276f142008-07-30 08:49:36 +000055v8::Handle<v8::Value> Print(const v8::Arguments& args);
ager@chromium.org65dad4b2009-04-23 08:48:43 +000056v8::Handle<v8::Value> Read(const v8::Arguments& args);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +000057v8::Handle<v8::Value> Load(const v8::Arguments& args);
58v8::Handle<v8::Value> Quit(const v8::Arguments& args);
59v8::Handle<v8::Value> Version(const v8::Arguments& args);
kasper.lund7276f142008-07-30 08:49:36 +000060v8::Handle<v8::String> ReadFile(const char* name);
ager@chromium.org9258b6b2008-09-11 09:11:10 +000061void ReportException(v8::TryCatch* handler);
kasper.lund7276f142008-07-30 08:49:36 +000062
63
rossberg@chromium.org28a37082011-08-22 11:03:23 +000064static bool run_shell;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000065
66
rossberg@chromium.org28a37082011-08-22 11:03:23 +000067int main(int argc, char* argv[]) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000068 v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
rossberg@chromium.org28a37082011-08-22 11:03:23 +000069 run_shell = (argc == 1);
kasper.lund7276f142008-07-30 08:49:36 +000070 v8::HandleScope handle_scope;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000071 v8::Persistent<v8::Context> context = CreateShellContext();
whesse@chromium.orgb08986c2011-03-14 16:13:42 +000072 if (context.IsEmpty()) {
73 printf("Error creating context\n");
74 return 1;
75 }
rossberg@chromium.org28a37082011-08-22 11:03:23 +000076 context->Enter();
77 int result = RunMain(argc, argv);
kasper.lund7276f142008-07-30 08:49:36 +000078 if (run_shell) RunShell(context);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000079 context->Exit();
kasperl@chromium.orga5551262010-12-07 12:49:48 +000080 context.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +000081 v8::V8::Dispose();
82 return result;
83}
84
85
iposva@chromium.org245aa852009-02-10 00:49:54 +000086// Extracts a C string from a V8 Utf8Value.
87const char* ToCString(const v8::String::Utf8Value& value) {
88 return *value ? *value : "<string conversion failed>";
89}
90
91
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000092// Creates a new execution environment containing the built-in
93// functions.
94v8::Persistent<v8::Context> CreateShellContext() {
95 // Create a template for the global object.
96 v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
97 // Bind the global 'print' function to the C++ Print callback.
98 global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
99 // Bind the global 'read' function to the C++ Read callback.
100 global->Set(v8::String::New("read"), v8::FunctionTemplate::New(Read));
101 // Bind the global 'load' function to the C++ Load callback.
102 global->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load));
103 // Bind the 'quit' function
104 global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit));
105 // Bind the 'version' function
106 global->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version));
vegorov@chromium.org74f333b2011-04-06 11:17:46 +0000107
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000108 return v8::Context::New(NULL, global);
109}
110
111
kasper.lund7276f142008-07-30 08:49:36 +0000112// The callback that is invoked by v8 whenever the JavaScript 'print'
113// function is called. Prints its arguments on stdout separated by
114// spaces and ending with a newline.
115v8::Handle<v8::Value> Print(const v8::Arguments& args) {
116 bool first = true;
117 for (int i = 0; i < args.Length(); i++) {
118 v8::HandleScope handle_scope;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000119 if (first) {
120 first = false;
121 } else {
122 printf(" ");
123 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000124 v8::String::Utf8Value str(args[i]);
iposva@chromium.org245aa852009-02-10 00:49:54 +0000125 const char* cstr = ToCString(str);
126 printf("%s", cstr);
kasper.lund7276f142008-07-30 08:49:36 +0000127 }
128 printf("\n");
ager@chromium.org41826e72009-03-30 13:30:57 +0000129 fflush(stdout);
kasper.lund7276f142008-07-30 08:49:36 +0000130 return v8::Undefined();
131}
132
133
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000134// The callback that is invoked by v8 whenever the JavaScript 'read'
135// function is called. This function loads the content of the file named in
136// the argument into a JavaScript string.
137v8::Handle<v8::Value> Read(const v8::Arguments& args) {
138 if (args.Length() != 1) {
139 return v8::ThrowException(v8::String::New("Bad parameters"));
140 }
141 v8::String::Utf8Value file(args[0]);
142 if (*file == NULL) {
143 return v8::ThrowException(v8::String::New("Error loading file"));
144 }
145 v8::Handle<v8::String> source = ReadFile(*file);
146 if (source.IsEmpty()) {
147 return v8::ThrowException(v8::String::New("Error loading file"));
148 }
149 return source;
150}
151
152
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000153// The callback that is invoked by v8 whenever the JavaScript 'load'
154// function is called. Loads, compiles and executes its argument
155// JavaScript file.
156v8::Handle<v8::Value> Load(const v8::Arguments& args) {
157 for (int i = 0; i < args.Length(); i++) {
158 v8::HandleScope handle_scope;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000159 v8::String::Utf8Value file(args[i]);
iposva@chromium.org245aa852009-02-10 00:49:54 +0000160 if (*file == NULL) {
161 return v8::ThrowException(v8::String::New("Error loading file"));
162 }
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000163 v8::Handle<v8::String> source = ReadFile(*file);
164 if (source.IsEmpty()) {
165 return v8::ThrowException(v8::String::New("Error loading file"));
166 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000167 if (!ExecuteString(source, v8::String::New(*file), false, false)) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000168 return v8::ThrowException(v8::String::New("Error executing file"));
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000169 }
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000170 }
171 return v8::Undefined();
172}
173
174
175// The callback that is invoked by v8 whenever the JavaScript 'quit'
176// function is called. Quits.
177v8::Handle<v8::Value> Quit(const v8::Arguments& args) {
178 // If not arguments are given args[0] will yield undefined which
179 // converts to the integer value 0.
180 int exit_code = args[0]->Int32Value();
rossberg@chromium.org28a37082011-08-22 11:03:23 +0000181 fflush(stdout);
182 fflush(stderr);
183 exit(exit_code);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000184 return v8::Undefined();
185}
186
187
188v8::Handle<v8::Value> Version(const v8::Arguments& args) {
189 return v8::String::New(v8::V8::GetVersion());
190}
191
192
kasper.lund7276f142008-07-30 08:49:36 +0000193// Reads a file into a v8 string.
194v8::Handle<v8::String> ReadFile(const char* name) {
195 FILE* file = fopen(name, "rb");
196 if (file == NULL) return v8::Handle<v8::String>();
197
198 fseek(file, 0, SEEK_END);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000199 int size = ftell(file);
kasper.lund7276f142008-07-30 08:49:36 +0000200 rewind(file);
201
202 char* chars = new char[size + 1];
203 chars[size] = '\0';
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000204 for (int i = 0; i < size;) {
kasper.lund7276f142008-07-30 08:49:36 +0000205 int read = fread(&chars[i], 1, size - i, file);
206 i += read;
207 }
208 fclose(file);
209 v8::Handle<v8::String> result = v8::String::New(chars, size);
210 delete[] chars;
211 return result;
212}
213
214
rossberg@chromium.org28a37082011-08-22 11:03:23 +0000215// Process remaining command line arguments and execute files
216int RunMain(int argc, char* argv[]) {
217 for (int i = 1; i < argc; i++) {
218 const char* str = argv[i];
219 if (strcmp(str, "--shell") == 0) {
220 run_shell = true;
221 } else if (strcmp(str, "-f") == 0) {
222 // Ignore any -f flags for compatibility with the other stand-
223 // alone JavaScript engines.
224 continue;
225 } else if (strncmp(str, "--", 2) == 0) {
226 printf("Warning: unknown flag %s.\nTry --help for options\n", str);
227 } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
228 // Execute argument given to -e option directly.
229 v8::Handle<v8::String> file_name = v8::String::New("unnamed");
230 v8::Handle<v8::String> source = v8::String::New(argv[++i]);
231 if (!ExecuteString(source, file_name, false, true)) return 1;
232 } else {
233 // Use all other arguments as names of files to load and run.
234 v8::Handle<v8::String> file_name = v8::String::New(str);
235 v8::Handle<v8::String> source = ReadFile(str);
236 if (source.IsEmpty()) {
237 printf("Error reading '%s'\n", str);
238 continue;
239 }
240 if (!ExecuteString(source, file_name, false, true)) return 1;
241 }
242 }
243 return 0;
244}
245
246
kasper.lund7276f142008-07-30 08:49:36 +0000247// The read-eval-execute loop of the shell.
248void RunShell(v8::Handle<v8::Context> context) {
rossberg@chromium.org28a37082011-08-22 11:03:23 +0000249 printf("V8 version %s [sample shell]\n", v8::V8::GetVersion());
kasper.lund7276f142008-07-30 08:49:36 +0000250 static const int kBufferSize = 256;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000251 // Enter the execution environment before evaluating any code.
252 v8::Context::Scope context_scope(context);
fschneider@chromium.org1805e212011-09-05 10:49:12 +0000253 v8::Local<v8::String> name(v8::String::New("(shell)"));
kasper.lund7276f142008-07-30 08:49:36 +0000254 while (true) {
255 char buffer[kBufferSize];
256 printf("> ");
257 char* str = fgets(buffer, kBufferSize, stdin);
258 if (str == NULL) break;
259 v8::HandleScope handle_scope;
fschneider@chromium.org1805e212011-09-05 10:49:12 +0000260 ExecuteString(v8::String::New(str), name, true, true);
kasper.lund7276f142008-07-30 08:49:36 +0000261 }
262 printf("\n");
263}
264
265
266// Executes a string within the current v8 context.
mads.s.agercbaa0602008-08-14 13:41:48 +0000267bool ExecuteString(v8::Handle<v8::String> source,
268 v8::Handle<v8::Value> name,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000269 bool print_result,
270 bool report_exceptions) {
kasper.lund7276f142008-07-30 08:49:36 +0000271 v8::HandleScope handle_scope;
272 v8::TryCatch try_catch;
mads.s.agercbaa0602008-08-14 13:41:48 +0000273 v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
kasper.lund7276f142008-07-30 08:49:36 +0000274 if (script.IsEmpty()) {
275 // Print errors that happened during compilation.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000276 if (report_exceptions)
277 ReportException(&try_catch);
kasper.lund7276f142008-07-30 08:49:36 +0000278 return false;
279 } else {
280 v8::Handle<v8::Value> result = script->Run();
281 if (result.IsEmpty()) {
kmillikin@chromium.org49edbdf2011-02-16 12:32:18 +0000282 assert(try_catch.HasCaught());
kasper.lund7276f142008-07-30 08:49:36 +0000283 // Print errors that happened during execution.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000284 if (report_exceptions)
285 ReportException(&try_catch);
kasper.lund7276f142008-07-30 08:49:36 +0000286 return false;
287 } else {
kmillikin@chromium.org49edbdf2011-02-16 12:32:18 +0000288 assert(!try_catch.HasCaught());
mads.s.agercbaa0602008-08-14 13:41:48 +0000289 if (print_result && !result->IsUndefined()) {
kasper.lund7276f142008-07-30 08:49:36 +0000290 // If all went well and the result wasn't undefined then print
291 // the returned value.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000292 v8::String::Utf8Value str(result);
iposva@chromium.org245aa852009-02-10 00:49:54 +0000293 const char* cstr = ToCString(str);
294 printf("%s\n", cstr);
kasper.lund7276f142008-07-30 08:49:36 +0000295 }
296 return true;
297 }
298 }
299}
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000300
301
302void ReportException(v8::TryCatch* try_catch) {
303 v8::HandleScope handle_scope;
304 v8::String::Utf8Value exception(try_catch->Exception());
iposva@chromium.org245aa852009-02-10 00:49:54 +0000305 const char* exception_string = ToCString(exception);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000306 v8::Handle<v8::Message> message = try_catch->Message();
307 if (message.IsEmpty()) {
308 // V8 didn't provide any extra information about this error; just
309 // print the exception.
iposva@chromium.org245aa852009-02-10 00:49:54 +0000310 printf("%s\n", exception_string);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000311 } else {
312 // Print (filename):(line number): (message).
313 v8::String::Utf8Value filename(message->GetScriptResourceName());
iposva@chromium.org245aa852009-02-10 00:49:54 +0000314 const char* filename_string = ToCString(filename);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000315 int linenum = message->GetLineNumber();
iposva@chromium.org245aa852009-02-10 00:49:54 +0000316 printf("%s:%i: %s\n", filename_string, linenum, exception_string);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000317 // Print line of source code.
318 v8::String::Utf8Value sourceline(message->GetSourceLine());
iposva@chromium.org245aa852009-02-10 00:49:54 +0000319 const char* sourceline_string = ToCString(sourceline);
320 printf("%s\n", sourceline_string);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000321 // Print wavy underline (GetUnderline is deprecated).
322 int start = message->GetStartColumn();
323 for (int i = 0; i < start; i++) {
324 printf(" ");
325 }
326 int end = message->GetEndColumn();
327 for (int i = start; i < end; i++) {
328 printf("^");
329 }
330 printf("\n");
vegorov@chromium.orgdff694e2010-05-17 09:10:26 +0000331 v8::String::Utf8Value stack_trace(try_catch->StackTrace());
332 if (stack_trace.length() > 0) {
333 const char* stack_trace_string = ToCString(stack_trace);
334 printf("%s\n", stack_trace_string);
335 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000336 }
337}