diff options
author | Zeno Albisser <zeno.albisser@digia.com> | 2013-08-15 21:46:11 +0200 |
---|---|---|
committer | Zeno Albisser <zeno.albisser@digia.com> | 2013-08-15 21:46:11 +0200 |
commit | 679147eead574d186ebf3069647b4c23e8ccace6 (patch) | |
tree | fc247a0ac8ff119f7c8550879ebb6d3dd8d1ff69 /chromium/v8/samples | |
download | qtwebengine-chromium-679147eead574d186ebf3069647b4c23e8ccace6.tar.gz |
Initial import.
Diffstat (limited to 'chromium/v8/samples')
-rw-r--r-- | chromium/v8/samples/count-hosts.js | 42 | ||||
-rw-r--r-- | chromium/v8/samples/lineprocessor.cc | 450 | ||||
-rw-r--r-- | chromium/v8/samples/process.cc | 654 | ||||
-rw-r--r-- | chromium/v8/samples/samples.gyp | 76 | ||||
-rw-r--r-- | chromium/v8/samples/shell.cc | 355 |
5 files changed, 1577 insertions, 0 deletions
diff --git a/chromium/v8/samples/count-hosts.js b/chromium/v8/samples/count-hosts.js new file mode 100644 index 00000000000..bea6553d27b --- /dev/null +++ b/chromium/v8/samples/count-hosts.js @@ -0,0 +1,42 @@ +// Copyright 2008 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +function Initialize() { } + +function Process(request) { + if (options.verbose) { + log("Processing " + request.host + request.path + + " from " + request.referrer + "@" + request.userAgent); + } + if (!output[request.host]) { + output[request.host] = 1; + } else { + output[request.host]++ + } +} + +Initialize(); diff --git a/chromium/v8/samples/lineprocessor.cc b/chromium/v8/samples/lineprocessor.cc new file mode 100644 index 00000000000..42048202fdd --- /dev/null +++ b/chromium/v8/samples/lineprocessor.cc @@ -0,0 +1,450 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include <v8.h> + +#ifdef ENABLE_DEBUGGER_SUPPORT +#include <v8-debug.h> +#endif // ENABLE_DEBUGGER_SUPPORT + +#include <fcntl.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> + +/** + * This sample program should demonstrate certain aspects of debugging + * standalone V8-based application. + * + * The program reads input stream, processes it line by line and print + * the result to output. The actual processing is done by custom JavaScript + * script. The script is specified with command line parameters. + * + * The main cycle of the program will sequentially read lines from standard + * input, process them and print to standard output until input closes. + * There are 2 possible configuration in regard to main cycle. + * + * 1. The main cycle is on C++ side. Program should be run with + * --main-cycle-in-cpp option. Script must declare a function named + * "ProcessLine". The main cycle in C++ reads lines and calls this function + * for processing every time. This is a sample script: + +function ProcessLine(input_line) { + return ">>>" + input_line + "<<<"; +} + + * + * 2. The main cycle is in JavaScript. Program should be run with + * --main-cycle-in-js option. Script gets run one time at all and gets + * API of 2 global functions: "read_line" and "print". It should read input + * and print converted lines to output itself. This a sample script: + +while (true) { + var line = read_line(); + if (!line) { + break; + } + var res = line + " | " + line; + print(res); +} + + * + * When run with "-p" argument, the program starts V8 Debugger Agent and + * allows remote debugger to attach and debug JavaScript code. + * + * Interesting aspects: + * 1. Wait for remote debugger to attach + * Normally the program compiles custom script and immediately runs it. + * If programmer needs to debug script from the very beginning, he should + * run this sample program with "--wait-for-connection" command line parameter. + * This way V8 will suspend on the first statement and wait for + * debugger to attach. + * + * 2. Unresponsive V8 + * V8 Debugger Agent holds a connection with remote debugger, but it does + * respond only when V8 is running some script. In particular, when this program + * is waiting for input, all requests from debugger get deferred until V8 + * is called again. See how "--callback" command-line parameter in this sample + * fixes this issue. + */ + +enum MainCycleType { + CycleInCpp, + CycleInJs +}; + +const char* ToCString(const v8::String::Utf8Value& value); +void ReportException(v8::Isolate* isolate, v8::TryCatch* handler); +v8::Handle<v8::String> ReadFile(const char* name); +v8::Handle<v8::String> ReadLine(); + +void Print(const v8::FunctionCallbackInfo<v8::Value>& args); +void ReadLine(const v8::FunctionCallbackInfo<v8::Value>& args); +bool RunCppCycle(v8::Handle<v8::Script> script, + v8::Local<v8::Context> context, + bool report_exceptions); + + +#ifdef ENABLE_DEBUGGER_SUPPORT +v8::Persistent<v8::Context> debug_message_context; + +void DispatchDebugMessages() { + // We are in some random thread. We should already have v8::Locker acquired + // (we requested this when registered this callback). We was called + // because new debug messages arrived; they may have already been processed, + // but we shouldn't worry about this. + // + // All we have to do is to set context and call ProcessDebugMessages. + // + // We should decide which V8 context to use here. This is important for + // "evaluate" command, because it must be executed some context. + // In our sample we have only one context, so there is nothing really to + // think about. + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope handle_scope(isolate); + v8::Local<v8::Context> context = + v8::Local<v8::Context>::New(isolate, debug_message_context); + v8::Context::Scope scope(context); + + v8::Debug::ProcessDebugMessages(); +} +#endif // ENABLE_DEBUGGER_SUPPORT + + +int RunMain(int argc, char* argv[]) { + v8::V8::SetFlagsFromCommandLine(&argc, argv, true); + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope handle_scope(isolate); + + v8::Handle<v8::String> script_source; + v8::Handle<v8::Value> script_name; + int script_param_counter = 0; + +#ifdef ENABLE_DEBUGGER_SUPPORT + int port_number = -1; + bool wait_for_connection = false; + bool support_callback = false; +#endif // ENABLE_DEBUGGER_SUPPORT + + MainCycleType cycle_type = CycleInCpp; + + for (int i = 1; i < argc; i++) { + const char* str = argv[i]; + if (strcmp(str, "-f") == 0) { + // Ignore any -f flags for compatibility with the other stand- + // alone JavaScript engines. + continue; + } else if (strcmp(str, "--main-cycle-in-cpp") == 0) { + cycle_type = CycleInCpp; + } else if (strcmp(str, "--main-cycle-in-js") == 0) { + cycle_type = CycleInJs; +#ifdef ENABLE_DEBUGGER_SUPPORT + } else if (strcmp(str, "--callback") == 0) { + support_callback = true; + } else if (strcmp(str, "--wait-for-connection") == 0) { + wait_for_connection = true; + } else if (strcmp(str, "-p") == 0 && i + 1 < argc) { + port_number = atoi(argv[i + 1]); // NOLINT + i++; +#endif // ENABLE_DEBUGGER_SUPPORT + } else if (strncmp(str, "--", 2) == 0) { + printf("Warning: unknown flag %s.\nTry --help for options\n", str); + } else if (strcmp(str, "-e") == 0 && i + 1 < argc) { + script_source = v8::String::New(argv[i + 1]); + script_name = v8::String::New("unnamed"); + i++; + script_param_counter++; + } else { + // Use argument as a name of file to load. + script_source = ReadFile(str); + script_name = v8::String::New(str); + if (script_source.IsEmpty()) { + printf("Error reading '%s'\n", str); + return 1; + } + script_param_counter++; + } + } + + if (script_param_counter == 0) { + printf("Script is not specified\n"); + return 1; + } + if (script_param_counter != 1) { + printf("Only one script may be specified\n"); + return 1; + } + + // Create a template for the global object. + v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); + + // Bind the global 'print' function to the C++ Print callback. + global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)); + + if (cycle_type == CycleInJs) { + // Bind the global 'read_line' function to the C++ Print callback. + global->Set(v8::String::New("read_line"), + v8::FunctionTemplate::New(ReadLine)); + } + + // Create a new execution environment containing the built-in + // functions + v8::Handle<v8::Context> context = v8::Context::New(isolate, NULL, global); + // Enter the newly created execution environment. + v8::Context::Scope context_scope(context); + +#ifdef ENABLE_DEBUGGER_SUPPORT + debug_message_context.Reset(isolate, context); + + v8::Locker locker(isolate); + + if (support_callback) { + v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true); + } + + if (port_number != -1) { + v8::Debug::EnableAgent("lineprocessor", port_number, wait_for_connection); + } +#endif // ENABLE_DEBUGGER_SUPPORT + + bool report_exceptions = true; + + v8::Handle<v8::Script> script; + { + // Compile script in try/catch context. + v8::TryCatch try_catch; + script = v8::Script::Compile(script_source, script_name); + if (script.IsEmpty()) { + // Print errors that happened during compilation. + if (report_exceptions) + ReportException(isolate, &try_catch); + return 1; + } + } + + { + v8::TryCatch try_catch; + + script->Run(); + if (try_catch.HasCaught()) { + if (report_exceptions) + ReportException(isolate, &try_catch); + return 1; + } + } + + if (cycle_type == CycleInCpp) { + bool res = RunCppCycle(script, + v8::Context::GetCurrent(), + report_exceptions); + return !res; + } else { + // All is already done. + } + return 0; +} + + +bool RunCppCycle(v8::Handle<v8::Script> script, + v8::Local<v8::Context> context, + bool report_exceptions) { + v8::Isolate* isolate = context->GetIsolate(); +#ifdef ENABLE_DEBUGGER_SUPPORT + v8::Locker lock(isolate); +#endif // ENABLE_DEBUGGER_SUPPORT + + v8::Handle<v8::String> fun_name = v8::String::New("ProcessLine"); + v8::Handle<v8::Value> process_val = context->Global()->Get(fun_name); + + // If there is no Process function, or if it is not a function, + // bail out + if (!process_val->IsFunction()) { + printf("Error: Script does not declare 'ProcessLine' global function.\n"); + return 1; + } + + // It is a function; cast it to a Function + v8::Handle<v8::Function> process_fun = + v8::Handle<v8::Function>::Cast(process_val); + + + while (!feof(stdin)) { + v8::HandleScope handle_scope(isolate); + + v8::Handle<v8::String> input_line = ReadLine(); + if (input_line == v8::Undefined()) { + continue; + } + + const int argc = 1; + v8::Handle<v8::Value> argv[argc] = { input_line }; + + v8::Handle<v8::Value> result; + { + v8::TryCatch try_catch; + result = process_fun->Call(v8::Context::GetCurrent()->Global(), + argc, argv); + if (try_catch.HasCaught()) { + if (report_exceptions) + ReportException(isolate, &try_catch); + return false; + } + } + v8::String::Utf8Value str(result); + const char* cstr = ToCString(str); + printf("%s\n", cstr); + } + + return true; +} + + +int main(int argc, char* argv[]) { + v8::V8::InitializeICU(); + int result = RunMain(argc, argv); + v8::V8::Dispose(); + return result; +} + + +// Extracts a C string from a V8 Utf8Value. +const char* ToCString(const v8::String::Utf8Value& value) { + return *value ? *value : "<string conversion failed>"; +} + + +// Reads a file into a v8 string. +v8::Handle<v8::String> ReadFile(const char* name) { + FILE* file = fopen(name, "rb"); + if (file == NULL) return v8::Handle<v8::String>(); + + fseek(file, 0, SEEK_END); + int size = ftell(file); + rewind(file); + + char* chars = new char[size + 1]; + chars[size] = '\0'; + for (int i = 0; i < size;) { + int read = static_cast<int>(fread(&chars[i], 1, size - i, file)); + i += read; + } + fclose(file); + v8::Handle<v8::String> result = v8::String::New(chars, size); + delete[] chars; + return result; +} + + +void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) { + v8::HandleScope handle_scope(isolate); + v8::String::Utf8Value exception(try_catch->Exception()); + const char* exception_string = ToCString(exception); + v8::Handle<v8::Message> message = try_catch->Message(); + if (message.IsEmpty()) { + // V8 didn't provide any extra information about this error; just + // print the exception. + printf("%s\n", exception_string); + } else { + // Print (filename):(line number): (message). + v8::String::Utf8Value filename(message->GetScriptResourceName()); + const char* filename_string = ToCString(filename); + int linenum = message->GetLineNumber(); + printf("%s:%i: %s\n", filename_string, linenum, exception_string); + // Print line of source code. + v8::String::Utf8Value sourceline(message->GetSourceLine()); + const char* sourceline_string = ToCString(sourceline); + printf("%s\n", sourceline_string); + // Print wavy underline (GetUnderline is deprecated). + int start = message->GetStartColumn(); + for (int i = 0; i < start; i++) { + printf(" "); + } + int end = message->GetEndColumn(); + for (int i = start; i < end; i++) { + printf("^"); + } + printf("\n"); + } +} + + +// The callback that is invoked by v8 whenever the JavaScript 'print' +// function is called. Prints its arguments on stdout separated by +// spaces and ending with a newline. +void Print(const v8::FunctionCallbackInfo<v8::Value>& args) { + bool first = true; + for (int i = 0; i < args.Length(); i++) { + v8::HandleScope handle_scope(args.GetIsolate()); + if (first) { + first = false; + } else { + printf(" "); + } + v8::String::Utf8Value str(args[i]); + const char* cstr = ToCString(str); + printf("%s", cstr); + } + printf("\n"); + fflush(stdout); +} + + +// The callback that is invoked by v8 whenever the JavaScript 'read_line' +// function is called. Reads a string from standard input and returns. +void ReadLine(const v8::FunctionCallbackInfo<v8::Value>& args) { + if (args.Length() > 0) { + v8::ThrowException(v8::String::New("Unexpected arguments")); + return; + } + args.GetReturnValue().Set(ReadLine()); +} + + +v8::Handle<v8::String> ReadLine() { + const int kBufferSize = 1024 + 1; + char buffer[kBufferSize]; + + char* res; + { +#ifdef ENABLE_DEBUGGER_SUPPORT + v8::Unlocker unlocker(v8::Isolate::GetCurrent()); +#endif // ENABLE_DEBUGGER_SUPPORT + res = fgets(buffer, kBufferSize, stdin); + } + if (res == NULL) { + v8::Handle<v8::Primitive> t = v8::Undefined(); + return v8::Handle<v8::String>::Cast(t); + } + // Remove newline char + for (char* pos = buffer; *pos != '\0'; pos++) { + if (*pos == '\n') { + *pos = '\0'; + break; + } + } + return v8::String::New(buffer); +} diff --git a/chromium/v8/samples/process.cc b/chromium/v8/samples/process.cc new file mode 100644 index 00000000000..844aee3d45f --- /dev/null +++ b/chromium/v8/samples/process.cc @@ -0,0 +1,654 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include <v8.h> + +#include <string> +#include <map> + +#ifdef COMPRESS_STARTUP_DATA_BZ2 +#error Using compressed startup data is not supported for this sample +#endif + +using namespace std; +using namespace v8; + +// These interfaces represent an existing request processing interface. +// The idea is to imagine a real application that uses these interfaces +// and then add scripting capabilities that allow you to interact with +// the objects through JavaScript. + +/** + * A simplified http request. + */ +class HttpRequest { + public: + virtual ~HttpRequest() { } + virtual const string& Path() = 0; + virtual const string& Referrer() = 0; + virtual const string& Host() = 0; + virtual const string& UserAgent() = 0; +}; + + +/** + * The abstract superclass of http request processors. + */ +class HttpRequestProcessor { + public: + virtual ~HttpRequestProcessor() { } + + // Initialize this processor. The map contains options that control + // how requests should be processed. + virtual bool Initialize(map<string, string>* options, + map<string, string>* output) = 0; + + // Process a single request. + virtual bool Process(HttpRequest* req) = 0; + + static void Log(const char* event); +}; + + +/** + * An http request processor that is scriptable using JavaScript. + */ +class JsHttpRequestProcessor : public HttpRequestProcessor { + public: + // Creates a new processor that processes requests by invoking the + // Process function of the JavaScript script given as an argument. + JsHttpRequestProcessor(Isolate* isolate, Handle<String> script) + : isolate_(isolate), script_(script) { } + virtual ~JsHttpRequestProcessor(); + + virtual bool Initialize(map<string, string>* opts, + map<string, string>* output); + virtual bool Process(HttpRequest* req); + + private: + // Execute the script associated with this processor and extract the + // Process function. Returns true if this succeeded, otherwise false. + bool ExecuteScript(Handle<String> script); + + // Wrap the options and output map in a JavaScript objects and + // install it in the global namespace as 'options' and 'output'. + bool InstallMaps(map<string, string>* opts, map<string, string>* output); + + // Constructs the template that describes the JavaScript wrapper + // type for requests. + static Handle<ObjectTemplate> MakeRequestTemplate(Isolate* isolate); + static Handle<ObjectTemplate> MakeMapTemplate(Isolate* isolate); + + // Callbacks that access the individual fields of request objects. + static void GetPath(Local<String> name, + const PropertyCallbackInfo<Value>& info); + static void GetReferrer(Local<String> name, + const PropertyCallbackInfo<Value>& info); + static void GetHost(Local<String> name, + const PropertyCallbackInfo<Value>& info); + static void GetUserAgent(Local<String> name, + const PropertyCallbackInfo<Value>& info); + + // Callbacks that access maps + static void MapGet(Local<String> name, + const PropertyCallbackInfo<Value>& info); + static void MapSet(Local<String> name, + Local<Value> value, + const PropertyCallbackInfo<Value>& info); + + // Utility methods for wrapping C++ objects as JavaScript objects, + // and going back again. + Handle<Object> WrapMap(map<string, string>* obj); + static map<string, string>* UnwrapMap(Handle<Object> obj); + Handle<Object> WrapRequest(HttpRequest* obj); + static HttpRequest* UnwrapRequest(Handle<Object> obj); + + Isolate* GetIsolate() { return isolate_; } + + Isolate* isolate_; + Handle<String> script_; + Persistent<Context> context_; + Persistent<Function> process_; + static Persistent<ObjectTemplate> request_template_; + static Persistent<ObjectTemplate> map_template_; +}; + + +// ------------------------- +// --- P r o c e s s o r --- +// ------------------------- + + +static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) { + if (args.Length() < 1) return; + HandleScope scope(args.GetIsolate()); + Handle<Value> arg = args[0]; + String::Utf8Value value(arg); + HttpRequestProcessor::Log(*value); +} + + +// Execute the script and fetch the Process method. +bool JsHttpRequestProcessor::Initialize(map<string, string>* opts, + map<string, string>* output) { + // Create a handle scope to hold the temporary references. + HandleScope handle_scope(GetIsolate()); + + // Create a template for the global object where we set the + // built-in global functions. + Handle<ObjectTemplate> global = ObjectTemplate::New(); + global->Set(String::New("log"), FunctionTemplate::New(LogCallback)); + + // Each processor gets its own context so different processors don't + // affect each other. Context::New returns a persistent handle which + // is what we need for the reference to remain after we return from + // this method. That persistent handle has to be disposed in the + // destructor. + v8::Handle<v8::Context> context = Context::New(GetIsolate(), NULL, global); + context_.Reset(GetIsolate(), context); + + // Enter the new context so all the following operations take place + // within it. + Context::Scope context_scope(context); + + // Make the options mapping available within the context + if (!InstallMaps(opts, output)) + return false; + + // Compile and run the script + if (!ExecuteScript(script_)) + return false; + + // The script compiled and ran correctly. Now we fetch out the + // Process function from the global object. + Handle<String> process_name = String::New("Process"); + Handle<Value> process_val = context->Global()->Get(process_name); + + // If there is no Process function, or if it is not a function, + // bail out + if (!process_val->IsFunction()) return false; + + // It is a function; cast it to a Function + Handle<Function> process_fun = Handle<Function>::Cast(process_val); + + // Store the function in a Persistent handle, since we also want + // that to remain after this call returns + process_.Reset(GetIsolate(), process_fun); + + // All done; all went well + return true; +} + + +bool JsHttpRequestProcessor::ExecuteScript(Handle<String> script) { + HandleScope handle_scope(GetIsolate()); + + // We're just about to compile the script; set up an error handler to + // catch any exceptions the script might throw. + TryCatch try_catch; + + // Compile the script and check for errors. + Handle<Script> compiled_script = Script::Compile(script); + if (compiled_script.IsEmpty()) { + String::Utf8Value error(try_catch.Exception()); + Log(*error); + // The script failed to compile; bail out. + return false; + } + + // Run the script! + Handle<Value> result = compiled_script->Run(); + if (result.IsEmpty()) { + // The TryCatch above is still in effect and will have caught the error. + String::Utf8Value error(try_catch.Exception()); + Log(*error); + // Running the script failed; bail out. + return false; + } + return true; +} + + +bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts, + map<string, string>* output) { + HandleScope handle_scope(GetIsolate()); + + // Wrap the map object in a JavaScript wrapper + Handle<Object> opts_obj = WrapMap(opts); + + v8::Local<v8::Context> context = + v8::Local<v8::Context>::New(GetIsolate(), context_); + + // Set the options object as a property on the global object. + context->Global()->Set(String::New("options"), opts_obj); + + Handle<Object> output_obj = WrapMap(output); + context->Global()->Set(String::New("output"), output_obj); + + return true; +} + + +bool JsHttpRequestProcessor::Process(HttpRequest* request) { + // Create a handle scope to keep the temporary object references. + HandleScope handle_scope(GetIsolate()); + + v8::Local<v8::Context> context = + v8::Local<v8::Context>::New(GetIsolate(), context_); + + // Enter this processor's context so all the remaining operations + // take place there + Context::Scope context_scope(context); + + // Wrap the C++ request object in a JavaScript wrapper + Handle<Object> request_obj = WrapRequest(request); + + // Set up an exception handler before calling the Process function + TryCatch try_catch; + + // Invoke the process function, giving the global object as 'this' + // and one argument, the request. + const int argc = 1; + Handle<Value> argv[argc] = { request_obj }; + v8::Local<v8::Function> process = + v8::Local<v8::Function>::New(GetIsolate(), process_); + Handle<Value> result = process->Call(context->Global(), argc, argv); + if (result.IsEmpty()) { + String::Utf8Value error(try_catch.Exception()); + Log(*error); + return false; + } else { + return true; + } +} + + +JsHttpRequestProcessor::~JsHttpRequestProcessor() { + // Dispose the persistent handles. When noone else has any + // references to the objects stored in the handles they will be + // automatically reclaimed. + Isolate* isolate = GetIsolate(); + context_.Dispose(isolate); + process_.Dispose(isolate); +} + + +Persistent<ObjectTemplate> JsHttpRequestProcessor::request_template_; +Persistent<ObjectTemplate> JsHttpRequestProcessor::map_template_; + + +// ----------------------------------- +// --- A c c e s s i n g M a p s --- +// ----------------------------------- + +// Utility function that wraps a C++ http request object in a +// JavaScript object. +Handle<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) { + // Handle scope for temporary handles. + HandleScope handle_scope(GetIsolate()); + + // Fetch the template for creating JavaScript map wrappers. + // It only has to be created once, which we do on demand. + if (map_template_.IsEmpty()) { + Handle<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate()); + map_template_.Reset(GetIsolate(), raw_template); + } + Handle<ObjectTemplate> templ = + Local<ObjectTemplate>::New(GetIsolate(), map_template_); + + // Create an empty map wrapper. + Handle<Object> result = templ->NewInstance(); + + // Wrap the raw C++ pointer in an External so it can be referenced + // from within JavaScript. + Handle<External> map_ptr = External::New(obj); + + // Store the map pointer in the JavaScript wrapper. + result->SetInternalField(0, map_ptr); + + // Return the result through the current handle scope. Since each + // of these handles will go away when the handle scope is deleted + // we need to call Close to let one, the result, escape into the + // outer handle scope. + return handle_scope.Close(result); +} + + +// Utility function that extracts the C++ map pointer from a wrapper +// object. +map<string, string>* JsHttpRequestProcessor::UnwrapMap(Handle<Object> obj) { + Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0)); + void* ptr = field->Value(); + return static_cast<map<string, string>*>(ptr); +} + + +// Convert a JavaScript string to a std::string. To not bother too +// much with string encodings we just use ascii. +string ObjectToString(Local<Value> value) { + String::Utf8Value utf8_value(value); + return string(*utf8_value); +} + + +void JsHttpRequestProcessor::MapGet(Local<String> name, + const PropertyCallbackInfo<Value>& info) { + // Fetch the map wrapped by this object. + map<string, string>* obj = UnwrapMap(info.Holder()); + + // Convert the JavaScript string to a std::string. + string key = ObjectToString(name); + + // Look up the value if it exists using the standard STL ideom. + map<string, string>::iterator iter = obj->find(key); + + // If the key is not present return an empty handle as signal + if (iter == obj->end()) return; + + // Otherwise fetch the value and wrap it in a JavaScript string + const string& value = (*iter).second; + info.GetReturnValue().Set( + String::New(value.c_str(), static_cast<int>(value.length()))); +} + + +void JsHttpRequestProcessor::MapSet(Local<String> name, + Local<Value> value_obj, + const PropertyCallbackInfo<Value>& info) { + // Fetch the map wrapped by this object. + map<string, string>* obj = UnwrapMap(info.Holder()); + + // Convert the key and value to std::strings. + string key = ObjectToString(name); + string value = ObjectToString(value_obj); + + // Update the map. + (*obj)[key] = value; + + // Return the value; any non-empty handle will work. + info.GetReturnValue().Set(value_obj); +} + + +Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate( + Isolate* isolate) { + HandleScope handle_scope(isolate); + + Handle<ObjectTemplate> result = ObjectTemplate::New(); + result->SetInternalFieldCount(1); + result->SetNamedPropertyHandler(MapGet, MapSet); + + // Again, return the result through the current handle scope. + return handle_scope.Close(result); +} + + +// ------------------------------------------- +// --- A c c e s s i n g R e q u e s t s --- +// ------------------------------------------- + +/** + * Utility function that wraps a C++ http request object in a + * JavaScript object. + */ +Handle<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) { + // Handle scope for temporary handles. + HandleScope handle_scope(GetIsolate()); + + // Fetch the template for creating JavaScript http request wrappers. + // It only has to be created once, which we do on demand. + if (request_template_.IsEmpty()) { + Handle<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate()); + request_template_.Reset(GetIsolate(), raw_template); + } + Handle<ObjectTemplate> templ = + Local<ObjectTemplate>::New(GetIsolate(), request_template_); + + // Create an empty http request wrapper. + Handle<Object> result = templ->NewInstance(); + + // Wrap the raw C++ pointer in an External so it can be referenced + // from within JavaScript. + Handle<External> request_ptr = External::New(request); + + // Store the request pointer in the JavaScript wrapper. + result->SetInternalField(0, request_ptr); + + // Return the result through the current handle scope. Since each + // of these handles will go away when the handle scope is deleted + // we need to call Close to let one, the result, escape into the + // outer handle scope. + return handle_scope.Close(result); +} + + +/** + * Utility function that extracts the C++ http request object from a + * wrapper object. + */ +HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Handle<Object> obj) { + Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0)); + void* ptr = field->Value(); + return static_cast<HttpRequest*>(ptr); +} + + +void JsHttpRequestProcessor::GetPath(Local<String> name, + const PropertyCallbackInfo<Value>& info) { + // Extract the C++ request object from the JavaScript wrapper. + HttpRequest* request = UnwrapRequest(info.Holder()); + + // Fetch the path. + const string& path = request->Path(); + + // Wrap the result in a JavaScript string and return it. + info.GetReturnValue().Set( + String::New(path.c_str(), static_cast<int>(path.length()))); +} + + +void JsHttpRequestProcessor::GetReferrer( + Local<String> name, + const PropertyCallbackInfo<Value>& info) { + HttpRequest* request = UnwrapRequest(info.Holder()); + const string& path = request->Referrer(); + info.GetReturnValue().Set( + String::New(path.c_str(), static_cast<int>(path.length()))); +} + + +void JsHttpRequestProcessor::GetHost(Local<String> name, + const PropertyCallbackInfo<Value>& info) { + HttpRequest* request = UnwrapRequest(info.Holder()); + const string& path = request->Host(); + info.GetReturnValue().Set( + String::New(path.c_str(), static_cast<int>(path.length()))); +} + + +void JsHttpRequestProcessor::GetUserAgent( + Local<String> name, + const PropertyCallbackInfo<Value>& info) { + HttpRequest* request = UnwrapRequest(info.Holder()); + const string& path = request->UserAgent(); + info.GetReturnValue().Set( + String::New(path.c_str(), static_cast<int>(path.length()))); +} + + +Handle<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate( + Isolate* isolate) { + HandleScope handle_scope(isolate); + + Handle<ObjectTemplate> result = ObjectTemplate::New(); + result->SetInternalFieldCount(1); + + // Add accessors for each of the fields of the request. + result->SetAccessor(String::NewSymbol("path"), GetPath); + result->SetAccessor(String::NewSymbol("referrer"), GetReferrer); + result->SetAccessor(String::NewSymbol("host"), GetHost); + result->SetAccessor(String::NewSymbol("userAgent"), GetUserAgent); + + // Again, return the result through the current handle scope. + return handle_scope.Close(result); +} + + +// --- Test --- + + +void HttpRequestProcessor::Log(const char* event) { + printf("Logged: %s\n", event); +} + + +/** + * A simplified http request. + */ +class StringHttpRequest : public HttpRequest { + public: + StringHttpRequest(const string& path, + const string& referrer, + const string& host, + const string& user_agent); + virtual const string& Path() { return path_; } + virtual const string& Referrer() { return referrer_; } + virtual const string& Host() { return host_; } + virtual const string& UserAgent() { return user_agent_; } + private: + string path_; + string referrer_; + string host_; + string user_agent_; +}; + + +StringHttpRequest::StringHttpRequest(const string& path, + const string& referrer, + const string& host, + const string& user_agent) + : path_(path), + referrer_(referrer), + host_(host), + user_agent_(user_agent) { } + + +void ParseOptions(int argc, + char* argv[], + map<string, string>& options, + string* file) { + for (int i = 1; i < argc; i++) { + string arg = argv[i]; + size_t index = arg.find('=', 0); + if (index == string::npos) { + *file = arg; + } else { + string key = arg.substr(0, index); + string value = arg.substr(index+1); + options[key] = value; + } + } +} + + +// Reads a file into a v8 string. +Handle<String> ReadFile(const string& name) { + FILE* file = fopen(name.c_str(), "rb"); + if (file == NULL) return Handle<String>(); + + fseek(file, 0, SEEK_END); + int size = ftell(file); + rewind(file); + + char* chars = new char[size + 1]; + chars[size] = '\0'; + for (int i = 0; i < size;) { + int read = static_cast<int>(fread(&chars[i], 1, size - i, file)); + i += read; + } + fclose(file); + Handle<String> result = String::New(chars, size); + delete[] chars; + return result; +} + + +const int kSampleSize = 6; +StringHttpRequest kSampleRequests[kSampleSize] = { + StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"), + StringHttpRequest("/", "localhost", "google.net", "firefox"), + StringHttpRequest("/", "localhost", "google.org", "safari"), + StringHttpRequest("/", "localhost", "yahoo.com", "ie"), + StringHttpRequest("/", "localhost", "yahoo.com", "safari"), + StringHttpRequest("/", "localhost", "yahoo.com", "firefox") +}; + + +bool ProcessEntries(HttpRequestProcessor* processor, int count, + StringHttpRequest* reqs) { + for (int i = 0; i < count; i++) { + if (!processor->Process(&reqs[i])) + return false; + } + return true; +} + + +void PrintMap(map<string, string>* m) { + for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) { + pair<string, string> entry = *i; + printf("%s: %s\n", entry.first.c_str(), entry.second.c_str()); + } +} + + +int main(int argc, char* argv[]) { + v8::V8::InitializeICU(); + map<string, string> options; + string file; + ParseOptions(argc, argv, options, &file); + if (file.empty()) { + fprintf(stderr, "No script was specified.\n"); + return 1; + } + Isolate* isolate = Isolate::GetCurrent(); + HandleScope scope(isolate); + Handle<String> source = ReadFile(file); + if (source.IsEmpty()) { + fprintf(stderr, "Error reading '%s'.\n", file.c_str()); + return 1; + } + JsHttpRequestProcessor processor(isolate, source); + map<string, string> output; + if (!processor.Initialize(&options, &output)) { + fprintf(stderr, "Error initializing processor.\n"); + return 1; + } + if (!ProcessEntries(&processor, kSampleSize, kSampleRequests)) + return 1; + PrintMap(&output); +} diff --git a/chromium/v8/samples/samples.gyp b/chromium/v8/samples/samples.gyp new file mode 100644 index 00000000000..be7b9ea696c --- /dev/null +++ b/chromium/v8/samples/samples.gyp @@ -0,0 +1,76 @@ +# Copyright 2012 the V8 project authors. All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +{ + 'variables': { + 'v8_code': 1, + 'v8_enable_i18n_support%': 0, + }, + 'includes': ['../build/toolchain.gypi', '../build/features.gypi'], + 'target_defaults': { + 'type': 'executable', + 'dependencies': [ + '../tools/gyp/v8.gyp:v8', + ], + 'include_dirs': [ + '../include', + ], + 'conditions': [ + ['v8_enable_i18n_support==1', { + 'dependencies': [ + '<(DEPTH)/third_party/icu/icu.gyp:icui18n', + '<(DEPTH)/third_party/icu/icu.gyp:icuuc', + ], + }], + ['OS=="win" and v8_enable_i18n_support==1', { + 'dependencies': [ + '<(DEPTH)/third_party/icu/icu.gyp:icudata', + ], + }], + ], + }, + 'targets': [ + { + 'target_name': 'shell', + 'sources': [ + 'shell.cc', + ], + }, + { + 'target_name': 'process', + 'sources': [ + 'process.cc', + ], + }, + { + 'target_name': 'lineprocessor', + 'sources': [ + 'lineprocessor.cc', + ], + } + ], +} diff --git a/chromium/v8/samples/shell.cc b/chromium/v8/samples/shell.cc new file mode 100644 index 00000000000..710547c3419 --- /dev/null +++ b/chromium/v8/samples/shell.cc @@ -0,0 +1,355 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include <v8.h> +#include <assert.h> +#include <fcntl.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> + +#ifdef COMPRESS_STARTUP_DATA_BZ2 +#error Using compressed startup data is not supported for this sample +#endif + +/** + * This sample program shows how to implement a simple javascript shell + * based on V8. This includes initializing V8 with command line options, + * creating global functions, compiling and executing strings. + * + * For a more sophisticated shell, consider using the debug shell D8. + */ + + +v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate); +void RunShell(v8::Handle<v8::Context> context); +int RunMain(v8::Isolate* isolate, int argc, char* argv[]); +bool ExecuteString(v8::Isolate* isolate, + v8::Handle<v8::String> source, + v8::Handle<v8::Value> name, + bool print_result, + bool report_exceptions); +void Print(const v8::FunctionCallbackInfo<v8::Value>& args); +void Read(const v8::FunctionCallbackInfo<v8::Value>& args); +void Load(const v8::FunctionCallbackInfo<v8::Value>& args); +void Quit(const v8::FunctionCallbackInfo<v8::Value>& args); +void Version(const v8::FunctionCallbackInfo<v8::Value>& args); +v8::Handle<v8::String> ReadFile(const char* name); +void ReportException(v8::Isolate* isolate, v8::TryCatch* handler); + + +static bool run_shell; + + +int main(int argc, char* argv[]) { + v8::V8::InitializeICU(); + v8::V8::SetFlagsFromCommandLine(&argc, argv, true); + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + run_shell = (argc == 1); + int result; + { + v8::HandleScope handle_scope(isolate); + v8::Handle<v8::Context> context = CreateShellContext(isolate); + if (context.IsEmpty()) { + fprintf(stderr, "Error creating context\n"); + return 1; + } + context->Enter(); + result = RunMain(isolate, argc, argv); + if (run_shell) RunShell(context); + context->Exit(); + } + v8::V8::Dispose(); + return result; +} + + +// Extracts a C string from a V8 Utf8Value. +const char* ToCString(const v8::String::Utf8Value& value) { + return *value ? *value : "<string conversion failed>"; +} + + +// Creates a new execution environment containing the built-in +// functions. +v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate) { + // Create a template for the global object. + v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); + // Bind the global 'print' function to the C++ Print callback. + global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)); + // Bind the global 'read' function to the C++ Read callback. + global->Set(v8::String::New("read"), v8::FunctionTemplate::New(Read)); + // Bind the global 'load' function to the C++ Load callback. + global->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load)); + // Bind the 'quit' function + global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit)); + // Bind the 'version' function + global->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version)); + + return v8::Context::New(isolate, NULL, global); +} + + +// The callback that is invoked by v8 whenever the JavaScript 'print' +// function is called. Prints its arguments on stdout separated by +// spaces and ending with a newline. +void Print(const v8::FunctionCallbackInfo<v8::Value>& args) { + bool first = true; + for (int i = 0; i < args.Length(); i++) { + v8::HandleScope handle_scope(args.GetIsolate()); + if (first) { + first = false; + } else { + printf(" "); + } + v8::String::Utf8Value str(args[i]); + const char* cstr = ToCString(str); + printf("%s", cstr); + } + printf("\n"); + fflush(stdout); +} + + +// The callback that is invoked by v8 whenever the JavaScript 'read' +// function is called. This function loads the content of the file named in +// the argument into a JavaScript string. +void Read(const v8::FunctionCallbackInfo<v8::Value>& args) { + if (args.Length() != 1) { + v8::ThrowException(v8::String::New("Bad parameters")); + return; + } + v8::String::Utf8Value file(args[0]); + if (*file == NULL) { + v8::ThrowException(v8::String::New("Error loading file")); + return; + } + v8::Handle<v8::String> source = ReadFile(*file); + if (source.IsEmpty()) { + v8::ThrowException(v8::String::New("Error loading file")); + return; + } + args.GetReturnValue().Set(source); +} + + +// The callback that is invoked by v8 whenever the JavaScript 'load' +// function is called. Loads, compiles and executes its argument +// JavaScript file. +void Load(const v8::FunctionCallbackInfo<v8::Value>& args) { + for (int i = 0; i < args.Length(); i++) { + v8::HandleScope handle_scope(args.GetIsolate()); + v8::String::Utf8Value file(args[i]); + if (*file == NULL) { + v8::ThrowException(v8::String::New("Error loading file")); + return; + } + v8::Handle<v8::String> source = ReadFile(*file); + if (source.IsEmpty()) { + v8::ThrowException(v8::String::New("Error loading file")); + return; + } + if (!ExecuteString(args.GetIsolate(), + source, + v8::String::New(*file), + false, + false)) { + v8::ThrowException(v8::String::New("Error executing file")); + return; + } + } +} + + +// The callback that is invoked by v8 whenever the JavaScript 'quit' +// function is called. Quits. +void Quit(const v8::FunctionCallbackInfo<v8::Value>& args) { + // If not arguments are given args[0] will yield undefined which + // converts to the integer value 0. + int exit_code = args[0]->Int32Value(); + fflush(stdout); + fflush(stderr); + exit(exit_code); +} + + +void Version(const v8::FunctionCallbackInfo<v8::Value>& args) { + args.GetReturnValue().Set(v8::String::New(v8::V8::GetVersion())); +} + + +// Reads a file into a v8 string. +v8::Handle<v8::String> ReadFile(const char* name) { + FILE* file = fopen(name, "rb"); + if (file == NULL) return v8::Handle<v8::String>(); + + fseek(file, 0, SEEK_END); + int size = ftell(file); + rewind(file); + + char* chars = new char[size + 1]; + chars[size] = '\0'; + for (int i = 0; i < size;) { + int read = static_cast<int>(fread(&chars[i], 1, size - i, file)); + i += read; + } + fclose(file); + v8::Handle<v8::String> result = v8::String::New(chars, size); + delete[] chars; + return result; +} + + +// Process remaining command line arguments and execute files +int RunMain(v8::Isolate* isolate, int argc, char* argv[]) { + for (int i = 1; i < argc; i++) { + const char* str = argv[i]; + if (strcmp(str, "--shell") == 0) { + run_shell = true; + } else if (strcmp(str, "-f") == 0) { + // Ignore any -f flags for compatibility with the other stand- + // alone JavaScript engines. + continue; + } else if (strncmp(str, "--", 2) == 0) { + fprintf(stderr, + "Warning: unknown flag %s.\nTry --help for options\n", str); + } else if (strcmp(str, "-e") == 0 && i + 1 < argc) { + // Execute argument given to -e option directly. + v8::Handle<v8::String> file_name = v8::String::New("unnamed"); + v8::Handle<v8::String> source = v8::String::New(argv[++i]); + if (!ExecuteString(isolate, source, file_name, false, true)) return 1; + } else { + // Use all other arguments as names of files to load and run. + v8::Handle<v8::String> file_name = v8::String::New(str); + v8::Handle<v8::String> source = ReadFile(str); + if (source.IsEmpty()) { + fprintf(stderr, "Error reading '%s'\n", str); + continue; + } + if (!ExecuteString(isolate, source, file_name, false, true)) return 1; + } + } + return 0; +} + + +// The read-eval-execute loop of the shell. +void RunShell(v8::Handle<v8::Context> context) { + fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion()); + static const int kBufferSize = 256; + // Enter the execution environment before evaluating any code. + v8::Context::Scope context_scope(context); + v8::Local<v8::String> name(v8::String::New("(shell)")); + while (true) { + char buffer[kBufferSize]; + fprintf(stderr, "> "); + char* str = fgets(buffer, kBufferSize, stdin); + if (str == NULL) break; + v8::HandleScope handle_scope(context->GetIsolate()); + ExecuteString(context->GetIsolate(), + v8::String::New(str), + name, + true, + true); + } + fprintf(stderr, "\n"); +} + + +// Executes a string within the current v8 context. +bool ExecuteString(v8::Isolate* isolate, + v8::Handle<v8::String> source, + v8::Handle<v8::Value> name, + bool print_result, + bool report_exceptions) { + v8::HandleScope handle_scope(isolate); + v8::TryCatch try_catch; + v8::Handle<v8::Script> script = v8::Script::Compile(source, name); + if (script.IsEmpty()) { + // Print errors that happened during compilation. + if (report_exceptions) + ReportException(isolate, &try_catch); + return false; + } else { + v8::Handle<v8::Value> result = script->Run(); + if (result.IsEmpty()) { + assert(try_catch.HasCaught()); + // Print errors that happened during execution. + if (report_exceptions) + ReportException(isolate, &try_catch); + return false; + } else { + assert(!try_catch.HasCaught()); + if (print_result && !result->IsUndefined()) { + // If all went well and the result wasn't undefined then print + // the returned value. + v8::String::Utf8Value str(result); + const char* cstr = ToCString(str); + printf("%s\n", cstr); + } + return true; + } + } +} + + +void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) { + v8::HandleScope handle_scope(isolate); + v8::String::Utf8Value exception(try_catch->Exception()); + const char* exception_string = ToCString(exception); + v8::Handle<v8::Message> message = try_catch->Message(); + if (message.IsEmpty()) { + // V8 didn't provide any extra information about this error; just + // print the exception. + fprintf(stderr, "%s\n", exception_string); + } else { + // Print (filename):(line number): (message). + v8::String::Utf8Value filename(message->GetScriptResourceName()); + const char* filename_string = ToCString(filename); + int linenum = message->GetLineNumber(); + fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string); + // Print line of source code. + v8::String::Utf8Value sourceline(message->GetSourceLine()); + const char* sourceline_string = ToCString(sourceline); + fprintf(stderr, "%s\n", sourceline_string); + // Print wavy underline (GetUnderline is deprecated). + int start = message->GetStartColumn(); + for (int i = 0; i < start; i++) { + fprintf(stderr, " "); + } + int end = message->GetEndColumn(); + for (int i = start; i < end; i++) { + fprintf(stderr, "^"); + } + fprintf(stderr, "\n"); + v8::String::Utf8Value stack_trace(try_catch->StackTrace()); + if (stack_trace.length() > 0) { + const char* stack_trace_string = ToCString(stack_trace); + fprintf(stderr, "%s\n", stack_trace_string); + } + } +} |