bool JSAPITest::exec(const char *bytes, const char *filename, int lineno) { JS::RootedValue v(cx); JS::HandleObject global = JS::HandleObject::fromMarkedLocation(&this->global); return JS_EvaluateScript(cx, global, bytes, strlen(bytes), filename, lineno, v.address()) || fail(bytes, filename, lineno); }
bool ScriptEngine_Execute(char const * script) { if(!g_JsRunning) return false; JSAutoCompartment ac(g_JsCx, g_JsGlobal); jsval rval; return JS_TRUE == JS_EvaluateScript(g_JsCx, JS_GetGlobalForScopeChain(g_JsCx), script, strlen(script), NULL, 0, &rval); }
bool round_js_sm_engine_run(RoundJavaScriptEngine* engine, const char* source, size_t sourceLen, RoundString* result, RoundError* err) { if (!engine) return false; if (!engine->rt || !engine->cx) return false; gCurrentJsEngine = engine; jsval rval; JSBool ok = JS_EvaluateScript(engine->cx, engine->obj, source, (uintN)sourceLen, "", 0, &rval); gCurrentJsEngine = NULL; if (ok) { JSString* rstr = JS_ValueToString(engine->cx, rval); if (rstr) { if (result) { round_string_setvalue(result, JS_EncodeString(engine->cx, rstr)); } } } return ok; }
unsigned char * spidermonkey_eval_stringback(struct ecmascript_interpreter *interpreter, struct string *code) { JSBool ret; JSContext *ctx; jsval rval; assert(interpreter); if (!js_module_init_ok) return NULL; ctx = interpreter->backend_data; interpreter->ret = NULL; #if defined(CONFIG_ECMASCRIPT_SMJS_HEARTBEAT) interpreter->heartbeat = add_heartbeat(interpreter); #elif defined(HAVE_JS_SETBRANCHCALLBACK) setup_safeguard(interpreter, ctx); #endif ret = JS_EvaluateScript(ctx, JS_GetGlobalObject(ctx), code->source, code->length, "", 0, &rval); #if defined(CONFIG_ECMASCRIPT_SMJS_HEARTBEAT) done_heartbeat(interpreter->heartbeat); #endif if (ret == JS_FALSE) { return NULL; } if (JSVAL_IS_VOID(rval) || JSVAL_IS_NULL(rval)) { /* Undefined value. */ return NULL; } return stracpy(jsval_to_string(ctx, &rval)); }
bool Context::evaluateScript(const char* script, JS::Value* val) { JSAutoCompartment ac(_jsctx, _global); return JS_EvaluateScript(_jsctx, _global, script, strlen(script), "inline", 1, val); }
static jsval anonEvaluate(JSContext *cx, JSObject *thisObj, const char* string) { jsval out; if (JS_EvaluateScript(cx, thisObj, string, strlen(string), "(string)", 1, &out) == JS_TRUE) { return out; } return JSVAL_VOID; }
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; }
static jsval anonEvaluate(JSContext *cx, JS::HandleObject thisObj, const char* string) { JS::RootedValue out(cx); // JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET if (JS_EvaluateScript(cx, thisObj, string, strlen(string), "(string)", 1, &out) == true) { return out.get(); } return JSVAL_VOID; }
static void EvaluateScript(JSContext* jscontext, JSObject* glob, MySecMan* sm, MySecMan::Mode mode, const char* msg, const char* t, jsval &rval) { sm->SetMode(mode); fputs(msg, stdout); JSAutoRequest ar(jscontext); JS_EvaluateScript(jscontext, glob, t, strlen(t), "builtin", 1, &rval); }
// PD_TRACE_DECLARE_FUNCTION ( SDB_SCOPE_EVALUATE2, "Scope::evaluate2" ) INT32 Scope::evaluate2 ( const CHAR *code, UINT32 len, UINT32 lineno, jsval *rval, CHAR **errMsg, INT32 printFlag ) { PD_TRACE_ENTRY ( SDB_SCOPE_EVALUATE2 ); INT32 rc = SDB_OK ; jsval exception = JSVAL_VOID ; CHAR *cstrException = NULL ; SDB_ASSERT ( _context && _global, "this scope has not been initilized" ) ; SDB_ASSERT ( code , "Invalid arguments" ) ; // set error report sdbSetPrintError( ( printFlag & SPT_EVAL_FLAG_PRINT ) ? TRUE : FALSE ) ; sdbSetNeedClearErrorInfo( TRUE ) ; if ( ! JS_EvaluateScript ( _context, _global, code, len, NULL, lineno, rval ) ) { rc = sdbGetErrno() ? sdbGetErrno() : SDB_SPT_EVAL_FAIL ; goto error ; } // clear return error if ( sdbIsNeedClearErrorInfo() && !JS_IsExceptionPending( _context ) ) { sdbClearErrorInfo() ; } done: PD_TRACE_EXITRC ( SDB_SCOPE_EVALUATE2, rc ); return rc ; error: if ( JS_IsExceptionPending( _context ) && JS_GetPendingException ( _context , &exception ) ) { cstrException = convertJsvalToString ( _context , exception ) ; if ( cstrException ) { if ( printFlag & SPT_EVAL_FLAG_PRINT ) { ossPrintf ( "Uncaught exception: %s\n" , cstrException ) ; } /// what to do when oom? *errMsg = ossStrdup( cstrException ) ; SAFE_JS_FREE ( _context , cstrException ) ; } else { JS_ClearPendingException ( _context ) ; } } goto done ; }
nsresult EvaluateAdminConfigScript(const char *js_buffer, size_t length, const char *filename, PRBool bGlobalContext, PRBool bCallbacks, PRBool skipFirstLine) { JSBool ok; jsval result; if (skipFirstLine) { /* In order to protect the privacy of the JavaScript preferences file * from loading by the browser, we make the first line unparseable * by JavaScript. We must skip that line here before executing * the JavaScript code. */ unsigned int i = 0; while (i < length) { char c = js_buffer[i++]; if (c == '\r') { if (js_buffer[i] == '\n') i++; break; } if (c == '\n') break; } length -= i; js_buffer += i; } nsresult rv; nsCOMPtr<nsIJSContextStack> cxstack = do_GetService("@mozilla.org/js/xpc/ContextStack;1"); rv = cxstack->Push(autoconfig_cx); if (NS_FAILED(rv)) { NS_ERROR("coudn't push the context on the stack"); return rv; } JS_BeginRequest(autoconfig_cx); ok = JS_EvaluateScript(autoconfig_cx, autoconfig_glob, js_buffer, length, filename, 0, &result); JS_EndRequest(autoconfig_cx); JS_MaybeGC(autoconfig_cx); JSContext *cx; cxstack->Pop(&cx); NS_ASSERTION(cx == autoconfig_cx, "AutoConfig JS contexts didn't match"); if (ok) return NS_OK; return NS_ERROR_FAILURE; }
static JSTrapStatus ThrowHook(JSContext *cx, JSScript *, jsbytecode *, jsval *rval, void *closure) { called = true; JSObject *global = JS_GetGlobalForScopeChain(cx); char text[] = "new Error()"; jsval _; JS_EvaluateScript(cx, global, text, strlen(text), "", 0, &_); return JSTRAP_CONTINUE; }
int JsParser::evaluate(JSContext *cx, JSObject *obj, const char *name, const char *buf, unsigned int len) { jsval res; unsigned int lineno; JSBool eval_res = JS_TRUE; func("JS evaluating script on object %p", __PRETTY_FUNCTION__, obj); eval_res = JS_EvaluateScript(cx, obj, buf, len, name, lineno, &res); // if anything more was wrong, our ErrorReporter was called! func("evaluation result: %i", eval_res); return(eval_res); // TODO: error message in script evaluation, with line number report }
// 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; }
static JSTrapStatus ThrowHook(JSContext *cx, JSScript *, jsbytecode *, jsval *rval, void *closure) { JS_ASSERT(!closure); called = true; JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx)); char text[] = "new Error()"; jsval _; JS_EvaluateScript(cx, global, text, strlen(text), "", 0, &_); return JSTRAP_CONTINUE; }
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; }
// filename, line and globalObject default to 0 (in which case we execute // the whole script / use our m_GlobalObject) void ScriptingHost::RunMemScript(const char* script, size_t size, const char* filename, int line, JSObject* globalObject) { if(!filename) filename = "unspecified file"; if(!globalObject) globalObject = m_GlobalObject; // Maybe TODO: support Unicode input formats? jsval rval; JSBool ok = JS_EvaluateScript(m_Context, globalObject, script, (uintN)size, filename, line, &rval); if (ok == JS_FALSE) throw PSERROR_Scripting_LoadFile_EvalErrors(); }
bool Engine::executeFile(FILE *file,JSContext *cx,JSObject *obj) { jsval rval; uintN lineno = 0; ContextPrivate *cxPrivate = (ContextPrivate*)JS_GetContextPrivate(cx); std::string script; if ( !parseFile(file,cxPrivate->getHttpRequest(),script) ) { throwParseError(cx); return false; } JSBool result = JS_EvaluateScript(cx,obj,script.c_str(),(uintN)script.length(), Util::UriUtil::getLastSegment(cxPrivate->getHttpRequest().getUri()).c_str(),1,&rval); return result==JS_TRUE; }
js::Function JSInterpreter::evaluateScript(std::string script){ jsval rval; JSBool ok; const char *filename = "noname"; uintN lineno = 0; ok = JS_EvaluateScript(cx, global, script.c_str(), script.length(), filename, lineno, &rval); if (rval == JSVAL_NULL || rval == JS_FALSE || ok == JS_FALSE){ throw * new std::runtime_error("Could not evaluate script"); } JSObject *obj; JS_ValueToObject(cx, rval, &obj); JSBool func = JS_ObjectIsFunction(cx, obj); //todo guard! return js::Function(obj); }
/** * shell_global_add_extension_importer: * @target_object_script: JavaScript code evaluating to a target object * @target_property: Name of property to use for importer * @directory: Source directory: * @error: A #GError * * This function sets a property named @target_property on the object * resulting from the evaluation of @target_object_script code, which * acts as a GJS importer for directory @directory. * * Returns: %TRUE on success */ gboolean shell_global_add_extension_importer (ShellGlobal *global, const char *target_object_script, const char *target_property, const char *directory, GError **error) { jsval target_object; JSObject *importer; JSContext *context = gjs_context_get_native_context (global->js_context); char *search_path[2] = { 0, 0 }; // This is a bit of a hack; ideally we'd be able to pass our target // object directly into this function, but introspection doesn't // support that at the moment. Instead evaluate a string to get it. if (!JS_EvaluateScript(context, JS_GetGlobalObject(context), target_object_script, strlen (target_object_script), "<target_object_script>", 0, &target_object)) { char *message; gjs_log_exception(context, &message); g_set_error(error, G_IO_ERROR, G_IO_ERROR_FAILED, "%s", message ? message : "(unknown)"); g_free(message); return FALSE; } if (!JSVAL_IS_OBJECT (target_object)) { g_error ("shell_global_add_extension_importer: invalid target object"); return FALSE; } search_path[0] = (char*)directory; importer = gjs_define_importer (context, JSVAL_TO_OBJECT (target_object), target_property, (const char **)search_path, FALSE); return TRUE; }
int run(JSContext * cx) { /* Enter a request before running anything in the context */ JSAutoRequest ar(cx); /* Create the global object in a new compartment. */ JSObject *global = JS_NewGlobalObject(cx, &global_class, nullptr); if (!global) return 3; /* 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. */ if (!JS_InitStandardClasses(cx, global)) return 4; /* Your application code here. This may include JSAPI calls to create your own custom JS objects and run scripts. */ js::RootedValue rval(cx); int rc = JS_EvaluateScript(cx, global, runCommand, strlen(runCommand), "TestCommand", 0, rval.address()); if (!rc) return 5; if (!JSVAL_IS_STRING(rval)) return 0; /* Result of the command is a string, print it out. */ js::RootedString str(cx, JSVAL_TO_STRING(rval)); size_t encodedLength = JS_GetStringEncodingLength(cx, str); rc = 0; char *buffer = (char *)malloc(encodedLength + 1); buffer[encodedLength] = '\0'; size_t result = JS_EncodeStringToBuffer(cx, str, buffer, encodedLength); if (result == (size_t) - 1) rc = 6; else puts(buffer); free(buffer); return rc; }
static void _loadModuleDir(SG_context *pCtx, const SG_pathname *path, const char *modname, JSContext *cx, JSObject *glob) { SG_rbtree * pJavascriptFiles = NULL; SG_rbtree_iterator * pJavascriptFile = NULL; const char *szJavascriptFile = NULL; SG_pathname *pJavascriptFilePath = NULL; SG_bool ok = SG_FALSE; SG_bool valid = SG_FALSE; char *psz_js = NULL; // free SG_uint32 len_js = 0; jsval rval = JSVAL_VOID; SG_ERR_CHECK( SG_dir__list(pCtx, path, NULL, NULL, ".js", &pJavascriptFiles) ); SG_ERR_CHECK( SG_rbtree__iterator__first(pCtx, &pJavascriptFile, pJavascriptFiles, &ok, &szJavascriptFile, NULL) ); SG_ERR_CHECK( SG_PATHNAME__ALLOC__COPY(pCtx, &pJavascriptFilePath, path) ); while(ok) { SG_ERR_CHECK( _isValidJsFile(pCtx, szJavascriptFile, &valid) ); if (valid) { SG_ERR_CHECK( SG_pathname__append__from_sz(pCtx, pJavascriptFilePath, szJavascriptFile) ); SG_ERR_CHECK( sg_read_entire_file(pCtx, pJavascriptFilePath, &psz_js, &len_js) ); if(!JS_EvaluateScript(cx, glob, psz_js, len_js, szJavascriptFile, 1, &rval)) { SG_ERR_CHECK_CURRENT; SG_ERR_THROW2(SG_ERR_JS, (pCtx, "An error occurred loading %s javascript file '%s'", modname, szJavascriptFile)); } SG_NULLFREE(pCtx, psz_js); SG_ERR_CHECK( SG_pathname__remove_last(pCtx, pJavascriptFilePath) ); } SG_ERR_CHECK( SG_rbtree__iterator__next(pCtx, pJavascriptFile, &ok, &szJavascriptFile, NULL) ); } fail: SG_PATHNAME_NULLFREE(pCtx, pJavascriptFilePath); SG_RBTREE_ITERATOR_NULLFREE(pCtx, pJavascriptFile); SG_RBTREE_NULLFREE(pCtx, pJavascriptFiles); SG_NULLFREE(pCtx, psz_js); }
string EvaluateScript(const string& script) { /* Your application code here. This may include JSAPI calls to create your own custom JS objects and run scripts. */ //char *script = "var o = {\"first_name\": \"matt\", \"last_name\":\"Jennings\", \"company\": \"walmart\"}; function getString(o){ if ( 'company' in o ) return o.company; else return o.first_name + \" \" + o.last_name; } getString(o);"; jsval rval; JSString *str; JSBool ok; const char *filename = "noname"; unsigned int lineno = 0; ok = JS_EvaluateScript(cx, global, script.c_str(), strlen(script.c_str()), filename, lineno, &rval); // if (rval == NULL | rval == JS_FALSE) // return 1; str = JS_ValueToString(cx, rval); return string(JS_EncodeString(cx, str)); }
JSBool XML_Init(JSContext *cx, JSObject *obj) { jsval rval; JSObject *proto; if (!JS_EvaluateScript(cx, JS_GetGlobalObject(cx), xmljs_newObj_str, xmljs_newObj_size, "XMLJS internal", 0, &rval)) return JS_FALSE; proto = JSVAL_TO_OBJECT(rval); if (!JS_DefineFunction(cx, proto, "parse", xmljs_parse, 1, 0) || !JS_DefineFunction(cx, proto, "parseFile", xmljs_parseFile, 1, 0)) return JS_FALSE; return XMLParser_Init(cx, obj, proto) && XMLGraph_Init(cx, obj, proto); }
JSBool ScriptingCore::evalString(const char *string, jsval *outVal, const char *filename) { jsval rval; const char *fname = (filename ? filename : "noname"); uint32_t lineno = 1; if (outVal == NULL) { outVal = &rval; } JSBool evaluatedOK = JS_EvaluateScript(cx, global, string, strlen(string), fname, lineno, outVal); if (JS_FALSE == evaluatedOK) { LOGD("(evaluatedOK == JS_FALSE)"); } else { this->string_report(*outVal); } return evaluatedOK; }
static int smjs_do_file(unsigned char *path) { int ret = 1; jsval rval; struct string script; if (!init_string(&script)) return 0; if (!add_file_to_string(&script, path) || JS_FALSE == JS_EvaluateScript(smjs_ctx, JS_GetGlobalObject(smjs_ctx), script.source, script.length, path, 1, &rval)) { alert_smjs_error("error loading script file"); ret = 0; } done_string(&script); return ret; }
jsman::jsman(BMessage *info) :BHandler("javascript_manager"),PlugClass(info) { js_enabled=false; script_head=NULL; JSSettings->FindBool("js_enabled",&js_enabled); uses_heartbeat=true; rt=JS_NewRuntime(8L*1024L*1024L); version = JSVERSION_DEFAULT; if (!rt) { printf("Javascript initialiation failed.\n"); return; } cx=JS_NewContext(rt,8192); if (cx==NULL) { printf("Unable to create Javascript context.\n"); return; } glob=JS_NewObject(cx,&globalClass,NULL,NULL); builtins=JS_InitStandardClasses(cx,glob); printf("JSMan: end of constructor. rt= %p\n",rt); printf("Javascript Implementation Version: %s\n",JS_GetImplementationVersion()); printf("performing simple Javascript test\n"); //! A very simple Javascript example. char *script="var today=Date();today.toString();\0"; jsval rval; uintN lineno=0; JSBool ok=JS_EvaluateScript(cx,glob,script,strlen(script),"script",lineno,&rval); if (ok==JS_TRUE) { JSString *str=JS_ValueToString(cx,rval); printf("Script executed properly: %s\n",JS_GetStringBytes(str)); } else { printf("Script failed.\n"); } }
bool RenderTargetConstructor( JSContext *cx, unsigned argc, jsval *vp ) { //printf( "RenderTarget Constructor!%d\n", argc ); JS::CallArgs args = JS::CallArgsFromVp( argc, vp ); JSObject *object = JS_NewObjectForConstructor( cx, &RenderTargetClass, args ); RootedObject obj(cx, object ); RootedValue v(cx, JS::UndefinedValue() ); JS_DefineFunctions( cx, HandleObject(obj), rendertarget_functions ); JS_DefineProperty( cx, HandleObject(obj), "w", HandleValue(&v), JSPROP_SHARED, (JSPropertyOp) GetRenderTargetProperty, (JSStrictPropertyOp) SetRenderTargetProperty ); JS_DefineProperty( cx, HandleObject(obj), "h", HandleValue(&v), JSPROP_SHARED, (JSPropertyOp) GetRenderTargetProperty, (JSStrictPropertyOp) SetRenderTargetProperty ); JS_DefineProperty( cx, HandleObject(obj), "autoResize", HandleValue(&v), JSPROP_SHARED, (JSPropertyOp) GetRenderTargetProperty, (JSStrictPropertyOp) SetRenderTargetProperty ); JS_DefineProperty( cx, HandleObject(obj), "main", HandleValue(&v), JSPROP_SHARED, (JSPropertyOp) GetRenderTargetProperty, (JSStrictPropertyOp) SetRenderTargetProperty ); GLint w=0; GLint h=0; bool main=false; if ( argc >= 1 ) w=args[0].toInt32(); if ( argc >= 2 ) h=args[1].toInt32(); if ( argc >= 3 ) main=args[2].toBoolean(); RenderTarget *target = new RenderTarget( w, h, main ); JS_SetPrivate( object, target ); args.rval().set( OBJECT_TO_JSVAL( object ) ); //VG.Renderer().addResource(this); RootedValue rendererRC(cx); RootedObject global( cx,JS_GetGlobalForObject( cx, object ) ); bool ok = JS_EvaluateScript( cx, HandleObject( global ), "VG.Renderer()", strlen("VG.Renderer()"), "unknown", 1, MutableHandleValue(&rendererRC) ); if ( ok ) { RootedValue objectValue( cx, OBJECT_TO_JSVAL(object) ); RootedObject renderer(cx, &rendererRC.toObject() ); MutableHandleValue handleValue( &rendererRC ); ok=Call( cx, HandleObject(renderer), "addResource", HandleValueArray( objectValue ), handleValue ); } return true; }
void test_spider_monkey() { JSRuntime *rt; JSContext *cx; JSObject *global; JSClass global_class = { "global",0, JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub, JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub }; /* * You always need: * a runtime per process, * a context per thread, * a global object per context, * standard classes (e.g. Date). */ rt = JS_NewRuntime(0x100000); cx = JS_NewContext(rt, 0x1000); global = JS_NewObject(cx, &global_class, NULL, NULL); JS_InitStandardClasses(cx, global); /* * Now suppose script contains some JS to evaluate, say "22/7" as a * bad approximation for Math.PI, or something longer, such as this: * "(function fact(n){if (n <= 1) return 1; return n * fact(n-1)})(5)" * to compute 5! */ char *script = "..."; jsval rval; JSString *str; JSBool ok; ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, &rval); str = JS_ValueToString(cx, rval); printf("script result: %s\n", JS_GetStringBytes(str)); }
int moduleLoadJS(JSContext *cx, char *moduleName){ char *fName = NULL; fName = (char*)malloc(sizeof (MODULES_DIR) + sizeof(moduleName) + sizeof(JSCRIPT_EXT) + 1); if(fName){ strcpy(fName,MODULES_DIR); strcat(fName,moduleName); strcat(fName,JSCRIPT_EXT); jsval vl; char *script = fileToString(fName); if(script){ if(JS_EvaluateScript(cx, JS_GetGlobalObject(cx), script, strlen(script), fName, 0, &vl) == JS_FALSE) fprint(stderr,"Error evaluating script %s\n",fName); } else { fprint(stderr,"Couldn't read script: %s\n",fName); } free(fName); free(script); return 1; } fprint(stderr,"Error loading Module %s\n",moduleName); return FALSE; }