Example #1
0
// Fetch the onDraw function from the global context.
bool JsContext::initialize() {

    // Create a stack-allocated handle scope.
    HandleScope handleScope(fGlobal->getIsolate());

    // Create a local context from our global context.
    Local<Context> context = fGlobal->getContext();

    // Enter the scope so all operations take place in the scope.
    Context::Scope contextScope(context);

    v8::TryCatch try_catch;

    Handle<String> fn_name = String::NewFromUtf8(
        fGlobal->getIsolate(), "onDraw");
    Handle<Value> fn_val = context->Global()->Get(fn_name);

    if (!fn_val->IsFunction()) {
        printf("Not a function.\n");
        return false;
    }

    // It is a function; cast it to a Function.
    Handle<Function> fn_fun = Handle<Function>::Cast(fn_val);

    // Store the function in a Persistent handle, since we also want that to
    // remain after this call returns.
    fOnDraw.Reset(fGlobal->getIsolate(), fn_fun);

    return true;
}
Example #2
0
void Server::FireEvent(std::string name, const int argc, Local<Value> argv[] ){
	Locker v8Locker(isolate);
	Isolate::Scope isoscope(isolate);
	HandleScope hs(isolate);
	Local<Context> ctx = Local<Context>::New(isolate, context);
	Context::Scope cs(ctx);
	TryCatch try_catch;

	JS_Object global(ctx->Global());

	Local<Object> serverjs = global.getObject("$server");
	Local<Value> fire = serverjs->Get(String::NewFromUtf8(isolate, "fire"));
	Local<Function> fn = Local<Function>::Cast(fire);

	if (name == "ScriptInit"){
		Local<Value> check = serverjs->Get(String::NewFromUtf8(isolate, "checkPlayers"));
		Local<Function> cpfn = Local<Function>::Cast(check);
		cpfn->Call(serverjs, 0, NULL);
	}
	Local<Value> *args = new Local<Value>[argc + 1];
	args[0] = String::NewFromUtf8(isolate, name.c_str());
	if (argc > 0){
		for (int i = 0; i < argc; i++){
			args[i + 1] = argv[i];
		}
	}
	fn->Call(serverjs, argc + 1, args);

	delete[] args;

	if (try_catch.HasCaught()){
		Utils::PrintException(&try_catch);
	}
}
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;
    }
}
void CallJSFunction(JavaScriptCompiler &jsc,  
		    JavaScriptSource *source,
		    const char *name)
{
	HandleScope scope(jsc.GetIsolate());
	Local<Context> ctx = Local<Context>::New(jsc.GetIsolate(), source->ctx_);
	Context::Scope context_scope(ctx);
	Handle<Value> rewriteFuncValue = ctx->Global()->Get(String::NewSymbol(name));
	if (!rewriteFuncValue.IsEmpty() && rewriteFuncValue->IsFunction()) {
		const int argc = 0;
		Handle<Function> initFunc = Handle<Function>::Cast(rewriteFuncValue);
		Handle<Value> ret = initFunc->Call(ctx->Global(), argc, NULL);
		String::AsciiValue ascii(ret);
		ASSERT_STREQ("OK", *ascii);
	}
}
Example #5
0
 TEST_F(JSDeviceTest, createTemplate) {
     HandleScope handle_scope(isolate);
     Local<Context> context = Context::New(isolate, nullptr);
     Context::Scope context_scope(context);
     Handle<Object> global = context->Global();
     jsDevice->initJsObjectsTemplate(isolate, global);
 }
