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
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.
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.
28 #include <include/v8.h>
30 #include <include/libplatform/libplatform.h>
38 #ifdef COMPRESS_STARTUP_DATA_BZ2
39 #error Using compressed startup data is not supported for this sample
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.
47 * For a more sophisticated shell, consider using the debug shell D8.
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,
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);
68 static bool run_shell;
71 class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
73 virtual void* Allocate(size_t length) {
74 void* data = AllocateUninitialized(length);
75 return data == NULL ? data : memset(data, 0, length);
77 virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
78 virtual void Free(void* data, size_t) { free(data); }
82 int main(int argc, char* argv[]) {
83 v8::V8::InitializeICU();
84 v8::Platform* platform = v8::platform::CreateDefaultPlatform();
85 v8::V8::InitializePlatform(platform);
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);
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");
101 v8::Context::Scope context_scope(context);
102 result = RunMain(isolate, argc, argv);
103 if (run_shell) RunShell(context);
106 v8::V8::ShutdownPlatform();
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>";
118 // Creates a new execution environment containing the built-in
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));
139 return v8::Context::New(isolate, NULL, global);
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) {
148 for (int i = 0; i < args.Length(); i++) {
149 v8::HandleScope handle_scope(args.GetIsolate());
155 v8::String::Utf8Value str(args[i]);
156 const char* cstr = ToCString(str);
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"));
173 v8::String::Utf8Value file(args[0]);
175 args.GetIsolate()->ThrowException(
176 v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
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"));
185 args.GetReturnValue().Set(source);
189 // The callback that is invoked by v8 whenever the JavaScript 'load'
190 // function is called. Loads, compiles and executes its argument
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]);
197 args.GetIsolate()->ThrowException(
198 v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file"));
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"));
207 if (!ExecuteString(args.GetIsolate(),
209 v8::String::NewFromUtf8(args.GetIsolate(), *file),
212 args.GetIsolate()->ThrowException(
213 v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file"));
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();
232 void Version(const v8::FunctionCallbackInfo<v8::Value>& args) {
233 args.GetReturnValue().Set(
234 v8::String::NewFromUtf8(args.GetIsolate(), v8::V8::GetVersion()));
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>();
243 fseek(file, 0, SEEK_END);
244 int size = ftell(file);
247 char* chars = new char[size + 1];
249 for (int i = 0; i < size;) {
250 int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
254 v8::Handle<v8::String> result =
255 v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size);
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) {
267 } else if (strcmp(str, "-f") == 0) {
268 // Ignore any -f flags for compatibility with the other stand-
269 // alone JavaScript engines.
271 } else if (strncmp(str, "--", 2) == 0) {
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;
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);
289 if (!ExecuteString(isolate, source, file_name, false, true)) return 1;
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)"));
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),
316 fprintf(stderr, "\n");
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,
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);
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);
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);
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);
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, " ");
382 int end = message->GetEndColumn();
383 for (int i = start; i < end; i++) {
384 fprintf(stderr, "^");
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);