/** * The function used as ZOOTranslate from the JavaScript environment. * Use the ZOO-Services messages translation function from the Python * environment (ZOO-API) * * @param cx the JavaScript context * @param argc the number of parameters * @param argv1 the parameter values * @return true */ JSBool JSTranslate(JSContext *cx, uintN argc, jsval *argv1) { jsval *argv = JS_ARGV(cx,argv1); char *str=JSValToChar(cx,&argv[0]); char *tmpValue=_ss(str); JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue)))); JS_MaybeGC(cx); return JS_TRUE; }
static JSBool AfxGlobal_maybeGc(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallReceiver rec = JS::CallReceiverFromVp(vp); JS_MaybeGC(cx); rec.rval().set(JSVAL_VOID); return JS_TRUE; }
void *GCThread::WrokFunc(void *args) { while (!isStop) { JSContext *context = static_cast<JSContext *> (args); if (context == NULL) { LogInfo("GCThread", "context is empty!!!!!!!!"); } JS_MaybeGC(context); sleep(1); } return NULL; }
char *sm_eval(jaegermonkey_vm *vm, const char *filename, const char *code, int handle_retval) { char *retval = NULL; JSScript *script; jsval result; begin_request(vm); script = JS_CompileScript(vm->context, vm->global, code, strlen(code), filename, 1); jaegermonkey_error *error = (jaegermonkey_error *) JS_GetContextPrivate(vm->context); if (error == NULL) { JS_ClearPendingException(vm->context); JS_ExecuteScript(vm->context, vm->global, script, &result); vm->invoke_count++; error = (jaegermonkey_error *) JS_GetContextPrivate(vm->context); if (error == NULL) { if (handle_retval) { if (JSVAL_IS_STRING(result)) { JSString *str = JS_ValueToString(vm->context, result); retval = copy_jsstring(str); } else if(strcmp(JS_GetStringBytes(JS_ValueToString(vm->context, result)), "undefined") == 0) { retval = copy_string("{\"error\": \"Expression returned undefined\", \"lineno\": 0, \"source\": \"unknown\"}"); } else { retval = copy_string("{\"error\": \"non-JSON return value\", \"lineno\": 0, \"source\": \"unknown\"}"); } } JS_DestroyScript(vm->context, script); } else { retval = error_to_json(error); free_error(error); JS_SetContextPrivate(vm->context, NULL); } } else { retval = error_to_json(error); free_error(error); JS_SetContextPrivate(vm->context, NULL); } if (vm->invoke_count > 200) { JS_GC(vm->context); vm->invoke_count = 0; } else { JS_MaybeGC(vm->context); } end_request(vm); return retval; }
/** * The function used as importScript from the JavaScript environment (ZOO-API) * * @param cx the JavaScript context * @param argc the number of parameters * @param argv1 the parameter values * @return true */ JSBool JSLoadScripts(JSContext *cx, uintN argc, jsval *argv1) { JS_MaybeGC(cx); jsval *argv = JS_ARGV(cx,argv1); int i=0; JS_MaybeGC(cx); for(i=0;i<argc;i++){ char *filename = JSValToChar(cx,&argv[i]); #ifdef JS_DEBUG fprintf(stderr,"Trying to load %s\n",api0); fflush(stderr); #endif JSObject *api_script1=loadZooApiFile(cx,JS_GetGlobalObject(cx),filename); } JS_MaybeGC(cx); JS_SET_RVAL(cx, argv1, JSVAL_VOID); return JS_TRUE; }
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 JSBool readline(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval) { JSString* line; /* GC Occasionally */ JS_MaybeGC(cx); line = couch_readline(cx, stdin); if(line == NULL) return JS_FALSE; *rval = STRING_TO_JSVAL(line); return JS_TRUE; }
static JSBool readline(JSContext* cx, uintN argc, jsval* vp) { JSString* line; /* GC Occasionally */ JS_MaybeGC(cx); line = couch_readline(cx, stdin); if(line == NULL) return JS_FALSE; JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(line)); return JS_TRUE; }
AutoEntryScript::~AutoEntryScript() { if (mDocShellForJSRunToCompletion) { mDocShellForJSRunToCompletion->NotifyJSRunToCompletionStop(); } if (mIsMainThread) { nsContentUtils::LeaveMicroTask(); } // GC when we pop a script entry point. This is a useful heuristic that helps // us out on certain (flawed) benchmarks like sunspider, because it lets us // avoid GCing during the timing loop. JS_MaybeGC(cx()); }
void SG_jscontext__release(SG_context * pCtx, SG_jscontext ** ppJs) { if(ppJs==NULL || *ppJs==NULL) return; if(gpJSContextPoolGlobalState->ssjsMutable) { SG_httprequestprofiler__start(SG_HTTPREQUESTPROFILER_CATEGORY__JSREQUEST_TOGGLING); JS_EndRequest((*ppJs)->cx); JS_DestroyContext((*ppJs)->cx); SG_httprequestprofiler__stop(); if(SG_context__has_err(pCtx)) // An error was produced during GC... { SG_log__report_error__current_error(pCtx); SG_context__err_reset(pCtx); } SG_NULLFREE(pCtx, (*ppJs)); } else { SG_jscontext * pJs = *ppJs; JS_MaybeGC(pJs->cx); JS_SetContextPrivate(pJs->cx, NULL); // Clear out the old pCtx pointer. SG_httprequestprofiler__start(SG_HTTPREQUESTPROFILER_CATEGORY__JSREQUEST_TOGGLING); JS_EndRequest(pJs->cx); pJs->isInARequest = SG_FALSE; (void)JS_ClearContextThread(pJs->cx); SG_httprequestprofiler__stop(); SG_ERR_CHECK_RETURN( SG_mutex__lock(pCtx, &gpJSContextPoolGlobalState->lock) ); pJs->pNextAvailableContext = gpJSContextPoolGlobalState->pFirstAvailableContext; gpJSContextPoolGlobalState->pFirstAvailableContext = pJs; --gpJSContextPoolGlobalState->numContextsCheckedOut; SG_ERR_CHECK_RETURN( SG_mutex__unlock(pCtx, &gpJSContextPoolGlobalState->lock) ); *ppJs = NULL; } }
PyObject* Context_rem_global(Context* self, PyObject* args, PyObject* kwargs) { PyObject* pykey = NULL; PyObject* ret = NULL; jsval jsk; jsid kid; jsval jsv; JS_BeginRequest(self->cx); if(!PyArg_ParseTuple(args, "O", &pykey)) goto error; jsk = py2js(self, pykey); if(jsk == JSVAL_VOID) goto error; if(!JS_ValueToId(self->cx, jsk, &kid)) { PyErr_SetString(JSError, "Failed to create key id."); } if(!js_GetProperty(self->cx, self->root, kid, &jsv)) { PyErr_SetString(JSError, "Failed to get global property."); goto error; } ret = js2py(self, jsv); if(ret == NULL) goto error; if(!js_DeleteProperty(self->cx, self->root, kid, &jsv)) { PyErr_SetString(JSError, "Failed to remove global property."); goto error; } JS_MaybeGC(self->cx); goto success; error: success: JS_EndRequest(self->cx); return ret; }
JSBool on_branch(JSContext *context) { JSBool return_value = JS_TRUE; spidermonkey_state *state = (spidermonkey_state *) JS_GetContextPrivate(context); state->branch_count++; if (state->terminate) { return_value = JS_FALSE; } else if (state->branch_count == 550) { JS_GC(context); state->branch_count = 0; } else if(state->branch_count % 100 == 0) { JS_MaybeGC(context); } return return_value; }
bool MozJSImplScope::_interruptCallback(JSContext* cx) { auto scope = getScope(cx); if (scope->_pendingGC.load()) { scope->_pendingGC.store(false); JS_GC(scope->_runtime); } else { JS_MaybeGC(cx); } bool kill = scope->isKillPending(); if (kill) { scope->_engine->getDeadlineMonitor().stopDeadline(scope); scope->unregisterOperation(); } return !kill; }
/** Garbage Collector method for Javascript. * One optional argument, boolean, whether or not to force the garbage collection. */ static JSBool vm_gc(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { JSBool b; if (argc == 0) { JS_GC(cx); } else { if (JS_ValueToBoolean(cx, argv[0], &b) == JS_FALSE) return JS_FALSE; if (b) JS_GC(cx); else JS_MaybeGC(cx); } return JS_TRUE; }
static JSBool js_gc(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { JSBool forced=JS_TRUE; js_branch_t* branch; if((branch=(js_branch_t*)JS_GetPrivate(cx,obj))==NULL) return(JS_FALSE); if(argc) JS_ValueToBoolean(cx,argv[0],&forced); if(forced) JS_GC(cx); else JS_MaybeGC(cx); branch->gc_attempts++; return(JS_TRUE); }
JSBool DLLCALL js_CommonOperationCallback(JSContext *cx, js_callback_t* cb) { cb->counter++; /* Terminated? */ if(cb->auto_terminate && (cb->terminated!=NULL && *cb->terminated)) { JS_ReportWarning(cx,"Terminated"); cb->counter=0; return(JS_FALSE); } /* Infinite loop? */ if(cb->limit && cb->counter > cb->limit) { JS_ReportError(cx,"Infinite loop (%lu operation callbacks) detected",cb->counter); cb->counter=0; return(JS_FALSE); } /* Give up timeslices every once in a while */ if(cb->yield_interval && (cb->counter%cb->yield_interval)==0) { jsrefcount rc; rc=JS_SUSPENDREQUEST(cx); YIELD(); JS_RESUMEREQUEST(cx, rc); } /* Permit other contexts to run GC */ JS_YieldRequest(cx); /* Periodic Garbage Collection */ if(cb->gc_interval && (cb->counter%cb->gc_interval)==0) JS_MaybeGC(cx), cb->gc_attempts++; return(JS_TRUE); }
bool MozJSImplScope::_interruptCallback(JSContext* cx) { auto scope = getScope(cx); JS_SetInterruptCallback(scope->_runtime, nullptr); auto guard = MakeGuard([&]() { JS_SetInterruptCallback(scope->_runtime, _interruptCallback); }); if (scope->_pendingGC.load()) { scope->_pendingGC.store(false); JS_GC(scope->_runtime); } else { JS_MaybeGC(cx); } bool kill = scope->isKillPending(); if (kill) { scope->_engine->getDeadlineMonitor().stopDeadline(scope); scope->unregisterOperation(); scope->_status = Status(ErrorCodes::JSInterpreterFailure, "Interrupted by the host"); } return !kill; }
void js_DestroyContext(JSContext *cx, JSGCMode gcmode) { JSRuntime *rt; JSBool last; JSArgumentFormatMap *map; rt = cx->runtime; /* Remove cx from context list first. */ JS_LOCK_RUNTIME(rt); JS_ASSERT(rt->state == JSRTS_UP || rt->state == JSRTS_LAUNCHING); JS_REMOVE_LINK(&cx->links); last = (rt->contextList.next == &rt->contextList); if (last) rt->state = JSRTS_LANDING; JS_UNLOCK_RUNTIME(rt); if (last) { /* Unpin all pinned atoms before final GC. */ js_UnpinPinnedAtoms(&rt->atomState); /* Unlock and clear GC things held by runtime pointers. */ js_FinishRuntimeNumberState(cx); js_FinishRuntimeStringState(cx); /* Clear debugging state to remove GC roots. */ JS_ClearAllTraps(cx); JS_ClearAllWatchPoints(cx); } #if JS_HAS_REGEXPS /* * Remove more GC roots in regExpStatics, then collect garbage. * XXX anti-modularity alert: we rely on the call to js_RemoveRoot within * XXX this function call to wait for any racing GC to complete, in the * XXX case where JS_DestroyContext is called outside of a request on cx */ js_FreeRegExpStatics(cx, &cx->regExpStatics); #endif #ifdef JS_THREADSAFE /* * Destroying a context implicitly calls JS_EndRequest(). Also, we must * end our request here in case we are "last" -- in that event, another * js_DestroyContext that was not last might be waiting in the GC for our * request to end. We'll let it run below, just before we do the truly * final GC and then free atom state. * * At this point, cx must be inaccessible to other threads. It's off the * rt->contextList, and it should not be reachable via any object private * data structure. */ while (cx->requestDepth != 0) JS_EndRequest(cx); #endif if (last) { /* Always force, so we wait for any racing GC to finish. */ js_ForceGC(cx); /* Iterate until no finalizer removes a GC root or lock. */ while (rt->gcPoke) js_GC(cx, GC_LAST_CONTEXT); /* Try to free atom state, now that no unrooted scripts survive. */ if (rt->atomState.liveAtoms == 0) js_FreeAtomState(cx, &rt->atomState); /* Take the runtime down, now that it has no contexts or atoms. */ JS_LOCK_RUNTIME(rt); rt->state = JSRTS_DOWN; JS_NOTIFY_ALL_CONDVAR(rt->stateChange); JS_UNLOCK_RUNTIME(rt); } else { if (gcmode == JS_FORCE_GC) js_ForceGC(cx); else if (gcmode == JS_MAYBE_GC) JS_MaybeGC(cx); } /* Free the stuff hanging off of cx. */ JS_FinishArenaPool(&cx->stackPool); JS_FinishArenaPool(&cx->codePool); JS_FinishArenaPool(&cx->notePool); JS_FinishArenaPool(&cx->tempPool); if (cx->lastMessage) free(cx->lastMessage); /* Remove any argument formatters. */ map = cx->argumentFormatMap; while (map) { JSArgumentFormatMap *temp = map; map = map->next; JS_free(cx, temp); } /* Destroy the resolve recursion damper. */ if (cx->resolvingTable) { JS_DHashTableDestroy(cx->resolvingTable); cx->resolvingTable = NULL; } /* Finally, free cx itself. */ free(cx); }
PyObject* Context_execute(Context* self, PyObject* args, PyObject* kwargs) { PyObject* obj = NULL; PyObject* ret = NULL; JSContext* cx = NULL; JSObject* root = NULL; JSString* script = NULL; jschar* schars = NULL; JSBool started_counter = JS_FALSE; char *fname = "<anonymous JavaScript>"; unsigned int lineno = 1; size_t slen; jsval rval; char *keywords[] = {"code", "filename", "lineno", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwargs, "O|sI", keywords, &obj, &fname, &lineno)) goto error; JS_BeginRequest(self->cx); script = py2js_string_obj(self, obj); if(script == NULL) goto error; schars = JS_GetStringChars(script); slen = JS_GetStringLength(script); cx = self->cx; root = self->root; // Mark us for time consumption if(self->start_time == 0) { started_counter = JS_TRUE; self->start_time = time(NULL); } if(!JS_EvaluateUCScript(cx, root, schars, slen, fname, lineno, &rval)) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "Script execution failed and no exception was set"); } goto error; } if(PyErr_Occurred()) goto error; ret = js2py(self, rval); JS_EndRequest(self->cx); JS_MaybeGC(self->cx); goto success; error: JS_EndRequest(self->cx); success: if(started_counter) { self->start_time = 0; } return ret; }
/** * The function used as ZOORequest from the JavaScript environment (ZOO-API) * * @param cx the JavaScript context * @param argc the number of parameters * @param argv1 the parameter values * @return true * @see setHeader */ JSBool JSRequest(JSContext *cx, uintN argc, jsval *argv1) { jsval *argv = JS_ARGV(cx,argv1); HINTERNET hInternet; JSObject *header; char *url; char *method; char* tmpValue; size_t dwRead; JS_MaybeGC(cx); hInternet=InternetOpen("ZooWPSClient\0", INTERNET_OPEN_TYPE_PRECONFIG, NULL,NULL, 0); if(!CHECK_INET_HANDLE(hInternet)) return JS_FALSE; if(argc>=2){ method=JSValToChar(cx,&argv[0]); url=JSValToChar(cx,&argv[1]); } else{ method=zStrdup("GET"); url=JSValToChar(cx,argv); } hInternet.waitingRequests[hInternet.nb]=strdup(url); if(argc==4){ char *body; body=JSValToChar(cx,&argv[2]); header=JSVAL_TO_OBJECT(argv[3]); #ifdef ULINET_DEBUG fprintf(stderr,"URL (%s) \nBODY (%s)\n",url,body); #endif if(JS_IsArrayObject(cx,header)) setHeader(&hInternet,cx,header); #ifdef ULINET_DEBUG fprintf(stderr,"BODY (%s)\n",body); #endif InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body), INTERNET_FLAG_NO_CACHE_WRITE,0); processDownloads(&hInternet); free(body); }else{ if(argc==3){ if(strncasecmp(method,"GET",3)==0){ header=JSVAL_TO_OBJECT(argv[2]); if(JS_IsArrayObject(cx,header)){ setHeader(&hInternet,cx,header); } InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0, INTERNET_FLAG_NO_CACHE_WRITE,0); processDownloads(&hInternet); }else{ char *body=JSValToChar(cx,&argv[2]); InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body), INTERNET_FLAG_NO_CACHE_WRITE,0); processDownloads(&hInternet); free(body); } }else{ InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0, INTERNET_FLAG_NO_CACHE_WRITE,0); processDownloads(&hInternet); } } tmpValue=(char*)malloc((hInternet.ihandle[0].nDataLen+1)*sizeof(char)); InternetReadFile(hInternet.ihandle[0],(LPVOID)tmpValue,hInternet.ihandle[0].nDataLen,&dwRead); #ifdef ULINET_DEBUG fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue); #endif if(dwRead==0){ JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,"Unable to access the file.",strlen("Unable to access the file.")))); return JS_TRUE; } #ifdef ULINET_DEBUG fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue); #endif JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue)))); free(url); if(argc>=2) free(method); InternetCloseHandle(&hInternet); JS_MaybeGC(cx); return JS_TRUE; }
void* vm_run(void* arg) { vm_ptr vm = (vm_ptr) arg; JSContext* cx; JSObject* gl; job_ptr job; ENTERM resp; int flags; cx = JS_NewContext(vm->runtime, vm->stack_size); if(cx == NULL) { fprintf(stderr, "Failed to create context.\n"); goto done; } JS_BeginRequest(cx); flags = 0; flags |= JSOPTION_VAROBJFIX; flags |= JSOPTION_STRICT; flags |= JSVERSION_LATEST; flags |= JSOPTION_COMPILE_N_GO; flags |= JSOPTION_XML; JS_SetOptions(cx, JS_GetOptions(cx) | flags); gl = JS_NewObject(cx, &global_class, NULL, NULL); if(gl == NULL) { fprintf(stderr, "Failed to create global object.\n"); goto done; } if(!JS_InitStandardClasses(cx, gl)) { fprintf(stderr, "Failed to initialize classes.\n"); goto done; } if(!install_jserl(cx, gl)) { fprintf(stderr, "Failed to install erlang object."); goto done; } JS_SetErrorReporter(cx, vm_report_error); JS_SetContextPrivate(cx, (void*) vm); JS_EndRequest(cx); while(1) { job = queue_pop(vm->jobs); if(job->type == job_close) { job_destroy(job); break; } JS_BeginRequest(cx); assert(vm->curr_job == NULL && "vm already has a job set."); vm->curr_job = job; if(job->type == job_eval) { resp = vm_eval(cx, gl, job); } else if(job->type == job_call) { resp = vm_call(cx, gl, job); } else { assert(0 && "Invalid job type."); } vm->curr_job = NULL; JS_EndRequest(cx); JS_MaybeGC(cx); // XXX: If pid is not alive, we just ignore it. enif_send(NULL, &(job->pid), job->env, resp); job_destroy(job); } done: JS_BeginRequest(cx); if(cx != NULL) JS_DestroyContext(cx); return NULL; }
void JsExecutionContext::gc() { JS_SetContextThread(cx); JS_MaybeGC(cx); JS_ClearContextThread(cx); }
/** * 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; }
void TS_Chrono_GC(void *ctx){ JS_MaybeGC(static_cast<JSContext *>(ctx)); }
void ScriptInterface::MaybeGC() { JS_MaybeGC(m->m_cx); }
void js_DestroyContext(JSContext *cx, JSDestroyContextMode mode) { JSRuntime *rt; JSContextCallback cxCallback; JSBool last; JSArgumentFormatMap *map; JSLocalRootStack *lrs; JSLocalRootChunk *lrc; rt = cx->runtime; if (mode != JSDCM_NEW_FAILED) { cxCallback = rt->cxCallback; if (cxCallback) { /* * JSCONTEXT_DESTROY callback is not allowed to fail and must * return true. */ #ifdef DEBUG JSBool callbackStatus = #endif cxCallback(cx, JSCONTEXT_DESTROY); JS_ASSERT(callbackStatus); } } /* Remove cx from context list first. */ JS_LOCK_GC(rt); JS_ASSERT(rt->state == JSRTS_UP || rt->state == JSRTS_LAUNCHING); JS_REMOVE_LINK(&cx->links); last = (rt->contextList.next == &rt->contextList); if (last) rt->state = JSRTS_LANDING; JS_UNLOCK_GC(rt); if (last) { #ifdef JS_THREADSAFE /* * If cx is not in a request already, begin one now so that we wait * for any racing GC started on a not-last context to finish, before * we plow ahead and unpin atoms. Note that even though we begin a * request here if necessary, we end all requests on cx below before * forcing a final GC. This lets any not-last context destruction * racing in another thread try to force or maybe run the GC, but by * that point, rt->state will not be JSRTS_UP, and that GC attempt * will return early. */ if (cx->requestDepth == 0) JS_BeginRequest(cx); #endif /* Unlock and clear GC things held by runtime pointers. */ js_FinishRuntimeNumberState(cx); js_FinishRuntimeStringState(cx); /* Unpin all common atoms before final GC. */ js_FinishCommonAtoms(cx); /* Clear debugging state to remove GC roots. */ JS_ClearAllTraps(cx); JS_ClearAllWatchPoints(cx); } /* * Remove more GC roots in regExpStatics, then collect garbage. * XXX anti-modularity alert: we rely on the call to js_RemoveRoot within * XXX this function call to wait for any racing GC to complete, in the * XXX case where JS_DestroyContext is called outside of a request on cx */ js_FreeRegExpStatics(cx, &cx->regExpStatics); #ifdef JS_THREADSAFE /* * Destroying a context implicitly calls JS_EndRequest(). Also, we must * end our request here in case we are "last" -- in that event, another * js_DestroyContext that was not last might be waiting in the GC for our * request to end. We'll let it run below, just before we do the truly * final GC and then free atom state. * * At this point, cx must be inaccessible to other threads. It's off the * rt->contextList, and it should not be reachable via any object private * data structure. */ while (cx->requestDepth != 0) JS_EndRequest(cx); #endif if (last) { js_GC(cx, GC_LAST_CONTEXT); /* * Free the script filename table if it exists and is empty. Do this * after the last GC to avoid finalizers tripping on free memory. */ if (rt->scriptFilenameTable && rt->scriptFilenameTable->nentries == 0) js_FinishRuntimeScriptState(rt); /* Take the runtime down, now that it has no contexts or atoms. */ JS_LOCK_GC(rt); rt->state = JSRTS_DOWN; JS_NOTIFY_ALL_CONDVAR(rt->stateChange); JS_UNLOCK_GC(rt); } else { if (mode == JSDCM_FORCE_GC) js_GC(cx, GC_NORMAL); else if (mode == JSDCM_MAYBE_GC) JS_MaybeGC(cx); } /* Free the stuff hanging off of cx. */ JS_FinishArenaPool(&cx->stackPool); JS_FinishArenaPool(&cx->tempPool); if (cx->lastMessage) free(cx->lastMessage); /* Remove any argument formatters. */ map = cx->argumentFormatMap; while (map) { JSArgumentFormatMap *temp = map; map = map->next; JS_free(cx, temp); } /* Destroy the resolve recursion damper. */ if (cx->resolvingTable) { JS_DHashTableDestroy(cx->resolvingTable); cx->resolvingTable = NULL; } lrs = cx->localRootStack; if (lrs) { while ((lrc = lrs->topChunk) != &lrs->firstChunk) { lrs->topChunk = lrc->down; JS_free(cx, lrc); } JS_free(cx, lrs); } #ifdef JS_THREADSAFE js_ClearContextThread(cx); #endif /* Finally, free cx itself. */ free(cx); }
PyObject* Function_call(Function* self, PyObject* args, PyObject* kwargs) { PyObject* item = NULL; PyObject* ret = NULL; Py_ssize_t argc; Py_ssize_t idx; JSContext* cx; JSObject* parent; jsval func; jsval* argv = NULL; jsval rval; JSBool started_counter = JS_FALSE; JS_BeginRequest(self->obj.cx->cx); argc = PySequence_Length(args); if(argc < 0) goto error; argv = malloc(sizeof(jsval) * argc); if(argv == NULL) { PyErr_NoMemory(); goto error; } for(idx = 0; idx < argc; idx++) { item = PySequence_GetItem(args, idx); if(item == NULL) goto error; argv[idx] = py2js(self->obj.cx, item); if(argv[idx] == JSVAL_VOID) goto error; Py_DECREF(item); item = NULL; // Prevent double decref. } func = self->obj.val; cx = self->obj.cx->cx; parent = JSVAL_TO_OBJECT(self->parent); // Mark us for execution time if not already marked if(self->obj.cx->start_time == 0) { started_counter = JS_TRUE; self->obj.cx->start_time = time(NULL); } if(!JS_CallFunctionValue(cx, parent, func, argc, argv, &rval)) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "JavaScript Function failed to execute"); } goto error; } ret = js2py(self->obj.cx, rval); JS_EndRequest(self->obj.cx->cx); JS_MaybeGC(cx); goto success; error: if(argv != NULL) free(argv); JS_EndRequest(self->obj.cx->cx); success: // Reset the time counter if we started it. if(started_counter) { self->obj.cx->start_time = 0; } Py_XDECREF(item); return ret; }
static JSBool gpsee_maybeGC(JSContext *cx, void *ignored, GPSEEAsyncCallback *cb) { JS_MaybeGC(cx); return JS_TRUE; }
/* Converts perl values to equivalent JS values */ JSBool PJS_ReflectPerl2JS( pTHX_ JSContext *cx, JSObject *pobj, SV *ref, jsval *rval ) { PJS_Context *pcx = PJS_GET_CONTEXT(cx); JSObject *newobj = NULL; if(++pcx->svconv % 2000 == 0) { JSErrorReporter older; ENTER; SAVETMPS; /* Scope for finalizers */ older = JS_SetErrorReporter(cx, NULL); if(pcx->svconv > 10000) { JS_GC(cx); pcx->svconv = 0; } else JS_MaybeGC(cx); JS_SetErrorReporter(cx, older); FREETMPS; LEAVE; } if(SvROK(ref)) { MAGIC *mg; /* First check old jsvisitors */ if((newobj = PJS_IsPerlVisitor(aTHX_ pcx, SvRV(ref)))) { PJS_DEBUG("Old jsvisitor returns\n"); *rval = OBJECT_TO_JSVAL(newobj); return JS_TRUE; } if(SvMAGICAL(SvRV(ref)) && (mg = mg_find(SvRV(ref), PERL_MAGIC_tied)) && mg->mg_obj && sv_derived_from(mg->mg_obj, PJS_BOXED_PACKAGE)) { PJS_DEBUG1("A magical ref %s, shortcircuit!\n", SvPV_nolen((SV*)mg->mg_obj)); ref = mg->mg_obj; } if(sv_derived_from(ref, PJS_BOXED_PACKAGE)) { SV **fref = av_fetch((AV *)SvRV(SvRV(ref)), 2, 0); assert(sv_derived_from(*fref, PJS_RAW_JSVAL)); *rval = (jsval)SvIV(SvRV(*fref)); return JS_TRUE; } if(sv_derived_from(ref, PJS_BOOLEAN)) { *rval = SvTRUE(SvRV(ref)) ? JSVAL_TRUE : JSVAL_FALSE; return JS_TRUE; } if(sv_isobject(ref)) { newobj = PJS_NewPerlObject(aTHX_ cx, pobj, ref); if(newobj) { *rval = OBJECT_TO_JSVAL(newobj); return JS_TRUE; } return JS_FALSE; } } SvGETMAGIC(ref); if(!SvOK(ref)) /* undef */ *rval = JSVAL_VOID; else if(SvIOK(ref) || SvIOKp(ref)) { if(SvIV(ref) <= JSVAL_INT_MAX) *rval = INT_TO_JSVAL(SvIV(ref)); else JS_NewDoubleValue(cx, (double) SvIV(ref), rval); } else if(SvNOK(ref)) JS_NewDoubleValue(cx, SvNV(ref), rval); else if(SvPOK(ref) || SvPOKp(ref)) { STRLEN len; char *str; SV *temp=NULL; if(SvREADONLY(ref)) { temp = newSVsv(ref); str = PJS_SvPV(temp, len); } else str = PJS_SvPV(ref, len); JSString *jstr = ((int)len >= 0) ? JS_NewStringCopyN(cx, str, len) : JS_NewUCStringCopyN(cx, (jschar *)str, -(int)len); sv_free(temp); if(!jstr) return JS_FALSE; *rval = STRING_TO_JSVAL(jstr); } else if(SvROK(ref)) { /* Plain reference */ I32 type = SvTYPE(SvRV(ref)); if(type == SVt_PVHV) newobj = PJS_NewPerlHash(aTHX_ cx, pobj, ref); else if(type == SVt_PVAV) newobj = PJS_NewPerlArray(aTHX_ cx, pobj, ref); else if(type == SVt_PVCV) newobj = PJS_NewPerlSub(aTHX_ cx, pobj, ref); else newobj = PJS_NewPerlScalar(aTHX_ cx, pobj, ref); if(!newobj) return JS_FALSE; *rval = OBJECT_TO_JSVAL(newobj); } else { warn("I have no idea what perl send us (it's of type %i), I'll pretend it's undef", SvTYPE(ref)); *rval = JSVAL_VOID; } return JS_TRUE; }