Example #6
0
void Server::Init(Local<Context> ctx){
	isolate = ctx->GetIsolate();
	context.Reset(ctx->GetIsolate(), ctx);


	ifstream serverFile("js/samp.js/Server.js", std::ios::in);
	if (!serverFile){
		sjs::logger::error("Missing required file Server.js");
		SAMPJS::Shutdown();
	}
	std::string serverSource((std::istreambuf_iterator<char>(serverFile)), std::istreambuf_iterator<char>());
	SAMPJS::ExecuteCode(ctx, "Server.js", serverSource);

	SAMPJS::ExecuteCode(ctx, "$server", "var $server = new Server();");

	JS_Object global(ctx->Global());

	global.Set("CallNative", Server::JS_CallNative);

	JS_Object server(global.getObject("$server"));

	JS_Object memory(server.getObject("memory"));

	memory.Set("current", Server::JS_CurrentMemory);
	memory.Set("peak", Server::JS_PeakMemory);
	
	server.Set("Debug", Utils::JS_Debug);

	
}
Example #7
0
extern "C" void Java_io_neft_Native_renderer_1callAnimationFrame(JNIEnv * env, jobject obj) {
    using namespace renderer;

    // enter isolate
    Isolate* isolate = JS::GetIsolate();
    Locker locker(isolate);
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);

    // get local context and enter it
    Local<Context> context = Local<Context>::New(isolate, JS::GetContext());
    Context::Scope context_scope(context);

    // call all registered functions
    const int length = animationFrameCalls.size();
    for (int i = 0; i < length; i++){
        Persistent<Function, CopyablePersistentTraits<Function>> func = animationFrameCalls[i];

        // get local function
        Local<Function> localFunc = Local<Function>::New(isolate, func);

        // call function
        localFunc->Call(context->Global(), 0, NULL);

        // clear persistent
        func.Reset();
    }

    // remove called functions
    animationFrameCalls.erase(animationFrameCalls.begin(), animationFrameCalls.begin() + length);
}
Example #8
0
/* static */
void V8Runtime::bootstrap(Local<Context> context)
{
	Isolate* isolate = context->GetIsolate();
	EventEmitter::initTemplate(context);

	Local<Object> kroll = Object::New(isolate);
	krollGlobalObject.Reset(isolate, kroll);
	Local<Array> mc = Array::New(isolate);
	moduleContexts.Reset(isolate, mc);

	KrollBindings::initFunctions(kroll, context);

	SetMethod(isolate, kroll, "log", krollLog);
	// Move this into the EventEmitter::initTemplate call?
	Local<FunctionTemplate> eect = Local<FunctionTemplate>::New(isolate, EventEmitter::constructorTemplate);
	{
		v8::TryCatch tryCatch(isolate);
		Local<Function> eventEmitterConstructor;
		MaybeLocal<Function> maybeEventEmitterConstructor = eect->GetFunction(context);
		if (!maybeEventEmitterConstructor.ToLocal(&eventEmitterConstructor)) {
			titanium::V8Util::fatalException(isolate, tryCatch);
			return;
		}
		kroll->Set(NEW_SYMBOL(isolate, "EventEmitter"), eventEmitterConstructor);
	}

	kroll->Set(NEW_SYMBOL(isolate, "runtime"), STRING_NEW(isolate, "v8"));
	kroll->Set(NEW_SYMBOL(isolate, "DBG"), v8::Boolean::New(isolate, V8Runtime::DBG));
	kroll->Set(NEW_SYMBOL(isolate, "moduleContexts"), mc);

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch(isolate);
	Local<Value> result = V8Util::executeString(isolate, KrollBindings::getMainSource(isolate), STRING_NEW(isolate, "ti:/kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(isolate, tryCatch, true);
	}

	// Add a reference to the global object
	Local<Object> global = context->Global();

	// Expose the global object as a property on itself
	// (Allows you to set stuff on `global` from anywhere in JavaScript.)
	global->Set(NEW_SYMBOL(isolate, "global"), global);

	Local<Function> mainFunction = result.As<Function>();
	Local<Value> args[] = { kroll };
	mainFunction->Call(context, global, 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Example #9
0
        void JSAttributeTest::createTemplateTest(std::shared_ptr<JSZAttribute> &jsZAttribute) {
            HandleScope handle_scope(isolate);
            Local<Context> context = Context::New(isolate, nullptr);
            Context::Scope context_scope(context);

            Handle<Object> global = context->Global();
            jsZAttribute->initJsObjectsTemplate(isolate, global);
        }
Example #10
0
void process_events( jsBrowser* js_exec, base_entity_ptr entity, bool is_jquery )
{
    /* simplest variant - recursive descent through DOM-tree */
    Local<Context> ctx = Context::GetCurrent();
    std::string src;
    std::string name;
    // get on... events
    LOG4CXX_INFO(iLogger::GetLogger(), _T("jsWindow::process_events entity = ") << entity->Name());

    AttrMap::iterator attrib = entity->attr_list().begin();

    while(attrib != entity->attr_list().end() ) {
        name = (*attrib).first;
        src = (*attrib).second;

        Local<Object> obj = Local<Object>::New(v8_wrapper::wrap_entity(boost::shared_dynamic_cast<html_entity>(entity))->m_this);
        ctx->Global()->Set(String::New("__evt_target__"), obj);
        if (boost::istarts_with(name, "on")) {
            // attribute name started with "on*" - this is the event
            LOG4CXX_INFO(iLogger::GetLogger(), _T("audit_jscript::process_events - ") << name << _T(" source = ") << src);
            boost::trim(src);
            if (! boost::istarts_with(src, "function")) {
                src = "__evt_target__.__event__" + name + "=function(){" + src + "}";
            } else {
                src = "__evt_target__.__event__" + name + "=" + src;
            }
            js_exec->execute_string(src, "", true, true);
            js_exec->execute_string("__evt_target__.__event__" + name + "()", "", true, true);
        }
        if (boost::istarts_with(src, "javascript:")) {
            LOG4CXX_INFO(iLogger::GetLogger(), _T("jsWindow::process_events (proto) - ") << name << _T(" source = ") << src);
            src = src.substr(11); // skip "javascript:"
            src = "__evt_target__.__event__=function(){ " + src + " }";
            js_exec->execute_string(src, "", true, true);
            js_exec->execute_string("__evt_target__.__event__()", "", true, true);
        }


        ++attrib;
    }

    if (is_jquery) {
        js_exec->execute_string("RunJqueryEvents(__evt_target__)", "", true, true);
    }

    // and process all children
    entity_list chld = entity->Children();
    entity_list::iterator  it;

    for(size_t i = 0; i < chld.size(); i++) {
        std::string nm = chld[i]->Name();
        if (nm != "#text" && nm != "#comment") {
            process_events(js_exec, chld[i], is_jquery);
        }
    }
    // all results will be processed in the caller parse_scripts function
}
TEST(JavaScriptCompiler, Load) {
	JavaScriptCompiler jsc;
	jsc.Load(DRAGON_TEST_PATH, "testJavaScriptCompiler/subdir");
        SourceMap &source= jsc.GetSource();
        JavaScriptSource *source1 = source["1"];

	HandleScope scope(jsc.GetIsolate());
	Local<Context> ctx = Local<Context>::New(jsc.GetIsolate(), source1->ctx_);
	Context::Scope context_scope(ctx);
	Handle<Value> rewriteFuncValue = ctx->Global()->Get(String::NewSymbol("test1"));
	if (!rewriteFuncValue.IsEmpty() && rewriteFuncValue->IsFunction()) {
		const int argc = 0;
		Handle<Function> initFunc = Handle<Function>::Cast(rewriteFuncValue);
		Handle<Value> ret = initFunc->Call(ctx->Global(), argc, NULL);
		String::AsciiValue ascii(ret);
		ASSERT_STREQ("OK1", *ascii);
	}
}
Example #12
0
shared_ptr<Server> Server::GetInstance(Local<Context> context){
	sjs::logger::debug("Getting Instance");
	Local<Object> self = Local<Object>::Cast(context->Global()->Get(STRING2JS(context->GetIsolate(), "$sampjs")));
	Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
	void* ptr = wrap->Value();
	Server* server = static_cast<Server*>(ptr);
	sjs::logger::debug("Casting");
	return make_shared<Server>(*server);
}
Example #13
0
TEST_F( JSRowTest, createTemplate) {
	JSRow jsRow;
	HandleScope handle_scope(isolate);
	Local<Context> context = Context::New(isolate, nullptr);
	Context::Scope context_scope(context);

	Handle<Object> global = context->Global();
	jsRow.initJsObjectsTemplate(isolate, global);
	jsRow.resetPersistences();
}
Example #14
0
/* for geomtransform, we don't have the mapObj */
shapeObj *msV8TransformShape(shapeObj *shape, const char* filename)
{
  TryCatch try_catch;
  Isolate *isolate = Isolate::GetCurrent();
  V8Context *v8context = (V8Context*)isolate->GetData();

  HandleScope handle_scope(v8context->isolate);

  /* execution context */
  Local<Context> context = Local<Context>::New(v8context->isolate, v8context->context);
  Context::Scope context_scope(context);
  Handle<Object> global = context->Global();

  Shape* shape_ = new Shape(shape);
  shape_->setLayer(v8context->layer);
  shape_->disableMemoryHandler();
  Handle<Value> ext = External::New(shape_);
  global->Set(String::New("shape"),
              Shape::Constructor()->NewInstance(1, &ext));

  msV8ExecuteScript(filename);
  Handle<Value> value = global->Get(String::New("geomtransform"));
  if (value->IsUndefined()) {
    msDebug("msV8TransformShape: Function 'geomtransform' is missing.\n");
    return NULL;
  }
  Handle<Function> func = Handle<Function>::Cast(value);
  Handle<Value> result = func->Call(global, 0, 0);
  if (result.IsEmpty() && try_catch.HasCaught()) {
    msV8ReportException(&try_catch);
  }

  if (!result.IsEmpty() && result->IsObject()) {
    Handle<Object> obj = result->ToObject();
    if (obj->GetConstructorName()->Equals(String::New("shapeObj"))) {
      Shape* new_shape = ObjectWrap::Unwrap<Shape>(result->ToObject());
      if (shape == new_shape->get()) {
        shapeObj *new_shape_ = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
        msInitShape(new_shape_);
        msCopyShape(shape, new_shape_);
        return new_shape_;
      }
      else {
        new_shape->disableMemoryHandler();
        return new_shape->get();
      }
    }
  }

  return NULL;
}
Example #15
0
void registerGlobalV8Function(const char * name, F function)
{
    using namespace v8;

    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    HandleScope handle_scope(isolate);
    Q_UNUSED(handle_scope);

    Local<Context> ctx = isolate->GetCurrentContext();
    Local<Object> global( ctx->Global() );
    v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate, function);
    v8::Local<v8::Function> fn = t->GetFunction();
    v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name);
    fn->SetName(fn_name);
    global->Set(fn_name, fn);
}
Example #16
0
/* Create a V8 execution context, execute a script and return the feature
 * style. */
char* msV8GetFeatureStyle(mapObj *map, const char *filename, layerObj *layer, shapeObj *shape)
{
  TryCatch try_catch;
  V8Context* v8context = V8CONTEXT(map);
  char *ret = NULL;
    
  if (!v8context) {
    msSetError(MS_V8ERR, "V8 Persistent Context is not created.", "msV8ReportException()");
    return NULL;
  }

  Isolate::Scope isolate_scope(v8context->isolate);
  HandleScope handle_scope(v8context->isolate);

  /* execution context */
  Local<Context> context = Local<Context>::New(v8context->isolate, v8context->context);
  Context::Scope context_scope(context);
  Handle<Object> global = context->Global();

  Shape *shape_ = new Shape(shape);
  shape_->setLayer(layer); // hack to set the attribute names, should change in future.
  shape_->disableMemoryHandler(); /* the internal object should not be freed by the v8 GC */
  Handle<Value> ext = External::New(shape_);
  global->Set(String::New("shape"),
              Shape::Constructor()->NewInstance(1, &ext));
  
  msV8ExecuteScript(filename);
  Handle<Value> value = global->Get(String::New("styleitem"));
  if (value->IsUndefined()) {
    msDebug("msV8GetFeatureStyle: Function 'styleitem' is missing.\n");
    return ret;
  }
  Handle<Function> func = Handle<Function>::Cast(value);
  Handle<Value> result = func->Call(global, 0, 0);
  if (result.IsEmpty() && try_catch.HasCaught()) {
    msV8ReportException(&try_catch);
  }

  if (!result.IsEmpty() && !result->IsUndefined()) {
     String::AsciiValue ascii(result);
     ret = msStrdup(*ascii);
  }

  return ret;
}
Example #17
0
void MySQL::Init(Local<Context> ctx){
	num_conns = 0;

	isolate = ctx->GetIsolate();

	V8CONTEXT(isolate, ctx);
	context.Reset(isolate, ctx);

	ifstream mysqlFile("js/samp.js/MySQL.js", std::ios::in);
	if (!mysqlFile){
		sjs::logger::error("Missing required file MySQL.js");
		SAMPJS::Shutdown();
	}
	std::string mysqlSource((std::istreambuf_iterator<char>(mysqlFile)), std::istreambuf_iterator<char>());
	SAMPJS::ExecuteCode(ctx, "MySQL.js", mysqlSource);

	ifstream mysqlcFile("js/samp.js/MySQLConnection.js", std::ios::in);
	if (!mysqlcFile){
		sjs::logger::error("Missing required file MySQLConnection.js");
		SAMPJS::Shutdown();
	}
	std::string mysqlcSource((std::istreambuf_iterator<char>(mysqlcFile)), std::istreambuf_iterator<char>());
	SAMPJS::ExecuteCode(ctx, "MySQLConnection.js", mysqlcSource);

	SAMPJS::ExecuteCode(ctx, "$mysql", "var $mysql = new MySQL();");

	JS_Object global(ctx->Global());

	JS_Object mysql(global.getObject("$mysql"));

	auto mysql_tmpl = ObjectTemplate::New(isolate);
	mysql_tmpl->SetInternalFieldCount(1);
	auto mysqli = mysql_tmpl->NewInstance();
	mysqli->SetInternalField(0, External::New(isolate, this));

	JS_Object mysqlo(mysqli);

	mysqlo.Set("createConnection", JS_New);
	mysqlo.Set("escape", JS_Escape);

	mysql.Set("internal", mysqlo.get());

}
Example #18
0
/* static */
void V8Runtime::bootstrap(Local<Context> context)
{
	Isolate* isolate = context->GetIsolate();
	EventEmitter::initTemplate(context);

	Local<Object> global = Object::New(isolate);
	krollGlobalObject.Reset(isolate, global);
	Local<Array> mc = Array::New(isolate);
	moduleContexts.Reset(isolate, mc);

	KrollBindings::initFunctions(global, context);

	SetMethod(isolate, global, "log", krollLog);
	// Move this into the EventEmitter::initTemplate call?
	Local<FunctionTemplate> eect = Local<FunctionTemplate>::New(isolate, EventEmitter::constructorTemplate);
	global->Set(NEW_SYMBOL(isolate, "EventEmitter"), eect->GetFunction());

	global->Set(NEW_SYMBOL(isolate, "runtime"), STRING_NEW(isolate, "v8"));
	global->Set(NEW_SYMBOL(isolate, "DBG"), v8::Boolean::New(isolate, V8Runtime::DBG));
	global->Set(NEW_SYMBOL(isolate, "moduleContexts"), mc);

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch(isolate);
	Local<Value> result = V8Util::executeString(isolate, KrollBindings::getMainSource(isolate), STRING_NEW(isolate, "ti:/kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(isolate, tryCatch, true);
	}

	Local<Function> mainFunction = result.As<Function>();
	Local<Value> args[] = { global };
	mainFunction->Call(context, context->Global(), 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Example #19
0
void JsContext::onDraw(SkCanvas* canvas) {
    // Record canvas and window in this.
    fCanvas = canvas;

    // Create a handle scope to keep the temporary object references.
    HandleScope handleScope(fGlobal->getIsolate());

    // Create a local context from our global context.
    Local<Context> context = fGlobal->getContext();

    // Enter the context so all the remaining operations take place there.
    Context::Scope contextScope(context);

    // Wrap the C++ this pointer in a JavaScript wrapper.
    Handle<Object> contextObj = this->wrap();

    // Set up an exception handler before calling the Process function.
    TryCatch tryCatch;

    // Invoke the process function, giving the global object as 'this'
    // and one argument, this JsContext.
    const int argc = 1;
    Handle<Value> argv[argc] = { contextObj };
    Local<Function> onDraw =
            Local<Function>::New(fGlobal->getIsolate(), fOnDraw);
    Handle<Value> result = onDraw->Call(context->Global(), argc, argv);

    // Handle any exceptions or output.
    if (result.IsEmpty()) {
        SkASSERT(tryCatch.HasCaught());
        // Print errors that happened during execution.
        fGlobal->reportException(&tryCatch);
    } else {
        SkASSERT(!tryCatch.HasCaught());
        if (!result->IsUndefined()) {
            // If all went well and the result wasn't undefined then print
            // the returned value.
            String::Utf8Value str(result);
            const char* cstr = to_cstring(str);
            printf("%s\n", cstr);
        }
    }
}
Example #20
0
// Callback function for SkEvents used to implement timeouts.
bool Global::TimeOutProc(const SkEvent& evt) {
    // Create a handle scope to keep the temporary object references.
    HandleScope handleScope(gGlobal->getIsolate());

    // Create a local context from our global context.
    Local<Context> context = gGlobal->getContext();

    // Enter the context so all the remaining operations take place there.
    Context::Scope contextScope(context);

    // Set up an exception handler before calling the Process function.
    TryCatch tryCatch;

    int32_t id = evt.getFast32();
    if (gGlobal->fTimeouts.find(gGlobal->fLastTimerID) == gGlobal->fTimeouts.end()) {
        printf("Not a valid timer ID.\n");
        return true;
    }

    const int argc = 0;
    Local<Function> onTimeout =
            Local<Function>::New(gGlobal->getIsolate(), gGlobal->fTimeouts[id]);
    Handle<Value> result = onTimeout->Call(context->Global(), argc, NULL);
    gGlobal->fTimeouts.erase(id);

    // Handle any exceptions or output.
    if (result.IsEmpty()) {
        SkASSERT(tryCatch.HasCaught());
        // Print errors that happened during execution.
        gGlobal->reportException(&tryCatch);
    } else {
        SkASSERT(!tryCatch.HasCaught());
        if (!result->IsUndefined()) {
            // If all went well and the result wasn't undefined then print the
            // returned value.
            String::Utf8Value str(result);
            const char* cstr = to_cstring(str);
            printf("%s\n", cstr);
        }
    }
    return true;
}
Example #21
0
void append_results(const std::string& data)
{
    {
        LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::append_results: data("<< data <<")");
    }
    HandleScope scope;

    // extract executor
    Local<Context> ctx = v8::Context::GetCurrent();
    Local<Value> exec = ctx->Global()->Get(String::New("v8_context"));
//     LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::append_results: gets v8_context");
    if (exec->IsObject()) {
        Local<Object> eObj = Local<Object>::Cast(exec);
//         LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::append_results: gets v8_context object");
        v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(eObj->GetInternalField(0));
//         LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::append_results: gets v8_context wrapper");
        webEngine::jsExecutor* jsExec = static_cast<webEngine::jsExecutor*>(wrap->Value());
        LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::append_results: gets jsExecutor");
        jsExec->append_results(data);
    }
}
Example #22
0
Handle<Value> jsBrowser::WinInterceptor( const Arguments& args )
{
    Handle<Value> retval;
    Local<Context> ctx = v8::Context::GetCurrent();
    Local<Object> exec = Local<Object>::Cast(ctx->Global()->Get(String::New("v8_context")));
    Local<External> wrap = Local<External>::Cast(exec->GetInternalField(0));
    void* ptr = wrap->Value();
    jsBrowser* el = static_cast<jsBrowser*>(ptr);

    string fname = value_to_string(args.Callee()->GetName()->ToString());

    Local<Object> _obj = Local<Object>::New(v8_wrapper::wrap_object<jsWindow>(el->window));
    Local<Function> _func = Local<Function>::Cast(_obj->Get(String::New(fname.c_str())));
    Handle<Value> *fargs = new Handle<Value>[args.Length()];
    for (int i = 0; i < args.Length(); ++i) {
        fargs[i] = args[i];
    }
    retval = _func->Call(_obj, args.Length(), fargs );

    return retval;
}
Example #23
0
Handle<Value> dump_object(const Arguments& args)
{
    Handle<Value> res = Undefined();
    string  nm;
    string  id;
    int     dp;

    Local<Context> ctx = v8::Context::GetCurrent();
    Local<Value> exec = ctx->Global()->Get(String::New("v8_context"));
//     LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::DumpObject: gets v8_context");
    if (exec->IsObject()) {
        Local<Object> eObj = Local<Object>::Cast(exec);
//         LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::DumpObject: gets v8_context object");
        v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(eObj->GetInternalField(0));
//         LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::DumpObject: gets v8_context wrapper");
        webEngine::jsExecutor* jsExec = static_cast<webEngine::jsExecutor*>(wrap->Value());
        LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), "js::DumpObject: gets jsExecutor");
        if (args.Length() > 1) {
            nm = value_to_string(args[1]);
        } else {
            nm = "";
        }
        if (args.Length() > 2) {
            id = value_to_string(args[2]);
        } else {
            id = "";
        }
        if (args.Length() > 3) {
            dp = args[3]->Int32Value();
        } else {
            dp = 0;
        }
        string dat = jsExec->obj_dump(args[0], nm, id, dp, ctx);
        res = String::New(dat.c_str());
    }

    return res;
}
Example #24
0
void EditorGetCurrentLineRange(const FunctionCallbackInfo<Value>& args)
{
	CComPtr<VirtualPoint> point;
	long charOffset;
	long lineLen;
	long absCharOffset;
	g_Options.m_selection->get_ActivePoint(&point);
	point->get_AbsoluteCharOffset(&absCharOffset);
	point->get_LineCharOffset(&charOffset);
	point->get_LineLength(&lineLen);

	long lineOffset = absCharOffset - charOffset;

	Local<Context> context = Isolate::GetCurrent()->GetCurrentContext();
	Handle<Function> fCreateRange =
		Handle<Function>::Cast(context->Global()->Get(String::New(L"createRange")));

	Handle<Value> argv[] = { Int32::New(lineOffset), Int32::New(lineOffset + lineLen) };

	Handle<Value> retVal = fCreateRange->Call(fCreateRange, 2, argv);

	args.GetReturnValue().Set(retVal);
}
Example #25
0
Handle<Value> Window(const v8::Arguments& args)
{
    // throw if called without `new'
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function"));

    HandleScope scope;

    Handle<Value> retval;
    Local<Context> ctx = v8::Context::GetCurrent();
    Local<Value> exec = ctx->Global()->Get(String::New("v8_context"));
    LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("js::Window: gets v8_context"));
    if (exec->IsObject()) {
        Local<Object> eObj = Local<Object>::Cast(exec);
        v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(eObj->GetInternalField(0));
        jsBrowser* jsExec = static_cast<jsBrowser*>(wrap->Value());
        LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("js::Window: gets jsBrowser"));
        jsWindow *p = new jsWindow(jsExec, jsExec->window, jsExec->window);
        jsExec->register_window(p);
        retval = v8_wrapper::wrap_object<jsWindow>(p);
    }

    return scope.Close(retval);
}
Example #26
0
int main()
{
	//Create the v8 environment
	/*Isolate**/ isolate = Isolate::GetCurrent();

	HandleScope handle_scope(isolate);

	/*Handle<ObjectTemplate>*/ global_template = ObjectTemplate::New();

	Handle<FunctionTemplate> obj = FunctionTemplate::New();
	obj->Set(String::New("Point"), FunctionTemplate::New(PointConstructor));

	// Tell global A JS Obj Point() can now be create and instructions on how to set up
	global_template->Set(String::New("Point"), FunctionTemplate::New(PointConstructor));

	Local<Context> context = Context::New(isolate, NULL, global_template);

	Context::Scope context_scope(context);

	Handle<v8::Object> global = context->Global();

	//global->Set(String::New("Point"), t);
	global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)->GetFunction());

	string file = "foo.js";

	while(true){
		cout << "How many times do you want to run the script? \n" << endl;

		int n; 

		cin >> n;

		cout << "" << endl;

		std::cin.get();

		Handle<String> source = ReadFile(file.c_str());

		if(source.IsEmpty())
		{
			cout << "Error reading file" << endl;
			cout << "Press enter to quit" << endl;
			cin.get();
			return 0;
		}

		//Compile
		Handle<Script> script = Script::Compile(source);
	
		//Run the script and print 
		Handle<Value> result;

		result = script->Run();

	} // End of while

	//Exit program
	cout << "\nTest completed.  Press enter to exit program. \n" << endl;
	std::cin.get();
	
	return 0;
}
Example #27
0
int Server::FireNative(std::string name, std::string param_types, std::vector<std::string> param_names, cell* params){
	Locker v8Locker(isolate);
	Isolate::Scope isoscope(isolate);
	HandleScope hs(isolate);
	Local<Context> ctx = Local<Context>::New(isolate, context);
	Context::Scope cs(ctx);
	TryCatch try_catch;



	JS_Object global(ctx->Global());
	JS_Object server(global.getObject("$server"));
	Local<Function> firefn = Local<Function>::Cast(server.getValue("fire"));
	if (try_catch.HasCaught()){
		Utils::PrintException(&try_catch);
	}

	if (firefn->IsFunction()){
		Local<Value>* argv = NULL;
		unsigned int argc = param_types.length() + 1;
		argv = new Local<Value>[argc];

		argv[0] = String::NewFromUtf8(isolate, name.c_str());
		for (unsigned int i = 1; i < argc; i++){
			switch (param_types[(i - 1)]){
			case 's':{
				cell* addr = NULL;
				int len = 0;
				amx_GetAddr(SAMPJS::amx, params[i], &addr);
				amx_StrLen(addr, &len);
				char* val = new char[len + 2];
				amx_GetString(val, addr, 0, len + 2);
				argv[i] = String::NewFromUtf8(isolate, val);

				delete[] val;

				break;
			}
			case 'i':{
				if (param_names[i - 1] == "playerid" ||
					param_names[i - 1] == "killerid" ||
					param_names[i - 1] == "forplayerid" ||
					param_names[i - 1] == "issuerid" ||
					param_names[i - 1] == "damagedid" ||
					param_names[i - 1] == "clickedplayerid" ||
					(param_names[i - 1] == "hitid" && params[i - 1] == 1)
					){

					int playerid = params[i];

					TryCatch trycatch;
					JS_Object players(global.getObject("$players"));
					
					Local<Value> player;
	
					if (name == "IncomingConnection" || name == "PlayerConnect"){

						auto addPlayer = Local<Function>::Cast(players.getValue("addPlayer"));
						Local<Value> argv[1] = { Integer::New(isolate, playerid) };
						player = addPlayer->Call(players.get(), 1, argv);
						if (trycatch.HasCaught()){
							Utils::PrintException(&trycatch);
						}
					}
					
					else if (name == "PlayerDisconnect"){
						auto removePlayer = Local<Function>::Cast(players.getValue("removePlayer"));
						Local<Value> argv[1] = { Integer::New(isolate, playerid) };
						player = removePlayer->Call(players.get(), 1, argv);
						if (trycatch.HasCaught()){
							Utils::PrintException(&trycatch);
						}
					}
					else {
						auto getPlayer = Local<Function>::Cast(players.getValue("getPlayer"));
						Local<Value> argv[1] = { Integer::New(isolate, playerid) };
						player = getPlayer->Call(players.get(), 1, argv);
						if (trycatch.HasCaught()){
							Utils::PrintException(&trycatch);
						}
					}
					argv[i] = player;

				}
				else {
					argv[i] = Integer::New(isolate, params[i]);
				}


				break;
			} case 'f':{
				argv[i] = Number::New(isolate, amx_ctof(params[i]));

				break;
			}
			}
		}

		Local<Value> ret = firefn->Call(server.get(), argc, argv);
		delete[] argv;
		int retval = 1;
		if (try_catch.HasCaught()){
			Utils::PrintException(&try_catch);
		}
		else {
			if (ret->IsNumber()) retval = ret->Int32Value();
			else if (name == "PlayerCommandText" || name == "RconCommand") retval = 0;
		}
		return retval;
	}
	return 1;
}
Example #28
0
Isolate* Runtime::PrepareV8Runtime(const string& filesPath, jstring packageName, jobject jsDebugger, jstring profilerOutputDir)
{
	Isolate::CreateParams create_params;
	bool didInitializeV8 = false;

	create_params.array_buffer_allocator = &g_allocator;
	// prepare the snapshot blob
	if (!Constants::V8_HEAP_SNAPSHOT_BLOB.empty() || !Constants::V8_HEAP_SNAPSHOT_SCRIPT.empty())
	{
		DEBUG_WRITE_FORCE("Snapshot enabled.");

		m_startupData = new StartupData();

		string snapshotPath;
		bool saveSnapshot = true;
		// we have a precompiled snapshot blob provided - try to load it directly
		if (Constants::V8_HEAP_SNAPSHOT_BLOB.size() > 0)
		{
			snapshotPath = Constants::V8_HEAP_SNAPSHOT_BLOB;
			saveSnapshot = false;
		}
		else
		{
			snapshotPath = filesPath + "/internal/snapshot.blob";
		}

		if (File::Exists(snapshotPath))
		{
			m_heapSnapshotBlob = new MemoryMappedFile(MemoryMappedFile::Open(snapshotPath.c_str()));
			m_startupData->data = static_cast<const char*>(m_heapSnapshotBlob->memory);
			m_startupData->raw_size = m_heapSnapshotBlob->size;

			DEBUG_WRITE_FORCE("Snapshot read %s (%dB).", snapshotPath.c_str(), m_heapSnapshotBlob->size);
		}
		else if (!saveSnapshot)
		{
			DEBUG_WRITE_FORCE("No snapshot file found at %s", snapshotPath.c_str());

		}
		else
		{
			// This should be executed before V8::Initialize, which calls it with false.
			NativeScriptExtension::Probe(true);
			InitializeV8();
			didInitializeV8 = true;

			string customScript;

			// check for custom script to include in the snapshot
			if (Constants::V8_HEAP_SNAPSHOT_SCRIPT.size() > 0 && File::Exists(Constants::V8_HEAP_SNAPSHOT_SCRIPT))
			{
				customScript = File::ReadText(Constants::V8_HEAP_SNAPSHOT_SCRIPT);
			}

			DEBUG_WRITE_FORCE("Creating heap snapshot");
			*m_startupData = V8::CreateSnapshotDataBlob(customScript.c_str());

			if (m_startupData->raw_size == 0)
			{
				DEBUG_WRITE_FORCE("Failed to create heap snapshot.");
			}
			else
			{
				bool writeSuccess = File::WriteBinary(snapshotPath, m_startupData->data, m_startupData->raw_size);

				if (!writeSuccess)
				{
					DEBUG_WRITE_FORCE("Failed to save created snapshot.");
				}
				else
				{
					DEBUG_WRITE_FORCE("Saved snapshot of %s (%dB) in %s (%dB)",
							Constants::V8_HEAP_SNAPSHOT_SCRIPT.c_str(), customScript.size(),
							snapshotPath.c_str(), m_startupData->raw_size);
				}
			}
		}

		create_params.snapshot_blob = m_startupData;
	}

	if (!didInitializeV8) {
		InitializeV8();
	}
	auto isolate = Isolate::New(create_params);
	Isolate::Scope isolate_scope(isolate);
	HandleScope handleScope(isolate);

	V8::SetFlagsFromString(Constants::V8_STARTUP_FLAGS.c_str(), Constants::V8_STARTUP_FLAGS.size());
	V8::SetCaptureStackTraceForUncaughtExceptions(true, 100, StackTrace::kOverview);
	V8::AddMessageListener(NativeScriptException::OnUncaughtError);
	__android_log_print(ANDROID_LOG_DEBUG, "TNS.Native", "V8 version %s", V8::GetVersion());

	auto globalTemplate = ObjectTemplate::New();

	const auto readOnlyFlags = static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);

	globalTemplate->Set(ConvertToV8String("__log"), FunctionTemplate::New(isolate, CallbackHandlers::LogMethodCallback));
	globalTemplate->Set(ConvertToV8String("__dumpReferenceTables"), FunctionTemplate::New(isolate, CallbackHandlers::DumpReferenceTablesMethodCallback));
	globalTemplate->Set(ConvertToV8String("__debugbreak"), FunctionTemplate::New(isolate, JsDebugger::DebugBreakCallback));
	globalTemplate->Set(ConvertToV8String("__consoleMessage"), FunctionTemplate::New(isolate, JsDebugger::ConsoleMessageCallback));
	globalTemplate->Set(ConvertToV8String("__enableVerboseLogging"), FunctionTemplate::New(isolate, CallbackHandlers::EnableVerboseLoggingMethodCallback));
	globalTemplate->Set(ConvertToV8String("__disableVerboseLogging"), FunctionTemplate::New(isolate, CallbackHandlers::DisableVerboseLoggingMethodCallback));
	globalTemplate->Set(ConvertToV8String("__exit"), FunctionTemplate::New(isolate, CallbackHandlers::ExitMethodCallback));
	globalTemplate->Set(ConvertToV8String("__nativeRequire"), FunctionTemplate::New(isolate, Module::RequireCallback));
	globalTemplate->Set(ConvertToV8String("__runtimeVersion"), ConvertToV8String(NATIVE_SCRIPT_RUNTIME_VERSION), readOnlyFlags);

	m_weakRef.Init(isolate, globalTemplate, m_objectManager);

	SimpleProfiler::Init(isolate, globalTemplate);

	CallbackHandlers::CreateGlobalCastFunctions(globalTemplate);

	Local<Context> context = Context::New(isolate, nullptr, globalTemplate);
	PrimaryContext = new Persistent<Context>(isolate, context);

	context_scope = new Context::Scope(context);

	m_objectManager->Init(isolate);

	auto global = context->Global();

	Module::Init(isolate);

	global->ForceSet(ConvertToV8String("global"), global, readOnlyFlags);
	global->ForceSet(ConvertToV8String("__global"), global, readOnlyFlags);

	ArgConverter::Init(isolate);

	CallbackHandlers::Init(isolate, m_objectManager);

	auto pckName = ArgConverter::jstringToString(packageName);
	auto outputDir = ArgConverter::jstringToString(profilerOutputDir);
	m_profiler.Init(isolate, global, pckName, outputDir);
	JsDebugger::Init(isolate, pckName, jsDebugger);

	MetadataNode::BuildMetadata(filesPath);

	MetadataNode::CreateTopLevelNamespaces(isolate, global);

	ArrayHelper::Init(context);

	m_arrayBufferHelper.CreateConvertFunctions(isolate, global, m_objectManager);

	return isolate;
}
void NativePlatform::PrepareV8Runtime(JEnv& env, string filesPath, jstring packageName)
{
	Platform* platform = v8::platform::CreateDefaultPlatform();
	V8::InitializePlatform(platform);
	V8::Initialize();

	Isolate::CreateParams create_params;
	create_params.array_buffer_allocator = &g_allocator;

	// prepare the snapshot blob
	if(Constants::V8_HEAP_SNAPSHOT)
	{
		auto snapshotPath = filesPath + "/internal/snapshot.dat";
		StartupData startup_data;
		if( File::Exists(snapshotPath))
		{
			int length;
			startup_data.data = reinterpret_cast<char*>(File::ReadBinary(snapshotPath, length));
			startup_data.raw_size = length;
		}
		else
		{
			startup_data = V8::CreateSnapshotDataBlob();
			File::WriteBinary(snapshotPath, startup_data.data, startup_data.raw_size);
		}

		create_params.snapshot_blob = &startup_data;
	}

	g_isolate = Isolate::New(create_params);
	auto isolate = g_isolate;
	Isolate::Scope isolate_scope(isolate);
	HandleScope handleScope(isolate);

	V8::SetFlagsFromString(Constants::V8_STARTUP_FLAGS.c_str(), Constants::V8_STARTUP_FLAGS.size());
	V8::SetCaptureStackTraceForUncaughtExceptions(true, 100, StackTrace::kOverview);
	V8::AddMessageListener(NativeScriptException::OnUncaughtError);

	auto globalTemplate = ObjectTemplate::New();

	const auto readOnlyFlags = static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);

	globalTemplate->Set(ConvertToV8String("__startNDKProfiler"), FunctionTemplate::New(isolate, Profiler::StartNDKProfilerCallback));
	globalTemplate->Set(ConvertToV8String("__stopNDKProfiler"), FunctionTemplate::New(isolate, Profiler::StopNDKProfilerCallback));
	globalTemplate->Set(ConvertToV8String("__startCPUProfiler"), FunctionTemplate::New(isolate, Profiler::StartCPUProfilerCallback));
	globalTemplate->Set(ConvertToV8String("__stopCPUProfiler"), FunctionTemplate::New(isolate, Profiler::StopCPUProfilerCallback));
	globalTemplate->Set(ConvertToV8String("__heapSnapshot"), FunctionTemplate::New(isolate, Profiler::HeapSnapshotMethodCallback));
	globalTemplate->Set(ConvertToV8String("__log"), FunctionTemplate::New(isolate, NativeScriptRuntime::LogMethodCallback));
	globalTemplate->Set(ConvertToV8String("__dumpReferenceTables"), FunctionTemplate::New(isolate, NativeScriptRuntime::DumpReferenceTablesMethodCallback));
	globalTemplate->Set(ConvertToV8String("__debugbreak"), FunctionTemplate::New(isolate, JsDebugger::DebugBreakCallback));
	globalTemplate->Set(ConvertToV8String("__enableVerboseLogging"), FunctionTemplate::New(isolate, NativeScriptRuntime::EnableVerboseLoggingMethodCallback));
	globalTemplate->Set(ConvertToV8String("__disableVerboseLogging"), FunctionTemplate::New(isolate, NativeScriptRuntime::DisableVerboseLoggingMethodCallback));
	globalTemplate->Set(ConvertToV8String("__exit"), FunctionTemplate::New(isolate, NativeScriptRuntime::ExitMethodCallback));

	WeakRef::Init(isolate, globalTemplate, g_objectManager);

	SimpleProfiler::Init(isolate, globalTemplate);

	NativeScriptRuntime::CreateGlobalCastFunctions(globalTemplate);

	Local<Context> context = Context::New(isolate, nullptr, globalTemplate);
	PrimaryContext = new Persistent<Context>(isolate, context);

	if(Constants::V8_HEAP_SNAPSHOT)
	{
		// we own the snapshot buffer, delete it
		delete[] create_params.snapshot_blob->data;
	}

	context_scope = new Context::Scope(context);

	Module::Init(isolate);

	g_objectManager->Init(isolate);

	auto global = context->Global();

	auto appTemplate = ObjectTemplate::New();
	appTemplate->Set(ConvertToV8String("init"), FunctionTemplate::New(isolate, AppInitCallback));
	auto appInstance = appTemplate->NewInstance();
	global->ForceSet(ConvertToV8String("app"), appInstance, readOnlyFlags);

	global->ForceSet(ConvertToV8String("global"), global, readOnlyFlags);
	global->ForceSet(ConvertToV8String("__global"), global, readOnlyFlags);

	ArgConverter::Init(g_jvm);

	NativeScriptRuntime::Init(g_jvm, g_objectManager);

	string pckName = ArgConverter::jstringToString(packageName);
	Profiler::Init(pckName);
	JsDebugger::Init(isolate, pckName);

	NativeScriptRuntime::BuildMetadata(env, filesPath);

	NativeScriptRuntime::CreateTopLevelNamespaces(global);
}