JNIEXPORT jobject JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeEvalString (JNIEnv *env, jobject self, jstring source, jstring filename) { HandleScope scope(V8Runtime::v8_isolate); titanium::JNIScope jniScope(env); Local<Value> jsSource = TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, source); if (jsSource.IsEmpty() || !jsSource->IsString()) { LOGE(TAG, "Error converting Javascript string, aborting evalString"); return NULL; } Local<Value> jsFilename = TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, filename); TryCatch tryCatch(V8Runtime::v8_isolate); Local<Script> script = Script::Compile(jsSource.As<String>(), jsFilename.As<String>()); Local<Value> result = script->Run(); if (tryCatch.HasCaught()) { V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch); V8Util::reportException(V8Runtime::v8_isolate, tryCatch, true); return NULL; } return TypeConverter::jsValueToJavaObject(V8Runtime::v8_isolate, env, result); }
void exec(Isolate *isolate){ Isolate::Scope isolate_scope(isolate); // Create a stack-allocated handle scope. HandleScope handle_scope(isolate); // Create a new context. Local<Context> context = Context::New(isolate); // Enter the context for compiling and running the hello world script. Context::Scope context_scope(context); // Create a string containing the JavaScript source code. Local<String> source = String::NewFromUtf8(isolate, "'Hello' + ', World!'", NewStringType::kNormal).ToLocalChecked(); // Compile the source code. Local<Script> script = Script::Compile(context, source).ToLocalChecked(); // Run the script to get the result. Local<Value> result = script->Run(context).ToLocalChecked(); // Convert the result to an UTF8 string and print it. String::Utf8Value utf8(result); Print(" result --->", *utf8); }
extern "C" void init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> logFunction = FunctionTemplate::New(LogWrapper); target->Set(String::NewSymbol("_logString"), logFunction->GetFunction()); Local<FunctionTemplate> logKeyValueFunction = FunctionTemplate::New(LogKeyValueWrapper); target->Set(String::NewSymbol("_logKeyValueString"), logKeyValueFunction->GetFunction()); target->Set(String::NewSymbol("LOG_CRITICAL"), Integer::New(kPmLogLevel_Critical)); target->Set(String::NewSymbol("LOG_ERR"), Integer::New(kPmLogLevel_Error)); target->Set(String::NewSymbol("LOG_WARNING"), Integer::New(kPmLogLevel_Warning)); target->Set(String::NewSymbol("LOG_INFO"), Integer::New(kPmLogLevel_Info)); target->Set(String::NewSymbol("LOG_DEBUG"), Integer::New(kPmLogLevel_Debug)); Local<String> scriptText = String::New((const char*)pmloglib_js, pmloglib_js_len); Local<Script> script = Script::New(scriptText, String::New("pmloglib.js")); if (!script.IsEmpty()) { Local<Value> v = script->Run(); Local<Function> f = Local<Function>::Cast(v); Local<Context> current = Context::GetCurrent(); Handle<Value> argv[1]; argv[0] = target; f->Call(current->Global(), 1, &argv[0]); } else { cerr << "Script was empty." << endl; } }
bool v8test_eval() { BEGINTEST(); HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Local<Object> qmlglobal = Object::New(); qmlglobal->Set(String::New("a"), Integer::New(1922)); Local<Script> script = Script::Compile(String::New("eval(\"a\")"), NULL, NULL, Handle<String>(), Script::QmlMode); TryCatch tc; Local<Value> result = script->Run(qmlglobal); VERIFY(!tc.HasCaught()); VERIFY(result->Int32Value() == 1922); cleanup: context.Dispose(); ENDTEST(); }
ScriptValuePtr V8Engine::runScript(std::string script, std::string identifier) { HandleScope handleScope; TryCatch tc; Local<String> source = String::New(script.c_str()); // Build data ScriptOrigin origin(String::New(identifier.c_str())); // Compile the source code. Local<Script> code = Script::Compile(source, &origin); if (code.IsEmpty()) handleException(tc); // Run the script to get the result. Local<Value> result = code->Run(); if (result.IsEmpty()) handleException(tc); return ScriptValuePtr( new V8Value(this, result) ); }
stdext::ustring JavaScriptContext::ExecuteReturnString(const stdext::ustring & source, const stdext::ustring & name, stdext::ustring & error) { stdext::ustring resultString; error = wstringToUstring(L""); Locker locker(m_isolate); Isolate::Scope isolate_scope(m_isolate); { Context::Scope contextScope(*m_ctx); HandleScope scope; Local<String> scriptSource = String::New(reinterpret_cast<const uint16_t *>(source.c_str())); Local<String> scriptName = String::New(reinterpret_cast<const uint16_t *>(name.c_str())); Local<Script> script = Script::New(scriptSource, scriptName); Local<Value> result; { TryCatch tryCatch; result = script->Run(); if (!result.IsEmpty()) { String::Value value(result); resultString.append(reinterpret_cast<const char16_t *>(*value)); } if (tryCatch.HasCaught()) { error.append(wstringToUstring(L"Error running script: ")); error.append(name); error.append(wstringToUstring(L" - ")); String::Value stackTrace(tryCatch.StackTrace()); error.append(reinterpret_cast<const char16_t*>(*stackTrace)); } } } return resultString; }
Local< v8::Value > newFunction( const char *code ) { stringstream codeSS; codeSS << "____MontoToV8_newFunction_temp = " << code; string codeStr = codeSS.str(); Local< Script > compiled = Script::New( v8::String::New( codeStr.c_str() ) ); Local< Value > ret = compiled->Run(); return ret; }
void V8Engine::init() { Logging::log(Logging::DEBUG, "V8Engine::init:\r\n"); INDENT_LOG(Logging::DEBUG); HandleScope handleScope; // Create a template for the global object. Logging::log(Logging::DEBUG, "Creating global\r\n"); // _global = ObjectTemplate::New(); Logging::log(Logging::DEBUG, "Creating context\r\n"); context = Context::New(); //NULL, _global); context->Enter(); // Create our internal wrappers Logging::log(Logging::DEBUG, "Creating wrapper for global\r\n"); globalValue = ScriptValuePtr(new V8Value(this, context->Global())); #if 0 // Setup debugger, if required - XXX Doesn't work // Debug::SetDebugEventListener(debuggerListener); // runFile("src/thirdparty/v8/src/debug-delay.js"); // FIXME: remove hardcoded src/.. runFile("src/javascript/intensity/V8Debugger.js"); // FIXME: remove hardcoded src/javascript v8::Handle<v8::Value> result = ((V8Value*)(getGlobal()->getProperty("__debuggerListener").get()))->value; assert(result->IsObject()); Local<Object> debuggerListener = result->ToObject(); assert(debuggerListener->IsFunction()); Debug::SetDebugEventListener(debuggerListener); runScript("Debug.setBrzzzzzzzzzeakOnException()"); Local<String> source = String::New( "temp = function () { Debug.setBreakOnException(); return 5098; } " ); Local<Script> code = Script::Compile(source); Local<Value> result2 = code->Run(); printV8Value(result2, true); assert(result2->IsObject()); Local<Object> obj = result2->ToObject(); assert(obj->IsFunction()); Local<Function> func = Function::Cast(*obj); Handle<Value> output = Debug::Call(func); printV8Value(output, true); assert(0); #endif Logging::log(Logging::DEBUG, "V8Engine::init complete.\r\n"); }
void Module::Init(Isolate *isolate) { JEnv env; MODULE_CLASS = env.FindClass("com/tns/Module"); assert(MODULE_CLASS != nullptr); RESOLVE_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "resolvePath", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); assert(RESOLVE_PATH_METHOD_ID != nullptr); string requireFactoryScript = "(function () { " " function require_factory(requireInternal, dirName) { " " return function require(modulePath) { " " if(global.__requireOverride) { " " var result = global.__requireOverride(modulePath, dirName); " " if(result) { " " return result; " " } " " } " " return requireInternal(modulePath, dirName); " " } " " } " " return require_factory; " "})()"; auto source = ConvertToV8String(requireFactoryScript); auto context = isolate->GetCurrentContext(); Local<Script> script; auto maybeScript = Script::Compile(context, source).ToLocal(&script); assert(!script.IsEmpty()); Local<Value> result; auto maybeResult = script->Run(context).ToLocal(&result); assert(!result.IsEmpty() && result->IsFunction()); auto requireFactoryFunction = result.As<Function>(); auto cache = GetCache(isolate); cache->RequireFactoryFunction = new Persistent<Function>(isolate, requireFactoryFunction); auto requireFuncTemplate = FunctionTemplate::New(isolate, RequireCallback); auto requireFunc = requireFuncTemplate->GetFunction(); cache->RequireFunction = new Persistent<Function>(isolate, requireFunc); auto global = isolate->GetCurrentContext()->Global(); auto globalRequire = GetRequireFunction(isolate, Constants::APP_ROOT_FOLDER_PATH); global->Set(ConvertToV8String("require"), globalRequire); }
jobject NativePlatform::RunScript(JNIEnv *_env, jobject obj, jstring scriptFile) { JEnv env(_env); jobject res = nullptr; auto isolate = g_isolate; Isolate::Scope isolate_scope(isolate); HandleScope handleScope(isolate); auto context = isolate->GetCurrentContext(); auto filename = ArgConverter::jstringToString(scriptFile); auto src = File::ReadText(filename); auto source = ConvertToV8String(src); TryCatch tc; Local<Script> script; ScriptOrigin origin(ConvertToV8String(filename)); auto maybeScript = Script::Compile(context, source, &origin).ToLocal(&script); if(tc.HasCaught()) { throw NativeScriptException(tc, "Script " + filename + " contains compilation errors!"); } if (!script.IsEmpty()) { Local<Value> result; auto maybeResult = script->Run(context).ToLocal(&result); if(tc.HasCaught()) { throw NativeScriptException(tc, "Error running script " + filename); } if (!result.IsEmpty()) { res = ConvertJsValueToJavaObject(env, result, static_cast<int>(Type::Null)); } else { DEBUG_WRITE(">>runScript maybeResult is empty"); } } else { DEBUG_WRITE(">>runScript maybeScript is empty"); } return res; }
bool JSWrapper::execute( const char *scr, JSWrapperData *data, const char *fileName ) { HandleScope handle_scope( m_isolate ); Local<String> source = String::NewFromUtf8( m_isolate, scr, NewStringType::kNormal ).ToLocalChecked(); ScriptOrigin origin( v8::String::NewFromUtf8( m_isolate, fileName ? fileName : "Unknown" ) ); MaybeLocal<Script> maybeScript = Script::Compile( m_context, source, &origin ); bool success=false; if ( !maybeScript.IsEmpty() ) { Local<Script> script = maybeScript.ToLocalChecked(); MaybeLocal<Value> maybeResult = script->Run(m_context); if ( !maybeResult.IsEmpty() ) { Local<Value> result = maybeResult.ToLocalChecked(); if ( data ) { if ( result->IsNumber() ) data->setNumber( result->ToNumber()->Value() ); else if ( result->IsString() ) { String::Utf8Value utf8( result ); data->setString( *utf8 ); } else if ( result->IsBoolean() ) data->setBoolean( result->ToBoolean()->Value() ); else if ( result->IsObject() ) data->setObject( new JSWrapperObject( m_isolate, result->ToObject() ) ); else if ( result->IsNull() ) data->setNull(); else data->setUndefined(); } success=true; } } return success; }
Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) { HandleScope scope; TryCatch tryCatch; Local<Script> script = Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&tryCatch); exit(1); } Local<Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&tryCatch); exit(1); } return scope.Close(result); } // ExecuteString
//C++版本的loadJSCode Handle<Value> LoadJsCode(LPCWSTR cjs,LPCWSTR fn){ if(cjs==0) return Undefined(); if(fn==0) fn = NULL_STR; HandleScope store; Handle<String> js = String::New((uint16_t*)cjs); Handle<Value> name = String::New((uint16_t*)fn); TryCatch err; Local<Script> script = Script::Compile(js,name); while(!script.IsEmpty()){ Local<Value> result = script->Run(); if(err.HasCaught()) break;//这两种判断方式可能是等价的。 //if(result.IsEmpty()) break; return store.Close(result); } ReportError(err); return Undefined(); }
//*,{ // "type":"function", // "name":"run(js,[name])", // "text":"加载一段js代码字串, 并且返回执行结果. 这个函数类似于 PHP 的 require 函数, 但是参数不是文件名, 而是 js 代码字串。", // "param":[ // { // "type":"string", // "name":"js", // "text":"Javascript 脚本字串。" // }, // { // "type":"string", // "name":"[name]", // "text":"这个名称用于调试时候显示的文件名。" // } // ], // "return":{ // "type":"any", // "text":"返回脚本执行结果。" // }, // "example":[ // "run('new Function(a,b){return a+b;}','test');", // "//运行结果返回一个函数。" // ] //}//* Handle<Value> loadJsCode(const Arguments& args){ HandleScope store; TryCatch err; Handle<String> js; Handle<Value> name; if(args.Length()>0) js = args[0]->ToString(); if(args.Length()>1) name = args[1]; Local<Script> script = Script::Compile(args[0]->ToString(),name); while(!script.IsEmpty()){ Local<Value> result = script->Run(); if(result.IsEmpty()) break; return store.Close(result); } ReportError(err); return Undefined(); }
void debuggerListener(DebugEvent event, Handle<Object> exec_state, Handle<Object> event_data, Handle<Value> data) { printf("************************ V8 debugger ***********************\r\n"); HandleScope handleScope; Local<String> source = String::New( "temp = function (exec_state) { " " log(WARNING, 'halp now'); " " return serializeJSON(exec_state); " "} " ); Local<Script> code = Script::Compile(source); Local<Value> result = code->Run(); // printV8Value(result, true); assert(result->IsObject()); Local<Object> obj = result->ToObject(); assert(obj->IsFunction()); Local<Function> func = Function::Cast(*obj); Handle<Value> output = Debug::Call(func, exec_state); printV8Value(output, true); printV8Value(exec_state, true); printV8Value(event_data, true); printV8Value(data, true); /* Local<Object> _func = obj->Get(String::New(funcName.c_str()))->ToObject(); assert(_func->IsFunction()); Local<Function> func = Function::Cast(*_func); */ assert(0); }
Handle<Value> V8Util::executeString(Handle<String> source, Handle<Value> filename) { HandleScope scope; TryCatch tryCatch; Local<Script> script = Script::Compile(source, filename); if (script.IsEmpty()) { LOGF(TAG, "Script source is empty"); reportException(tryCatch, true); return Undefined(); } Local<Value> result = script->Run(); if (result.IsEmpty()) { LOGF(TAG, "Script result is empty"); reportException(tryCatch, true); return Undefined(); } return scope.Close(result); }
Handle<Value> evalScript(const Arguments& args) { if (args.Length() < 2) { return ThrowException(Exception::TypeError(String::New("evalScript takes 2 arguments."))); } TryCatch tc; Local<Script> compiled = Script::Compile(args[0]->ToString(), args[1]->ToString()); if (compiled.IsEmpty()) { return tc.ReThrow(); } Handle<Value> value = compiled->Run(); if (value.IsEmpty()) { return tc.ReThrow(); } return value; }
Handle<Value> evalInContext(const Arguments& args) { if (args.Length() < 3) { return ThrowException(Exception::TypeError(String::New("evalInContext takes 3 arguments."))); } if (!args[1]->IsObject()) { return ThrowException(Exception::TypeError(String::New("evalInContext expects an object as second argument."))); } HandleScope scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Local<Object> global = context->Global(); Local<Object> jscontext = args[1]->ToObject()->Clone(); Local<Array> names = jscontext->GetOwnPropertyNames(); for (int i = 0; i < names->Length(); i++) { global->Set(names->Get(i), jscontext->Get(names->Get(i))); } TryCatch tc; Local<Script> compiled = Script::Compile(args[0]->ToString(), args[2]->ToString()); if (compiled.IsEmpty()) { return tc.ReThrow(); } Handle<Value> value = compiled->Run(); if (value.IsEmpty()) { return tc.ReThrow(); } return scope.Close(value); }
static void gum_script_do_load (GumScriptTask * task, gpointer source_object, gpointer task_data, GCancellable * cancellable) { GumScript * self = GUM_SCRIPT (source_object); GumScriptPrivate * priv = self->priv; { Locker locker (priv->isolate); Isolate::Scope isolate_scope (priv->isolate); HandleScope handle_scope (priv->isolate); if (priv->code == NULL) { gboolean created; created = gum_script_create_context (self, NULL); g_assert (created); } if (!priv->loaded) { priv->loaded = TRUE; ScriptScope scope (self); gum_script_bundle_run (gum_script_get_platform ()->GetUserRuntime ()); Local<Script> code (Local<Script>::New (priv->isolate, *priv->code)); code->Run (); } } gum_script_task_return_pointer (task, NULL, NULL); }
void* worker_routine(void *vdbc) { struct dbcontext * dbc = (struct dbcontext *) vdbc; //allocate array for objects that will be automatically removed after th_alloc_array(1000); // Socket to talk to dispatcher void *receiver = zmq_socket (dbc->context, ZMQ_REP); zmq_connect (receiver, "inproc://workers"); //Initialize our Isoloate Isolate *isolate = Isolate::New(); if(!isolate) { cout << "Failed to initialize Isolate, we can't work"; return 0; } Locker lock(isolate); Isolate::Scope isolateScope(isolate); HandleScope scope; Local<ObjectTemplate> globals = ObjectTemplate::New(); #define SETGLOB(name) globals->Set(String::New(""#name), FunctionTemplate::New(name)); globals->Set(String::New("addnum"), FunctionTemplate::New(addnum)); SETGLOB(print) globals->Set(String::New("put"), FunctionTemplate::New(put)); globals->Set(String::New("get"), FunctionTemplate::New(get)); globals->Set(String::New("del"), FunctionTemplate::New(del)); //iterator globals->Set(String::New("it_del"), FunctionTemplate::New(it_del)); globals->Set(String::New("it_new"), FunctionTemplate::New(it_new)); globals->Set(String::New("it_first"), FunctionTemplate::New(it_first)); globals->Set(String::New("it_last"), FunctionTemplate::New(it_last)); globals->Set(String::New("it_seek"), FunctionTemplate::New(it_seek)); globals->Set(String::New("it_next"), FunctionTemplate::New(it_next)); globals->Set(String::New("it_prev"), FunctionTemplate::New(it_prev)); globals->Set(String::New("it_valid"), FunctionTemplate::New(it_valid)); globals->Set(String::New("it_key"), FunctionTemplate::New(it_key)); globals->Set(String::New("it_val"), FunctionTemplate::New(it_val)); //BITSET SETGLOB(bs_new) SETGLOB(bs_reset) SETGLOB(bs_set) SETGLOB(bs_logicalor) SETGLOB(bs_logicalnot) SETGLOB(bs_inplace_logicalnot) SETGLOB(bs_logicaland) SETGLOB(bs_sparselogicaland) SETGLOB(bs_tostring) SETGLOB(bs_makeSameSize) SETGLOB(bs_eq) SETGLOB(putbs) SETGLOB(getbs) SETGLOB(bs_it_new) SETGLOB(bs_it_end) SETGLOB(bs_it_isend) SETGLOB(bs_it_next) SETGLOB(bs_it_val) SETGLOB(bs_it_end) SETGLOB(bs_it_eq) Handle<Context> context = Context::New(NULL, globals); context->Enter(); //Running init script with library functions if (dbc->init_code != NULL) { TryCatch try_catch; Local<String> source = String::New(dbc->init_code); Local<Script> script = Script::Compile(source); if(script.IsEmpty()) { ReportException(&try_catch); } else { // Run the function once and catch the error to generate machine code Local<Value> result = script->Run(); } } while (1) { zmq_msg_t req; int rc = zmq_msg_init (&req); assert (rc == 0); rc = zmq_recv (receiver, &req, 0); assert (rc == 0); zmq_msg_t reply; //rc = zmq_msg_init_size (&reply, 200); //assert (rc == 0); //test mq speed only #if 0 rc = zmq_msg_init_size (&reply, 200); assert (rc == 0); rc = zmq_msg_copy (&reply, &req); assert (rc == 0); rc = zmq_send (receiver, &reply, 0); assert (rc == 0); //s_sleep(1); zmq_msg_close (&req); zmq_msg_close (&reply); continue; #endif //std::cout << "thread: " << pthread_self() << " Received script: " << (char*) zmq_msg_data(&req) << std::endl; //leveldb::Status s; #if 1 Context::Scope contextScope(context); // Compile a function which will keep using the stack until v8 cuts it off //Local<Script> script = Local<Script>::New(Script::Compile(String::New( (char*) zmq_msg_data(&req) ))); TryCatch try_catch; Local<String> source = String::New((char*) zmq_msg_data(&req)); Local<Script> script = Script::Compile(source); if(script.IsEmpty()) { ReportException(&try_catch); String::Utf8Value error(try_catch.Exception()); v8::Handle<v8::Message> message = try_catch.Message(); int line_num = 0; int col_num = 0; if (message.IsEmpty()) { }else { line_num = message->GetLineNumber(); col_num = message->GetStartColumn(); } int mess_size = error.length()+100; rc = zmq_msg_init_size (&reply, mess_size); assert (rc == 0); //cerr << "compile error line: " << " message: " << *error << endl; snprintf ((char*) zmq_msg_data (&reply), mess_size, "2; {res: 'COMPILE ERROR', line: %d, col: %d, message: '%s'}", line_num, col_num, *error); } else { // Run the function once and catch the error to generate machine code Local<Value> result = script->Run(); if (try_catch.HasCaught()) { //TODO: escape string String::Utf8Value message(try_catch.Exception()); int mess_size = message.length()+100; rc = zmq_msg_init_size (&reply, mess_size); assert (rc == 0); std::cout <<"exception->" <<*message <<"\n"; snprintf ((char*) zmq_msg_data (&reply), mess_size, "1; {res: 'ERROR', message: '%s'}", *message); } else { //TODO: escape string String::Utf8Value message(result->ToString()); int mess_size = message.length()+2; rc = zmq_msg_init_size (&reply, mess_size); assert (rc == 0); snprintf ((char*) zmq_msg_data (&reply), mess_size, " %s", *message); } } #endif /* Send the message to the socket */ rc = zmq_send (receiver, &reply, 0); assert (rc == 0); //s_sleep(1); zmq_msg_close (&req); zmq_msg_close (&reply); free_objects(); } context->Exit(); //printf("Iter: %d , Result: %ld ; from thread: %ld \n", i, res, tid); //context.Dispose(); //script.Dispose(); Unlocker unlock(isolate); //isolate->Exit(); //isolate->Dispose(); zmq_close (receiver); return NULL; }
v8::Local<v8::Value> JSDeviceTest::runScript(const std::string &script) { Local<String> source = String::NewFromUtf8(isolate, script.c_str()); Local<Script> jsScript = Script::Compile(source); return jsScript->Run(); }
inline bool runscript(const char *source) { Local<Script> script = Script::Compile(String::New(source)); Local<Value> result = script->Run(); return result->BooleanValue(); }
bool V8Engine::runScript(const char* js, std::string& result) { bool rval = true; // lock V8 while script is running Locker locker; // Create a stack-allocated handle scope. HandleScope handle_scope; // Enter the engine context for compiling and running the script. Context::Scope context_scope(mContext); // We're just about to compile the script; set up an error handler to // catch any exceptions the script might throw. TryCatch tryCatch; // Create a string containing the JavaScript source code. Local< ::v8::String> source = ::v8::String::New(js); // Script containing the compiled source. Local< ::v8::Script> script; // Result of the script after it has been run. Local<Value> resultval; if(rval) { // Compile the source code. script = ::v8::Script::Compile(source); if(script.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); // The script failed to compile ExceptionRef e = new rt::Exception( "Script failed to compile.", EXCEPTION_PREFIX ".CompileError"); e->getDetails()["error"] = *error; rt::Exception::set(e); rval = false; } } if(rval) { // Run the script to get the result. resultval = script->Run(); if(resultval.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); // The script failed to run ExceptionRef e = new rt::Exception( "Script failed to run.", EXCEPTION_PREFIX ".RunError"); e->getDetails()["error"] = *error; rt::Exception::set(e); rval = false; } } if(rval) { ::v8::String::AsciiValue ascii(resultval); result = *ascii; } return rval; }
int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_EVERYTHING); V8::Initialize(); isolate = Isolate::GetCurrent(); HandleScope handle_scope(isolate); Persistent<Context> context = Context::New(); Context::Scope context_scope(context); Local<Object> global = context->Global(); Local<Object> sphere = Object::New(); global->Set(String::New("sphere"), sphere); API::fs::Init(sphere); API::engine::Init(sphere); API::graphics::Init(sphere); API::events::Init(sphere); Local<Object> engine = sphere->Get(String::New("engine"))->ToObject(); engine->Set(String::New("argc"), Integer::New(argc)); Local<Array> js_argv = Array::New(argc); for (int i = 0; i < argc; i++) { js_argv->Set(Number::New(i), String::New(argv[i])); } engine->Set(String::New("argv"), js_argv); const char* gameScript = Files::readTextFile("system/sphere.js"); if (gameScript == NULL) { debug("Error loading bootstrap script.\n"); exit(1); } TryCatch trycatch; Local<Script> compiled = Script::Compile(String::New(gameScript), String::New("system/sphere.js")); if (compiled.IsEmpty()) { Handle<Value> exception = trycatch.Exception(); String::Utf8Value exception_str(exception); printf("Exception: %s\n", *exception_str); exit(1); } Handle<Value> value = compiled->Run(); if (value.IsEmpty()) { Handle<Object> exception = trycatch.Exception()->ToObject(); Handle<String> str; if (exception->Has(String::New("stack"))) { str = exception->Get(String::New("stack"))->ToString(); } else { str = exception->ToString(); } String::Utf8Value exception_str(str); printf("Exception: %s\n", *exception_str); exit(1); } return 0; }
//事件循环 //TAGG核心代码程序 static void eventLoop (typeThread* thread) { thread->isolate->Enter(); //进入 isolate thread->context= Context::New(); //创建一个sandbox沙箱用来执行js代码,他的上下文将有他自己控制 thread->context->Enter(); //进入这个上下文 { HandleScope scope1; //返回这个分离的沙箱内的全局对象 //Local< Object > Global () Local<Object> global= thread->context->Global(); global->Set(String::NewSymbol("_Global"), global); //将puts方法设置到全局中去,代替console.log Handle<Object> console_obj = Object::New(); console_obj->Set(String::New("log"), FunctionTemplate::New(Puts)->GetFunction()); global->Set(String::New("console"), console_obj); global->Set(String::New("require"), FunctionTemplate::New(require_file)->GetFunction(), ReadOnly); //定义一个thread对象到全局变量中 Local<Object> threadObject= Object::New(); global->Set(String::NewSymbol("thread"), threadObject); //设置这个全局对象thread的id和emit属性 threadObject->Set(String::NewSymbol("id"), Number::New(thread->id)); threadObject->Set(String::NewSymbol("emit"), FunctionTemplate::New(threadEmit)->GetFunction()); threadObject->Set(String::NewSymbol("end"), FunctionTemplate::New(threadEnd)->GetFunction()); threadObject->Set(String::New("_TAGG_RES"), Undefined()); //返回的全局变量字符串 //将global对象放入全局global中,每次都会初始化 Handle<Object> user_global = Object::New(); global->Set(String::NewSymbol("global"), user_global); global->Set(String::NewSymbol("Global"), user_global); //让threadObject继承event接口 Local<Object> dispatchEvents= Script::Compile(String::New(kEvents_js))->Run()->ToObject()->CallAsFunction(threadObject, 0, NULL)->ToObject(); //获得下个事件循环的函数 Local<Object> dispatchNextTicks= Script::Compile(String::New(kThread_nextTick_js))->Run()->ToObject(); //获得thread_nextTick.js中定义的 next回调函数的数组 Local<Array> _ntq= (v8::Array*) *threadObject->Get(String::NewSymbol("_ntq")); double nextTickQueueLength= 0; //事件循环次数 long int ctr= 0; //SetFatalErrorHandler(FatalErrorCB); while (!thread->sigkill) { //当线程的信号不为kill时,则循环执行下面代码 typeJob* job; typeQueueItem* qitem; {//while循环代码块 HandleScope scope2; //v8的TryCatch类, //一个外部的异常控制类 TryCatch onError; String::Utf8Value* str;//临时保存js源代码的指针 Local<String> source; //保存js源代码字符串 Local<Script> script; //保存js源代码 Local<Value> resultado; //保存js源代码执行的return 结果值 while ((qitem= queue_pull(&thread->inQueue))) { //当队列中有项目时,循环执行如下代码 job= (typeJob*) qitem->asPtr; //队列中的任务 if ((++ctr) > 2e3) { //如果ctr 大于 2*10的3次方 ctr= 0; V8::IdleNotification(); //强制V8进行GC while(!V8::IdleNotification()) {}; } if (job->jobType == kJobTypeEval) { //如果执行的任务 //Ejecutar un texto if (job->typeEval.useStringObject) { //如果是eval方法传入的参数进来的 str= job->typeEval.scriptText_StringObject; source= String::New(**str, (*str).length()); delete str; //删除str指针 } else { //如果是load js 文件进来的 source= String::New(job->typeEval.scriptText_CharPtr);//创建js源代码string, free(job->typeEval.scriptText_CharPtr); //释放 } script= Script::New(source); //将源代码字符串,转存为js代码 //这里进行判断,如果上下问里的js代码执行抛出了异常,则本次循环将不执行js代码了 //将global对象放入全局global中,每次都会初始化 Handle<Object> user_global = Object::New(); global->Set(String::NewSymbol("global"), user_global); global->Set(String::NewSymbol("Global"), user_global); if (!onError.HasCaught()){ //如果没有错误 //Local<Object> obj = job->buffer->Clone(); //resultado = String::NewSymbol("id"); //将char* 的job->buf_ptr又转换为Buffer指针 //node::Buffer *buf = node::Buffer::New(job->buf_ptr, job->buf_len); //Local<Object> buf_obj = External::Wrap(buf)->ToObject(); threadObject->Set(String::New("_TAGG_RES"), Undefined()); //返回的全局变量字符串 Local<Object> buf_obj = Object::New(); if(job->buf_ptr){ buf_obj->SetHiddenValue(String::New("buffer"), String::New(job->buf_ptr, job->buf_len)); buf_obj->SetHiddenValue(String::New("isBuffer"),Number::New(1)); } else{ buf_obj->SetHiddenValue(String::New("isBuffer"),Number::New(0)); } buf_obj->Set(String::NewSymbol("toString"), FunctionTemplate::New(Buffer_toString)->GetFunction()); threadObject->Set(String::NewSymbol("buffer"), buf_obj); global->Set(String::NewSymbol("__dirname"), String::New(**job->__dirname)); global->SetPointerInInternalField(0, job->__dirname); script->Run(); //执行js代码,返回值为 resultado resultado = threadObject->Get(String::New("_TAGG_RES")); }//如果没有错误 if (_ntq->Length() && !onError.HasCaught()) { //当有错误时,不执行异步 if ((++ctr) > 2e3) { ctr= 0; V8::IdleNotification();//强制GC } resultado = dispatchNextTicks->CallAsFunction(global, 0, NULL); //调用线程内的 nexttick } if (job->typeEval.tiene_callBack) { //如果执行任务具有回调函数 //如果有错误,则 job->typeEval.error 是1,否则为0; job->typeEval.error= onError.HasCaught() ? 1 : 0; if(job->typeEval.error){ _ntq= Array::New(); } //如果有异常,则返回值 resultado 为异常内容,否则为函数返回内容 job->typeEval.resultado= new String::Utf8Value(job->typeEval.error ? onError.Exception() : threadObject->Get(String::New("_TAGG_RES"))); //执行完毕,将qtiem项丢入线程的出列队列 queue_push(qitem, &thread->outQueue); // wake up callback //丢入异步队列 uv_async_send(&thread->async_watcher); } else { //如果没有回调函数,则把改item丢入闲置任务队列 queue_push(qitem, freeJobsQueue); } if (onError.HasCaught()){ nextTickQueueLength= 1; onError.Reset(); //如果此次执行有错误,则清空 } else{ nextTickQueueLength= resultado->NumberValue(); } }//如果执行的任务 else if (job->jobType == kJobTypeEvent) { //如果是事件的任务 //Emitir evento. Local<Value> args[2]; //定义一个数组长度为2,保存 Local<Value> 类型的值 str= job->typeEvent.eventName; //获得事件名字 args[0]= String::New(**str, (*str).length()); //数组第一个保存event事件的名字,保存为local<string>类型 delete str; Local<Array> array= Array::New(job->typeEvent.length); args[1]= array; //设置参数长度 int i= 0; while (i < job->typeEvent.length) { //将参数保存入Local<Array> str= job->typeEvent.argumentos[i]; array->Set(i, String::New(**str, (*str).length())); delete str; i++; } free(job->typeEvent.argumentos); //释放任务的 typeEvent 内存 queue_push(qitem, freeJobsQueue); //将本项丢入闲置任务队列 dispatchEvents->CallAsFunction(global, 2, args); //执行回调函数,并且加入参数 }//如果是事件的任务 }//while2 结束 /* if (_ntq->Length()) { //执行异步 if ((++ctr) > 2e3) { ctr= 0; V8::IdleNotification();//强制GC } resultado = dispatchNextTicks->CallAsFunction(global, 0, NULL); //调用线程内的 nexttick if (onError.HasCaught()) { //如果有错误 nextTickQueueLength= 1; //nexttick队列长度为1 onError.Reset(); } else { nextTickQueueLength= resultado->NumberValue(); } } */ if (thread->inQueue.length) continue; if (thread->sigkill) break; //如果收到线程杀死信号,条春循环 pthread_mutex_lock(&thread->IDLE_mutex); //锁住线程 if (!thread->inQueue.length) { //如果线程的入队列长度为0 thread->IDLE= 1; //则把线程设置为闲置 pthread_cond_wait(&thread->IDLE_cv, &thread->IDLE_mutex); //休眠线程 thread->IDLE= 0; } pthread_mutex_unlock(&thread->IDLE_mutex); //解锁线程 }//while 结束 } thread->context.Dispose(); //摧毁上下文 } }
INT32_MAIN_INT32_ARGC_TCHAR_ARGV() { GEngineLoop.PreInit(ArgC, ArgV); UE_LOG(LogUnrealNode, Display, TEXT("Hello World")); // Initialize V8. V8::InitializeICU(); //V8::InitializeExternalStartupData(ArgV[0]); Platform* platform = platform::CreateDefaultPlatform(); V8::InitializePlatform(platform); V8::Initialize(); // Create a new Isolate and make it the current one. ArrayBufferAllocator allocator; Isolate::CreateParams create_params; create_params.array_buffer_allocator = &allocator; Isolate* isolate = Isolate::New(create_params); { Isolate::Scope isolate_scope(isolate); // Create a stack-allocated handle scope. HandleScope handle_scope(isolate); // Create a new context. Local<Context> context = Context::New(isolate); // Enter the context for compiling and running the hello world script. Context::Scope context_scope(context); // Create a string containing the JavaScript source code. Local<String> source = String::NewFromUtf8(isolate, "'Hello World' + ' from JavaScript'", NewStringType::kNormal).ToLocalChecked(); // Compile the source code. Local<Script> script = Script::Compile(context, source).ToLocalChecked(); // Run the script to get the result. Local<Value> result = script->Run(context).ToLocalChecked(); // Convert the result to an UTF8 string and print it. String::Utf8Value utf8(result); printf("%s\n", *utf8); } // Dispose the isolate and tear down V8. isolate->Dispose(); V8::Dispose(); V8::ShutdownPlatform(); delete platform; //uv_idle_t idler; //uv_idle_init(uv_default_loop(), &idler); //uv_idle_start(&idler, wait_for_a_while); //printf("Idling...\n"); //uv_run(uv_default_loop(), UV_RUN_DEFAULT); //uv_loop_close(uv_default_loop()); return 0; }