Exemplo n.º 1
0
void JavaScriptEngine::Start() {

	globalRuntime = JS_NewRuntime(32L * 1024L * 1024L);
	if (globalRuntime == NULL) {
		LogInfo(TAG, "(globalRuntime == NULL)");
		return;
	}
	globalContext = JS_NewContext(globalRuntime, 8192);
	if (globalContext == NULL) {
		LogInfo(TAG, "(globalContext == NULL)");
		return;
	}
	JS_SetOptions(globalContext, JSOPTION_VAROBJFIX);
	JS_SetVersion(globalContext, JSVERSION_LATEST);
	JS_SetErrorReporter(globalContext, ReportError);
	globalObject = JS_NewCompartmentAndGlobalObject(globalContext,
			&globalClass, NULL);
	if (globalObject == NULL) {
		LogInfo(TAG, "(globalObject == NULL)");
		return;
	}
	if (!JS_InitStandardClasses(globalContext, globalObject)) {
		LogInfo(TAG, "(!JS_InitStandardClasses(globalContext, global))");
		return;
	}
	BindingGlobalObject();
	BindingObject();
	RunScript("index.js");
}
Exemplo n.º 2
0
bool round_js_sm_engine_init(RoundJavaScriptEngine* engine)
{
  if (!engine)
    return NULL;

  JS_SetCStringsAreUTF8();

  engine->cx = NULL;
  engine->rt = NULL;
  engine->obj = NULL;

  engine->rt = JS_NewRuntime(8L * 1024L * 1024L);
  if (!engine->rt)
    return false;

  engine->cx = JS_NewContext(engine->rt, 8192);
  if (!engine->cx)
    return false;

  JS_SetErrorReporter(engine->cx, RoundJSReportError);

  // Obsolete since JSAPI 16
  engine->obj = JS_NewCompartmentAndGlobalObject(engine->cx, &RoundJSGlobalClass, NULL);
  if (!engine->obj)
    return false;

  JS_InitStandardClasses(engine->cx, engine->obj);
  JS_DefineFunctions(engine->cx, engine->obj, JS_SM_FUNCTIONS);

  return true;
}
Exemplo n.º 3
0
void SetupScripting() {
    /* Initialize the JS engine -- new/required as of SpiderMonkey 31. */
    JS_Init(120000);

    /* Create a JS runtime. */
    rt = JS_NewRuntime(8L * 1024L * 1024L);
    
    /* Create a context. */
	cx = JS_NewContext(rt, 8192);
    JS_SetOptions(cx, JSOPTION_VAROBJFIX);
    JS_SetErrorReporter(cx, reportError);


	/* Enter a request before running anything in the context */
    JSAutoRequest ar(cx);

    /* Create the global object in a new compartment. */
    global = JS_NewGlobalObject(cx, &global_class, NULL);
    
    /* Set the context's global */
    JSAutoCompartment ac(cx, global);
    JS_SetGlobalObject(cx, global);

    /* Populate the global object with the standard globals, like Object and Array. */
    JS_InitStandardClasses(cx, global);
	
}
Exemplo n.º 4
0
/*
  Create PJS_Context structure
*/
PJS_Context * PJS_CreateContext(PJS_Runtime *rt) {
    PJS_Context *pcx;
    JSObject *obj;

    Newz(1, pcx, 1, PJS_Context);
    if (pcx == NULL) {
        croak("Failed to allocate memory for PJS_Context");
    }
    
    /* 
        The 'stack size' param here isn't actually the stack size, it's
        the "chunk size of the stack pool--an obscure memory management
        tuning knob"
        
        http://groups.google.com/group/mozilla.dev.tech.js-engine/browse_thread/thread/be9f404b623acf39
    */
    
    pcx->cx = JS_NewContext(rt->rt, 8192);

    if(pcx->cx == NULL) {
        Safefree(pcx);
        croak("Failed to create JSContext");
    }

    JS_SetOptions(pcx->cx, JSOPTION_DONT_REPORT_UNCAUGHT);

    obj = JS_NewObject(pcx->cx, &global_class, NULL, NULL);
    if (JS_InitStandardClasses(pcx->cx, obj) == JS_FALSE) {
        PJS_DestroyContext(pcx);
        croak("Standard classes not loaded properly.");
    }
    
    pcx->function_by_name = newHV();
    pcx->class_by_name = newHV();
    pcx->class_by_package = newHV();
    
    if (PJS_InitPerlArrayClass(pcx, obj) == JS_FALSE) {
        PJS_DestroyContext(pcx);
        croak("Perl classes not loaded properly.");        
    }

    if (PJS_InitPerlHashClass(pcx, obj) == JS_FALSE) {
        PJS_DestroyContext(pcx);
        croak("Perl classes not loaded properly.");        
    }

    if (PJS_InitPerlSubClass(pcx, obj) == JS_FALSE) {
        PJS_DestroyContext(pcx);
        croak("Perl class 'PerlSub' not loaded properly.");        
    }

    pcx->rt = rt;
    /* Add context to context list */
    pcx->next = rt->list;
    rt->list = pcx;

    JS_SetContextPrivate(pcx->cx, (void *) pcx);

    return pcx;
}
JSInterpreter::JSInterpreter() {
        /* Create a JS runtime. You always need at least one runtime per process. */
        rt = JS_NewRuntime(8 * 1024 * 1024);
        if (rt == NULL)
            throw * new std::runtime_error("Can't create JS runtime.");

        /*
         * Create a context. You always need a context per thread.
         * Note that this program is not multi-threaded.
         */
        cx = JS_NewContext(rt, 8192);
        if (cx == NULL)
            throw * new std::runtime_error("Can't create js context.");

        JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
        JS_SetVersion(cx, JSVERSION_LATEST);
        JS_SetErrorReporter(cx, reportError);

        /*
         * Create the global object in a new compartment.
         * You always need a global object per context.
         */
        global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
        if (global == NULL)
            throw * new std::runtime_error("Can't create global object.");

        /*
         * Populate the global object with the standard JavaScript
         * function and object classes, such as Object, Array, Date.
         */
        if (!JS_InitStandardClasses(cx, global))
            throw * new std::runtime_error("Can't initialise standard classes.");

    }
