diff options
author | Ben Murdoch <benm@google.com> | 2014-11-26 15:28:44 +0000 |
---|---|---|
committer | Ben Murdoch <benm@google.com> | 2014-12-04 14:47:29 +0000 |
commit | b8a8cc1952d61a2f3a2568848933943a543b5d3e (patch) | |
tree | 83e9846202f2a441db91efdd164d7d8478ba9897 /samples | |
parent | b7a971bd8c35b5952b1f25fca56de6113506d3da (diff) | |
download | v8-b8a8cc1952d61a2f3a2568848933943a543b5d3e.tar.gz |
Upgrade to 3.29
Update V8 to 3.29.88.17 and update makefiles to support building on
all the relevant platforms.
Bug: 17370214
Change-Id: Ia3407c157fd8d72a93e23d8318ccaf6ecf77fa4e
Diffstat (limited to 'samples')
-rw-r--r-- | samples/lineprocessor.cc | 202 | ||||
-rw-r--r-- | samples/process.cc | 242 | ||||
-rw-r--r-- | samples/samples.gyp | 30 | ||||
-rw-r--r-- | samples/shell.cc | 226 |
4 files changed, 386 insertions, 314 deletions
diff --git a/samples/lineprocessor.cc b/samples/lineprocessor.cc index 1606a8f9..69bfab49 100644 --- a/samples/lineprocessor.cc +++ b/samples/lineprocessor.cc @@ -1,4 +1,4 @@ -// Copyright 2009 the V8 project authors. All rights reserved. +// 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: @@ -25,24 +25,15 @@ // (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 <include/v8.h> -// This controls whether this sample is compiled with debugger support. -// You may trace its usages in source text to see what parts of program -// are responsible for debugging support. -// Note that V8 itself should be compiled with enabled debugger support -// to have it all working. -#define SUPPORT_DEBUGGING - -#include <v8.h> - -#ifdef SUPPORT_DEBUGGING -#include <v8-debug.h> -#endif +#include <include/libplatform/libplatform.h> +#include <include/v8-debug.h> #include <fcntl.h> -#include <string.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> /** * This sample program should demonstrate certain aspects of debugging @@ -79,25 +70,6 @@ while (true) { 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 { @@ -106,52 +78,29 @@ enum MainCycleType { }; const char* ToCString(const v8::String::Utf8Value& value); -void ReportException(v8::TryCatch* handler); -v8::Handle<v8::String> ReadFile(const char* name); +void ReportException(v8::Isolate* isolate, v8::TryCatch* handler); +v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name); v8::Handle<v8::String> ReadLine(); -v8::Handle<v8::Value> Print(const v8::Arguments& args); -v8::Handle<v8::Value> ReadLine(const v8::Arguments& args); -bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context, +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 SUPPORT_DEBUGGING 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::Context::Scope scope(debug_message_context); - - v8::Debug::ProcessDebugMessages(); -} -#endif - - int RunMain(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); - v8::HandleScope handle_scope; + v8::Isolate* isolate = v8::Isolate::New(); + v8::Isolate::Scope isolate_scope(isolate); + v8::HandleScope handle_scope(isolate); - v8::Handle<v8::String> script_source(NULL); - v8::Handle<v8::Value> script_name(NULL); + v8::Handle<v8::String> script_source; + v8::Handle<v8::Value> script_name; int script_param_counter = 0; -#ifdef SUPPORT_DEBUGGING - int port_number = -1; - bool wait_for_connection = false; - bool support_callback = false; -#endif - MainCycleType cycle_type = CycleInCpp; for (int i = 1; i < argc; i++) { @@ -164,26 +113,17 @@ int RunMain(int argc, char* argv[]) { cycle_type = CycleInCpp; } else if (strcmp(str, "--main-cycle-in-js") == 0) { cycle_type = CycleInJs; -#ifdef SUPPORT_DEBUGGING - } 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 } 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"); + script_source = v8::String::NewFromUtf8(isolate, argv[i + 1]); + script_name = v8::String::NewFromUtf8(isolate, "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); + script_source = ReadFile(isolate, str); + script_name = v8::String::NewFromUtf8(isolate, str); if (script_source.IsEmpty()) { printf("Error reading '%s'\n", str); return 1; @@ -202,36 +142,25 @@ int RunMain(int argc, char* argv[]) { } // Create a template for the global object. - v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); + v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate); // Bind the global 'print' function to the C++ Print callback. - global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)); + global->Set(v8::String::NewFromUtf8(isolate, "print"), + v8::FunctionTemplate::New(isolate, 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)); + global->Set(v8::String::NewFromUtf8(isolate, "read_line"), + v8::FunctionTemplate::New(isolate, ReadLine)); } // Create a new execution environment containing the built-in // functions - v8::Handle<v8::Context> context = v8::Context::New(NULL, global); + v8::Handle<v8::Context> context = v8::Context::New(isolate, NULL, global); // Enter the newly created execution environment. v8::Context::Scope context_scope(context); -#ifdef SUPPORT_DEBUGGING - debug_message_context = v8::Persistent<v8::Context>::New(context); - - v8::Locker locker; - - if (support_callback) { - v8::Debug::SetDebugMessageDispatchHandler(DispatchDebugMessages, true); - } - - if (port_number != -1) { - v8::Debug::EnableAgent("lineprocessor", port_number, wait_for_connection); - } -#endif + debug_message_context.Reset(isolate, context); bool report_exceptions = true; @@ -239,11 +168,12 @@ int RunMain(int argc, char* argv[]) { { // Compile script in try/catch context. v8::TryCatch try_catch; - script = v8::Script::Compile(script_source, script_name); + v8::ScriptOrigin origin(script_name); + script = v8::Script::Compile(script_source, &origin); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions) - ReportException(&try_catch); + ReportException(isolate, &try_catch); return 1; } } @@ -254,13 +184,14 @@ int RunMain(int argc, char* argv[]) { script->Run(); if (try_catch.HasCaught()) { if (report_exceptions) - ReportException(&try_catch); + ReportException(isolate, &try_catch); return 1; } } if (cycle_type == CycleInCpp) { - bool res = RunCppCycle(script, v8::Context::GetCurrent(), + bool res = RunCppCycle(script, + isolate->GetCurrentContext(), report_exceptions); return !res; } else { @@ -270,15 +201,14 @@ int RunMain(int argc, char* argv[]) { } -bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context, +bool RunCppCycle(v8::Handle<v8::Script> script, + v8::Local<v8::Context> context, bool report_exceptions) { -#ifdef SUPPORT_DEBUGGING - v8::Locker lock; -#endif + v8::Isolate* isolate = context->GetIsolate(); - v8::Handle<v8::String> fun_name = v8::String::New("ProcessLine"); - v8::Handle<v8::Value> process_val = - v8::Context::GetCurrent()->Global()->Get(fun_name); + v8::Handle<v8::String> fun_name = + v8::String::NewFromUtf8(isolate, "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 @@ -293,10 +223,10 @@ bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context, while (!feof(stdin)) { - v8::HandleScope handle_scope; + v8::HandleScope handle_scope(isolate); v8::Handle<v8::String> input_line = ReadLine(); - if (input_line == v8::Undefined()) { + if (input_line == v8::Undefined(isolate)) { continue; } @@ -306,11 +236,11 @@ bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context, v8::Handle<v8::Value> result; { v8::TryCatch try_catch; - result = process_fun->Call(v8::Context::GetCurrent()->Global(), + result = process_fun->Call(isolate->GetCurrentContext()->Global(), argc, argv); if (try_catch.HasCaught()) { if (report_exceptions) - ReportException(&try_catch); + ReportException(isolate, &try_catch); return false; } } @@ -322,9 +252,16 @@ bool RunCppCycle(v8::Handle<v8::Script> script, v8::Local<v8::Context> context, return true; } + int main(int argc, char* argv[]) { + v8::V8::InitializeICU(); + v8::Platform* platform = v8::platform::CreateDefaultPlatform(); + v8::V8::InitializePlatform(platform); + v8::V8::Initialize(); int result = RunMain(argc, argv); v8::V8::Dispose(); + v8::V8::ShutdownPlatform(); + delete platform; return result; } @@ -336,7 +273,7 @@ const char* ToCString(const v8::String::Utf8Value& value) { // Reads a file into a v8 string. -v8::Handle<v8::String> ReadFile(const char* name) { +v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); @@ -347,18 +284,19 @@ v8::Handle<v8::String> ReadFile(const char* name) { char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { - int read = fread(&chars[i], 1, size - i, file); + 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); + v8::Handle<v8::String> result = + v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size); delete[] chars; return result; } -void ReportException(v8::TryCatch* try_catch) { - v8::HandleScope handle_scope; +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(); @@ -368,7 +306,7 @@ void ReportException(v8::TryCatch* try_catch) { printf("%s\n", exception_string); } else { // Print (filename):(line number): (message). - v8::String::Utf8Value filename(message->GetScriptResourceName()); + v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); printf("%s:%i: %s\n", filename_string, linenum, exception_string); @@ -393,10 +331,10 @@ void ReportException(v8::TryCatch* try_catch) { // 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. -v8::Handle<v8::Value> Print(const v8::Arguments& args) { +void Print(const v8::FunctionCallbackInfo<v8::Value>& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { - v8::HandleScope handle_scope; + v8::HandleScope handle_scope(args.GetIsolate()); if (first) { first = false; } else { @@ -408,40 +346,40 @@ v8::Handle<v8::Value> Print(const v8::Arguments& args) { } printf("\n"); fflush(stdout); - return v8::Undefined(); } // The callback that is invoked by v8 whenever the JavaScript 'read_line' // function is called. Reads a string from standard input and returns. -v8::Handle<v8::Value> ReadLine(const v8::Arguments& args) { +void ReadLine(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() > 0) { - return v8::ThrowException(v8::String::New("Unexpected arguments")); + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Unexpected arguments")); + return; } - return ReadLine(); + args.GetReturnValue().Set(ReadLine()); } + v8::Handle<v8::String> ReadLine() { const int kBufferSize = 1024 + 1; char buffer[kBufferSize]; char* res; { -#ifdef SUPPORT_DEBUGGING - v8::Unlocker unlocker; -#endif res = fgets(buffer, kBufferSize, stdin); } + v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (res == NULL) { - v8::Handle<v8::Primitive> t = v8::Undefined(); - return reinterpret_cast<v8::Handle<v8::String>&>(t); + v8::Handle<v8::Primitive> t = v8::Undefined(isolate); + return v8::Handle<v8::String>::Cast(t); } - // remove newline char + // Remove newline char for (char* pos = buffer; *pos != '\0'; pos++) { if (*pos == '\n') { *pos = '\0'; break; } } - return v8::String::New(buffer); + return v8::String::NewFromUtf8(isolate, buffer); } diff --git a/samples/process.cc b/samples/process.cc index c0cee4c2..e5c9b7a5 100644 --- a/samples/process.cc +++ b/samples/process.cc @@ -1,4 +1,4 @@ -// Copyright 2008 the V8 project authors. All rights reserved. +// 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: @@ -25,10 +25,12 @@ // (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 <include/v8.h> + +#include <include/libplatform/libplatform.h> -#include <string> #include <map> +#include <string> #ifdef COMPRESS_STARTUP_DATA_BZ2 #error Using compressed startup data is not supported for this sample @@ -54,6 +56,7 @@ class HttpRequest { virtual const string& UserAgent() = 0; }; + /** * The abstract superclass of http request processors. */ @@ -72,6 +75,7 @@ class HttpRequestProcessor { static void Log(const char* event); }; + /** * An http request processor that is scriptable using JavaScript. */ @@ -79,7 +83,8 @@ 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. - explicit JsHttpRequestProcessor(Handle<String> script) : script_(script) { } + JsHttpRequestProcessor(Isolate* isolate, Handle<String> script) + : isolate_(isolate), script_(script) { } virtual ~JsHttpRequestProcessor(); virtual bool Initialize(map<string, string>* opts, @@ -97,30 +102,36 @@ class JsHttpRequestProcessor : public HttpRequestProcessor { // Constructs the template that describes the JavaScript wrapper // type for requests. - static Handle<ObjectTemplate> MakeRequestTemplate(); - static Handle<ObjectTemplate> MakeMapTemplate(); + static Handle<ObjectTemplate> MakeRequestTemplate(Isolate* isolate); + static Handle<ObjectTemplate> MakeMapTemplate(Isolate* isolate); // Callbacks that access the individual fields of request objects. - static Handle<Value> GetPath(Local<String> name, const AccessorInfo& info); - static Handle<Value> GetReferrer(Local<String> name, - const AccessorInfo& info); - static Handle<Value> GetHost(Local<String> name, const AccessorInfo& info); - static Handle<Value> GetUserAgent(Local<String> name, - const AccessorInfo& info); + 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 Handle<Value> MapGet(Local<String> name, const AccessorInfo& info); - static Handle<Value> MapSet(Local<String> name, - Local<Value> value, - const AccessorInfo& info); + 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. - static Handle<Object> WrapMap(map<string, string>* obj); + Handle<Object> WrapMap(map<string, string>* obj); static map<string, string>* UnwrapMap(Handle<Object> obj); - static Handle<Object> WrapRequest(HttpRequest* 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_; @@ -128,18 +139,18 @@ class JsHttpRequestProcessor : public HttpRequestProcessor { static Persistent<ObjectTemplate> map_template_; }; + // ------------------------- // --- P r o c e s s o r --- // ------------------------- -static Handle<Value> LogCallback(const Arguments& args) { - if (args.Length() < 1) return v8::Undefined(); - HandleScope scope; +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); - return v8::Undefined(); } @@ -147,23 +158,25 @@ static Handle<Value> LogCallback(const Arguments& args) { bool JsHttpRequestProcessor::Initialize(map<string, string>* opts, map<string, string>* output) { // Create a handle scope to hold the temporary references. - HandleScope handle_scope; + 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)); + Handle<ObjectTemplate> global = ObjectTemplate::New(GetIsolate()); + global->Set(String::NewFromUtf8(GetIsolate(), "log"), + FunctionTemplate::New(GetIsolate(), 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. - context_ = Context::New(NULL, global); + 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_); + Context::Scope context_scope(context); // Make the options mapping available within the context if (!InstallMaps(opts, output)) @@ -175,8 +188,8 @@ bool JsHttpRequestProcessor::Initialize(map<string, string>* opts, // 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); + Handle<String> process_name = String::NewFromUtf8(GetIsolate(), "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 @@ -187,7 +200,7 @@ bool JsHttpRequestProcessor::Initialize(map<string, string>* opts, // Store the function in a Persistent handle, since we also want // that to remain after this call returns - process_ = Persistent<Function>::New(process_fun); + process_.Reset(GetIsolate(), process_fun); // All done; all went well return true; @@ -195,7 +208,7 @@ bool JsHttpRequestProcessor::Initialize(map<string, string>* opts, bool JsHttpRequestProcessor::ExecuteScript(Handle<String> script) { - HandleScope handle_scope; + 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. @@ -225,16 +238,21 @@ bool JsHttpRequestProcessor::ExecuteScript(Handle<String> script) { bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts, map<string, string>* output) { - HandleScope handle_scope; + 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); + context->Global()->Set(String::NewFromUtf8(GetIsolate(), "options"), + opts_obj); Handle<Object> output_obj = WrapMap(output); - context_->Global()->Set(String::New("output"), output_obj); + context->Global()->Set(String::NewFromUtf8(GetIsolate(), "output"), + output_obj); return true; } @@ -242,11 +260,14 @@ bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts, bool JsHttpRequestProcessor::Process(HttpRequest* request) { // Create a handle scope to keep the temporary object references. - HandleScope handle_scope; + 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_); + Context::Scope context_scope(context); // Wrap the C++ request object in a JavaScript wrapper Handle<Object> request_obj = WrapRequest(request); @@ -258,7 +279,9 @@ bool JsHttpRequestProcessor::Process(HttpRequest* request) { // and one argument, the request. const int argc = 1; Handle<Value> argv[argc] = { request_obj }; - Handle<Value> result = process_->Call(context_->Global(), argc, argv); + 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); @@ -273,8 +296,8 @@ JsHttpRequestProcessor::~JsHttpRequestProcessor() { // Dispose the persistent handles. When noone else has any // references to the objects stored in the handles they will be // automatically reclaimed. - context_.Dispose(); - process_.Dispose(); + context_.Reset(); + process_.Reset(); } @@ -290,22 +313,23 @@ Persistent<ObjectTemplate> JsHttpRequestProcessor::map_template_; // JavaScript object. Handle<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) { // Handle scope for temporary handles. - HandleScope handle_scope; + EscapableHandleScope 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(); - map_template_ = Persistent<ObjectTemplate>::New(raw_template); + Handle<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate()); + map_template_.Reset(GetIsolate(), raw_template); } - Handle<ObjectTemplate> templ = map_template_; + Handle<ObjectTemplate> templ = + Local<ObjectTemplate>::New(GetIsolate(), map_template_); // Create an empty map wrapper. - Handle<Object> result = templ->NewInstance(); + Local<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); + Handle<External> map_ptr = External::New(GetIsolate(), obj); // Store the map pointer in the JavaScript wrapper. result->SetInternalField(0, map_ptr); @@ -314,7 +338,7 @@ Handle<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) { // 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); + return handle_scope.Escape(result); } @@ -335,8 +359,8 @@ string ObjectToString(Local<Value> value) { } -Handle<Value> JsHttpRequestProcessor::MapGet(Local<String> name, - const AccessorInfo& info) { +void JsHttpRequestProcessor::MapGet(Local<String> name, + const PropertyCallbackInfo<Value>& info) { // Fetch the map wrapped by this object. map<string, string>* obj = UnwrapMap(info.Holder()); @@ -347,17 +371,19 @@ Handle<Value> JsHttpRequestProcessor::MapGet(Local<String> name, 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 Handle<Value>(); + if (iter == obj->end()) return; // Otherwise fetch the value and wrap it in a JavaScript string const string& value = (*iter).second; - return String::New(value.c_str(), value.length()); + info.GetReturnValue().Set(String::NewFromUtf8( + info.GetIsolate(), value.c_str(), String::kNormalString, + static_cast<int>(value.length()))); } -Handle<Value> JsHttpRequestProcessor::MapSet(Local<String> name, - Local<Value> value_obj, - const AccessorInfo& info) { +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()); @@ -369,19 +395,20 @@ Handle<Value> JsHttpRequestProcessor::MapSet(Local<String> name, (*obj)[key] = value; // Return the value; any non-empty handle will work. - return value_obj; + info.GetReturnValue().Set(value_obj); } -Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate() { - HandleScope handle_scope; +Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate( + Isolate* isolate) { + EscapableHandleScope handle_scope(isolate); - Handle<ObjectTemplate> result = ObjectTemplate::New(); + Local<ObjectTemplate> result = ObjectTemplate::New(isolate); result->SetInternalFieldCount(1); result->SetNamedPropertyHandler(MapGet, MapSet); // Again, return the result through the current handle scope. - return handle_scope.Close(result); + return handle_scope.Escape(result); } @@ -395,22 +422,23 @@ Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate() { */ Handle<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) { // Handle scope for temporary handles. - HandleScope handle_scope; + EscapableHandleScope 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(); - request_template_ = Persistent<ObjectTemplate>::New(raw_template); + Handle<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate()); + request_template_.Reset(GetIsolate(), raw_template); } - Handle<ObjectTemplate> templ = request_template_; + Handle<ObjectTemplate> templ = + Local<ObjectTemplate>::New(GetIsolate(), request_template_); // Create an empty http request wrapper. - Handle<Object> result = templ->NewInstance(); + Local<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); + Handle<External> request_ptr = External::New(GetIsolate(), request); // Store the request pointer in the JavaScript wrapper. result->SetInternalField(0, request_ptr); @@ -419,7 +447,7 @@ Handle<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) { // 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); + return handle_scope.Escape(result); } @@ -434,8 +462,8 @@ HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Handle<Object> obj) { } -Handle<Value> JsHttpRequestProcessor::GetPath(Local<String> name, - const AccessorInfo& info) { +void JsHttpRequestProcessor::GetPath(Local<String> name, + const PropertyCallbackInfo<Value>& info) { // Extract the C++ request object from the JavaScript wrapper. HttpRequest* request = UnwrapRequest(info.Holder()); @@ -443,48 +471,67 @@ Handle<Value> JsHttpRequestProcessor::GetPath(Local<String> name, const string& path = request->Path(); // Wrap the result in a JavaScript string and return it. - return String::New(path.c_str(), path.length()); + info.GetReturnValue().Set(String::NewFromUtf8( + info.GetIsolate(), path.c_str(), String::kNormalString, + static_cast<int>(path.length()))); } -Handle<Value> JsHttpRequestProcessor::GetReferrer(Local<String> name, - const AccessorInfo& info) { +void JsHttpRequestProcessor::GetReferrer( + Local<String> name, + const PropertyCallbackInfo<Value>& info) { HttpRequest* request = UnwrapRequest(info.Holder()); const string& path = request->Referrer(); - return String::New(path.c_str(), path.length()); + info.GetReturnValue().Set(String::NewFromUtf8( + info.GetIsolate(), path.c_str(), String::kNormalString, + static_cast<int>(path.length()))); } -Handle<Value> JsHttpRequestProcessor::GetHost(Local<String> name, - const AccessorInfo& info) { +void JsHttpRequestProcessor::GetHost(Local<String> name, + const PropertyCallbackInfo<Value>& info) { HttpRequest* request = UnwrapRequest(info.Holder()); const string& path = request->Host(); - return String::New(path.c_str(), path.length()); + info.GetReturnValue().Set(String::NewFromUtf8( + info.GetIsolate(), path.c_str(), String::kNormalString, + static_cast<int>(path.length()))); } -Handle<Value> JsHttpRequestProcessor::GetUserAgent(Local<String> name, - const AccessorInfo& info) { +void JsHttpRequestProcessor::GetUserAgent( + Local<String> name, + const PropertyCallbackInfo<Value>& info) { HttpRequest* request = UnwrapRequest(info.Holder()); const string& path = request->UserAgent(); - return String::New(path.c_str(), path.length()); + info.GetReturnValue().Set(String::NewFromUtf8( + info.GetIsolate(), path.c_str(), String::kNormalString, + static_cast<int>(path.length()))); } -Handle<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate() { - HandleScope handle_scope; +Handle<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate( + Isolate* isolate) { + EscapableHandleScope handle_scope(isolate); - Handle<ObjectTemplate> result = ObjectTemplate::New(); + Local<ObjectTemplate> result = ObjectTemplate::New(isolate); 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); + result->SetAccessor( + String::NewFromUtf8(isolate, "path", String::kInternalizedString), + GetPath); + result->SetAccessor( + String::NewFromUtf8(isolate, "referrer", String::kInternalizedString), + GetReferrer); + result->SetAccessor( + String::NewFromUtf8(isolate, "host", String::kInternalizedString), + GetHost); + result->SetAccessor( + String::NewFromUtf8(isolate, "userAgent", String::kInternalizedString), + GetUserAgent); // Again, return the result through the current handle scope. - return handle_scope.Close(result); + return handle_scope.Escape(result); } @@ -529,7 +576,7 @@ StringHttpRequest::StringHttpRequest(const string& path, void ParseOptions(int argc, char* argv[], - map<string, string>& options, + map<string, string>* options, string* file) { for (int i = 1; i < argc; i++) { string arg = argv[i]; @@ -539,14 +586,14 @@ void ParseOptions(int argc, } else { string key = arg.substr(0, index); string value = arg.substr(index+1); - options[key] = value; + (*options)[key] = value; } } } // Reads a file into a v8 string. -Handle<String> ReadFile(const string& name) { +Handle<String> ReadFile(Isolate* isolate, const string& name) { FILE* file = fopen(name.c_str(), "rb"); if (file == NULL) return Handle<String>(); @@ -557,11 +604,12 @@ Handle<String> ReadFile(const string& name) { char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { - int read = fread(&chars[i], 1, size - i, file); + int read = static_cast<int>(fread(&chars[i], 1, size - i, file)); i += read; } fclose(file); - Handle<String> result = String::New(chars, size); + Handle<String> result = + String::NewFromUtf8(isolate, chars, String::kNormalString, size); delete[] chars; return result; } @@ -597,20 +645,26 @@ void PrintMap(map<string, string>* m) { int main(int argc, char* argv[]) { + v8::V8::InitializeICU(); + v8::Platform* platform = v8::platform::CreateDefaultPlatform(); + v8::V8::InitializePlatform(platform); + v8::V8::Initialize(); map<string, string> options; string file; - ParseOptions(argc, argv, options, &file); + ParseOptions(argc, argv, &options, &file); if (file.empty()) { fprintf(stderr, "No script was specified.\n"); return 1; } - HandleScope scope; - Handle<String> source = ReadFile(file); + Isolate* isolate = Isolate::New(); + Isolate::Scope isolate_scope(isolate); + HandleScope scope(isolate); + Handle<String> source = ReadFile(isolate, file); if (source.IsEmpty()) { fprintf(stderr, "Error reading '%s'.\n", file.c_str()); return 1; } - JsHttpRequestProcessor processor(source); + JsHttpRequestProcessor processor(isolate, source); map<string, string> output; if (!processor.Initialize(&options, &output)) { fprintf(stderr, "Error initializing processor.\n"); diff --git a/samples/samples.gyp b/samples/samples.gyp index 55b2a98a..0c4c7056 100644 --- a/samples/samples.gyp +++ b/samples/samples.gyp @@ -1,4 +1,4 @@ -# Copyright 2011 the V8 project authors. All rights reserved. +# 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: @@ -26,14 +26,32 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. { - 'includes': ['../build/common.gypi'], + 'variables': { + 'v8_code': 1, + 'v8_enable_i18n_support%': 1, + }, + 'includes': ['../build/toolchain.gypi', '../build/features.gypi'], 'target_defaults': { 'type': 'executable', 'dependencies': [ '../tools/gyp/v8.gyp:v8', + '../tools/gyp/v8.gyp:v8_libplatform', ], 'include_dirs': [ - '../include', + '..', + ], + 'conditions': [ + ['v8_enable_i18n_support==1', { + 'dependencies': [ + '<(icu_gyp_path):icui18n', + '<(icu_gyp_path):icuuc', + ], + }], + ['OS=="win" and v8_enable_i18n_support==1', { + 'dependencies': [ + '<(icu_gyp_path):icudata', + ], + }], ], }, 'targets': [ @@ -48,6 +66,12 @@ 'sources': [ 'process.cc', ], + }, + { + 'target_name': 'lineprocessor', + 'sources': [ + 'lineprocessor.cc', + ], } ], } diff --git a/samples/shell.cc b/samples/shell.cc index b40eca2f..b66e8f74 100644 --- a/samples/shell.cc +++ b/samples/shell.cc @@ -1,4 +1,4 @@ -// Copyright 2011 the V8 project authors. All rights reserved. +// 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: @@ -25,12 +25,15 @@ // (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 <include/v8.h> + +#include <include/libplatform/libplatform.h> + #include <assert.h> #include <fcntl.h> -#include <string.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> #ifdef COMPRESS_STARTUP_DATA_BZ2 #error Using compressed startup data is not supported for this sample @@ -45,40 +48,63 @@ */ -v8::Persistent<v8::Context> CreateShellContext(); +v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate); void RunShell(v8::Handle<v8::Context> context); -int RunMain(int argc, char* argv[]); -bool ExecuteString(v8::Handle<v8::String> source, +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); -v8::Handle<v8::Value> Print(const v8::Arguments& args); -v8::Handle<v8::Value> Read(const v8::Arguments& args); -v8::Handle<v8::Value> Load(const v8::Arguments& args); -v8::Handle<v8::Value> Quit(const v8::Arguments& args); -v8::Handle<v8::Value> Version(const v8::Arguments& args); -v8::Handle<v8::String> ReadFile(const char* name); -void ReportException(v8::TryCatch* handler); +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(v8::Isolate* isolate, const char* name); +void ReportException(v8::Isolate* isolate, v8::TryCatch* handler); static bool run_shell; +class ShellArrayBufferAllocator : public v8::ArrayBuffer::Allocator { + public: + virtual void* Allocate(size_t length) { + void* data = AllocateUninitialized(length); + return data == NULL ? data : memset(data, 0, length); + } + virtual void* AllocateUninitialized(size_t length) { return malloc(length); } + virtual void Free(void* data, size_t) { free(data); } +}; + + int main(int argc, char* argv[]) { + v8::V8::InitializeICU(); + v8::Platform* platform = v8::platform::CreateDefaultPlatform(); + v8::V8::InitializePlatform(platform); + v8::V8::Initialize(); v8::V8::SetFlagsFromCommandLine(&argc, argv, true); + ShellArrayBufferAllocator array_buffer_allocator; + v8::V8::SetArrayBufferAllocator(&array_buffer_allocator); + v8::Isolate* isolate = v8::Isolate::New(); run_shell = (argc == 1); - v8::HandleScope handle_scope; - v8::Persistent<v8::Context> context = CreateShellContext(); - if (context.IsEmpty()) { - printf("Error creating context\n"); - return 1; + int result; + { + v8::Isolate::Scope isolate_scope(isolate); + v8::HandleScope handle_scope(isolate); + v8::Handle<v8::Context> context = CreateShellContext(isolate); + if (context.IsEmpty()) { + fprintf(stderr, "Error creating context\n"); + return 1; + } + v8::Context::Scope context_scope(context); + result = RunMain(isolate, argc, argv); + if (run_shell) RunShell(context); } - context->Enter(); - int result = RunMain(argc, argv); - if (run_shell) RunShell(context); - context->Exit(); - context.Dispose(); v8::V8::Dispose(); + v8::V8::ShutdownPlatform(); + delete platform; return result; } @@ -91,31 +117,36 @@ const char* ToCString(const v8::String::Utf8Value& value) { // Creates a new execution environment containing the built-in // functions. -v8::Persistent<v8::Context> CreateShellContext() { +v8::Handle<v8::Context> CreateShellContext(v8::Isolate* isolate) { // Create a template for the global object. - v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); + v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate); // Bind the global 'print' function to the C++ Print callback. - global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)); + global->Set(v8::String::NewFromUtf8(isolate, "print"), + v8::FunctionTemplate::New(isolate, Print)); // Bind the global 'read' function to the C++ Read callback. - global->Set(v8::String::New("read"), v8::FunctionTemplate::New(Read)); + global->Set(v8::String::NewFromUtf8(isolate, "read"), + v8::FunctionTemplate::New(isolate, Read)); // Bind the global 'load' function to the C++ Load callback. - global->Set(v8::String::New("load"), v8::FunctionTemplate::New(Load)); + global->Set(v8::String::NewFromUtf8(isolate, "load"), + v8::FunctionTemplate::New(isolate, Load)); // Bind the 'quit' function - global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(Quit)); + global->Set(v8::String::NewFromUtf8(isolate, "quit"), + v8::FunctionTemplate::New(isolate, Quit)); // Bind the 'version' function - global->Set(v8::String::New("version"), v8::FunctionTemplate::New(Version)); + global->Set(v8::String::NewFromUtf8(isolate, "version"), + v8::FunctionTemplate::New(isolate, Version)); - return v8::Context::New(NULL, global); + 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. -v8::Handle<v8::Value> Print(const v8::Arguments& args) { +void Print(const v8::FunctionCallbackInfo<v8::Value>& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { - v8::HandleScope handle_scope; + v8::HandleScope handle_scope(args.GetIsolate()); if (first) { first = false; } else { @@ -127,71 +158,85 @@ v8::Handle<v8::Value> Print(const v8::Arguments& args) { } printf("\n"); fflush(stdout); - return v8::Undefined(); } // 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. -v8::Handle<v8::Value> Read(const v8::Arguments& args) { +void Read(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 1) { - return v8::ThrowException(v8::String::New("Bad parameters")); + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Bad parameters")); + return; } v8::String::Utf8Value file(args[0]); if (*file == NULL) { - return v8::ThrowException(v8::String::New("Error loading file")); + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file")); + return; } - v8::Handle<v8::String> source = ReadFile(*file); + v8::Handle<v8::String> source = ReadFile(args.GetIsolate(), *file); if (source.IsEmpty()) { - return v8::ThrowException(v8::String::New("Error loading file")); + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file")); + return; } - return source; + 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. -v8::Handle<v8::Value> Load(const v8::Arguments& args) { +void Load(const v8::FunctionCallbackInfo<v8::Value>& args) { for (int i = 0; i < args.Length(); i++) { - v8::HandleScope handle_scope; + v8::HandleScope handle_scope(args.GetIsolate()); v8::String::Utf8Value file(args[i]); if (*file == NULL) { - return v8::ThrowException(v8::String::New("Error loading file")); + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file")); + return; } - v8::Handle<v8::String> source = ReadFile(*file); + v8::Handle<v8::String> source = ReadFile(args.GetIsolate(), *file); if (source.IsEmpty()) { - return v8::ThrowException(v8::String::New("Error loading file")); + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file")); + return; } - if (!ExecuteString(source, v8::String::New(*file), false, false)) { - return v8::ThrowException(v8::String::New("Error executing file")); + if (!ExecuteString(args.GetIsolate(), + source, + v8::String::NewFromUtf8(args.GetIsolate(), *file), + false, + false)) { + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file")); + return; } } - return v8::Undefined(); } // The callback that is invoked by v8 whenever the JavaScript 'quit' // function is called. Quits. -v8::Handle<v8::Value> Quit(const v8::Arguments& args) { +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); - return v8::Undefined(); } -v8::Handle<v8::Value> Version(const v8::Arguments& args) { - return v8::String::New(v8::V8::GetVersion()); +void Version(const v8::FunctionCallbackInfo<v8::Value>& args) { + args.GetReturnValue().Set( + v8::String::NewFromUtf8(args.GetIsolate(), v8::V8::GetVersion())); } // Reads a file into a v8 string. -v8::Handle<v8::String> ReadFile(const char* name) { +v8::Handle<v8::String> ReadFile(v8::Isolate* isolate, const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return v8::Handle<v8::String>(); @@ -202,18 +247,19 @@ v8::Handle<v8::String> ReadFile(const char* name) { char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { - int read = fread(&chars[i], 1, size - i, file); + 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); + v8::Handle<v8::String> result = + v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size); delete[] chars; return result; } // Process remaining command line arguments and execute files -int RunMain(int argc, char* argv[]) { +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) { @@ -223,21 +269,24 @@ int RunMain(int argc, char* argv[]) { // alone JavaScript engines. continue; } else if (strncmp(str, "--", 2) == 0) { - printf("Warning: unknown flag %s.\nTry --help for options\n", str); + 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(source, file_name, false, true)) return 1; + v8::Handle<v8::String> file_name = + v8::String::NewFromUtf8(isolate, "unnamed"); + v8::Handle<v8::String> source = + v8::String::NewFromUtf8(isolate, 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); + v8::Handle<v8::String> file_name = v8::String::NewFromUtf8(isolate, str); + v8::Handle<v8::String> source = ReadFile(isolate, str); if (source.IsEmpty()) { - printf("Error reading '%s'\n", str); + fprintf(stderr, "Error reading '%s'\n", str); continue; } - if (!ExecuteString(source, file_name, false, true)) return 1; + if (!ExecuteString(isolate, source, file_name, false, true)) return 1; } } return 0; @@ -246,35 +295,42 @@ int RunMain(int argc, char* argv[]) { // The read-eval-execute loop of the shell. void RunShell(v8::Handle<v8::Context> context) { - printf("V8 version %s [sample shell]\n", v8::V8::GetVersion()); + 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)")); + v8::Local<v8::String> name( + v8::String::NewFromUtf8(context->GetIsolate(), "(shell)")); while (true) { char buffer[kBufferSize]; - printf("> "); + fprintf(stderr, "> "); char* str = fgets(buffer, kBufferSize, stdin); if (str == NULL) break; - v8::HandleScope handle_scope; - ExecuteString(v8::String::New(str), name, true, true); + v8::HandleScope handle_scope(context->GetIsolate()); + ExecuteString(context->GetIsolate(), + v8::String::NewFromUtf8(context->GetIsolate(), str), + name, + true, + true); } - printf("\n"); + fprintf(stderr, "\n"); } // Executes a string within the current v8 context. -bool ExecuteString(v8::Handle<v8::String> source, +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; + v8::HandleScope handle_scope(isolate); v8::TryCatch try_catch; - v8::Handle<v8::Script> script = v8::Script::Compile(source, name); + v8::ScriptOrigin origin(name); + v8::Handle<v8::Script> script = v8::Script::Compile(source, &origin); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions) - ReportException(&try_catch); + ReportException(isolate, &try_catch); return false; } else { v8::Handle<v8::Value> result = script->Run(); @@ -282,7 +338,7 @@ bool ExecuteString(v8::Handle<v8::String> source, assert(try_catch.HasCaught()); // Print errors that happened during execution. if (report_exceptions) - ReportException(&try_catch); + ReportException(isolate, &try_catch); return false; } else { assert(!try_catch.HasCaught()); @@ -299,39 +355,39 @@ bool ExecuteString(v8::Handle<v8::String> source, } -void ReportException(v8::TryCatch* try_catch) { - v8::HandleScope handle_scope; +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); + fprintf(stderr, "%s\n", exception_string); } else { // Print (filename):(line number): (message). - v8::String::Utf8Value filename(message->GetScriptResourceName()); + v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); - printf("%s:%i: %s\n", filename_string, linenum, exception_string); + 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); - printf("%s\n", sourceline_string); + fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { - printf(" "); + fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { - printf("^"); + fprintf(stderr, "^"); } - printf("\n"); + fprintf(stderr, "\n"); v8::String::Utf8Value stack_trace(try_catch->StackTrace()); if (stack_trace.length() > 0) { const char* stack_trace_string = ToCString(stack_trace); - printf("%s\n", stack_trace_string); + fprintf(stderr, "%s\n", stack_trace_string); } } } |