예제 #1
0
파일: V8.cpp 프로젝트: kenahoo/V8
// [[Rcpp::export]]
std::string context_eval(std::string src, Rcpp::XPtr< v8::Persistent<v8::Context> > ctx){
  // Test if context still exists
  if(!ctx)
    throw std::runtime_error("Context has been disposed.");

  // Create a scope
  HandleScope handle_scope;
  Context::Scope context_scope(*ctx);

  // Compile source code
  TryCatch trycatch;
  Handle<Script> script = compile_source(src);
  if(script.IsEmpty()) {
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::invalid_argument(*exception_str);
  }

  // Run the script to get the result.
  Handle<Value> result = script->Run();
  if(result.IsEmpty()){
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::runtime_error(*exception_str);
  }

  // Convert result to UTF8.
  String::Utf8Value utf8(result);
  return *utf8;
}
예제 #2
0
extern "C" Handle<Value> execute_string(Persistent<Context> context,
					const char* s,
					bool* is_exception) {
    // Create a stack-allocated handle scope.
    HandleScope handle_scope;

    // Enter the created context for compiling and
    // running the hello world script.
    Context::Scope context_scope(context);

    // Create a string containing the JavaScript source code.
    Handle<String> source = String::New(s);

    // Compile it
    Handle<Script> script = Script::Compile(source);

    // try-catch handler
    TryCatch trycatch;
    // Run it
    Persistent<Value> result = Persistent<Value>::New(script->Run());

    // Script->Run() returns an empty handle if the code threw an exception
    if (result.IsEmpty()) {
	*is_exception = true;
	Handle<Value> exception = trycatch.Exception();
	// String::AsciiValue exception_str(exception);
	return Persistent<Value>::New(exception);	
    }
    
    return result;
}
예제 #3
0
void
test_Exception()
{
  HandleScope handle_scope;

  Persistent<Context> context = Context::New();
  Handle<Script> script = Script::New(String::New("function foo(x) { throw x; };"));

  Context::Scope scope(context);
  TryCatch trycatch;

  Handle<Value> v = script->Run();
  do_check_true(!v.IsEmpty());
  do_check_true(!trycatch.HasCaught());
  Handle<Function> fn = context->Global()->Get(String::NewSymbol("foo")).As<Function>();
  do_check_true(!fn.IsEmpty());
  Local<Value> args[1] = { Integer::New(4) };
  v = fn->Call(context->Global(), 1, args);
  do_check_true(v.IsEmpty());
  do_check_true(trycatch.HasCaught());
  Handle<Value> exn = trycatch.Exception();
  do_check_true(exn->IsInt32());
  do_check_eq(exn->Int32Value(), 4);

  context.Dispose();
}
std::string V8Engine::compileScript(std::string script)
{
    HandleScope handleScope;
    TryCatch tc;

    Local<String> source = String::New(script.c_str());

    // Compile the source code.

    Local<Script> code = Script::Compile(source);
    if (!code.IsEmpty())
        return "";

    // There were errors, return them

    std::string ret = "";

    Handle<Object> exception = tc.Exception()->ToObject();
    String::AsciiValue exception_str(exception);

    ret += *exception_str; ret += "\n";

    Local<Message> message = tc.Message();

    ret += *(v8::String::Utf8Value( message->Get() )); ret += "\n";
    ret += "Source line: "; ret += *(v8::String::Utf8Value( message->GetSourceLine() )); ret += "\n";
    ret += "Source line number: "; ret += Utility::toString(message->GetLineNumber()); ret += "\n";

    return ret;
}
예제 #5
0
파일: JSEngine.cpp 프로젝트: Spacefish/susi
void Susi::JS::Engine::RegisterProcessor(const v8::FunctionCallbackInfo<v8::Value>& args) {
	if (args.Length() < 2) return;
	Handle<Value> callbackValue = args[1];
	if(callbackValue->IsFunction()){
		Handle<Value> topicValue = args[0];
		std::string topic{Susi::JS::Engine::convertFromJS(topicValue).toString()};
		std::shared_ptr<Persistent<Function>> jsCallback{new Persistent<Function>(Isolate::GetCurrent(),Handle<Function>::Cast(callbackValue))};
		Susi::Events::Processor callback = [jsCallback](Susi::Events::EventPtr event){
			Local<Function> func = Local<Function>::New(Isolate::GetCurrent(),*jsCallback);
			Handle<Value> callbackArguments[1];
			callbackArguments[0] = Susi::JS::Engine::convertFromCPP(event->toAny());
			TryCatch trycatch;
			auto res = func->Call(func,1,callbackArguments);
			if (res.IsEmpty()) {
				Handle<Value> exception = trycatch.Exception();
				String::Utf8Value exception_str(exception);
				std::cout<<*exception_str<<std::endl;
			}
		};
		long id = Susi::JS::engine->susi_client.subscribe(topic,callback);
		args.GetReturnValue().Set((double)id);
	}else{
		args.GetReturnValue().Set(false);
	}
}
예제 #6
0
파일: main.cpp 프로젝트: pgmsoul/JSApp
int __stdcall wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow){
	int rt = -1;
	initContext();
	HandleScope store;
	runJSRes(IDR_JS_STRUCT,L"app.lib");
	Handle<Value> result = runJSFile(L"main.js",L"utf-8");
	if(!result.IsEmpty()){//只有出错的时候才会返回Empty, 否则即使没有返回值, result仍然是Undefined.
		Local<Object> gObj = getGlobal();
		Local<Function> main = GetJSVariant<Function>(gObj,L"main");
		if(main.IsEmpty()){
			//InnerMsg(L"没有发现 main 函数",MT_ERROR);
		}else if(!main->IsFunction()){
			//InnerMsg(L"main 不是函数",MT_ERROR);
		}else{
			TryCatch err;
			Handle<Value> args[1];
			args[0] = String::New((uint16_t*)lpCmdLine);
			Local<Value> r = main->Call(gObj,1,args);
			if(!err.Exception().IsEmpty()){
				ReportError(err);
			}else
				rt = r->Int32Value();
		}
	}
	releaseContext();
	return rt;
}
예제 #7
0
파일: utils.cpp 프로젝트: Mirwangsir/fibjs
std::string GetException(TryCatch &try_catch, result_t hr)
{
    if (try_catch.HasCaught())
    {
        v8::String::Utf8Value exception(try_catch.Exception());

        v8::Local<v8::Message> message = try_catch.Message();
        if (message.IsEmpty())
            return ToCString(exception);
        else
        {
            v8::Local<v8::Value> trace_value = try_catch.StackTrace();

            if (!IsEmpty(trace_value))
            {
                v8::String::Utf8Value stack_trace(trace_value);
                return ToCString(stack_trace);
            }

            std::string strError;

            v8::String::Utf8Value filename(message->GetScriptResourceName());

            if (qstrcmp(ToCString(exception), "SyntaxError: ", 13))
            {
                strError.append(ToCString(exception));
                strError.append("\n    at ");
            }
            else
            {
                strError.append((ToCString(exception) + 13));
                strError.append("\n    at ");
            }

            strError.append(ToCString(filename));
            int lineNumber = message->GetLineNumber();
            if (lineNumber > 0)
            {
                char numStr[32];

                strError.append(1, ':');
                sprintf(numStr, "%d", lineNumber);
                strError.append(numStr);
                strError.append(1, ':');
                sprintf(numStr, "%d", message->GetStartColumn() + 1);
                strError.append(numStr);
            }

            return strError;
        }
    }
    else if (hr < 0)
        return getResultMessage(hr);

    return "";
}
예제 #8
0
 void JSHandler::done() {
     if (!done_cb.IsEmpty()) {
         Local<Value> argv[0] = { };
         TryCatch trycatch;
         Handle<Value> v = done_cb->Call(Context::GetCurrent()->Global(), 0, argv);
         if (v.IsEmpty()) {
             Handle<Value> exception = trycatch.Exception();
             String::AsciiValue exception_str(exception);
             printf("Exception: %s\n", *exception_str);
             exit(1);
         }
     }
 }
