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) );
}
예제 #2
0
void
test_BasicCall()
{
  HandleScope handle_scope;
  Handle<ObjectTemplate> templ = ObjectTemplate::New();
  Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne);
  templ->Set("AddOne", fnT);

  Persistent<Context> context = Context::New(NULL, templ);
  Context::Scope context_scope(context);
  Local<Value> addone = context->Global()->Get(String::New("AddOne"));
  do_check_true(!addone.IsEmpty());
  do_check_true(!addone->IsUndefined());
  do_check_true(addone->IsObject());
  do_check_true(addone->IsFunction());
  Local<Function> fn = addone.As<Function>();
  do_check_eq(fn, fnT->GetFunction());
  Local<Number> n = Number::New(0.5);
  Handle<Value> args[] = { n };
  Local<Value> v = fn->Call(context->Global(), 1, args);
  do_check_true(!v.IsEmpty());
  do_check_true(v->IsNumber());
  Local<Number> n2 = v->ToNumber();
  do_check_eq(n2->Value(), 1.5);
  context.Dispose();
}
예제 #3
0
파일: jscontext.cpp 프로젝트: killf/V8Net
jsvalue JsContext::InvokeProperty(Persistent<Object>* obj, const uint16_t* name, jsvalue args)
{
    jsvalue v;

    Locker locker(isolate_);
    Isolate::Scope isolate_scope(isolate_);
    (*context_)->Enter();
        
    HandleScope scope;    
    TryCatch trycatch;
        
    Local<Value> prop = (*obj)->Get(String::New(name));
    if (prop.IsEmpty() || !prop->IsFunction()) {
        v = engine_->StringFromV8(String::New("property not found or isn't a function"));
        v.type = JSVALUE_TYPE_STRING_ERROR;   
    }
    else {
        std::vector<Local<Value> > argv(args.length);
        engine_->ArrayToV8Args(args, id_, &argv[0]);
        // TODO: Check ArrayToV8Args return value (but right now can't fail, right?)                   
        Local<Function> func = Local<Function>::Cast(prop);
        Local<Value> value = func->Call(*obj, args.length, &argv[0]);
        if (!value.IsEmpty()) {
            v = engine_->AnyFromV8(value);        
        }
        else {
            v = engine_->ErrorFromV8(trycatch);
        }         
    }
    
    (*context_)->Exit();
    
    return v;
}
예제 #4
0
char *JSMain::GetStackInfo(Isolate *isolate, int *lineNumber)
{
	HandleScope handle_scope(isolate);
	const char *file = __FILE__; /* Use current filename if we can't find the correct from JS stack */
	int line = __LINE__; /* Use current line number if we can't find the correct from JS stack */
	char *ret = NULL;

	/* Try to get the current stack trace (script file) */
	Local<StackTrace> stFile = StackTrace::CurrentStackTrace(isolate, 1, StackTrace::kScriptName);

	if (!stFile.IsEmpty()) {
		Local<StackFrame> sf = stFile->GetFrame(0);

		if (!sf.IsEmpty()) {
			Local<String> fn = sf->GetScriptName();

			if (!fn.IsEmpty()) {
				String::Utf8Value str(fn);

				if (*str) {
					js_strdup(ret, *str); // We must dup here
				}
			}
		}
	}

	/* dup current filename if we got nothing from stack */
	if (ret == NULL) {
		js_strdup(ret, file);
	}

	/* Try to get the current stack trace (line number) */
	if (lineNumber) {
		*lineNumber = 0;

		Local<StackTrace> stLine = StackTrace::CurrentStackTrace(isolate, 1, StackTrace::kLineNumber);

		if (!stLine.IsEmpty()) {
			Local<StackFrame> sf = stLine->GetFrame(0);

			if (!sf.IsEmpty()) {
				*lineNumber = sf->GetLineNumber();
			}
		}

		/* Use current file number if we got nothing from stack */
		if (*lineNumber == 0) {
			*lineNumber = line;
		}
	}

	/* Return dup'ed value - this must be freed by the calling function */
	return ret;
}
예제 #5
0
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);
}
예제 #6
0
void
test_HandleScope() {
  HandleScope outer;
  Local<Value> v;
  {
    HandleScope inner;
    v = inner.Close(String::New("hey"));
  }
  do_check_true(!v.IsEmpty());
  Local<String> s = v->ToString();
  do_check_true(!s.IsEmpty());
  do_check_true(s->Equals(v));
}
예제 #7
0
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;
}
예제 #8
0
파일: Conv.cpp 프로젝트: Armen138/anode
/* called by the Java environment for objects that have been finalized */
void Conv::releaseV8Handle(JNIEnv *jniEnv, Persistent<Object> val, int type) {
  HandleScope scope;
  Handle<String> sHiddenKey;
  Interface *interface = 0;
  ArrayType *arr = 0;
  if(type == -1) {
    sHiddenKey = sObjectHiddenKey;
  } else if(isArray(type)) {
    arrayConv->GetRefsForComponentType(jniEnv, getComponentType(type), &arr);
    sHiddenKey = arr->getHiddenKey();
  } else if(isInterface(type)) {
    interface = env->getInterface(getClassId(type));
    sHiddenKey = interface->getHiddenKey();
  }
  //LOGV("releaseV8Handle; interface = %p; getting hidden value; sHiddenKey = %p\n", interface, sHiddenKey);
  if(!sHiddenKey.IsEmpty()) {
    Local<Value> hiddenVal = val->GetHiddenValue(sHiddenKey);
    if(!hiddenVal.IsEmpty() && !hiddenVal->IsUndefined()) {
      jobject extRef = (jobject)External::Unwrap(hiddenVal);
      Conv::deleteGlobalRef(jniEnv, extRef);
      val->DeleteHiddenValue(sHiddenKey);
      if(interface) {
        while((interface = interface->getParent())) {
          val->DeleteHiddenValue(interface->getHiddenKey());
        }
      }
    }
  }
  val.Dispose();
}
예제 #9
0
파일: Conv.cpp 프로젝트: Armen138/anode
int Conv::UnwrapObject(JNIEnv *jniEnv, Handle<Object> val, Handle<String> key, jobject *jVal) {
  int result = ErrorNotfound;
  //LOGV("UnwrapObject; getting hidden value; key = %p\n", key);
  Local<Value> hiddenVal = val->GetHiddenValue(key);
  if(!hiddenVal.IsEmpty() && !hiddenVal->IsUndefined()) {
    jobject extRef = (jobject)External::Unwrap(hiddenVal);
    if(jniEnv->GetObjectRefType(extRef) == JNIWeakGlobalRefType) {
      jobject localRef = jniEnv->NewLocalRef(extRef);
      if(localRef == 0) {
        /* the Java object died */
        jniEnv->DeleteWeakGlobalRef(extRef);
        val->DeleteHiddenValue(key);
      } else {
        /* the java object is alive */
        *jVal = localRef;
        result = OK;
      }
    } else {
      /* the object is strongly referenced */
      *jVal = extRef;
      result = OK;
    }
  }
  return result;
}
예제 #10
0
void *ScriptObject::extractHolder(const Arguments &args)
{
    HandleScope handleScope;

    // Extract first internal field from Argument's holder object

    Local<Object> holderObject = args.Holder();

    if (holderObject->InternalFieldCount() < 1)
        throw bit::Exception("No internal fields found in holder object");

    Local<Value> holderValue = holderObject->GetInternalField(0);

    if (holderValue.IsEmpty())
        throw bit::Exception("Internal field could not be extracted from object");

    if (!holderValue->IsExternal())
        throw bit::Exception("The first field of holder object is not an ExternalObject");

    // Extract void pointer

    void *holderPointer = External::Unwrap(holderValue);

    if (holderPointer == NULL)
        throw bit::Exception("Extracted pointer is null");

    return holderPointer;
}
예제 #11
0
bool ArgConverter::TryConvertToJavaLong(const Local<Value>& value, jlong& javaLong)
{
	bool success = false;

	if (!value.IsEmpty())
	{
		if (value->IsNumber() || value->IsNumberObject())
		{
			javaLong = (jlong)value->IntegerValue();
			success = true;
		}
		else if (value->IsObject())
		{
			auto obj = Local<Object>::Cast(value);
			auto isJavaLongValue = obj->GetHiddenValue(V8StringConstants::GetJavaLong());
			if (!isJavaLongValue.IsEmpty() && isJavaLongValue->BooleanValue())
			{
				javaLong = (jlong)ConvertToJavaLong(value);
				success = true;
			}
		}
	}

	return success;
}
예제 #12
0
// プロパティ取得共通処理
tjs_error
TJSInstance::getProp(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, tTJSVariant *result)
{
	if (!membername) {
		return TJS_E_NOTIMPL;
	}
	
	HandleScope handle_scope(isolate);
	Context::Scope context_scope(getContext());
	TryCatch try_catch;
	
	Local<Value> ret = obj->Get(String::NewFromTwoByte(isolate, membername));
	if (ret.IsEmpty()) {
		return TJS_E_MEMBERNOTFOUND;
	} else {
		if (result) {
			if (ret->IsFunction()) {
				*result = toVariant(isolate, ret->ToObject(), obj);
			} else {
				*result = toVariant(isolate, ret);
			}
		}
	}
	return TJS_S_OK;
}
예제 #13
0
// メソッド呼び出し共通処理
tjs_error
TJSInstance::callMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, tTJSVariant *result, tjs_int numparams, tTJSVariant **param, iTJSDispatch2 *objthis)
{
	HandleScope handle_scope(isolate);
	Context::Scope context_scope(getContext());
	TryCatch try_catch;

	Local<Object> context = membername ? obj : objthis ? toJSValue(isolate, tTJSVariant(objthis))->ToObject() : getContext()->Global();
	Local<Object> method  = membername ? obj->Get(String::NewFromTwoByte(isolate, membername))->ToObject() : obj;

	if (!method->IsFunction()) {
		return TJS_E_NOTIMPL;
	}
	
	// 関数抽出
	Local<Function> func = Local<Function>::Cast(method);
	// 引数
	Handle<Value> *argv = new Handle<Value>[numparams];
	for (int i=0;i<numparams;i++) {
		argv[i] = toJSValue(isolate, *param[i]);
	}
	Local<Value> ret = func->Call(context, numparams, argv);
	delete argv;
	
	if (ret.IsEmpty()) {
		JSEXCEPTION(isolate, &try_catch);
	} else {
		if (result) {
			*result = toVariant(isolate, ret);
		}
	}
	return TJS_S_OK;
}
static void Set_DialogState_height(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
    HandleScope scope;

    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    if (wrap.IsEmpty())
        return;

    DialogState *tmp = (DialogState *) wrap->Value();
    if (tmp == NULL)
        return;

    if (!value.IsEmpty() && value->IsNumber())
        tmp->setHeight(value->Int32Value());
}
예제 #15
0
static gboolean
gum_script_process_thread_match (const GumThreadDetails * details,
                                 gpointer user_data)
{
  GumScriptMatchContext * ctx =
      static_cast<GumScriptMatchContext *> (user_data);
  GumScriptCore * core = ctx->self->core;
  Isolate * isolate = ctx->isolate;

  if (gum_script_is_ignoring (details->id))
    return TRUE;

  Local<Object> thread (Object::New (isolate));
  _gum_script_set (thread, "id", Number::New (isolate, details->id), core);
  _gum_script_set (thread, "state", String::NewFromOneByte (isolate,
          reinterpret_cast<const uint8_t *> (gum_script_thread_state_to_string (
          details->state))),
      core);
  _gum_script_set (thread, "context", _gum_script_cpu_context_new (
      &details->cpu_context, ctx->self->core), core);

  Handle<Value> argv[] = { thread };
  Local<Value> result = ctx->on_match->Call (ctx->receiver, 1, argv);

  gboolean proceed = TRUE;
  if (!result.IsEmpty () && result->IsString ())
  {
    String::Utf8Value str (result);
    proceed = (strcmp (*str, "stop") != 0);
  }

  return proceed;
}
예제 #16
0
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;
}
예제 #17
0
    int V8Scope::invoke( ScriptingFunction func , const BSONObj& argsObject, int timeoutMs , bool ignoreReturn ){
        Handle<Value> funcValue = _funcs[func-1];
        
        TryCatch try_catch;        
        int nargs = argsObject.nFields();
        auto_ptr< Handle<Value> > args;
        if ( nargs ){
            args.reset( new Handle<Value>[nargs] );
            BSONObjIterator it( argsObject );
            for ( int i=0; i<nargs; i++ ){
                BSONElement next = it.next();
                args.get()[i] = mongoToV8Element( next );
            }
        }
        Local<Value> result = ((v8::Function*)(*funcValue))->Call( _this , nargs , args.get() );
                
        if ( result.IsEmpty() ){
            stringstream ss;
            ss << "error in invoke: " << toSTLString( &try_catch );
            _error = ss.str();
            log() << _error << endl;
            return 1;
        }

        if ( ! ignoreReturn ){
            _global->Set( v8::String::New( "return" ) , result );
        }

        return 0;
    }