Exemplo n.º 6
0
spidermonkey_vm *sm_initialize(long thread_stack, long heap_size) {
  spidermonkey_vm *vm = ejs_alloc(sizeof(spidermonkey_vm));
  spidermonkey_state *state = ejs_alloc(sizeof(spidermonkey_state));
  state->branch_count = 0;
  state->error = NULL;
  state->terminate = 0;
  int gc_size = (int) heap_size * 0.25;
  vm->runtime = JS_NewRuntime(MAX_GC_SIZE);
  JS_SetGCParameter(vm->runtime, JSGC_MAX_BYTES, heap_size);
  JS_SetGCParameter(vm->runtime, JSGC_MAX_MALLOC_BYTES, gc_size);
  vm->context = JS_NewContext(vm->runtime, 8192);
  JS_SetScriptStackQuota(vm->context, thread_stack);

  begin_request(vm);
  JS_SetOptions(vm->context, JSOPTION_VAROBJFIX);
  JS_SetOptions(vm->context, JSOPTION_STRICT);
  JS_SetOptions(vm->context, JSOPTION_COMPILE_N_GO);
  JS_SetOptions(vm->context, JSVERSION_LATEST);
  vm->global = JS_NewCompartmentAndGlobalObject(vm->context, &global_class, NULL);
  JS_InitStandardClasses(vm->context, vm->global);
  JS_SetErrorReporter(vm->context, on_error);
  JS_SetOperationCallback(vm->context, on_branch);
  JS_SetContextPrivate(vm->context, state);
  JSNative funptr = (JSNative) &js_log;
  JS_DefineFunction(vm->context, JS_GetGlobalObject(vm->context), "ejsLog", funptr,
                    0, 0);
  end_request(vm);

  return vm;
}
Exemplo n.º 7
0
/*! @decl void create(void|int version, void|int stacksize)
 *!
 *! Creates an instance of the Context class.
 *!
 *! @param version
 *!  This context will be initially made compatible with the specified
 *!  JavaScript version. The following constants are accepted as the value
 *!  of this parameter:
 *!
 *!   @dl
 *!    @item JSVERSION_1_0
 *!     JavaScript v1.0
 *!    @item JSVERSION_1_1
 *!     JavaScript v1.1
 *!    @item JSVERSION_1_2
 *!     JavaScript v1.2
 *!    @item JSVERSION_1_3
 *!     JavaScript v1.3 (ECMA)
 *!    @item JSVERSION_1_4
 *!     JavaScript v1.4 (ECMA)
 *!    @item JSVERSION_1_5
 *!     JavaScript v1.5 (ECMA)
 *!   @enddl
 *!
 *!  The default value is @b{JSVERSION_1_5@}
 *!
 *! @param stacksize
 *!  Sets the size of the private stack for this context. Value given in
 *!  bytes. Defaults to 8192.
 */