void CoreClrNodejsFuncInvokeContext::InvokeCallback(void* data)
{
	DBG("CoreClrNodejsFuncInvokeContext::InvokeCallback");

	CoreClrNodejsFuncInvokeContext* context = (CoreClrNodejsFuncInvokeContext*) data;
	v8::Local<v8::Value> v8Payload = CoreClrFunc::MarshalCLRToV8(context->Payload, context->PayloadType);

	static Nan::Persistent<v8::Function> callbackFactory;
	static Nan::Persistent<v8::Function> callbackFunction;

	Nan::HandleScope scope;

	// See https://github.com/tjanczuk/edge/issues/125 for context
	if (callbackFactory.IsEmpty())
	{
		v8::Local<v8::Function> v8FuncCallbackFunction = Nan::New<v8::FunctionTemplate>(coreClrV8FuncCallback)->GetFunction();
		callbackFunction.Reset(v8FuncCallbackFunction);
		v8::Local<v8::String> code = Nan::New<v8::String>(
			"(function (cb, ctx) { return function (e, d) { return cb(e, d, ctx); }; })").ToLocalChecked();
		v8::Local<v8::Function> callbackFactoryFunction = v8::Local<v8::Function>::Cast(v8::Script::Compile(code)->Run());
		callbackFactory.Reset(callbackFactoryFunction);
	}

	v8::Local<v8::Value> factoryArgv[] = { Nan::New(callbackFunction), Nan::New<v8::External>((void*)context) };
	v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(
		Nan::New(callbackFactory)->Call(Nan::GetCurrentContext()->Global(), 2, factoryArgv));

	v8::Local<v8::Value> argv[] = { v8Payload, callback };
	TryCatch tryCatch;

	DBG("CoreClrNodejsFuncInvokeContext::InvokeCallback - Calling JavaScript function");
	Nan::Call(Nan::New(*(context->FunctionContext->Func)), Nan::GetCurrentContext()->Global(), 2, argv);
	DBG("CoreClrNodejsFuncInvokeContext::InvokeCallback - Called JavaScript function");

	if (tryCatch.HasCaught())
	{
		DBG("CoreClrNodejsFuncInvokeContext::InvokeCallback - Caught JavaScript exception");

		void* exceptionData;
		CoreClrFunc::MarshalV8ExceptionToCLR(tryCatch.Exception(), &exceptionData);

		DBG("CoreClrNodejsFuncInvokeContext::InvokeCallback - Exception message is: %s", (char*)exceptionData);

		context->Complete(TaskStatusFaulted, exceptionData, V8TypeException);
	}
    else
    {
        // Kick the next tick
        CallbackHelper::KickNextTick();
    }
}
void handleException(TryCatch& tc)
{
    Logging::log(Logging::ERROR, "V8 exception:\r\n");

    HandleScope handleScope;

    Handle<Object> exception = tc.Exception()->ToObject();
    String::AsciiValue exception_str(exception);

    Logging::log(Logging::ERROR, "            : %s\r\n", *exception_str);

/*
    Handle<Array> names = exception->GetPropertyNames();
    for (unsigned int i = 0; i < names->Length(); i++)
    {
        std::string strI = Utility::toString((int)i);
        Logging::log(Logging::ERROR, "    %d : %s : %s\r\n", i,
            *(v8::String::Utf8Value(names->Get(String::New(strI.c_str()))->ToString())),
            *(v8::String::Utf8Value(exception->Get(names->Get(String::New(strI.c_str()))->ToString())->ToString()))
        );
    }
*/

    Local<Message> message = tc.Message();

    Logging::log(Logging::ERROR, "Message: Get: %s\r\n", *(v8::String::Utf8Value( message->Get() )));
    Logging::log(Logging::ERROR, "Message: GetSourceLine: %s\r\n", *(v8::String::Utf8Value( message->GetSourceLine() )));
    Logging::log(Logging::ERROR, "Message: GetScriptResourceName: %s\r\n", *(v8::String::Utf8Value( message->GetScriptResourceName()->ToString() )));
    Logging::log(Logging::ERROR, "Message: GetLineNumber: %d\r\n", message->GetLineNumber() );

    Local<Value> stackTrace = tc.StackTrace();
    if (!stackTrace.IsEmpty())
    {
        Logging::log(Logging::ERROR, "Stack trace: %s\r\n", *(v8::String::Utf8Value( stackTrace->ToString() )));
        printf("\r\n\r\n^Stack trace^: %s\r\n", *(v8::String::Utf8Value( stackTrace->ToString() )));
    }
    else
        Logging::log(Logging::ERROR, "No stack trace available in C++ handler (see above for possible in-script stack trace)\r\n");

    #ifdef SERVER
        std::string clientMessage = *(v8::String::Utf8Value( message->Get() ));
        clientMessage += "  -  ";
        clientMessage += *(v8::String::Utf8Value( message->GetSourceLine() ));
        ServerSystem::fatalMessageToClients(clientMessage);
    #endif

//    assert(0);
    throw ScriptException("Bad!");
}
예제 #11
0
jsvalue JsEngine::ErrorFromV8(TryCatch& trycatch)
{
    jsvalue v;

    HandleScope scope;
    
    Local<Value> exception = trycatch.Exception();
	    
	v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
	v.value.str = 0;
    v.length = 0;

	// If this is a managed exception we need to place its ID inside the jsvalue
    // and set the type JSVALUE_TYPE_MANAGED_ERROR to make sure the CLR side will
    // throw on it.

    if (exception->IsObject()) {
        Local<Object> obj = Local<Object>::Cast(exception);
        if (obj->InternalFieldCount() == 1) {
			Local<External> wrap = Local<External>::Cast(obj->GetInternalField(0));
			ManagedRef* ref = (ManagedRef*)wrap->Value();
	        v.type = JSVALUE_TYPE_MANAGED_ERROR;
            v.length = ref->Id();
			return v;
		}
	}

	jserror *error = new jserror();
	memset(error, 0, sizeof(jserror));
	
	Local<Message> message = trycatch.Message();

	if (!message.IsEmpty()) {
		error->line = message->GetLineNumber();
		error->column = message->GetStartColumn();
		error->resource = AnyFromV8(message->GetScriptResourceName());
		error->message = AnyFromV8(message->Get());
	}
	 if (exception->IsObject()) {
        Local<Object> obj2 = Local<Object>::Cast(exception);
		error->type = AnyFromV8(obj2->GetConstructorName());
	 }

	error->exception = AnyFromV8(exception);
	v.type = JSVALUE_TYPE_ERROR;
	v.value.ptr = error;
    
	return v;
}
예제 #12
0
void set_perl_error(const TryCatch& try_catch) {
    Handle<Message> msg = try_catch.Message();

    char message[1024];
    snprintf(
        message,
        1024,
        "%s at %s:%d",
        *(String::Utf8Value(try_catch.Exception())),
        !msg.IsEmpty() ? *(String::AsciiValue(msg->GetScriptResourceName())) : "EVAL",
        !msg.IsEmpty() ? msg->GetLineNumber() : 0
    );

    sv_setpv(ERRSV, message);
    sv_utf8_upgrade(ERRSV);
}
예제 #13
0
Local<String> V8EngineProxy::GetErrorMessage(TryCatch &tryCatch)
{
	auto msg = tryCatch.Exception()->ToString();

	auto stack = tryCatch.StackTrace();
	bool showStackMsg = !stack.IsEmpty() && !stack->IsUndefined();
	Local<String> stackStr;

	if (showStackMsg)
	{
		stackStr = stack->ToString();

		// ... detect if the start of the stack message is the same as the exception message, then remove it (seems to happen when managed side returns an error) ...

		if (stackStr->Length() >= msg->Length())
		{
			uint16_t* ss = new uint16_t[stackStr->Length() + 1];
			stack->ToString()->Write(ss);
			auto subStackStr = NewSizedUString(ss, msg->Length());
			auto stackPartStr = NewSizedUString(ss + msg->Length(), stackStr->Length() - msg->Length());
			delete[] ss;

			if (msg->Equals(subStackStr))
				stackStr = stackPartStr;
		}
	}

	msg = msg->Concat(msg, NewString("\r\n"));

	msg = msg->Concat(msg, NewString("  Line: "));
	auto line = NewInteger(tryCatch.Message()->GetLineNumber())->ToString();
	msg = msg->Concat(msg, line);

	msg = msg->Concat(msg, NewString("  Column: "));
	auto col = NewInteger(tryCatch.Message()->GetStartColumn())->ToString();
	msg = msg->Concat(msg, col);
	msg = msg->Concat(msg, NewString("\r\n"));

	if (showStackMsg)
	{
		msg = msg->Concat(msg, NewString("  Stack: "));
		msg = msg->Concat(msg, stackStr);
		msg = msg->Concat(msg, NewString("\r\n"));
	}

	return msg;
}
예제 #14
0
void V8Util::reportException(TryCatch &tryCatch, bool showLine)
{
	HandleScope scope;
	Handle<Message> message = tryCatch.Message();

	if (nameSymbol.IsEmpty()) {
		nameSymbol = SYMBOL_LITERAL("name");
		messageSymbol = SYMBOL_LITERAL("message");
	}

	if (showLine) {
		Handle<Message> message = tryCatch.Message();
		if (!message.IsEmpty()) {
			String::Utf8Value filename(message->GetScriptResourceName());
			String::Utf8Value msg(message->Get());
			int linenum = message->GetLineNumber();
			LOGE(EXC_TAG, "Exception occurred at %s:%i: %s", *filename, linenum, *msg);
		}
	}

	Local<Value> stackTrace = tryCatch.StackTrace();
	String::Utf8Value trace(tryCatch.StackTrace());

	if (trace.length() > 0 && !stackTrace->IsUndefined()) {
		LOGD(EXC_TAG, *trace);
	} else {
		Local<Value> exception = tryCatch.Exception();
		if (exception->IsObject()) {
			Handle<Object> exceptionObj = exception->ToObject();
			Handle<Value> message = exceptionObj->Get(messageSymbol);
			Handle<Value> name = exceptionObj->Get(nameSymbol);

			if (!message->IsUndefined() && !name->IsUndefined()) {
				String::Utf8Value nameValue(name);
				String::Utf8Value messageValue(message);
				LOGE(EXC_TAG, "%s: %s", *nameValue, *messageValue);
			}
		} else {
			String::Utf8Value error(exception);
			LOGE(EXC_TAG, *error);
		}
	}
}
예제 #15
0
파일: utils.cpp 프로젝트: Mirwangsir/fibjs
result_t throwSyntaxError(TryCatch &try_catch)
{
    v8::String::Utf8Value exception(try_catch.Exception());

    v8::Local<v8::Message> message = try_catch.Message();
    if (message.IsEmpty())
        ThrowError(ToCString(exception));
    else
    {
        std::string strError;

        v8::String::Utf8Value filename(message->GetScriptResourceName());

        if (qstrcmp(ToCString(exception), "SyntaxError: ", 13))
        {
            strError.append(ToCString(exception));
            strError.append("\n    at ");
        }
        else
        {
            strError.append((ToCString(exception) + 13));
            strError.append("\n    at ");
        }

        strError.append(ToCString(filename));
        int lineNumber = message->GetLineNumber();
        if (lineNumber > 0)
        {
            char numStr[32];

            strError.append(1, ':');
            sprintf(numStr, "%d", lineNumber);
            strError.append(numStr);
            strError.append(1, ':');
            sprintf(numStr, "%d", message->GetStartColumn() + 1);
            strError.append(numStr);
        }

        return Runtime::setError(strError);
    }

    return CALL_E_JAVASCRIPT;
}
예제 #16
0
파일: v8base.cpp 프로젝트: pgmsoul/GitLib
	int ReportError(TryCatch& try_catch){
		cs::String str;
		HandleScope handle_scope;
		v8::String::Value exception(try_catch.Exception());
		const wchar_t* exception_string = ToCString(exception);
		Handle<v8::Message> message = try_catch.Message();
		if (message.IsEmpty()) {
			str.Format(L"%s\n",exception_string);
		} else {
			cs::String buf;
			v8::String::Value filename(message->GetScriptResourceName());
			const wchar_t* filename_string = ToCString(filename);
			int linenum = message->GetLineNumber();
			buf.Format(L"file:\t%s\r\nline:\t%i\r\n%s\r\n\r\n", filename_string, linenum, exception_string);
			str += buf;
			v8::String::Value sourceline(message->GetSourceLine());
			const wchar_t* sourceline_string = ToCString(sourceline);
			buf.Format(L"%s", sourceline_string);
			int start = message->GetStartColumn();
			for (int i = 0; i < start; i++) {
				//str += L" ";
			}
			buf.Insert('^',start);
			buf.Trim();
			str += buf;
			int end = message->GetEndColumn();
			for (int i = start; i < end; i++) {
				//str += L"^";
			}
			/*str += L"\n";
			v8::String::Value stack_trace(try_catch.StackTrace());
			if (stack_trace.length() > 0) {
				const wchar_t* stack_trace_string = ToCString(stack_trace);
				buf.Format(L"%s\n", stack_trace_string);
				str += buf;
			}*/
		}
		return MessageBox(0,str,L"Error",MB_ICONERROR);
	}