예제 #18
0
void Server::New(std::string filename, AMX *amx){

	if (Server::_scripts.find(filename) != Server::_scripts.end()){
		sjs::logger::error("load: Script already loaded (%s)", filename.c_str());
		return;
	}
	auto jsfile = std::make_shared<Server>();
	jsfile->SetAMX(amx);
	jsfile->SetScriptName(filename);
	jsfile->Init();

	jsfile->AddModule("utils", Utils(jsfile));
	jsfile->AddModule("$fs", FileSystem(jsfile));
	jsfile->AddModule("players", Players(jsfile));
	jsfile->AddModule("$sockets", Sockets(jsfile));
	
	JS_SCOPE(jsfile->GetIsolate())
	
		JS_CONTEXT(jsfile->GetIsolate(), jsfile->_context)
	
		Local<Value> ret = jsfile->LoadScript("js/" + filename);

	if (ret.IsEmpty()){
		sjs::logger::error("Could not create new script (%s)", filename.c_str());
		return;
	}
	

	String::Utf8Value jsStr(ret);
	char* str = *jsStr;
	Server::_scripts[filename] = jsfile;

	Server::_scripts[filename]->EventManager()->FireEvent("ScriptInit");

}
예제 #19
0
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);
}
예제 #20
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;
}
예제 #21
0
static gboolean
gum_script_process_handle_module_match (const GumModuleDetails * details,
                                        gpointer user_data)
{
  GumScriptMatchContext * ctx =
      static_cast<GumScriptMatchContext *> (user_data);
  GumScriptCore * core = ctx->self->core;
  Isolate * isolate = ctx->isolate;

  Local<Object> module (Object::New (isolate));
  _gum_script_set_ascii (module, "name", details->name, core);
  _gum_script_set_pointer (module, "base", details->range->base_address, core);
  _gum_script_set_uint (module, "size", details->range->size, core);
  _gum_script_set_utf8 (module, "path", details->path, core);

  Handle<Value> argv[] = {
    module
  };
  Local<Value> result = ctx->on_match->Call (ctx->receiver, 1, argv);

  gboolean proceed = TRUE;
  if (!result.IsEmpty () && result->IsString ())
  {
    String::Utf8Value str (result);
    proceed = (strcmp (*str, "stop") != 0);
  }

  return proceed;
}
예제 #22
0
static gboolean
gum_v8_process_handle_malloc_range_match (const GumMallocRangeDetails * details,
                                          gpointer user_data)
{
  GumV8MatchContext * ctx =
      static_cast<GumV8MatchContext *> (user_data);
  GumV8Core * core = ctx->self->core;
  Isolate * isolate = ctx->isolate;

  Local<Object> range (Object::New (isolate));
  _gum_v8_object_set_pointer (range, "base", details->range->base_address, core);
  _gum_v8_object_set_uint (range, "size", details->range->size, core);

  Handle<Value> argv[] = {
    range
  };
  Local<Value> result = ctx->on_match->Call (ctx->receiver, 1, argv);

  gboolean proceed = TRUE;
  if (!result.IsEmpty () && result->IsString ())
  {
    String::Utf8Value str (result);
    proceed = (strcmp (*str, "stop") != 0);
  }

  return proceed;
}
예제 #23
0
JSONValue JSONValue::operator[](int index)
{
	Locker locker(isolate);
	Isolate::Scope isolateScope(isolate);
	HandleScope handleScope;
	
	// Check if value is an array
	
	if (!value->IsArray())
		throw bit::Exception("JSONValue is not an array");
	
	Local<Value> valueLocal = Local<Value>::New(value);
	Local<Array> valueArray = Local<Array>::Cast(valueLocal);
	
	if (valueArray.IsEmpty())
		throw bit::Exception("V8 array could not be created");
	
	// Check if index exists
	
	if (!valueArray->Has(index))
		throw bit::Exception("Index does not exist");
	
	// Return JSONValue
	
	Local<Value> newValue = valueArray->Get(index);
	JSONValue jsonValue(newValue, isolate);
	
	return jsonValue;
}
예제 #24
0
static gboolean
gum_v8_exception_handler_on_exception (GumExceptionDetails * details,
                                       gpointer user_data)
{
  GumV8ExceptionHandler * handler = (GumV8ExceptionHandler *) user_data;
  GumV8Core * core = handler->core;

  ScriptScope scope (core->script);
  Isolate * isolate = core->isolate;

  Local<Function> callback (Local<Function>::New (isolate, *handler->callback));

  Local<Object> ex, context;
  _gum_v8_parse_exception_details (details, ex, context, core);

  Handle<Value> argv[] = { ex };
  Local<Value> result = callback->Call (Null (isolate), 1, argv);

  _gum_v8_cpu_context_free_later (
      new GumPersistent<Object>::type (isolate, context),
      core);

  if (!result.IsEmpty () && result->IsBoolean ())
  {
    bool handled = result.As<Boolean> ()->Value ();
    return handled ? TRUE : FALSE;
  }

  return FALSE;
}
예제 #25
0
// コンストラクタ呼び出し共通処理
tjs_error
TJSInstance::createMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, iTJSDispatch2 **result, tjs_int numparams, tTJSVariant **param)
{
	if (membername) {
		return TJS_E_MEMBERNOTFOUND;
	}

	HandleScope handle_scope(isolate);
	Context::Scope context_scope(getContext());
	TryCatch try_catch;

	if (!obj->IsFunction()) {
		return TJS_E_NOTIMPL;
	}
	
	// 関数抽出
	Local<Function> func = Local<Function>::Cast(obj->ToObject());
	// 引数
	Handle<Value> *argv = new Handle<Value>[numparams];
	for (int i=0;i<numparams;i++) {
		argv[i] = toJSValue(isolate, *param[i]);
	}
	Local<Object> ret = func->NewInstance(numparams, argv);
	delete argv;
	
	if (ret.IsEmpty()) {
		JSEXCEPTION(isolate, &try_catch);
	} else {
		if (result) {
			*result = toVariant(isolate, ret);
		}
	}
	return TJS_S_OK;
}
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;
    }
}
예제 #27
0
파일: jscontext.cpp 프로젝트: killf/V8Net
jsvalue JsContext::GetPropertyValue(Persistent<Object>* obj, const uint16_t* name)
{
    jsvalue v;
    
    Locker locker(isolate_);
    Isolate::Scope isolate_scope(isolate_);
    (*context_)->Enter();
        
    HandleScope scope;
    TryCatch trycatch;
                
    Local<Value> value = (*obj)->Get(String::New(name));
    if (!value.IsEmpty()) {

		Handle<v8::Object> obj_handle = Handle<v8::Object>(*obj);
        v = engine_->AnyFromV8(value,obj_handle);        
    }
    else {
        v = engine_->ErrorFromV8(trycatch);
    }
    
    (*context_)->Exit();
    
    return v;
}
Ti::TiValue Ti::TiViewProxy::remove(Ti::TiValue value)
{
	Ti::TiValue val;
	val.setUndefined();

	Ti::TiViewProxy *childProxy = static_cast<Ti::TiViewProxy*>(value.toProxy());
	if(!_childViewsProxies.contains(childProxy)) return val;

	Ti::TiView* childView = childProxy->getView();
	Ti::TiView* thisView = getView();
	childProxy->makeWeak();
	thisView->remove(childView);
	_childViewsProxies.removeOne(childProxy);

	childProxy->_parentProxy = NULL;
    Local<Value> children = _jsObject->Get(String::New("children"));
    if(!children.IsEmpty() && !children->IsUndefined())
    {
    	Local<Array> array = Local<Array>::Cast(children);
    	for(int i = 0, len = array->Length(); i < len; i++) {
    		if(array->Get(i) == value.toJSValue())
    		{
    	    	array->Delete(i);
    	    	break;
    		}
    	}
    }

	return val;
}
예제 #29
0
파일: jscontext.cpp 프로젝트: killf/V8Net
jsvalue JsContext::Execute(JsScript *jsscript)
{
    jsvalue v;

    Locker locker(isolate_);
    Isolate::Scope isolate_scope(isolate_);
    (*context_)->Enter();
        
    HandleScope scope;
    TryCatch trycatch;
   
	Handle<Script> script = (*jsscript->GetScript());

	if (!script.IsEmpty()) {
		Local<Value> result = script->Run();
	
		if (result.IsEmpty())
			v = engine_->ErrorFromV8(trycatch);
		else
			v = engine_->AnyFromV8(result);        
	}

    (*context_)->Exit();
	return v;     
}
예제 #30
0
bool
WeechatJsV8::execScript()
{
    v8::TryCatch trycatch;

    this->context = Context::New(NULL, this->global);
    Context::Scope context_scope(this->context);
    Handle<Script> script = Script::Compile(this->source);

    if (script.IsEmpty())
    {
        PRINT_EXCEPTION;
        return false;
    }
    else
    {
        Local<Value> value = script->Run();
        if (value.IsEmpty())
        {
            PRINT_EXCEPTION;
            return false;
        }
    }

    return true;
}