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"); }
// PD_TRACE_DECLARE_FUNCTION ( SDB_SCOPE_INIT, "Scope::init" ) BOOLEAN Scope::init() { BOOLEAN ret = FALSE ; PD_TRACE_ENTRY ( SDB_SCOPE_INIT ); SDB_ASSERT( globalEngine, "Script engine has not been initialized" ); SDB_ASSERT( ! _context && ! _global, "Can't init a scope twice" ); _context = JS_NewContext( globalEngine->_runtime, 1024 * 1024 ) ; VERIFY( _context ); JS_SetOptions( _context, JSOPTION_VAROBJFIX ); JS_SetVersion( _context, JSVERSION_LATEST ); JS_SetErrorReporter( _context, sdbReportError ); _global = JS_NewCompartmentAndGlobalObject( _context, &global_class, NULL ); VERIFY( _global ); VERIFY( JS_InitStandardClasses( _context, _global ) ); VERIFY( InitDbClasses( _context, _global ) ) ; VERIFY ( SDB_OK == evalInitScripts ( this ) ) ; ret = TRUE ; done : PD_TRACE_EXIT ( SDB_SCOPE_INIT ); return ret ; error : goto done ; }
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; }
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; }
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."); }
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_NewCompartmentAndGlobalObject(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; }
/* 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); }
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); } }
static void _egueb_script_js_sm_init_global_object(Egueb_Script_Js_Sm_Scripter *thiz) { /* Create a global object and a set of standard objects */ thiz->global = JS_NewCompartmentAndGlobalObject(thiz->cx, &global_class, NULL); /* TODO add the global dom functions: alert... */ JS_DefineFunctions(thiz->cx, thiz->global, global_functions); /* Populate the global object with the standard globals, * like Object and Array. */ JS_InitStandardClasses(thiz->cx, thiz->global); }
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; }
/** * gjs_init_context_standard: * @context: a #JSContext * * This function creates a default global object for @context, * and calls JS_InitStandardClasses using it. * * Returns: %TRUE on success, %FALSE otherwise */ gboolean gjs_init_context_standard (JSContext *context) { JSObject *global; global = JS_NewCompartmentAndGlobalObject(context, &global_class, NULL); if (global == NULL) return FALSE; if (!JS_InitStandardClasses(context, global)) return FALSE; return TRUE; }
static JSObject * smjs_get_global_object(void) { JSObject *jsobj; assert(smjs_ctx); jsobj = JS_NewCompartmentAndGlobalObject(smjs_ctx, (JSClass *) &global_class, NULL); if (!jsobj) return NULL; JS_InitStandardClasses(smjs_ctx, jsobj); return jsobj; }
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; }
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"); }
bool JetpackChild::Init(base::ProcessHandle aParentProcessHandle, MessageLoop* aIOLoop, IPC::Channel* aChannel) { if (!Open(aChannel, aParentProcessHandle, aIOLoop)) return false; if (!(mRuntime = JS_NewRuntime(32L * 1024L * 1024L)) || !(mCx = JS_NewContext(mRuntime, 8192))) return false; JS_SetVersion(mCx, JSVERSION_LATEST); JS_SetOptions(mCx, JS_GetOptions(mCx) | JSOPTION_DONT_REPORT_UNCAUGHT | JSOPTION_ATLINE | JSOPTION_JIT); JS_SetErrorReporter(mCx, ReportError); { JSAutoRequest request(mCx); JS_SetContextPrivate(mCx, this); JSObject* implGlobal = JS_NewCompartmentAndGlobalObject(mCx, const_cast<JSClass*>(&sGlobalClass), NULL); if (!implGlobal) return false; JSAutoEnterCompartment ac; if (!ac.enter(mCx, implGlobal)) return false; jsval ctypes; if (!JS_InitStandardClasses(mCx, implGlobal) || #ifdef BUILD_CTYPES !JS_InitCTypesClass(mCx, implGlobal) || !JS_GetProperty(mCx, implGlobal, "ctypes", &ctypes) || !JS_SetCTypesCallbacks(mCx, JSVAL_TO_OBJECT(ctypes), &sCallbacks) || #endif !JS_DefineFunctions(mCx, implGlobal, const_cast<JSFunctionSpec*>(sImplMethods))) return false; } return true; }
ScriptingCore::ScriptingCore() { /* Create the JSRuntime. */ this->mJSRuntime = JS_NewRuntime(8L * 1024L * 1024L); if (this->mJSRuntime == NULL) { LOG_D("Could not create JSRuntime!"); } /* Create the JSContext. */ this->mJSContext = JS_NewContext(this->mJSRuntime, 8192); if (this->mJSContext == NULL) { LOG_D("Could not create JSContext!"); } /* Set flags. */ JS_SetOptions(this->mJSContext, JSOPTION_VAROBJFIX); JS_SetVersion(this->mJSContext, JSVERSION_LATEST); JS_SetErrorReporter(this->mJSContext, reportError); /* Create the global object in a new compartment. */ this->mGlobal = JS_NewCompartmentAndGlobalObject(this->mJSContext, &global_class, NULL); if (this->mGlobal == NULL) { LOG_D("Could not create global!"); } if (!JS_InitStandardClasses(this->mJSContext, this->mGlobal)) { LOG_D("Could not initialize standard classes!"); } /* Create the AndEngine namespace. */ JSObject* andengineNamespace = JS_NewObject(this->mJSContext, NULL, NULL, NULL); jsval andengineNamespaceVal = OBJECT_TO_JSVAL(andengineNamespace); JS_SetProperty(this->mJSContext, this->mGlobal, "andengine", &andengineNamespaceVal); /* Register AndEngine classes. */ S_Entity::jsCreateClass(this->mJSContext, andengineNamespace, "Entity"); // S_CCSize::jsCreateClass(this->mJSContext, andengineNamespace, "Size"); // S_CCRect::jsCreateClass(this->mJSContext, andengineNamespace, "Rect"); /* Register some global functions. */ // JS_DefineFunction(this->mJSContext, andengineNamespace, "log", ScriptingCore::log, 0, JSPROP_READONLY | JSPROP_PERMANENT); // JS_DefineFunction(this->mJSContext, andengineNamespace, "forceGC", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT); }
JSBool JetpackChild::CreateSandbox(JSContext* cx, uintN argc, jsval* vp) { if (argc > 0) { JS_ReportError(cx, "createSandbox takes zero arguments"); return JS_FALSE; } JSObject* obj = JS_NewCompartmentAndGlobalObject(cx, const_cast<JSClass*>(&sGlobalClass), NULL); if (!obj) return JS_FALSE; jsval rval = OBJECT_TO_JSVAL(obj); if (!JS_WrapValue(cx, &rval)) return JS_FALSE; JSAutoEnterCompartment ac; if (!ac.enter(cx, obj)) return JS_FALSE; JS_SET_RVAL(cx, vp, rval); return JS_InitStandardClasses(cx, obj); }
/* * Purpose: Carry out rule running in this spun off thread * * Entry: * 1st - Queue entry * * Exit: * SUCCESS = ERR_NONE * FAILURE = ERR_* (type of error) */ ERRTYPE spawnRuleRunner(Queue_Entry *qentry) { JSObject *script = NULL; JSRuntime *rt = NULL; JSContext *cx = NULL; JSBool ret; JSObject *global; jsval rval; Logic_Entry *lentry; if((lentry = getLogicEntryForVoid(qentry->voidId)) == NULL) { printf("logic 2\r\n"); return ERR_NONE; } rt = JS_NewRuntime(SPIDERMONKEY_ALLOC_RAM); if(rt == NULL) { return ERR_UNKNOWN; } /* * 8192 = size of each stack chunk (not stack size) * * Apparently this is an internal variable in spidermonkey * that shouldn't be tweaked without knowing a lot about * spidermonkey's garbage collection. */ cx = JS_NewContext(rt, 8192); if(cx == NULL) { JS_DestroyRuntime(rt); return ERR_UNKNOWN; } JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_COMPILE_N_GO); // JSOPTION_METHODJIT JS_SetVersion(cx, JSVERSION_LATEST); JS_SetErrorReporter(cx, jsErrorHandler); // Create the global object in a new compartment. See http://developer.mozilla.org/En/SpiderMonkey/JSAPI_User_Guide#Native_functions global = JS_NewCompartmentAndGlobalObject(cx, &js_global_object_class, NULL); if (global == NULL) { JS_DestroyContext(cx); JS_DestroyRuntime(rt); return ERR_UNKNOWN; } if(JS_InitStandardClasses(cx, global) == false) { JS_DestroyContext(cx); JS_DestroyRuntime(rt); return ERR_UNKNOWN; } createJSObjectThwonk(cx, global, qentry); script = JS_CompileScript(cx, global, lentry->logic, strlen(lentry->logic), "<inline>", 0); if(script == NULL) { // TODO: Log error to database for script writer to see printf("Couldn't compiled the script\n"); JS_DestroyContext(cx); JS_DestroyRuntime(rt); return ERR_UNKNOWN; } ret = JS_ExecuteScript(cx, global, script, &rval); if(ret == JS_FALSE) { // TODO: Log error to database for script writer to see printf("Failed to run compiled script.\n"); JS_DestroyContext(cx); JS_DestroyRuntime(rt); return ERR_UNKNOWN; } // str = JS_ValueToString(cx, rval); // printf("script result: %s\n", JS_GetStringBytes(str)); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); // Is this needed since thread is ending on return from this function? return ERR_NONE; }
int main() { JSRuntime *rt; JSContext *jscontext; JSObject *glob; nsresult rv; gErrFile = stderr; gOutFile = stdout; { nsCOMPtr<nsIServiceManager> servMan; NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull); // get the JSRuntime from the runtime svc, if possible nsCOMPtr<nsIJSRuntimeService> rtsvc = do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv); if(NS_FAILED(rv) || NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt) DIE("FAILED to get a JSRuntime"); jscontext = JS_NewContext(rt, 8192); if(!jscontext) DIE("FAILED to create a JSContext"); JS_SetErrorReporter(jscontext, my_ErrorReporter); nsCOMPtr<nsIXPConnect> xpc(do_GetService(nsIXPConnect::GetCID(), &rv)); if(!xpc) DIE("FAILED to get xpconnect service\n"); nsCOMPtr<nsIJSContextStack> cxstack = do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv); if(NS_FAILED(rv)) DIE("FAILED to get the nsThreadJSContextStack service!\n"); if(NS_FAILED(cxstack->Push(jscontext))) DIE("FAILED to push the current jscontext on the nsThreadJSContextStack service!\n"); // XXX I'd like to replace this with code that uses a wrapped xpcom object // as the global object. The old TextXPC did this. The support for this // is not working now in the new xpconnect code. { JSAutoRequest ar(jscontext); glob = JS_NewCompartmentAndGlobalObject(jscontext, &global_class, NULL); if (!glob) DIE("FAILED to create global object"); JSAutoEnterCompartment ac; if (!ac.enter(jscontext, glob)) DIE("FAILED to enter compartment"); if (!JS_InitStandardClasses(jscontext, glob)) DIE("FAILED to init standard classes"); if (!JS_DefineFunctions(jscontext, glob, glob_functions)) DIE("FAILED to define global functions"); if (NS_FAILED(xpc->InitClasses(jscontext, glob))) DIE("FAILED to init xpconnect classes"); } /**********************************************/ // run the tests... TestCategoryManmager(); TestSecurityManager(jscontext, glob, xpc); TestArgFormatter(jscontext, glob, xpc); TestThreadJSContextStack(jscontext); /**********************************************/ if(NS_FAILED(cxstack->Pop(nsnull))) DIE("FAILED to pop the current jscontext from the nsThreadJSContextStack service!\n"); { JSAutoRequest ar(jscontext); JS_ClearScope(jscontext, glob); JS_GC(jscontext); JS_GC(jscontext); } JS_DestroyContext(jscontext); xpc->DebugDump(4); cxstack = nsnull; // release service held by nsCOMPtr xpc = nsnull; // release service held by nsCOMPtr rtsvc = nsnull; // release service held by nsCOMPtr } rv = NS_ShutdownXPCOM( NULL ); NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM FAILED"); return 0; }
static PyObject *spindly_js(PyObject *self, PyObject *args) { JSRuntime *runtime; JSContext *context; JSObject *global; char *script; Py_ssize_t script_length; PyObject *params = NULL; int timeout = 10; jsval rvalue; int error = 0; struct watchdog *wd = NULL; if (!PyArg_ParseTuple(args, "s#|Oi:js", &script, &script_length, ¶ms, &timeout)) { return NULL; } if (params != NULL && !PyDict_Check(params)) { return PyErr_Format(PyExc_TypeError, "params must be a dict"); } runtime = JS_NewRuntime(1024L * 1024L); if (!runtime) { return PyErr_Format(PyExc_SystemError, "unable to initialize JS runtime\n"); } context = JS_NewContext(runtime, 8192); if (!context) { JS_DestroyRuntime(runtime); return PyErr_Format(PyExc_SystemError, "unable to initialize JS context\n"); } JS_SetContextPrivate(context, &error); JS_SetOptions(context, JSOPTION_VAROBJFIX); JS_SetVersion(context, JSVERSION_LATEST); JS_SetErrorReporter(context, raise_python_exception); JS_SetOperationCallback(context, js_destroy); global = JS_NewCompartmentAndGlobalObject(context, &global_class, NULL); JS_InitStandardClasses(context, global); if (params != NULL) { populate_javascript_object(context, global, params); } if (timeout > 0) { wd = run_watchdog(context, timeout); if (wd == NULL) { shutdown(runtime, context); return PyErr_Format(PyExc_SystemError, "unable to initialize JS watchdog\n"); } } JSBool retval = JS_EvaluateScript(context, global, script, script_length, "spindly", 1, &rvalue); if (wd) { shutdown_watchdog(wd); } if (retval == JS_FALSE || error == 1) { shutdown(runtime, context); return NULL; } PyObject *obj = to_python_object(context, rvalue); shutdown(runtime, context); return obj; }
int main(int argc, const char *argv[]) { int index; /* JS variables. */ JSRuntime* rt; JSContext* cx; JSObject* global; JSObject* alpha; JSObject* bindings; jsval global_val; JSObject* args; jsval args_val; /* Create a JS runtime. */ rt = JS_NewRuntime(8L * 1024L * 1024L); 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_NewCompartmentAndGlobalObject(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; alpha = JS_DefineObject(cx, global, "alpha", NULL, NULL, 0); /* Attach the global functions */ if (!JS_DefineFunctions(cx, alpha, global_functions)) return 1; /* expose the binding functions for require to use */ bindings = JS_DefineObject(cx, alpha, "bindings", NULL, NULL, 0); if (!JS_DefineFunctions(cx, bindings, binding_functions)) return 1; /* Set global on alpha */ global_val = OBJECT_TO_JSVAL(global); if (!JS_SetProperty(cx, alpha, "global", &global_val)) return 1; /* Set args on alpha */ args = JS_NewArrayObject(cx, 0, NULL); args_val = OBJECT_TO_JSVAL(args); if (!JS_SetProperty(cx, alpha, "args", &args_val)) return 1; for (index = 0; index < argc; index++) { jsval arg = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, argv[index])); if (!JS_SetElement(cx, args, index, &arg)) return 1; } /* Bootstrap using the code in main.js */ JS_EvaluateScript(cx, global, embedded_src_main_js, strlen(embedded_src_main_js), "main.js", 1, NULL); /* Cleanup. */ JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return 0; }
/** * Load a JavaScript file then run the function corresponding to the service by * passing the conf, inputs and outputs parameters by value as JavaScript * Objects. * * @param main_conf the conf maps containing the main.cfg settings * @param request the map containing the HTTP request * @param s the service structure * @param inputs the maps containing the inputs * @param outputs the maps containing the outputs * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1 * if the service failed to load or throw error at runtime. */ int zoo_js_support(maps** main_conf,map* request,service* s,maps **inputs,maps **outputs) { /*maps* main=*main_conf; maps* _inputs=*inputs; maps* _outputs=*outputs;*/ /* The class of the global object. */ JSClass global_class= { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; /* JS variables. */ JSRuntime *rt; JSContext *cx; JSObject *global; /* Create a JS runtime. */ rt = JS_NewRuntime(8L * 1024L * 1024L); if (rt == NULL) return 1; /* Create a context. */ cx = JS_NewContext(rt,8192); if (cx == NULL){ return 1; } JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT); JS_SetVersion(cx, JSVERSION_LATEST); JS_SetErrorReporter(cx, reportError); /* Create the global object. */ global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL); /* Populate the global object with the standard globals, like Object and Array. */ if (!JS_InitStandardClasses(cx, global)){ return 1; } /* Define specific function and global variable to share with JS runtime */ jsval tmp=INT_TO_JSVAL(3); if (!JS_SetProperty(cx, global, "SERVICE_SUCCEEDED", &tmp)) return 1; tmp=INT_TO_JSVAL(4); if (!JS_SetProperty(cx, global, "SERVICE_FAILED", &tmp)) return 1; if (!JS_DefineFunction(cx, global, "ZOORequest", JSRequest, 4, 0)) return 1; if (!JS_DefineFunction(cx, global, "ZOOTranslate", JSTranslate, 4, 0)) return 1; if (!JS_DefineFunction(cx, global, "ZOOUpdateStatus", JSUpdateStatus, 2, 0)) return 1; if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0)) return 1; if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0)) return 1; /** * Add private context object */ void* cxPrivate = request; JS_SetContextPrivate(cx,cxPrivate); map* tmpm1=getMap(request,"metapath"); char ntmp[1024]; map* cwdMap=getMapFromMaps(*main_conf,"main","servicePath"); if(cwdMap!=NULL) sprintf(ntmp,"%s",cwdMap->value); else getcwd(ntmp,1024); /** * Load the first part of the ZOO-API */ char *api0=(char*)malloc((strlen(ntmp)+17)*sizeof(char)); sprintf(api0,"%s/ZOO-proj4js.js",ntmp); #ifdef JS_DEBUG fprintf(stderr,"Trying to load %s\n",api0); #endif JSObject *api_script1=loadZooApiFile(cx,global,api0); free(api0); fflush(stderr); char *api1=(char*)malloc((strlen(ntmp)+13)*sizeof(char)); sprintf(api1,"%s/ZOO-api.js",ntmp); #ifdef JS_DEBUG fprintf(stderr,"Trying to load %s\n",api1); #endif JSObject *api_script2=loadZooApiFile(cx,global,api1); free(api1); fflush(stderr); /* Your application code here. This may include JSAPI calls to create your own custom JS objects and run scripts. */ //maps* out=*outputs; int res=SERVICE_FAILED; //maps* mc=*main_conf; map* tmpm2=getMap(s->content,"serviceProvider"); char *filename=(char*)malloc(strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+3); sprintf(filename,"%s/%s/%s",ntmp,tmpm1->value,tmpm2->value); filename[strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+2]=0; #ifdef JS_DEBUG fprintf(stderr,"FILENAME %s\n",filename); #endif struct stat file_status; stat(filename, &file_status); //char *source=(char*)malloc(file_status.st_size); //uint16 lineno; jsval rval; JSBool ok ; JSObject *script = JS_CompileFile(cx, global, filename); if(script!=NULL){ (void)JS_ExecuteScript(cx, global, script, &rval); } else{ char tmp1[1024]; sprintf(tmp1,"Unable to load JavaScript file %s",filename); free(filename); errorException(*main_conf,tmp1,"NoApplicableCode",NULL); JS_MaybeGC(cx); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return -1; } /* Call a function in obj's scope. */ jsval argv[3]; JSObject *jsargv1=JSObject_FromMaps(cx,*main_conf); argv[0] = OBJECT_TO_JSVAL(jsargv1); JSObject *jsargv2=JSObject_FromMaps(cx,*inputs); argv[1] = OBJECT_TO_JSVAL(jsargv2); JSObject *jsargv3=JSObject_FromMaps(cx,*outputs); argv[2] = OBJECT_TO_JSVAL(jsargv3); jsval rval1=JSVAL_NULL; #ifdef JS_DEBUG fprintf(stderr, "object %p\n", (void *) argv[2]); #endif ok = JS_CallFunctionName(cx, global, s->name, 3, argv, &rval1); #ifdef JS_DEBUG fprintf(stderr, "object %p\n", (void *) argv[2]); #endif JSObject *d; if (ok==JS_TRUE && JSVAL_IS_OBJECT(rval1)==JS_TRUE) { #ifdef JS_DEBUG fprintf(stderr,"Function run sucessfully !\n"); #endif /* Should get a number back from the service function call. */ ok = JS_ValueToObject(cx, rval1, &d); }else{ /* Unable to run JS function */ char tmp1[1024]; if(strlen(dbg)==0) sprintf(dbg,"No result was found after the function call"); sprintf(tmp1,"Unable to run %s from the JavaScript file %s : \n %s",s->name,filename,dbg); #ifdef JS_DEBUG fprintf(stderr,"%s",tmp1); #endif errorException(*main_conf,tmp1,"NoApplicableCode",NULL); free(filename); JS_MaybeGC(cx); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); // Should return -1 here but the unallocation won't work from zoo_service_loader.c line 1847 return -1; } //jsval t=OBJECT_TO_JSVAL(d); if(JS_IsArrayObject(cx,d)){ #ifdef JS_DEBUG fprintf(stderr,"An array was returned !\n"); #endif jsuint len; if((JS_GetArrayLength(cx, d, &len)==JS_FALSE)){ #ifdef JS_DEBUG fprintf(stderr,"outputs array is empty\n"); #endif } jsval tmp1; JSBool hasResult=JS_GetElement(cx,d,0,&tmp1); res=JSVAL_TO_INT(tmp1); #ifdef JS_DEBUG fprintf(stderr," * %d * \n",res); #endif if(res==SERVICE_SUCCEEDED){ jsval tmp2; JSBool hasElement=JS_GetElement(cx,d,1,&tmp2); if(hasElement==JS_TRUE){ freeMaps(outputs); free(*outputs); *outputs=mapsFromJSObject(cx,tmp2); } }else{ jsval tmp3; JSBool hasConf=JS_GetElement(cx,d,1,&tmp3); if(hasConf==JS_TRUE){ freeMaps(main_conf); free(*main_conf); *main_conf=mapsFromJSObject(cx,tmp3); } } } else{ #ifdef JS_DEBUG fprintf(stderr,"The service didn't return an array !\n"); #endif /** * Extract result */ jsval tmp1; JSBool hasResult=JS_GetProperty(cx,d,"result",&tmp1); res=JSVAL_TO_INT(tmp1); #ifdef JS_DEBUG fprintf(stderr," * %d * \n",res); #endif /** * Extract outputs when available. */ jsval tmp2; JSBool hasElement=JS_GetProperty(cx,d,"outputs",&tmp2); if(!JSVAL_IS_VOID(tmp2) && hasElement==JS_TRUE){ freeMaps(outputs); free(*outputs); *outputs=mapsFromJSObject(cx,tmp2); } JS_MaybeGC(cx); #ifdef JS_DEBUG if(JSVAL_IS_VOID(tmp2)) fprintf(stderr,"No outputs property returned\n"); else{ if(JS_IsArrayObject(cx,JSVAL_TO_OBJECT(tmp2))) fprintf(stderr,"outputs is an array as expected\n"); else fprintf(stderr,"outputs is not an array as expected\n"); } JS_MaybeGC(cx); #endif /** * Extract conf when available. */ jsval tmp3; JSBool hasConf=JS_GetProperty(cx,d,"conf",&tmp3); if(!JSVAL_IS_VOID(tmp3) && hasConf==JS_TRUE){ freeMaps(main_conf); free(*main_conf); *main_conf=mapsFromJSObject(cx,tmp3); } JS_MaybeGC(cx); #ifdef JS_DEBUG dumpMaps(*outputs); #endif } /* Cleanup. */ JS_MaybeGC(cx); JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); free(filename); #ifdef JS_DEBUG fprintf(stderr,"Returned value %d\n",res); #endif return res; }
int SDL_main(int argc, char **argv) { bool referenceMode = false; bool javaScriptMode = false; char* scripts [32]; int scriptCount = 0; char* args; int o = 0; while ((o = getopt (argc, argv, "rjs:a:")) != -1) { switch (o) { case 'r': referenceMode = true; break; case 'j': javaScriptMode = true; break; case 's': scripts[scriptCount++] = optarg; break; case 'a': args = optarg; break; case '?': printf("[-r] [-s FILE] [-a ARGUMENTS]\n"); break; } } if (referenceMode) { Avc avc(args); avc.Play(); } else if (javaScriptMode) { /* JS variables. */ JSRuntime *rt; JSContext *cx; JSObject *global; /* Create a JS runtime. */ rt = JS_NewRuntime(8L * 1024L * 1024L); if (rt == NULL) return 1; /* Create a context. */ cx = JS_NewContext(rt, 8192); if (cx == NULL) return 1; 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. */ global = JS_NewCompartmentAndGlobalObject(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; if (!JS_DefineFunctions(cx, global, globalFunctions)) return JS_FALSE; for (int i = 0; i < scriptCount; i++) { JSScript *script = JS_CompileFile(cx, global, scripts[i]); if (script == NULL) return 1; jsval rval; JSBool result = JS_ExecuteScript(cx, global, script, &rval); if (!result) { printf("Cannot execute script %s", scripts[i]); } } /* Cleanup. */ JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); } return 0; }
int main() { std::string a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbccccccccccccaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; std::string output; ZopfliOptions options; ZopfliInitOptions(&options); snappy::Compress(a.data(), a.size(), &output); if(!checkhash((unsigned char *)output.data(), output.size(), (char *)"0x5a8f06cf6817a74bc75c3c8290196928acb04c189ecdd192a93eb3c3")) { std::cout<<"Something wrong\n"; } unsigned char b[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbccccccccccccaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; unsigned char *out = NULL; size_t outsize = 0; ZopfliCompress(&options, ZOPFLI_FORMAT_GZIP, b, a.size(), &out, &outsize); if(!checkhash(out, outsize, (char *)"0x0f66ce213d2d27067ff9ffa8bbde2dd06d7f3e687549fad846169e16")) { std::cout<<"Something wrong\n"; } HangulInputContext* ic; const char* p = "dekde"; const ucschar* commit; ic = hangul_ic_new("2y"); while (*p != '\0') { hangul_ic_process(ic, *p); p++; } commit = hangul_ic_get_commit_string(ic); int len = wcslen((const wchar_t*)commit); if(!checkhash((unsigned char*)commit, len * sizeof(const wchar_t), (char *)"0xc9bf9374fbc9f4989afd0af7ac9824a4dcc768b33bfa3bb38e42617b")) { std::cout<<"Something wrong\n"; } hangul_ic_delete(ic); static JSClass global_class = { "global", JSCLASS_NEW_RESOLVE | JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, NULL, JSCLASS_NO_OPTIONAL_MEMBERS }; JSRuntime *rt = JS_NewRuntime(8 * 1024 * 1024); JSContext *cx = JS_NewContext(rt, 8192); JS_SetOptions(cx, JSOPTION_VAROBJFIX); JS_SetErrorReporter(cx, reportError); JSObject *global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL); JS_SetGlobalObject(cx, global); if (!JS_InitStandardClasses(cx, global)) { return 1; } char source[] = "Math.random()"; jsval rval; cx->rngSeed = 31337; JS_EvaluateScript(cx, global, source, strlen(source), "none", 10, &rval); double nums[2]; nums[0] = JSVAL_TO_DOUBLE(rval); JS_EvaluateScript(cx, global, source, strlen(source), "none", 10, &rval); nums[1] = JSVAL_TO_DOUBLE(rval); if(!checkhash((unsigned char*)nums, 2 * sizeof(double), (char *)"0x61b35e8d466f24ee1ea502350ec6f5d1134fe6ec543c17845fa62f8a")) { std::cout<<"Something wrong\n"; } JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); mtprngParam mt; byte bay[] = "qqqqqqqqqqqqqqqq"; byte result[100]; for(int i=0; i< 100; i++) { result[i] = 0; } mtprngSetup(&mt); mtprngSeed(&mt, bay, 16); mtprngNext(&mt, result, 100); if(!checkhash((unsigned char*)&result, 100, (char *)"0x7754dfd27fe6fa00551861ff41e4f48315bd89bef6da652f182ce2d6")) { std::cout<<"Something wrong\n"; } ranlib::ChiSquare<double> gen(4); gen.seed(31337); double f[16]; for(int i = 0; i<16; i++) { f[i] = gen.random(); } if(!checkhash((unsigned char*)&f, 16 * sizeof(double), (char *)"0xd19d0c167fe93b11004c0167c226d2e92c17dfa36ffb243f39824098")) { std::cout<<"Something wrong\n"; } Botan::byte pass[] = "aaaabbbb"; Botan::PBKDF* pbkdf = Botan::get_pbkdf("PBKDF2(SHA-256)"); Botan::OctetString aes_key = pbkdf->derive_key(32, "pass1337", pass, 8, 31337); std::string aa = aes_key.as_string(); if(!checkhash((unsigned char*)aa.c_str(), aa.size(), (char *)"0x0c33d122ed50848a676539ae48eb84db0dcbf69e9ee857094755f2d7")) { std::cout<<"Something wrong\n"; } std::cout<<"Answer is RUCTF_"; checkhash((unsigned char*)together, pos, (char *)""); return 0; }
int SpiderMonkeyMain(int argc, char ** argv, char ** envp) { JSContext * context = InitializeSpiderMonkey(); JSObject * global = JS_NewCompartmentAndGlobalObject(context, &global_class, NULL); JS_InitStandardClasses(context, global); int c, r = 0; JSObject * env; jsval result; while (1) { static struct option long_options[] = { /* These options set a flag. */ {"verbose", no_argument, &verbose_flag, 1}, {"brief", no_argument, &verbose_flag, 0}, /* These options don’t set a flag. We distinguish them by their indices. */ {"print-result", no_argument, 0, 'p'}, {"run-script", no_argument, 0, 'r'}, {"shell-script", required_argument, 0, 's'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long(argc, argv, "prs:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) { //printf ("got end of options\n"); break; } switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; printf("option %s", long_options[option_index].name); if (optarg) printf(" with arg %s", optarg); printf("\n"); break; case 'p': print_result_flag = 1; break; case 'r': printf("option -r with value `%s'\n", optarg); break; case 's': r = ExecShellScript(optarg, argc - optind, argv + optind, context, global, &result); if (r == JS_FALSE && exitcode == 0) exitcode = 1; optind = argc; break; case '?': /* getopt_long already printed an error message. */ break; default: break; } } if (print_result_flag && result) { JSString * result_string = JS_ValueToString(context, result); char * bytes = JS_EncodeString(context, result_string); if (!bytes) { return 1; } else { printf("%s\n", bytes); JS_free(context, bytes); } } TerminateSpiderMonkey(context); /* Print any remaining command line arguments (not options). */ if (optind < argc) { printf("non-option ARGV-elements: "); while (optind < argc) printf("%s ", argv[optind++]); putchar('\n'); } return (exitcode); }
ScriptInterface_impl::ScriptInterface_impl(const char* nativeScopeName, const shared_ptr<ScriptRuntime>& runtime) : m_runtime(runtime) { JSBool ok; m_cx = JS_NewContext(m_runtime->m_rt, STACK_CHUNK_SIZE); ENSURE(m_cx); // For GC debugging: // JS_SetGCZeal(m_cx, 2); JS_SetContextPrivate(m_cx, NULL); JS_SetErrorReporter(m_cx, ErrorReporter); uint32 options = 0; options |= JSOPTION_STRICT; // "warn on dubious practice" options |= JSOPTION_XML; // "ECMAScript for XML support: parse <!-- --> as a token" options |= JSOPTION_VAROBJFIX; // "recommended" (fixes variable scoping) // Enable method JIT, unless script profiling/debugging is enabled (since profiling/debugging // hooks are incompatible with the JIT) // TODO: Verify what exactly is incompatible if (!g_ScriptProfilingEnabled && !g_JSDebuggerEnabled) { options |= JSOPTION_METHODJIT; // Some other JIT flags to experiment with: options |= JSOPTION_JIT; options |= JSOPTION_PROFILING; } JS_SetOptions(m_cx, options); JS_SetVersion(m_cx, JSVERSION_LATEST); // Threadsafe SpiderMonkey requires that we have a request before doing anything much JS_BeginRequest(m_cx); // We only want a single compartment per runtime if (m_runtime->m_compartmentGlobal) { m_call = JS_EnterCrossCompartmentCall(m_cx, m_runtime->m_compartmentGlobal); m_glob = JS_NewGlobalObject(m_cx, &global_class); } else { m_call = NULL; m_glob = JS_NewCompartmentAndGlobalObject(m_cx, &global_class, NULL); m_runtime->m_compartmentGlobal = m_glob; } ok = JS_InitStandardClasses(m_cx, m_glob); ENSURE(ok); JS_DefineProperty(m_cx, m_glob, "global", OBJECT_TO_JSVAL(m_glob), NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); m_nativeScope = JS_DefineObject(m_cx, m_glob, nativeScopeName, NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "print", ::print, 0, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "log", ::logmsg, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "warn", ::warn, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "error", ::error, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "deepcopy", ::deepcopy, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); Register("ProfileStart", ::ProfileStart, 1); Register("ProfileStop", ::ProfileStop, 0); }
/** * Create a new GPSEE Realm. New realm will be initialized to have all members NULL, except * - the context and name provided (name only present in debug build) * - an initialized module system (and hence module data store) * - an initialized I/O hooks data store * - an initialized global object * - a prototype for the module object * * @param grt The GPSEE runtime to which the new realm will belong * @param name A symbolic name, for use in debugging, to describe this realm. Does not need to be unique. * * @returns The new realm, or NULL if we threw an exception. */ gpsee_realm_t *gpsee_createRealm(gpsee_runtime_t *grt, const char *name) { gpsee_realm_t *realm = NULL; JSContext *cx; cx = JS_NewContext(grt->rt, 8192); if (!cx) return NULL; JS_BeginRequest(cx); JS_SetOptions(cx, JS_GetOptions(grt->coreCx)); gpsee_enterAutoMonitor(cx, &grt->monitors.realms); realm = JS_malloc(cx, sizeof(*realm)); if (!realm) goto err_out; memset(realm, 0, sizeof(*realm)); realm->grt = grt; #ifdef GPSEE_DEBUG_BUILD realm->name = JS_strdup(cx, name); if (!realm->name) goto err_out; #endif realm->user_io_pendingWrites = gpsee_ds_create(grt, GPSEE_DS_OTM_KEYS, 0); if (!realm->user_io_pendingWrites) return JS_FALSE; #if defined(JSRESERVED_GLOBAL_COMPARTMENT) realm->globalObject = JS_NewCompartmentAndGlobalObject(cx, gpsee_getGlobalClass(), NULL); #else realm->globalObject = JS_NewGlobalObject(cx, gpsee_getGlobalClass()); #endif if (!realm->globalObject) goto err_out; { static JSClass moduleObjectClass = { GPSEE_GLOBAL_NAMESPACE_NAME ".Module", 0, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; #undef JS_InitClass moduleObjectClass.name += sizeof(GPSEE_GLOBAL_NAMESPACE_NAME); realm->moduleObjectProto = JS_InitClass(cx, realm->globalObject, NULL, &moduleObjectClass, ModuleObject, 0, NULL, NULL, NULL, NULL); moduleObjectClass.name -= sizeof(GPSEE_GLOBAL_NAMESPACE_NAME); realm->moduleObjectClass = &moduleObjectClass; #define JS_InitClass poison } if (!realm->moduleObjectProto) goto err_out; JS_AddNamedObjectRoot(cx, &realm->globalObject, "super-global"); if (gpsee_ds_put(grt->realms, realm, NULL) == JS_FALSE) goto err_out; if (gpsee_initializeModuleSystem(cx, realm) == JS_FALSE) panic("Unable to initialize module system"); if (gpsee_initGlobalObject(cx, realm, realm->globalObject) == JS_FALSE) goto err_out; realm->cachedCx = cx; goto out; err_out: if (realm) { JS_free(cx, realm); #ifdef GPSEE_DEBUG_BUILD if (realm->name) JS_free(cx, (char *)realm->name); #endif realm = NULL; } if (cx) { JS_DestroyContext(cx); cx = NULL; } out: gpsee_leaveAutoMonitor(grt->monitors.realms); if (cx) JS_EndRequest(cx); return realm; }
static JSDContext* _newJSDContext(JSRuntime* jsrt, JSD_UserCallbacks* callbacks, void* user, JSObject* scopeobj) { JSDContext* jsdc = NULL; JSCrossCompartmentCall *call = NULL; JSBool ok; if( ! jsrt ) return NULL; if( ! _validateUserCallbacks(callbacks) ) return NULL; jsdc = (JSDContext*) calloc(1, sizeof(JSDContext)); if( ! jsdc ) goto label_newJSDContext_failure; if( ! JSD_INIT_LOCKS(jsdc) ) goto label_newJSDContext_failure; JS_INIT_CLIST(&jsdc->links); jsdc->jsrt = jsrt; if( callbacks ) memcpy(&jsdc->userCallbacks, callbacks, callbacks->size); jsdc->user = user; #ifdef JSD_HAS_DANGEROUS_THREAD jsdc->dangerousThread = _dangerousThread; #endif JS_INIT_CLIST(&jsdc->threadsStates); JS_INIT_CLIST(&jsdc->sources); JS_INIT_CLIST(&jsdc->removedSources); jsdc->sourceAlterCount = 1; if( ! jsd_CreateAtomTable(jsdc) ) goto label_newJSDContext_failure; if( ! jsd_InitObjectManager(jsdc) ) goto label_newJSDContext_failure; if( ! jsd_InitScriptManager(jsdc) ) goto label_newJSDContext_failure; jsdc->dumbContext = JS_NewContext(jsdc->jsrt, 256); if( ! jsdc->dumbContext ) goto label_newJSDContext_failure; JS_BeginRequest(jsdc->dumbContext); JS_SetOptions(jsdc->dumbContext, JS_GetOptions(jsdc->dumbContext) | JSOPTION_ALLOW_XML); jsdc->glob = JS_NewCompartmentAndGlobalObject(jsdc->dumbContext, &global_class, NULL); if( ! jsdc->glob ) goto label_newJSDContext_failure; call = JS_EnterCrossCompartmentCall(jsdc->dumbContext, jsdc->glob); if( ! call ) goto label_newJSDContext_failure; if ( ! JS_AddNamedObjectRoot(jsdc->dumbContext, &jsdc->glob, "JSD context global") ) goto label_newJSDContext_failure; ok = JS_InitStandardClasses(jsdc->dumbContext, jsdc->glob); JS_LeaveCrossCompartmentCall(call); if( ! ok ) goto label_newJSDContext_failure; JS_EndRequest(jsdc->dumbContext); jsdc->data = NULL; jsdc->inited = JS_TRUE; JSD_LOCK(); JS_INSERT_LINK(&jsdc->links, &_jsd_context_list); JSD_UNLOCK(); return jsdc; label_newJSDContext_failure: if( jsdc ) { if ( jsdc->dumbContext && jsdc->glob ) JS_RemoveObjectRootRT(JS_GetRuntime(jsdc->dumbContext), &jsdc->glob); jsd_DestroyObjectManager(jsdc); jsd_DestroyAtomTable(jsdc); if( jsdc->dumbContext ) JS_EndRequest(jsdc->dumbContext); free(jsdc); } return NULL; }
int runJS(char* script) { LOGD("runJS"); // LOGD("script :\n%s", script); /* Create a JS runtime. */ JSRuntime *rt = JS_NewRuntime(8L * 1024L * 1024L); if (rt == NULL) { LOGD("(rt == NULL)"); return 1; } /* Create a context. */ JSContext *cx = JS_NewContext(rt, 8192); if (cx == NULL) { LOGD("(cx == NULL)"); return 1; } JS_SetOptions(cx, JSOPTION_VAROBJFIX); JS_SetVersion(cx, JSVERSION_LATEST); JS_SetErrorReporter(cx, jsbindings::reportError); /* Create the global object in a new compartment. */ JSObject *global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL); if (global == NULL) { LOGD("(global == NULL)"); return 1; } // Populate the global object with the standard globals, // like Object and Array. if (!JS_InitStandardClasses(cx, global)) { LOGD("(!JS_InitStandardClasses(cx, global))"); return 1; } const char *filename = NULL; int lineno = 0; jsval rval; JSBool evaluatedOK = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, &rval); if (JS_FALSE == evaluatedOK) { LOGD("evaluatedOK == JS_FALSE)"); // return 1; } else { if (JSVAL_IS_NULL(rval)) { LOGD("rval : (JSVAL_IS_NULL(rval)"); // return 1; } else if ((JSVAL_IS_BOOLEAN(rval)) && (JS_FALSE == (JSVAL_TO_BOOLEAN(rval)))) { LOGD("rval : (return value is JS_FALSE"); // return 1; } else if (JSVAL_IS_STRING(rval)) { JSString *str = JS_ValueToString(cx, rval); if (NULL == str) { LOGD("rval : return string is NULL"); } else { LOGD("rval : return string =\n%s\n", JS_EncodeString(cx, str)); } } else if (JSVAL_IS_NUMBER(rval)) { double number; if (JS_FALSE == JS_ValueToNumber(cx, rval, &number)) { LOGD("rval : return number could not be converted"); } else { LOGD("rval : return number =\n%f", number); } } } // Cleanup JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); LOGD("runJS done."); return 0; }
void * spidermonkey_get_interpreter(struct ecmascript_interpreter *interpreter) { JSContext *ctx; JSObject *window_obj, *document_obj, *forms_obj, *history_obj, *location_obj, *statusbar_obj, *menubar_obj, *navigator_obj; assert(interpreter); if (!js_module_init_ok) return NULL; ctx = JS_NewContext(spidermonkey_runtime, 8192 /* Stack allocation chunk size */); if (!ctx) return NULL; interpreter->backend_data = ctx; JS_SetContextPrivate(ctx, interpreter); JS_SetOptions(ctx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT); JS_SetVersion(ctx, JSVERSION_LATEST); JS_SetErrorReporter(ctx, error_reporter); #if defined(CONFIG_ECMASCRIPT_SMJS_HEARTBEAT) JS_SetOperationCallback(ctx, heartbeat_callback); #endif window_obj = JS_NewCompartmentAndGlobalObject(ctx, (JSClass *) &window_class, NULL); if (!window_obj) goto release_and_fail; if (!JS_InitStandardClasses(ctx, window_obj)) goto release_and_fail; if (!JS_DefineProperties(ctx, window_obj, (JSPropertySpec *) window_props)) goto release_and_fail; if (!spidermonkey_DefineFunctions(ctx, window_obj, window_funcs)) goto release_and_fail; if (!JS_SetPrivate(ctx, window_obj, interpreter->vs)) /* to @window_class */ goto release_and_fail; document_obj = spidermonkey_InitClass(ctx, window_obj, NULL, (JSClass *) &document_class, NULL, 0, (JSPropertySpec *) document_props, document_funcs, NULL, NULL); if (!document_obj) goto release_and_fail; forms_obj = spidermonkey_InitClass(ctx, document_obj, NULL, (JSClass *) &forms_class, NULL, 0, (JSPropertySpec *) forms_props, forms_funcs, NULL, NULL); if (!forms_obj) goto release_and_fail; history_obj = spidermonkey_InitClass(ctx, window_obj, NULL, (JSClass *) &history_class, NULL, 0, (JSPropertySpec *) NULL, history_funcs, NULL, NULL); if (!history_obj) goto release_and_fail; location_obj = spidermonkey_InitClass(ctx, window_obj, NULL, (JSClass *) &location_class, NULL, 0, (JSPropertySpec *) location_props, location_funcs, NULL, NULL); if (!location_obj) goto release_and_fail; menubar_obj = JS_InitClass(ctx, window_obj, NULL, (JSClass *) &menubar_class, NULL, 0, (JSPropertySpec *) unibar_props, NULL, NULL, NULL); if (!menubar_obj) goto release_and_fail; if (!JS_SetPrivate(ctx, menubar_obj, "t")) /* to @menubar_class */ goto release_and_fail; statusbar_obj = JS_InitClass(ctx, window_obj, NULL, (JSClass *) &statusbar_class, NULL, 0, (JSPropertySpec *) unibar_props, NULL, NULL, NULL); if (!statusbar_obj) goto release_and_fail; if (!JS_SetPrivate(ctx, statusbar_obj, "s")) /* to @statusbar_class */ goto release_and_fail; navigator_obj = JS_InitClass(ctx, window_obj, NULL, (JSClass *) &navigator_class, NULL, 0, (JSPropertySpec *) navigator_props, NULL, NULL, NULL); if (!navigator_obj) goto release_and_fail; return ctx; release_and_fail: spidermonkey_put_interpreter(interpreter); return NULL; }