static void ctx_create(INT32 args)
{
  INT32      version = JSVERSION_1_5;
  INT32      stacksize = 8192;

  switch(args) {
      case 2:
        get_all_args("create", args, "%i%i", &version, &stacksize);
        break;

      case 1:
        get_all_args("create", args, "%i", &version);
        break;
  }

  THIS->ctx = JS_NewContext(smrt, stacksize);
  if (!THIS->ctx)
    Pike_error("Could not create a new context\n");
    
  if (!init_globals(THIS->ctx))
    Pike_error("Could not initialize the new context.\n");

  if (!JS_DefineFunctions(THIS->ctx, global, output_functions))
    Pike_error("Could not populate the global object with output functions\n");
    
  JS_SetVersion(THIS->ctx, version);

  /* create some privacy for us */
  if (!JS_SetPrivate(THIS->ctx, global, THIS))
    Pike_error("Could not set the private storage for the global object\n");
    
  pop_n_elems(args);
}
Exemplo n.º 8
0
static void * testfunc(void *ignored) {
    JSContext *cx = JS_NewContext(rt, 0x1000);
    if (cx) {
        JS_BeginRequest(cx);
        JS_DestroyContext(cx);
    }
}
Exemplo n.º 9
0
nsresult CentralizedAdminPrefManagerInit()
{
    nsresult rv;
    JSRuntime *rt;

    // If autoconfig_cx already created, no need to create it again
    if (autoconfig_cx) 
        return NS_OK;

    // We need the XPCONNECT service
    nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID(), &rv);
    if (NS_FAILED(rv)) {
        return rv;
    }

    // Get the JS RunTime
    nsCOMPtr<nsIJSRuntimeService> rtsvc = 
        do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv);
    if (NS_SUCCEEDED(rv))
        rv = rtsvc->GetRuntime(&rt);

    if (NS_FAILED(rv)) {
        NS_ERROR("Couldn't get JS RunTime");
        return rv;
    }

    // Create a new JS context for autoconfig JS script
    autoconfig_cx = JS_NewContext(rt, 1024);
    if (!autoconfig_cx)
        return NS_ERROR_OUT_OF_MEMORY;

    JSAutoRequest ar(autoconfig_cx);

    JS_SetErrorReporter(autoconfig_cx, autoConfigErrorReporter);

    // Create a new Security Manger and set it for the new JS context
    nsCOMPtr<nsIXPCSecurityManager> secman =
        static_cast<nsIXPCSecurityManager*>(new AutoConfigSecMan());
    xpc->SetSecurityManagerForJSContext(autoconfig_cx, secman, 0);

    autoconfig_glob = JS_NewGlobalObject(autoconfig_cx, &global_class, NULL);
    if (autoconfig_glob) {
        JSAutoEnterCompartment ac;
        if(!ac.enter(autoconfig_cx, autoconfig_glob))
            return NS_ERROR_FAILURE;
        if (JS_InitStandardClasses(autoconfig_cx, autoconfig_glob)) {
            // XPCONNECT enable this JS context
            rv = xpc->InitClasses(autoconfig_cx, autoconfig_glob);
            if (NS_SUCCEEDED(rv)) 
                return NS_OK;
        }
    }

    // failue exit... clean up the JS context
    JS_DestroyContext(autoconfig_cx);
    autoconfig_cx = nsnull;
    return NS_ERROR_FAILURE;
}
Exemplo n.º 10
0
/* Execute a string in its own context (away from Synchronet objects) */
static JSBool
js_eval(JSContext *parent_cx, uintN argc, jsval *arglist)
{
	jsval *argv=JS_ARGV(parent_cx, arglist);
	char*			buf;
	size_t			buflen;
	JSString*		str;
    JSObject*		script;
	JSContext*		cx;
	JSObject*		obj;
	JSErrorReporter	reporter;

	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc<1)
		return(JS_TRUE);

	if((str=JS_ValueToString(parent_cx, argv[0]))==NULL)
		return(JS_FALSE);
	JSSTRING_TO_MSTRING(parent_cx, str, buf, &buflen);
	HANDLE_PENDING(parent_cx);
	if(buf==NULL)
		return(JS_TRUE);

	if((cx=JS_NewContext(JS_GetRuntime(parent_cx),JAVASCRIPT_CONTEXT_STACK))==NULL) {
		free(buf);
		return(JS_FALSE);
	}

	/* Use the error reporter from the parent context */
	reporter=JS_SetErrorReporter(parent_cx,NULL);
	JS_SetErrorReporter(parent_cx,reporter);
	JS_SetErrorReporter(cx,reporter);

	/* Use the operation callback from the parent context */
	JS_SetContextPrivate(cx, JS_GetContextPrivate(parent_cx));
	JS_SetOperationCallback(cx, JS_GetOperationCallback(parent_cx));

	if((obj=JS_NewCompartmentAndGlobalObject(cx, &eval_class, NULL))==NULL
		|| !JS_InitStandardClasses(cx,obj)) {
		JS_DestroyContext(cx);
		free(buf);
		return(JS_FALSE);
	}

	if((script=JS_CompileScript(cx, obj, buf, buflen, NULL, 0))!=NULL) {
		jsval	rval;

		JS_ExecuteScript(cx, obj, script, &rval);
		JS_SET_RVAL(cx, arglist, rval);
	}
	free(buf);

	JS_DestroyContext(cx);

    return(JS_TRUE);
}
int main(int argc, const char *argv[]) {
    /* JS variables. */
    JSRuntime *rt;
    JSContext *cx;
    JSObject *global;

    /* Create a JS runtime. */
    rt = JS_NewRuntime(8L * 1024L * 1024L,JS_NO_HELPER_THREADS);
    if (rt == NULL)
       return 1;

    /* Create a context. */
    cx = JS_NewContext(rt, 8192);
    if (cx == NULL)
       return 1;
    JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_METHODJIT);
    JS_SetVersion(cx, JSVERSION_LATEST);
    JS_SetErrorReporter(cx, reportError);

    /* Create the global object in a new compartment. */
    global = JS_NewGlobalObject(cx, &global_class, NULL);
    if (global == NULL)
       return 1;

    /* Populate the global object with the standard globals, like Object and Array. */
    if (!JS_InitStandardClasses(cx, global))
       return 1;

 
    /* Your application code here. This may include JSAPI calls
     * to create your own custom JavaScript objects and to run scripts.
     *
     * The following example code creates a literal JavaScript script,
     * evaluates it, and prints the result to stdout.
     *
     * Errors are conventionally saved in a JSBool variable named ok.
     */
	
	JS_DefineFunction(cx,global,"print",&js_print,0,0);
	
	// execJsFile(cx,"t.js");
	
	// testObj(cx);
	
	beforeTest(cx);
	execJsFile(cx,"t4.js");
	test(cx);
    
 
    /* End of your application code */
 
    /* Clean things up and shut down SpiderMonkey. */
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return 0;
}
Exemplo n.º 12
0
void SG_jscore__new_context(SG_context * pCtx, JSContext ** pp_cx, JSObject ** pp_glob,
	const SG_vhash * pServerConfig)
{
	JSContext * cx = NULL;
	JSObject * glob = NULL;

	SG_ASSERT(pCtx!=NULL);
	SG_NULLARGCHECK_RETURN(pp_cx);

	if(gpJSCoreGlobalState==NULL)
		SG_ERR_THROW2_RETURN(SG_ERR_UNINITIALIZED, (pCtx, "jscore has not been initialized"));

	if (gpJSCoreGlobalState->cb)
		JS_SetContextCallback(gpJSCoreGlobalState->rt, gpJSCoreGlobalState->cb);

	cx = JS_NewContext(gpJSCoreGlobalState->rt, 8192);
	if(cx==NULL)
		SG_ERR_THROW2_RETURN(SG_ERR_MALLOCFAILED, (pCtx, "Failed to allocate new JS context"));

	(void)JS_SetContextThread(cx);
	JS_BeginRequest(cx);

	JS_SetOptions(cx, JSOPTION_VAROBJFIX);
	JS_SetVersion(cx, JSVERSION_LATEST);
	JS_SetContextPrivate(cx, pCtx);

	glob = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
	if(glob==NULL)
		SG_ERR_THROW2(SG_ERR_JS, (pCtx, "Failed to create JavaScript global object for new JSContext."));
	if(!JS_InitStandardClasses(cx, glob))
		SG_ERR_THROW2(SG_ERR_JS, (pCtx, "JS_InitStandardClasses() failed."));
	if (gpJSCoreGlobalState->shell_functions)
		if (!JS_DefineFunctions(cx, glob, gpJSCoreGlobalState->shell_functions))
			SG_ERR_THROW2(SG_ERR_JS, (pCtx, "Failed to install shell functions"));

    SG_jsglue__set_sg_context(pCtx, cx);

	SG_ERR_CHECK(  SG_jsglue__install_scripting_api(pCtx, cx, glob)  );
	SG_ERR_CHECK(  SG_zing_jsglue__install_scripting_api(pCtx, cx, glob)  );

	if (! gpJSCoreGlobalState->bSkipModules)
	{
		_sg_jscore__install_modules(pCtx, cx, glob, pServerConfig);
		SG_ERR_CHECK_CURRENT_DISREGARD(SG_ERR_NOTAFILE);
	}

	*pp_cx = cx;
	*pp_glob = glob;

	return;
fail:
	if (cx)
	{
		JS_EndRequest(cx);
		JS_DestroyContext(cx);
	}
}
Exemplo n.º 13
0
/* Execute a string in its own context (away from Synchronet objects) */
static JSBool
js_eval(JSContext *parent_cx, JSObject *parent_obj, uintN argc, jsval *argv, jsval *rval)
{
    char*			buf;
    size_t			buflen;
    JSString*		str;
    JSScript*		script;
    JSContext*		cx;
    JSObject*		obj;
    JSErrorReporter	reporter;
#ifndef EVAL_BRANCH_CALLBACK
    JSBranchCallback callback;
#endif

    if(argc<1)
        return(JS_TRUE);

    if((str=JS_ValueToString(parent_cx, argv[0]))==NULL)
        return(JS_FALSE);
    if((buf=JS_GetStringBytes(str))==NULL)
        return(JS_FALSE);
    buflen=JS_GetStringLength(str);

    if((cx=JS_NewContext(JS_GetRuntime(parent_cx),JAVASCRIPT_CONTEXT_STACK))==NULL)
        return(JS_FALSE);

    /* Use the error reporter from the parent context */
    reporter=JS_SetErrorReporter(parent_cx,NULL);
    JS_SetErrorReporter(parent_cx,reporter);
    JS_SetErrorReporter(cx,reporter);

#ifdef EVAL_BRANCH_CALLBACK
    JS_SetContextPrivate(cx, JS_GetPrivate(parent_cx, parent_obj));
    JS_SetBranchCallback(cx, js_BranchCallback);
#else	/* Use the branch callback from the parent context */
    JS_SetContextPrivate(cx, JS_GetContextPrivate(parent_cx));
    callback=JS_SetBranchCallback(parent_cx,NULL);
    JS_SetBranchCallback(parent_cx, callback);
    JS_SetBranchCallback(cx, callback);
#endif

    if((obj=JS_NewObject(cx, NULL, NULL, NULL))==NULL
            || !JS_InitStandardClasses(cx,obj)) {
        JS_DestroyContext(cx);
        return(JS_FALSE);
    }

    if((script=JS_CompileScript(cx, obj, buf, buflen, NULL, 0))!=NULL) {
        JS_ExecuteScript(cx, obj, script, rval);
        JS_DestroyScript(cx, script);
    }

    JS_DestroyContext(cx);

    return(JS_TRUE);
}
Exemplo n.º 14
0
qq_js_t* qq_js_init()
{
    qq_js_t* h =(qq_js_t*) s_malloc0(sizeof(*h));
    h->runtime = JS_NewRuntime(8L*1024L*1024L);
    h->context = JS_NewContext(h->runtime, 8*1024);
    JS_SetOptions(h->context, JSOPTION_VAROBJFIX);
    JS_SetErrorReporter(h->context, report_error);
    h->global = JS_NewCompartmentAndGlobalObject(h->context, &global_class, NULL);
    JS_InitStandardClasses(h->context, h->global);
    return h;
}
Exemplo n.º 15
0
ScriptInterface_impl::ScriptInterface_impl(const char* nativeScopeName, const shared_ptr<ScriptRuntime>& runtime) :
	m_runtime(runtime), m_glob(runtime->m_rt), m_nativeScope(runtime->m_rt)
{
	bool ok;

	m_cx = JS_NewContext(m_runtime->m_rt, STACK_CHUNK_SIZE);
	ENSURE(m_cx);

	JS_SetOffthreadIonCompilationEnabled(m_runtime->m_rt, true);

	// For GC debugging:
	// JS_SetGCZeal(m_cx, 2, JS_DEFAULT_ZEAL_FREQ);

	JS_SetContextPrivate(m_cx, NULL);

	JS_SetErrorReporter(m_runtime->m_rt, ErrorReporter);

	JS_SetGlobalJitCompilerOption(m_runtime->m_rt, JSJITCOMPILER_ION_ENABLE, 1);
	JS_SetGlobalJitCompilerOption(m_runtime->m_rt, JSJITCOMPILER_BASELINE_ENABLE, 1);

	JS::RuntimeOptionsRef(m_cx).setExtraWarnings(1)
		.setWerror(0)
		.setVarObjFix(1)
		.setStrictMode(1);

	JS::CompartmentOptions opt;
	opt.setVersion(JSVERSION_LATEST);
	// Keep JIT code during non-shrinking GCs. This brings a quite big performance improvement.
	opt.setPreserveJitCode(true);

	JSAutoRequest rq(m_cx);
	JS::RootedObject globalRootedVal(m_cx, JS_NewGlobalObject(m_cx, &global_class, NULL, JS::OnNewGlobalHookOption::FireOnNewGlobalHook, opt));
	m_comp = JS_EnterCompartment(m_cx, globalRootedVal);
	ok = JS_InitStandardClasses(m_cx, globalRootedVal);
	ENSURE(ok);
	m_glob = globalRootedVal.get();

	JS_DefineProperty(m_cx, m_glob, "global", globalRootedVal, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

	m_nativeScope = JS_DefineObject(m_cx, m_glob, nativeScopeName, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

	JS_DefineFunction(m_cx, globalRootedVal, "print", ::print,        0, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, globalRootedVal, "log",   ::logmsg,       1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, globalRootedVal, "warn",  ::warn,         1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, globalRootedVal, "error", ::error,        1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, globalRootedVal, "deepcopy", ::deepcopy,  1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

	Register("ProfileStart", ::ProfileStart, 1);
	Register("ProfileStop", ::ProfileStop, 0);
	Register("ProfileAttribute", ::ProfileAttribute, 1);

	runtime->RegisterContext(m_cx);
}
Exemplo n.º 16
0
static JSBool
evalcx(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    JSString *str;
    JSObject *sandbox;
    JSContext *subcx;
    const jschar *src;
    size_t srclen;
    JSBool ret = JS_FALSE;
    char *name = NULL;

    sandbox = NULL;
    if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) {
        return JS_FALSE;
    }

    subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L);
    if(!subcx) {
        JS_ReportOutOfMemory(cx);
        return JS_FALSE;
    }

    SETUP_REQUEST(subcx);

    src = JS_GetStringChars(str);
    srclen = JS_GetStringLength(str);

    if(!sandbox) {
        sandbox = JS_NewObject(subcx, NULL, NULL, NULL);
        if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) {
            goto done;
        }
    }

    if(argc > 2) {
      name = enc_string(cx, argv[2], NULL);
    }

    if(srclen == 0) {
        *rval = OBJECT_TO_JSVAL(sandbox);
    } else {
        JS_EvaluateUCScript(subcx, sandbox, src, srclen, name, 1, rval);
    }
    
    ret = JS_TRUE;

done:
    if(name) JS_free(cx, name);
    FINISH_REQUEST(subcx);
    JS_DestroyContext(subcx);
    return ret;
}
nsresult
nsInProcessTabChildGlobal::InitTabChildGlobal()
{
  nsCOMPtr<nsIJSRuntimeService> runtimeSvc = 
    do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
  NS_ENSURE_STATE(runtimeSvc);

  JSRuntime* rt = nsnull;
  runtimeSvc->GetRuntime(&rt);
  NS_ENSURE_STATE(rt);

  JSContext* cx = JS_NewContext(rt, 8192);
  NS_ENSURE_STATE(cx);

  mCx = cx;

  nsContentUtils::XPConnect()->SetSecurityManagerForJSContext(cx, nsContentUtils::GetSecurityManager(), 0);
  nsContentUtils::GetSecurityManager()->GetSystemPrincipal(getter_AddRefs(mPrincipal));

  JS_SetNativeStackQuota(cx, 128 * sizeof(size_t) * 1024);

  JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_JIT | JSOPTION_PRIVATE_IS_NSISUPPORTS);
  JS_SetVersion(cx, JSVERSION_LATEST);
  JS_SetErrorReporter(cx, ContentScriptErrorReporter);

  xpc_LocalizeContext(cx);

  JSAutoRequest ar(cx);
  nsIXPConnect* xpc = nsContentUtils::XPConnect();
  const PRUint32 flags = nsIXPConnect::INIT_JS_STANDARD_CLASSES |
                         /*nsIXPConnect::OMIT_COMPONENTS_OBJECT ?  |*/
                         nsIXPConnect::FLAG_SYSTEM_GLOBAL_OBJECT;

  nsISupports* scopeSupports =
    NS_ISUPPORTS_CAST(nsIDOMEventTarget*, this);
  JS_SetContextPrivate(cx, scopeSupports);

  nsresult rv =
    xpc->InitClassesWithNewWrappedGlobal(cx, scopeSupports,
                                         NS_GET_IID(nsISupports),
                                         GetPrincipal(), nsnull,
                                         flags, getter_AddRefs(mGlobal));
  NS_ENSURE_SUCCESS(rv, false);

  JSObject* global = nsnull;
  rv = mGlobal->GetJSObject(&global);
  NS_ENSURE_SUCCESS(rv, false);

  JS_SetGlobalObject(cx, global);
  DidCreateCx();
  return NS_OK;
}
Exemplo n.º 18
0
// Initialize PAC parser.
//
// - Initializes JavaScript engine,
// - Exports dns_functions (defined above) to JavaScript context.
// - Sets error reporting function to print_jserror,
// - Evaluates JavaScript code in pacUtils variable defined in pac_utils.h.
int                                     // 0 (=Failure) or 1 (=Success)
pacparser_init()
{
  jsval rval;
  char *error_prefix = "pacparser.c: pacparser_init:";
  // Initialize JS engine
  if (!(rt = JS_NewRuntime(8L * 1024L * 1024L)) ||
      !(cx = JS_NewContext(rt, 8192)) ||
      !(global = JS_NewObject(cx, &global_class, NULL, NULL)) ||
      !JS_InitStandardClasses(cx, global)) {
    print_error("%s %s\n", error_prefix, "Could not initialize  JavaScript "
		  "runtime.");
    return 0;
  }
  JS_SetErrorReporter(cx, print_jserror);
  // Export our functions to Javascript engine
  if (!JS_DefineFunction(cx, global, "dnsResolve", dns_resolve, 1, 0)) {
    print_error("%s %s\n", error_prefix,
		  "Could not define dnsResolve in JS context.");
    return 0;
  }
  if (!JS_DefineFunction(cx, global, "myIpAddress", my_ip, 0, 0)) {
    print_error("%s %s\n", error_prefix,
		  "Could not define myIpAddress in JS context.");
    return 0;
  }
  if (!JS_DefineFunction(cx, global, "dnsResolveEx", dns_resolve_ex, 1, 0)) {
    print_error("%s %s\n", error_prefix,
      "Could not define dnsResolveEx in JS context.");
    return 0;
  }
  if (!JS_DefineFunction(cx, global, "myIpAddressEx", my_ip_ex, 0, 0)) {
    print_error("%s %s\n", error_prefix,
		  "Could not define myIpAddressEx in JS context.");
    return 0;
  }
  // Evaluate pacUtils. Utility functions required to parse pac files.
  if (!JS_EvaluateScript(cx,           // JS engine context
                         global,       // global object
                         pacUtils,     // this is defined in pac_utils.h
                         strlen(pacUtils),
                         NULL,         // filename (NULL in this case)
                         1,            // line number, used for reporting.
                         &rval)) {
    print_error("%s %s\n", error_prefix,
		  "Could not evaluate pacUtils defined in pac_utils.h.");
    return 0;
  }
  if (_debug()) print_error("DEBUG: Pacparser Initalized.\n");
  return 1;
}
Exemplo n.º 19
0
bool CompileFile(const std::string &inputFilePath, const std::string &outputFilePath) {
    bool result = false;
    std::string ofp;
    if (!outputFilePath.empty()) {
        ofp = outputFilePath;
    }
    else {
        ofp = RemoveFileExt(inputFilePath) + BYTE_CODE_FILE_EXT;
    }
    std::cout << "Input file: " << inputFilePath << std::endl;
    JSRuntime * runtime = JS_NewRuntime(10 * 1024 * 1024, JS_NO_HELPER_THREADS);
    JSContext *context = JS_NewContext(runtime, 10240);
    JS_SetOptions(context, JSOPTION_TYPE_INFERENCE);
    JS_SetVersion(context, JSVERSION_LATEST);
    JS_SetOptions(context, JS_GetOptions(context) & ~JSOPTION_METHODJIT);
    JS_SetOptions(context, JS_GetOptions(context) & ~JSOPTION_METHODJIT_ALWAYS);
	JSObject* global = JS_NewGlobalObject(context, &GlobalClass, NULL);
    JS_SetErrorReporter(context, &ReportError);
	if (JS_InitStandardClasses(context, global)) {

        JS::CompileOptions options(context);
        options.setUTF8(true);
        options.setSourcePolicy(JS::CompileOptions::NO_SOURCE);
        js::RootedObject rootedObject(context, global);
        std::cout << "Compiling ..." << std::endl;
        JSScript *script = JS::Compile(context, rootedObject, options, inputFilePath.c_str());
        if (script) {
            void *data = NULL;
            uint32_t length = 0;
            std::cout << "Encoding ..." << std::endl;
            data = JS_EncodeScript(context, script, &length);
            if (data) {
                if (WriteFile(ofp, data, length)) {
                    std::cout << "Done! " << "Output file: " << ofp << std::endl;
                    result = true;
                }
            }
        }
        
    }
    if (context) {
        JS_DestroyContext(context);
        context = NULL;
    }
    if (runtime) {
        JS_DestroyRuntime(runtime);
        runtime = NULL;
    }
    return result;
}
Exemplo n.º 20
0
static JSBool
evalcx(JSContext *cx, uintN argc, jsval* vp)
{
    jsval* argv = JS_ARGV(cx, vp);
    JSString *str;
    JSObject *sandbox;
    JSContext *subcx;
    const jschar *src;
    size_t srclen;
    jsval rval;
    JSBool ret = JS_FALSE;

    sandbox = NULL;
    if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) {
        return JS_FALSE;
    }

    subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L);
    if(!subcx) {
        JS_ReportOutOfMemory(cx);
        return JS_FALSE;
    }

    SETUP_REQUEST(subcx);

    src = JS_GetStringChars(str);
    srclen = JS_GetStringLength(str);

    if(!sandbox) {
        sandbox = JS_NewObject(subcx, NULL, NULL, NULL);
        if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) {
            goto done;
        }
    }

    if(srclen == 0) {
        JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(sandbox));
    } else {
        JS_EvaluateUCScript(subcx, sandbox, src, srclen, NULL, 0, &rval);
        JS_SET_RVAL(cx, vp, rval);
    }

    ret = JS_TRUE;