예제 #17
0
extern "C" Handle<Value> apply_function_arr(Handle<Context> context,
					    Handle<Function> func, int argc,
					    Handle<Value>* argv, bool* is_exception) {
    HandleScope handle_scope;

    Context::Scope context_scope(context);

    TryCatch trycatch;
    
    Handle<Value> result = func->Call(context->Global(), argc, argv);

    if (result.IsEmpty()) {
	*is_exception = true;
	Handle<Value> exception = trycatch.Exception();
	// String::AsciiValue exception_str(exception);
	return Persistent<Value>::New(exception);
    }

    Persistent<Value> js_result = Persistent<Value>::New(result);

    return js_result;
}
예제 #18
0
char* js_eval(UDF_INIT *initid, UDF_ARGS* args, char *result_buf, unsigned long *res_length, char *null_value, char *error) {

    HandleScope handle_scope;

    Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);

    //fprintf(stderr, "[mylog] input: %s\n", (char*)(args->args[0]));

    Handle<String> source = String::New((char*)(args->args[0]));
    Handle<Script> script = Script::Compile(source);

    TryCatch trycatch;
    Handle<Value> result = script->Run();

    if ( result.IsEmpty() ) {
        Handle<Value> exception = trycatch.Exception();
        String::AsciiValue exception_str(exception);

        //fprintf(stderr, "[mylog] exception: %s\n", *exception_str);

        strcpy(result_buf, *exception_str);
        *res_length = strlen(*exception_str);
    }
    else {
        String::AsciiValue ascii(result);

        //fprintf(stderr, "[mylog] output: %s\n", *ascii);

        strcpy(result_buf, *ascii);
        *res_length = strlen(*ascii);
    }

    context.Dispose();

    return result_buf;
}
void ReportException(TryCatch &try_catch, bool show_line, std::string& err_msg) {
  HandleScope scope;

  if (show_line) DisplayExceptionLine(try_catch, err_msg);

  String::Utf8Value trace(try_catch.StackTrace());

  // range errors have a trace member set to undefined
  if (trace.length() > 0 && !try_catch.StackTrace()->IsUndefined()) {
    fprintf(stderr, "%s\n", *trace);
    err_msg +=  *trace;
    err_msg +=  "\n";
  } else {
    // this really only happens for RangeErrors, since they're the only
    // kind that won't have all this info in the trace, or when non-Error
    // objects are thrown manually.
    Local<Value> er = try_catch.Exception();
    bool isErrorObject = er->IsObject() &&
      !(er->ToObject()->Get(String::New("message"))->IsUndefined()) &&
      !(er->ToObject()->Get(String::New("name"))->IsUndefined());

    if (isErrorObject) {
      String::Utf8Value name(er->ToObject()->Get(String::New("name")));
      fprintf(stderr, "%s: ", *name);
      err_msg += *name;
      err_msg += ": ";
    }

    String::Utf8Value msg(!isErrorObject ? er
                         : er->ToObject()->Get(String::New("message")));
    fprintf(stderr, "%s\n", *msg);
    err_msg += *msg;
    err_msg += "\n";
  }

  fflush(stderr);
}
예제 #20
0
파일: JSEngine.cpp 프로젝트: Spacefish/susi
Handle<Value> Susi::JS::Engine::convertFromCPP(Susi::Util::Any cppVal){
	if(cppVal.isNull()){
		return Handle<Value>{};
	}
	std::cout<<Susi::JS::engine->isolate<<std::endl;
	auto isolate = Susi::JS::engine->isolate;
	Handle<Context> context = isolate->GetCurrentContext();
    Handle<Object> global = context->Global();
 	Handle<Object> JSON = global->Get(String::NewFromUtf8(isolate,"JSON"))->ToObject();
    Handle<Function> JSON_parse = Handle<Function>::Cast(JSON->Get(String::NewFromUtf8(isolate,"parse")));
	Handle<Value> arguments[1];
	std::cout<<cppVal.toString()<<std::endl;

	arguments[0] = String::NewFromUtf8(isolate,cppVal.toString().c_str());
	TryCatch trycatch;
	auto res = JSON_parse->Call(JSON, 1, arguments);
	if (res.IsEmpty()) {
		Handle<Value> exception = trycatch.Exception();
		String::Utf8Value exception_str(exception);
		std::cout<<*exception_str<<std::endl;
		throw std::runtime_error{*exception_str};
	}
	return res;
}
예제 #21
0
   HandleScope handle_scope;

   // Enter the created context for compiling and running the script.
   Context::Scope context_scope(context);

   // Create a string containing the JavaScript source code.
   Handle<String> source = String::New(U_STRING_TO_PARAM(x));

   // Compile the source code.
   TryCatch tryCatch;

   Handle<Script> script = Script::Compile(source);

   if (script.IsEmpty())
      {
      String::Utf8Value error(tryCatch.Exception());

      (void) x.replace(*error, error.length());

      return;
      }

   // Run the script
   Handle<Value> result = script->Run();

   if (result.IsEmpty())
      {
      String::Utf8Value error (tryCatch.Exception());

      (void) x.replace(*error, error.length());
예제 #22
0
파일: beascript.cpp 프로젝트: bagobor/bea
	//Report the error from an exception, store it in lastError
	void BeaContext::reportError(TryCatch& try_catch){
		lastError = *v8::String::Utf8Value(try_catch.Exception());
		if (m_logger)
			m_logger(*v8::String::Utf8Value(try_catch.StackTrace()));
	}
예제 #23
0
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;
}
예제 #24
0
    void JSHandler::dispatch_object(const input_iterator& it) {
        HandleScope scope;
        switch (it->type()) {
            case osmium::item_type::node:
                if (!node_cb.IsEmpty() && (!node_callback_for_tagged_only || !it->tags().empty())) {
                    const int argc = 1;

                    Handle<Value> ext = External::New(new OSMNodeWrap(it));
                    Local<Object> obj = OSMNodeWrap::constructor->GetFunction()->NewInstance(1, &ext);
                    Local<Value> argv[argc] = { obj };

                    TryCatch trycatch;
                    Handle<Value> v = node_cb->Call(Context::GetCurrent()->Global(), argc, argv);
                    if (v.IsEmpty()) {
                        Handle<Value> exception = trycatch.Exception();
                        String::AsciiValue exception_str(exception);
                        printf("Exception: %s\n", *exception_str);
                        exit(1);
                    }
                }
                break;
            case osmium::item_type::way:
                if (!way_cb.IsEmpty()) {
                    const int argc = 1;

                    Handle<Value> ext = External::New(new OSMWayWrap(it));
                    Local<Object> obj = OSMWayWrap::constructor->GetFunction()->NewInstance(1, &ext);
                    Local<Value> argv[argc] = { obj };

                    TryCatch trycatch;
                    Handle<Value> v = way_cb->Call(Context::GetCurrent()->Global(), argc, argv);
                    if (v.IsEmpty()) {
                        Handle<Value> exception = trycatch.Exception();
                        String::AsciiValue exception_str(exception);
                        printf("Exception: %s\n", *exception_str);
                        exit(1);
                    }
                }
                break;
            case osmium::item_type::relation:
                if (!relation_cb.IsEmpty()) {
                    const int argc = 1;

                    Handle<Value> ext = External::New(new OSMRelationWrap(it));
                    Local<Object> obj = OSMRelationWrap::constructor->GetFunction()->NewInstance(1, &ext);
                    Local<Value> argv[argc] = { obj };

                    TryCatch trycatch;
                    Handle<Value> v = relation_cb->Call(Context::GetCurrent()->Global(), argc, argv);
                    if (v.IsEmpty()) {
                        Handle<Value> exception = trycatch.Exception();
                        String::AsciiValue exception_str(exception);
                        printf("Exception: %s\n", *exception_str);
                        exit(1);
                    }
                }
                break;
            default:
                break;
        }
    }
