blob: 64f78f02c61ec6df0e0c1a8f2504478e2b0816be [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 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>
Ben Murdochb0fe1622011-05-05 13:52:32 +010029#include <v8-testing.h>
Ben Murdoche0cee9b2011-05-25 10:26:03 +010030#include <assert.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000031#include <fcntl.h>
32#include <string.h>
33#include <stdio.h>
34#include <stdlib.h>
35
36
37void RunShell(v8::Handle<v8::Context> context);
38bool ExecuteString(v8::Handle<v8::String> source,
39 v8::Handle<v8::Value> name,
40 bool print_result,
41 bool report_exceptions);
42v8::Handle<v8::Value> Print(const v8::Arguments& args);
43v8::Handle<v8::Value> Read(const v8::Arguments& args);
44v8::Handle<v8::Value> Load(const v8::Arguments& args);
45v8::Handle<v8::Value> Quit(const v8::Arguments& args);
46v8::Handle<v8::Value> Version(const v8::Arguments& args);
47v8::Handle<v8::String> ReadFile(const char* name);
48void ReportException(v8::TryCatch* handler);
49
50
51int RunMain(int argc, char* argv[]) {
Steve Blocka7e24c12009-10-30 11:49:00 +000052 v8::HandleScope handle_scope;
53 // Create a template for the global object.
54 v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
55 // Bind the global 'print' function to the C++ Print callback.
56 global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
57 // Bind the global 'read' function to the C++ Read callback.
58 global->Set(v8::String::New("read"), v8::FunctionTemplate::New(Read));
59 // Bind the global 'load' function to the C++ Load callback.
60 global->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load));
61 // Bind the 'quit' function
62 global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit));
63 // Bind the 'version' function
64 global->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version));
65 // Create a new execution environment containing the built-in
66 // functions
Ben Murdochb0fe1622011-05-05 13:52:32 +010067 v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);
Steve Blocka7e24c12009-10-30 11:49:00 +000068 bool run_shell = (argc == 1);
69 for (int i = 1; i < argc; i++) {
Ben Murdochb0fe1622011-05-05 13:52:32 +010070 // Enter the execution environment before evaluating any code.
71 v8::Context::Scope context_scope(context);
Steve Blocka7e24c12009-10-30 11:49:00 +000072 const char* str = argv[i];
73 if (strcmp(str, "--shell") == 0) {
74 run_shell = true;
75 } else if (strcmp(str, "-f") == 0) {
76 // Ignore any -f flags for compatibility with the other stand-
77 // alone JavaScript engines.
78 continue;
79 } else if (strncmp(str, "--", 2) == 0) {
80 printf("Warning: unknown flag %s.\nTry --help for options\n", str);
81 } else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
82 // Execute argument given to -e option directly
83 v8::HandleScope handle_scope;
84 v8::Handle<v8::String> file_name = v8::String::New("unnamed");
85 v8::Handle<v8::String> source = v8::String::New(argv[i + 1]);
86 if (!ExecuteString(source, file_name, false, true))
87 return 1;
88 i++;
89 } else {
90 // Use all other arguments as names of files to load and run.
91 v8::HandleScope handle_scope;
92 v8::Handle<v8::String> file_name = v8::String::New(str);
93 v8::Handle<v8::String> source = ReadFile(str);
94 if (source.IsEmpty()) {
95 printf("Error reading '%s'\n", str);
96 return 1;
97 }
98 if (!ExecuteString(source, file_name, false, true))
99 return 1;
100 }
101 }
102 if (run_shell) RunShell(context);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100103 context.Dispose();
Steve Blocka7e24c12009-10-30 11:49:00 +0000104 return 0;
105}
106
107
108int main(int argc, char* argv[]) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100109 // Figure out if we're requested to stress the optimization
110 // infrastructure by running tests multiple times and forcing
111 // optimization in the last run.
112 bool FLAG_stress_opt = false;
113 bool FLAG_stress_deopt = false;
114 for (int i = 0; i < argc; i++) {
115 if (strcmp(argv[i], "--stress-opt") == 0) {
116 FLAG_stress_opt = true;
117 argv[i] = NULL;
118 } else if (strcmp(argv[i], "--stress-deopt") == 0) {
119 FLAG_stress_deopt = true;
120 argv[i] = NULL;
121 } else if (strcmp(argv[i], "--noalways-opt") == 0) {
122 // No support for stressing if we can't use --always-opt.
123 FLAG_stress_opt = false;
124 FLAG_stress_deopt = false;
125 break;
126 }
127 }
128
129 v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
130 int result = 0;
131 if (FLAG_stress_opt || FLAG_stress_deopt) {
132 v8::Testing::SetStressRunType(FLAG_stress_opt
133 ? v8::Testing::kStressTypeOpt
134 : v8::Testing::kStressTypeDeopt);
135 int stress_runs = v8::Testing::GetStressRuns();
136 for (int i = 0; i < stress_runs && result == 0; i++) {
137 printf("============ Stress %d/%d ============\n",
138 i + 1, stress_runs);
139 v8::Testing::PrepareStressRun(i);
140 result = RunMain(argc, argv);
141 }
142 } else {
143 result = RunMain(argc, argv);
144 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000145 v8::V8::Dispose();
146 return result;
147}
148
149
150// Extracts a C string from a V8 Utf8Value.
151const char* ToCString(const v8::String::Utf8Value& value) {
152 return *value ? *value : "<string conversion failed>";
153}
154
155
156// The callback that is invoked by v8 whenever the JavaScript 'print'
157// function is called. Prints its arguments on stdout separated by
158// spaces and ending with a newline.
159v8::Handle<v8::Value> Print(const v8::Arguments& args) {
160 bool first = true;
161 for (int i = 0; i < args.Length(); i++) {
162 v8::HandleScope handle_scope;
163 if (first) {
164 first = false;
165 } else {
166 printf(" ");
167 }
168 v8::String::Utf8Value str(args[i]);
169 const char* cstr = ToCString(str);
170 printf("%s", cstr);
171 }
172 printf("\n");
173 fflush(stdout);
174 return v8::Undefined();
175}
176
177
178// The callback that is invoked by v8 whenever the JavaScript 'read'
179// function is called. This function loads the content of the file named in
180// the argument into a JavaScript string.
181v8::Handle<v8::Value> Read(const v8::Arguments& args) {
182 if (args.Length() != 1) {
183 return v8::ThrowException(v8::String::New("Bad parameters"));
184 }
185 v8::String::Utf8Value file(args[0]);
186 if (*file == NULL) {
187 return v8::ThrowException(v8::String::New("Error loading file"));
188 }
189 v8::Handle<v8::String> source = ReadFile(*file);
190 if (source.IsEmpty()) {
191 return v8::ThrowException(v8::String::New("Error loading file"));
192 }
193 return 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.
200v8::Handle<v8::Value> Load(const v8::Arguments& args) {
201 for (int i = 0; i < args.Length(); i++) {
202 v8::HandleScope handle_scope;
203 v8::String::Utf8Value file(args[i]);
204 if (*file == NULL) {
205 return v8::ThrowException(v8::String::New("Error loading file"));
206 }
207 v8::Handle<v8::String> source = ReadFile(*file);
208 if (source.IsEmpty()) {
209 return v8::ThrowException(v8::String::New("Error loading file"));
210 }
211 if (!ExecuteString(source, v8::String::New(*file), false, false)) {
212 return v8::ThrowException(v8::String::New("Error executing file"));
213 }
214 }
215 return v8::Undefined();
216}
217
218
219// The callback that is invoked by v8 whenever the JavaScript 'quit'
220// function is called. Quits.
221v8::Handle<v8::Value> Quit(const v8::Arguments& 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 exit(exit_code);
226 return v8::Undefined();
227}
228
229
230v8::Handle<v8::Value> Version(const v8::Arguments& args) {
231 return v8::String::New(v8::V8::GetVersion());
232}
233
234
235// Reads a file into a v8 string.
236v8::Handle<v8::String> ReadFile(const char* name) {
237 FILE* file = fopen(name, "rb");
238 if (file == NULL) return v8::Handle<v8::String>();
239
240 fseek(file, 0, SEEK_END);
241 int size = ftell(file);
242 rewind(file);
243
244 char* chars = new char[size + 1];
245 chars[size] = '\0';
246 for (int i = 0; i < size;) {
247 int read = fread(&chars[i], 1, size - i, file);
248 i += read;
249 }
250 fclose(file);
251 v8::Handle<v8::String> result = v8::String::New(chars, size);
252 delete[] chars;
253 return result;
254}
255
256
257// The read-eval-execute loop of the shell.
258void RunShell(v8::Handle<v8::Context> context) {
259 printf("V8 version %s\n", v8::V8::GetVersion());
260 static const int kBufferSize = 256;
Ben Murdochb0fe1622011-05-05 13:52:32 +0100261 // Enter the execution environment before evaluating any code.
262 v8::Context::Scope context_scope(context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000263 while (true) {
264 char buffer[kBufferSize];
265 printf("> ");
266 char* str = fgets(buffer, kBufferSize, stdin);
267 if (str == NULL) break;
268 v8::HandleScope handle_scope;
269 ExecuteString(v8::String::New(str),
270 v8::String::New("(shell)"),
271 true,
272 true);
273 }
274 printf("\n");
275}
276
277
278// Executes a string within the current v8 context.
279bool ExecuteString(v8::Handle<v8::String> source,
280 v8::Handle<v8::Value> name,
281 bool print_result,
282 bool report_exceptions) {
283 v8::HandleScope handle_scope;
284 v8::TryCatch try_catch;
285 v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
286 if (script.IsEmpty()) {
287 // Print errors that happened during compilation.
288 if (report_exceptions)
289 ReportException(&try_catch);
290 return false;
291 } else {
292 v8::Handle<v8::Value> result = script->Run();
293 if (result.IsEmpty()) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100294 assert(try_catch.HasCaught());
Steve Blocka7e24c12009-10-30 11:49:00 +0000295 // Print errors that happened during execution.
296 if (report_exceptions)
297 ReportException(&try_catch);
298 return false;
299 } else {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100300 assert(!try_catch.HasCaught());
Steve Blocka7e24c12009-10-30 11:49:00 +0000301 if (print_result && !result->IsUndefined()) {
302 // If all went well and the result wasn't undefined then print
303 // the returned value.
304 v8::String::Utf8Value str(result);
305 const char* cstr = ToCString(str);
306 printf("%s\n", cstr);
307 }
308 return true;
309 }
310 }
311}
312
313
314void ReportException(v8::TryCatch* try_catch) {
315 v8::HandleScope handle_scope;
316 v8::String::Utf8Value exception(try_catch->Exception());
317 const char* exception_string = ToCString(exception);
318 v8::Handle<v8::Message> message = try_catch->Message();
319 if (message.IsEmpty()) {
320 // V8 didn't provide any extra information about this error; just
321 // print the exception.
322 printf("%s\n", exception_string);
323 } else {
324 // Print (filename):(line number): (message).
325 v8::String::Utf8Value filename(message->GetScriptResourceName());
326 const char* filename_string = ToCString(filename);
327 int linenum = message->GetLineNumber();
328 printf("%s:%i: %s\n", filename_string, linenum, exception_string);
329 // Print line of source code.
330 v8::String::Utf8Value sourceline(message->GetSourceLine());
331 const char* sourceline_string = ToCString(sourceline);
332 printf("%s\n", sourceline_string);
333 // Print wavy underline (GetUnderline is deprecated).
334 int start = message->GetStartColumn();
335 for (int i = 0; i < start; i++) {
336 printf(" ");
337 }
338 int end = message->GetEndColumn();
339 for (int i = start; i < end; i++) {
340 printf("^");
341 }
342 printf("\n");
Kristian Monsen25f61362010-05-21 11:50:48 +0100343 v8::String::Utf8Value stack_trace(try_catch->StackTrace());
344 if (stack_trace.length() > 0) {
345 const char* stack_trace_string = ToCString(stack_trace);
346 printf("%s\n", stack_trace_string);
347 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000348 }
349}