done:
    FINISH_REQUEST(subcx);
    JS_DestroyContext(subcx);
    return ret;
}
Exemplo n.º 21
0
MozJSImplScope::MozRuntime::MozRuntime() {
    mongo::sm::reset(kMallocMemoryLimit);

    // If this runtime isn't running on an NSPR thread, then it is
    // running on a mongo thread. In that case, we need to insert a
    // fake NSPR thread so that the SM runtime can call PR functions
    // without falling over.
    auto thread = PR_GetCurrentThread();
    if (!thread) {
        PR_BindThread(_thread = PR_CreateFakeThread());
    }

    {
        stdx::unique_lock<stdx::mutex> lk(gRuntimeCreationMutex);

        if (gFirstRuntimeCreated) {
            // If we've already made a runtime, just proceed
            lk.unlock();
        } else {
            // If this is the first one, hold the lock until after the first
            // one's done
            gFirstRuntimeCreated = true;
        }

        _runtime = JS_NewRuntime(kMaxBytesBeforeGC);

        const StackLocator locator;
        const auto available = locator.available();
        if (available) {
            // We fudge by 64k for a two reasons. First, it appears
            // that the internal recursion checks that SM performs can
            // have stack usage between checks of more than 32k in
            // some builds. Second, some platforms report the guard
            // page (in the linux sense) as "part of the stack", even
            // though accessing that page will fault the process. We
            // don't have a good way of getting information about the
            // guard page on those platforms.
            //
            // TODO: What if we are running on a platform with very
            // large pages, like 4MB?
            JS_SetNativeStackQuota(_runtime, available.get() - (64 * 1024));
        }
    }

    uassert(ErrorCodes::JSInterpreterFailure, "Failed to initialize JSRuntime", _runtime);

    _context = JS_NewContext(_runtime, kStackChunkSize);
    uassert(ErrorCodes::JSInterpreterFailure, "Failed to initialize JSContext", _context);
}
Exemplo n.º 22
0
    static void threadMain(void *arg) {
        ThreadData *d = (ThreadData *) arg;

        JSContext *cx = JS_NewContext(d->rt, 8192);
        if (!cx)
            return;
        JS_BeginRequest(cx);
        {
            jsvalRoot v(cx);
            if (!JS_EvaluateScript(cx, d->obj, d->code, strlen(d->code), __FILE__, __LINE__, v.addr()))
                return;
        }
        JS_DestroyContext(cx);
        d->ok = true;
    }