예제 #25
0
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;
}
예제 #26
0
static gboolean
gum_script_create_context (GumScript * self,
                           GError ** error)
{
  GumScriptPrivate * priv = self->priv;

  g_assert (priv->context == NULL);

  {
    Locker locker (priv->isolate);
    Isolate::Scope isolate_scope (priv->isolate);
    HandleScope handle_scope (priv->isolate);

    Handle<ObjectTemplate> global_templ = ObjectTemplate::New ();
    _gum_script_core_init (&priv->core, self, priv->main_context, priv->isolate,
        global_templ);
    _gum_script_memory_init (&priv->memory, &priv->core, global_templ);
    _gum_script_process_init (&priv->process, &priv->core, global_templ);
    _gum_script_thread_init (&priv->thread, &priv->core, global_templ);
    _gum_script_module_init (&priv->module, &priv->core, global_templ);
    _gum_script_file_init (&priv->file, &priv->core, global_templ);
    _gum_script_socket_init (&priv->socket, &priv->core, global_templ);
    _gum_script_interceptor_init (&priv->interceptor, &priv->core,
        global_templ);
    _gum_script_stalker_init (&priv->stalker, &priv->core, global_templ);
    _gum_script_instruction_init (&priv->instruction, &priv->core,
        global_templ);

    Local<Context> context (Context::New (priv->isolate, NULL, global_templ));
    priv->context = new GumPersistent<Context>::type (priv->isolate, context);
    Context::Scope context_scope (context);
    _gum_script_core_realize (&priv->core);
    _gum_script_memory_realize (&priv->memory);
    _gum_script_process_realize (&priv->process);
    _gum_script_thread_realize (&priv->thread);
    _gum_script_module_realize (&priv->module);
    _gum_script_file_realize (&priv->file);
    _gum_script_socket_realize (&priv->socket);
    _gum_script_interceptor_realize (&priv->interceptor);
    _gum_script_stalker_realize (&priv->stalker);
    _gum_script_instruction_realize (&priv->instruction);

    gchar * combined_source = g_strconcat (
#include "gumscript-runtime.h"
        "\n",
        priv->source,
        static_cast<void *> (NULL));
    Local<String> source_value (String::NewFromUtf8 (priv->isolate, combined_source));
    g_free (combined_source);
    TryCatch trycatch;
    Handle<Script> raw_script = Script::Compile (source_value);
    if (raw_script.IsEmpty ())
    {
      Handle<Message> message = trycatch.Message ();
      Handle<Value> exception = trycatch.Exception ();
      String::Utf8Value exception_str (exception);
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Script(line %d): %s",
          message->GetLineNumber () - GUM_SCRIPT_RUNTIME_SOURCE_LINE_COUNT,
          *exception_str);
    }
    else
    {
      priv->raw_script =
          new GumPersistent<Script>::type (priv->isolate, raw_script);
    }
  }

  if (priv->raw_script == NULL)
  {
    gum_script_destroy_context (self);
    return FALSE;
  }

  return TRUE;
}
예제 #27
0
void UiWindow::InvokeEventCallback(Isolate* isolate, WindowEventData* data) {
    WINDOW_EVENT evt = data->Evt;

    Local<Object> hndl = handle();
    Local<Function> emitFn = Local<Function>::New(isolate, _emitFn);

    if (evt == WINDOW_EVENT_READY) {
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "ready") };
        emitFn->Call(hndl, 1, argv);
    }
    else if (evt == WINDOW_EVENT_CLOSING) {
        if (!_shouldClose) {
            auto closeArg = Object::New(isolate);
            Handle<Value> argv[] = { String::NewFromUtf8(isolate, "closing"), closeArg };
            auto result = emitFn->Call(hndl, 2, argv);
            result->BooleanValue();
            _shouldClose = !closeArg->Get(String::NewFromUtf8(isolate, "cancel"))->BooleanValue();
        }
        if (_shouldClose) {
            Close();
        }
    }
    else if (evt == WINDOW_EVENT_CLOSED) {
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "closed") };
        emitFn->Call(hndl, 1, argv);
    }
    else if (evt == WINDOW_EVENT_RESIZE) {
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "resize"),
            Int32::New(isolate, (int)data->Arg1), Int32::New(isolate, (int)data->Arg2) };
        emitFn->Call(hndl, 3, argv);
    }
    else if (evt == WINDOW_EVENT_STATE) {
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "state"), Int32::New(isolate, (int)data->Arg1) };
        emitFn->Call(hndl, 2, argv);
    }
    else if (evt == WINDOW_EVENT_MOVE) {
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "move"),
            Int32::New(isolate, (int)data->Arg1), Int32::New(isolate, (int)data->Arg2) };
        emitFn->Call(hndl, 3, argv);
    }
    else if (evt == WINDOW_EVENT_DOCUMENT_COMPLETE) {
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "documentComplete") };
        emitFn->Call(hndl, 1, argv);
    }
    else if (evt == WINDOW_EVENT_MENU) {
        UiMenu* menu = (UiMenu*)data->Arg1;
        Handle<Value> argId = menu->Id ? (Handle<Value>)*menu->Id : (Handle<Value>)Null(isolate);
        Handle<Value> argTitle = menu->Title ? (Handle<Value>)*menu->Title : (Handle<Value>)Null(isolate);
        Handle<Value> argv[] = { String::NewFromUtf8(isolate, "menu"), argId, argTitle };
        emitFn->Call(hndl, 3, argv);
        if (!menu->Callback.IsEmpty()) {
            Local<Function> fn = Local<Function>::New(isolate, menu->Callback);
            Handle<Value> callbackArgv[] = { argId, argTitle };
            fn->Call(hndl, 2, callbackArgv);
        }
    }
    else if (evt == WINDOW_EVENT_MESSAGE) {
        Utf8String* msg = (Utf8String*)data->Arg1;
        auto callback = (void*)data->Arg2;
        if (!_onMessageFn.IsEmpty()) {
            auto onMessage = Local<Function>::New(isolate, _onMessageFn);
            Handle<Value> argv[] = { JsonParse(*msg) };
            auto result = onMessage->Call(hndl, 1, argv);
            if (callback) {
                TryCatch tc;
                result = JsonStringify(result);
                Utf8String* resultStr = new Utf8String(result);
                Utf8String* errorStr = NULL;
                if (tc.HasCaught())
                    errorStr = new Utf8String(tc.Exception()->ToString());
                this->MsgCallback(callback, resultStr, errorStr);
            }
        }
        delete msg;
    }
    else if (evt == WINDOW_EVENT_MESSAGE_CALLBACK) {
        Persistent<Function>* callback = (Persistent<Function>*)data->Arg1;
        Utf8String* result = (Utf8String*)data->Arg2;
        Utf8String* error = (Utf8String*)data->Arg3;
        if (callback) {
            auto callbackFn = Local<Function>::New(isolate, *callback);
            Handle<Value> argv[] = { Null(isolate), Null(isolate) };
            if (result)
                argv[0] = JsonParse(*result);
            if (error)
                argv[0] = *error;
            callbackFn->Call(hndl, 2, argv);
            callback->Reset();
            delete callback;
        }
        if (result)
            delete result;
        if (error)
            delete error;
    }
    else if (evt == WINDOW_EVENT_SELECT_FILE) {
        auto params = (WindowOpenFileParams*)data->Arg1;
        auto result = (Utf8String**)data->Arg2;
        Handle<Value> callbackResult;
        if (result) {
            auto len = 0;
            for (len = 0; result[len]; ) {
                len++;
            }
            auto resArr = Array::New(isolate, len);
            callbackResult = resArr;
            for (auto i = 0; result[i]; i++) {
                resArr->Set(i, *result[i]);
                delete result[i];
            }
            delete[] result;
        } else {
            callbackResult = (Handle<Value>)Null(isolate);
        }
        if (!params->Complete.IsEmpty()) {
            auto callbackFn = Local<Function>::New(isolate, params->Complete);
            Handle<Value> argv[] = { callbackResult };
            callbackFn->Call(hndl, 1, argv);
        }
        delete params;
    }
}
//事件循环
//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(); //摧毁上下文
}

}
예제 #29
0
static gboolean
gum_script_create_context (GumScript * self,
                           GError ** error)
{
  GumScriptPrivate * priv = self->priv;

  g_assert (priv->context == NULL);

  {
    Handle<ObjectTemplate> global_templ = ObjectTemplate::New ();
    _gum_script_core_init (&priv->core, self, gum_script_emit_message,
        gum_script_get_scheduler (), priv->isolate, global_templ);
    _gum_script_memory_init (&priv->memory, &priv->core, global_templ);
    _gum_script_process_init (&priv->process, &priv->core, global_templ);
    _gum_script_thread_init (&priv->thread, &priv->core, global_templ);
    _gum_script_module_init (&priv->module, &priv->core, global_templ);
    _gum_script_file_init (&priv->file, &priv->core, global_templ);
    _gum_script_socket_init (&priv->socket, &priv->core, global_templ);
    _gum_script_interceptor_init (&priv->interceptor, &priv->core,
        global_templ);
    _gum_script_stalker_init (&priv->stalker, &priv->core, global_templ);
    _gum_script_symbol_init (&priv->symbol, &priv->core, global_templ);
    _gum_script_instruction_init (&priv->instruction, &priv->core,
        global_templ);

    Local<Context> context (Context::New (priv->isolate, NULL, global_templ));
    priv->context = new GumPersistent<Context>::type (priv->isolate, context);
    Context::Scope context_scope (context);
    _gum_script_core_realize (&priv->core);
    _gum_script_memory_realize (&priv->memory);
    _gum_script_process_realize (&priv->process);
    _gum_script_thread_realize (&priv->thread);
    _gum_script_module_realize (&priv->module);
    _gum_script_file_realize (&priv->file);
    _gum_script_socket_realize (&priv->socket);
    _gum_script_interceptor_realize (&priv->interceptor);
    _gum_script_stalker_realize (&priv->stalker);
    _gum_script_symbol_realize (&priv->symbol);
    _gum_script_instruction_realize (&priv->instruction);

    gchar * resource_name_str = g_strconcat (priv->name, ".js",
        (gpointer) NULL);
    Local<String> resource_name (String::NewFromUtf8 (priv->isolate,
        resource_name_str));
    ScriptOrigin origin (resource_name);
    g_free (resource_name_str);

    Local<String> source (String::NewFromUtf8 (priv->isolate,
        priv->source));

    TryCatch trycatch;
    MaybeLocal<Script> maybe_code =
        Script::Compile (context, source, &origin);
    Local<Script> code;
    if (maybe_code.ToLocal (&code))
    {
      priv->code =
          new GumPersistent<Script>::type (priv->isolate, code);
    }
    else
    {
      Handle<Message> message = trycatch.Message ();
      Handle<Value> exception = trycatch.Exception ();
      String::Utf8Value exception_str (exception);
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Script(line %d): %s",
          message->GetLineNumber (), *exception_str);
    }
  }

  if (priv->code == NULL)
  {
    gum_script_destroy_context (self);
    return FALSE;
  }

  return TRUE;
}
int TiRootObject::executeScript(NativeObjectFactory* objectFactory, const char* javaScript,
                                MESSAGELOOPENTRY messageLoopEntry, void* context)
{
    HandleScope handleScope;
    objectFactory_ = objectFactory;
    globalTemplate_ = ObjectTemplate::New();
    TiV8EventContainerFactory* eventFactory = TiV8EventContainerFactory::createEventContainerFactory(globalTemplate_);
    objectFactory->setEventContainerFactory(eventFactory);
    onSetGetPropertyCallback(&globalTemplate_);
    onSetFunctionCallback(&globalTemplate_);
    g_rootTemplate = ObjectTemplate::New();
    context_ = Context::New(NULL, g_rootTemplate);
    forceSetValue(context_->Global());
    context_->Global()->SetHiddenValue(String::New("globalTemplate_"), External::New(&globalTemplate_));
    context_->Global()->SetHiddenValue(String::New("context_"), External::New(&context_));
    setTiObjectToJsObject(context_->Global(), this);
    Context::Scope context_scope(context_);
    initializeTiObject(NULL);

    const char* bootstrapFilename = "bootstrap.js";
    string bootstrapJavascript;
    {
        ifstream ifs((string("app/native/framework/") + bootstrapFilename).c_str());
        if (!ifs)
        {
            TiLogger::getInstance().log(Ti::Msg::ERROR__Cannot_load_bootstrap_js);
            return -1;
        }
        getline(ifs, bootstrapJavascript, string::traits_type::to_char_type(string::traits_type::eof()));
        ifs.close();
    }

    TryCatch tryCatch;
    Handle<Script> compiledBootstrapScript = Script::Compile(String::New(bootstrapJavascript.c_str()), String::New(bootstrapFilename));
    if (compiledBootstrapScript.IsEmpty())
    {
        String::Utf8Value error(tryCatch.Exception());
        TiLogger::getInstance().log(*error);
        return -1;
    }
    Handle<Value> bootstrapResult = compiledBootstrapScript->Run();
    if (bootstrapResult.IsEmpty())
    {
        Local<Value> exception = tryCatch.Exception();
        // FIXME: need a way to prevent double "filename + line" output
        Handle<Message> msg = tryCatch.Message();
        stringstream ss;
        ss << bootstrapFilename << " line ";
        if (msg.IsEmpty())
        {
            ss << "?";
        }
        else
        {
            ss << msg->GetLineNumber();
        }
        ss << ": " << *String::Utf8Value(exception);
        TiLogger::getInstance().log(ss.str().c_str());
        return -1;
    }

    const char* filename = "app.js";
    Handle<Script> compiledScript = Script::Compile(String::New(javaScript), String::New(filename));
    if (compiledScript.IsEmpty())
    {
        ReportException(tryCatch, true);
        return 1;
    }
    compiledScript->Run();
    if (tryCatch.HasCaught())
    {
        ReportException(tryCatch, true);
        return 1;
    }
    onStartMessagePump();
    return (messageLoopEntry)(context);
}