1 // Copyright 2011 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> 29 #include <assert.h> 30 #include <fcntl.h> 31 #include <string.h> 32 #include <stdio.h> 33 #include <stdlib.h> 34 35 #ifdef COMPRESS_STARTUP_DATA_BZ2 36 #error Using compressed startup data is not supported for this sample 37 #endif 38 39 /** 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 47 48 v8::Persistent<v8::Context> CreateShellContext(); 49 void RunShell(v8::Handle<v8::Context> context); 50 int RunMain(int argc, char* argv[]); 51 bool ExecuteString(v8::Handle<v8::String> source, 52 v8::Handle<v8::Value> name, 53 bool print_result, 54 bool report_exceptions); 55 v8::Handle<v8::Value> Print(const v8::Arguments& args); 56 v8::Handle<v8::Value> Read(const v8::Arguments& args); 57 v8::Handle<v8::Value> Load(const v8::Arguments& args); 58 v8::Handle<v8::Value> Quit(const v8::Arguments& args); 59 v8::Handle<v8::Value> Version(const v8::Arguments& args); 60 v8::Handle<v8::String> ReadFile(const char* name); 61 void ReportException(v8::TryCatch* handler); 62 63 64 static bool run_shell; 65 66 67 int main(int argc, char* argv[]) { 68 v8::V8::SetFlagsFromCommandLine(&argc, argv, true); 69 run_shell = (argc == 1); 70 v8::HandleScope handle_scope; 71 v8::Persistent<v8::Context> context = CreateShellContext(); 72 if (context.IsEmpty()) { 73 printf("Error creating context\n"); 74 return 1; 75 } 76 context->Enter(); 77 int result = RunMain(argc, argv); 78 if (run_shell) RunShell(context); 79 context->Exit(); 80 context.Dispose(); 81 v8::V8::Dispose(); 82 return result; 83 } 84 85 86 // Extracts a C string from a V8 Utf8Value. 87 const char* ToCString(const v8::String::Utf8Value& value) { 88 return *value ? *value : "<string conversion failed>"; 89 } 90 91 92 // Creates a new execution environment containing the built-in 93 // functions. 94 v8::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)); 107 108 return v8::Context::New(NULL, global); 109 } 110 111 112 // 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. 115 v8::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; 119 if (first) { 120 first = false; 121 } else { 122 printf(" "); 123 } 124 v8::String::Utf8Value str(args[i]); 125 const char* cstr = ToCString(str); 126 printf("%s", cstr); 127 } 128 printf("\n"); 129 fflush(stdout); 130 return v8::Undefined(); 131 } 132 133 134 // 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. 137 v8::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 153 // The callback that is invoked by v8 whenever the JavaScript 'load' 154 // function is called. Loads, compiles and executes its argument 155 // JavaScript file. 156 v8::Handle<v8::Value> Load(const v8::Arguments& args) { 157 for (int i = 0; i < args.Length(); i++) { 158 v8::HandleScope handle_scope; 159 v8::String::Utf8Value file(args[i]); 160 if (*file == NULL) { 161 return v8::ThrowException(v8::String::New("Error loading file")); 162 } 163 v8::Handle<v8::String> source = ReadFile(*file); 164 if (source.IsEmpty()) { 165 return v8::ThrowException(v8::String::New("Error loading file")); 166 } 167 if (!ExecuteString(source, v8::String::New(*file), false, false)) { 168 return v8::ThrowException(v8::String::New("Error executing file")); 169 } 170 } 171 return v8::Undefined(); 172 } 173 174 175 // The callback that is invoked by v8 whenever the JavaScript 'quit' 176 // function is called. Quits. 177 v8::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(); 181 fflush(stdout); 182 fflush(stderr); 183 exit(exit_code); 184 return v8::Undefined(); 185 } 186 187 188 v8::Handle<v8::Value> Version(const v8::Arguments& args) { 189 return v8::String::New(v8::V8::GetVersion()); 190 } 191 192 193 // Reads a file into a v8 string. 194 v8::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); 199 int size = ftell(file); 200 rewind(file); 201 202 char* chars = new char[size + 1]; 203 chars[size] = '\0'; 204 for (int i = 0; i < size;) { 205 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 215 // Process remaining command line arguments and execute files 216 int 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 247 // The read-eval-execute loop of the shell. 248 void RunShell(v8::Handle<v8::Context> context) { 249 printf("V8 version %s [sample shell]\n", v8::V8::GetVersion()); 250 static const int kBufferSize = 256; 251 // Enter the execution environment before evaluating any code. 252 v8::Context::Scope context_scope(context); 253 v8::Local<v8::String> name(v8::String::New("(shell)")); 254 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; 260 ExecuteString(v8::String::New(str), name, true, true); 261 } 262 printf("\n"); 263 } 264 265 266 // Executes a string within the current v8 context. 267 bool ExecuteString(v8::Handle<v8::String> source, 268 v8::Handle<v8::Value> name, 269 bool print_result, 270 bool report_exceptions) { 271 v8::HandleScope handle_scope; 272 v8::TryCatch try_catch; 273 v8::Handle<v8::Script> script = v8::Script::Compile(source, name); 274 if (script.IsEmpty()) { 275 // Print errors that happened during compilation. 276 if (report_exceptions) 277 ReportException(&try_catch); 278 return false; 279 } else { 280 v8::Handle<v8::Value> result = script->Run(); 281 if (result.IsEmpty()) { 282 assert(try_catch.HasCaught()); 283 // Print errors that happened during execution. 284 if (report_exceptions) 285 ReportException(&try_catch); 286 return false; 287 } else { 288 assert(!try_catch.HasCaught()); 289 if (print_result && !result->IsUndefined()) { 290 // If all went well and the result wasn't undefined then print 291 // the returned value. 292 v8::String::Utf8Value str(result); 293 const char* cstr = ToCString(str); 294 printf("%s\n", cstr); 295 } 296 return true; 297 } 298 } 299 } 300 301 302 void ReportException(v8::TryCatch* try_catch) { 303 v8::HandleScope handle_scope; 304 v8::String::Utf8Value exception(try_catch->Exception()); 305 const char* exception_string = ToCString(exception); 306 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. 310 printf("%s\n", exception_string); 311 } else { 312 // Print (filename):(line number): (message). 313 v8::String::Utf8Value filename(message->GetScriptResourceName()); 314 const char* filename_string = ToCString(filename); 315 int linenum = message->GetLineNumber(); 316 printf("%s:%i: %s\n", filename_string, linenum, exception_string); 317 // Print line of source code. 318 v8::String::Utf8Value sourceline(message->GetSourceLine()); 319 const char* sourceline_string = ToCString(sourceline); 320 printf("%s\n", sourceline_string); 321 // 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"); 331 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 } 336 } 337 } 338