Exemplo n.º 23
0
JSContext *
js_newctx(JSErrorReporter er)
{
  JSContext *cx = JS_NewContext(runtime, 8192);

  JS_SetOptions(cx, 
		JSOPTION_STRICT |
		JSOPTION_WERROR | 
		JSOPTION_VAROBJFIX);
  JS_SetErrorReporter(cx, er ?: err_reporter);
#ifdef JS_GC_ZEAL
  //  JS_SetGCZeal(cx, 1);
#endif
  return cx;
}
Exemplo n.º 24
0
JsExecutionContext::JsExecutionContext(JsParser *jsParser)
{
  parser = jsParser;
  /* Create a new runtime environment. */
  rt = JS_NewRuntime(8L * 1024L * 1024L);
  if (!rt) {
    error("JsParser :: error creating runtime");
    return; /* XXX should return int or ptr! */
  }

  /* Create a new context. */
  cx = JS_NewContext(rt, STACK_CHUNK_SIZE);
  /* if global_context does not have a value, end the program here */
  if (cx == NULL) {
    error("JsParser :: error creating context");
    return;
  }

  JS_BeginRequest(cx);
  // Store a reference to ourselves in the context ...
  JS_SetContextPrivate(cx, parser);

  /* Set a more strict error checking */
  JS_SetOptions(cx, JSOPTION_VAROBJFIX); // | JSOPTION_STRICT);

  /* Set the branch callback */
#if defined JSOPTION_NATIVE_BRANCH_CALLBACK
  JS_SetBranchCallback(cx, js_static_branch_callback);
#else
  JS_SetOperationCallback(cx, js_static_branch_callback);
#endif

  /* Set the error reporter */
  JS_SetErrorReporter(cx, js_error_reporter);

  /* Create the global object here */
  //  JS_SetGlobalObject(global_context, global_object);
  //  this is done in init_class / JS_InitStandardClasses.
  obj = JS_NewObject(cx, &global_class, NULL, NULL);
  init_class();
  JS_EndRequest(cx);
  // deassociate this context from the creating thread
  // so that it can be used in other threads
  // https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_NewContext
  JS_ClearContextThread(cx);
  /** register SIGINT signal */
  //   signal(SIGINT, js_sigint_handler);
}
Exemplo n.º 25
0
    static JSBool chk(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
    {
        JSRuntime *rt = JS_GetRuntime(cx);
        JSContext *acx = JS_NewContext(rt, 8192);
        if (!acx) {
            JS_ReportOutOfMemory(cx);
            return JS_FALSE;
        }

        // acx should not be running
        bool ok = !JS_IsRunning(acx);
        if (!ok)
            JS_ReportError(cx, "Assertion failed: brand new context claims to be running");
        JS_DestroyContext(acx);
        return ok;
    }
Exemplo n.º 26
0
    static bool chk(JSContext *cx, unsigned argc, jsval *vp)
    {
        JSRuntime *rt = JS_GetRuntime(cx);
        JSContext *acx = JS_NewContext(rt, 8192);
        if (!acx) {
            JS_ReportOutOfMemory(cx);
            return false;
        }

        // acx should not be running
        bool ok = !JS_IsRunning(acx);
        if (!ok)
            JS_ReportError(cx, "Assertion failed: brand new context claims to be running");
        JS_DestroyContext(acx);
        return ok;
    }
Exemplo n.º 27
0
Arquivo: flim.c Projeto: mrdg/flim
void initialize_js(struct flim *flim)
{
    flim->js_runtime = JS_NewRuntime(8L * 1024L * 1024L);
    flim->js_context = JS_NewContext(flim->js_runtime, 8192);
    JS_SetOptions(flim->js_context, JSOPTION_VAROBJFIX | JSOPTION_METHODJIT);
    JS_SetVersion(flim->js_context, JSVERSION_LATEST);
    JS_SetErrorReporter(flim->js_context, report_error);

    flim->global = JS_NewCompartmentAndGlobalObject(
                                    flim->js_context, &global_class, NULL);
    JS_InitStandardClasses(flim->js_context, flim->global);
    JS_DefineFunctions(flim->js_context, flim->global, js_functions);

    eval_file("runtime/flim.js");
    eval_file("runtime/underscore.js");
}
Exemplo n.º 28
0
Arquivo: lwjs.c Projeto: fsky/webqq
lwqq_js_t* lwqq_js_init()
{
    lwqq_js_t* h = s_malloc0(sizeof(*h));
    h->runtime = JS_NewRuntime(8L*1024L*1024L);
    h->context = JS_NewContext(h->runtime, 16*1024);
    JS_SetOptions(h->context, 
	JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);
    JS_SetErrorReporter(h->context, report_error);
#ifdef MOZJS_185
    h->global = JS_NewCompartmentAndGlobalObject(h->context, &global_class, NULL);
#else
    h->global = JS_NewGlobalObject(h->context,&global_class,NULL);
#endif
    JS_InitStandardClasses(h->context, h->global);
    return h;
}
Exemplo n.º 29
0
static ctxStore *ctxs_new(pxPAC *pac)
{
	JSObject *global = NULL;
	jsval     rval;

	// Create the basic context
	ctxStore *self = px_malloc0(sizeof(ctxStore));

	// Setup Javascript global class
	self->cls     = px_malloc0(sizeof(JSClass));
	self->cls->name        = "global";
	self->cls->flags       = 0;
	self->cls->addProperty = JS_PropertyStub;
	self->cls->delProperty = JS_PropertyStub;
	self->cls->getProperty = JS_PropertyStub;
	self->cls->setProperty = JS_PropertyStub;
	self->cls->enumerate   = JS_EnumerateStub;
	self->cls->resolve     = JS_ResolveStub;
	self->cls->convert     = JS_ConvertStub;
	self->cls->finalize    = JS_FinalizeStub;

	// Initialize Javascript runtime environment
	if (!(self->run = JS_NewRuntime(1024 * 1024)))                   goto error;
	if (!(self->ctx = JS_NewContext(self->run, 1024 * 1024)))        goto error;
	if (!(global  = JS_NewObject(self->ctx, self->cls, NULL, NULL))) goto error;
	JS_InitStandardClasses(self->ctx, global);

	// Define Javascript functions
	JS_DefineFunction(self->ctx, global, "dnsResolve", dnsResolve, 1, 0);
	JS_DefineFunction(self->ctx, global, "myIpAddress", myIpAddress, 0, 0);
	JS_EvaluateScript(self->ctx, global, JAVASCRIPT_ROUTINES,
			        strlen(JAVASCRIPT_ROUTINES), "pacutils.js", 0, &rval);

	// Add PAC to the environment
	JS_EvaluateScript(self->ctx, global, px_pac_to_string(pac),
                       strlen(px_pac_to_string(pac)),
                       px_url_to_string((pxURL *) px_pac_get_url(pac)),
                       0, &rval);

	// Save the pac
	self->pac = px_strdup(px_pac_to_string(pac));
	return self;

error:
	ctxs_free(self);
	return NULL;
}
Exemplo n.º 30
0
/*----------------------------------------------------------------------------*
 *                           Scripter descriptor                              *
 *----------------------------------------------------------------------------*/
static void * _egueb_script_js_sm_scripter_new(void)
{
	Egueb_Script_Js_Sm_Scripter *thiz;

	thiz = calloc(1, sizeof(Egueb_Script_Js_Sm_Scripter));
	/* Create an instance of the engine */
	thiz->rt = JS_NewRuntime(1024 * 1024);
	JS_SetRuntimePrivate(thiz->rt, thiz);

	/* Create an execution context */
	thiz->cx = JS_NewContext(thiz->rt, 8192);
	JS_SetOptions(thiz->cx, JS_GetOptions(thiz->cx) | JSOPTION_VAROBJFIX);
	JS_SetErrorReporter(thiz->cx, _egueb_script_js_sm_scripter_report_error);

	_egueb_script_js_sm_init_global_object(thiz);
	return thiz;
}