~SafeCallGuard() {
   if (cx) {
     JS_SetOptions(cx, options);
     JS_RestoreFrameChain(cx, fp);
     js_RestoreRegExpStatics(cx, &statics, &tvr, &tvr2);
     nsIScriptSecurityManager_1_9_2 *ssm = XPCWrapper::GetSecurityManager();
     if (ssm) {
       ssm->PopContextPrincipal(cx);
     }
   }
 }
jaegermonkey_vm *sm_initialize(long thread_stack, long heap_size) {
  jaegermonkey_vm *vm = (jaegermonkey_vm*) driver_alloc(sizeof(jaegermonkey_vm));
  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_NewGlobalObject(vm->context, &global_class);
  JS_InitStandardClasses(vm->context, vm->global);
  JS_SetErrorReporter(vm->context, on_error);
  JS_DefineFunction(vm->context, JS_GetGlobalObject(vm->context), "ejsLog", js_log, 2, 0);
  end_request(vm);
  vm->invoke_count = 0;
  return vm;
}
nsresult
nsInProcessTabChildGlobal::InitTabChildGlobal()
{
  nsCOMPtr<nsIJSRuntimeService> runtimeSvc = 
    do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
  NS_ENSURE_STATE(runtimeSvc);

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

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

  mCx = cx;

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

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

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

  xpc_LocalizeContext(cx);

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

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

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

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

  JS_SetGlobalObject(cx, global);
  DidCreateCx();
  return NS_OK;
}
Esempio n. 4
0
/* XXX FIXME: Iargv/Ienviron are now associated with running. */
rpmjs rpmjsNew(char ** av, uint32_t flags)
{
    rpmjs js =
#ifdef	NOTYET
	(flags & 0x80000000) ? rpmjsI() :
#endif
	rpmjsGetPool(_rpmjsPool);
    JSI_t I = NULL;

#if defined(WITH_GPSEE)

#if defined(XXX_GPSEE_DEBUGGER)	/* XXX js->jsdc? */
    JSDContext *jsdc;
#endif

    if (flags == 0)
	flags = _rpmjs_options;

    if (F_ISSET(flags, NOUTF8) || getenv("GPSEE_NO_UTF8_C_STRINGS")) {
	JS_DestroyRuntime(JS_NewRuntime(1024));
	putenv((char *) "GPSEE_NO_UTF8_C_STRINGS=1");
    }

    /* XXX FIXME: js->Iargv/js->Ienviron for use by rpmjsRunFile() */
    I = gpsee_createInterpreter();
#if defined(XXX_GPSEE_DEBUGGER)
    js->jsdc = gpsee_initDebugger(I->cx, I->realm, DEBUGGER_JS);
#endif

#ifdef	NOTYET	/* FIXME: dig out where NOCACHE has moved. */
    if (F_ISSET(flags, NOCACHE))
	I->useCompilerCache = 0;
#endif
    if (F_ISSET(flags, NOWARN)) {
	gpsee_runtime_t * grt = JS_GetRuntimePrivate(JS_GetRuntime(I->cx));
	grt->errorReport |= er_noWarnings;
    }

    JS_SetOptions(I->cx, (flags & 0xffff));
#if defined(JS_GC_ZEAL)
    JS_SetGCZeal(I->cx, _rpmjs_zeal);
#endif
#endif	/* WITH_GPSEE */

    js->flags = flags;
    js->I = I;

    return rpmjsLink(js);
}
nsresult
nsDOMWorkerScriptLoader::ExecuteScripts(JSContext* aCx)
{
  NS_ASSERTION(aCx, "Shouldn't be null!");

  // Now execute all the scripts.
  for (PRUint32 index = 0; index < mScriptCount; index++) {
    ScriptLoadInfo& loadInfo = mLoadInfos[index];

    JSAutoRequest ar(aCx);

    JSScript* script =
      static_cast<JSScript*>(JS_GetPrivate(aCx, loadInfo.scriptObj.ToJSObject()));
    NS_ASSERTION(script, "This shouldn't ever be null!");

    JSObject* global = mWorker->mGlobal ?
                       mWorker->mGlobal :
                       JS_GetGlobalObject(aCx);
    NS_ENSURE_STATE(global);

    // Because we may have nested calls to this function we don't want the
    // execution to automatically report errors. We let them propagate instead.
    uint32 oldOpts =
      JS_SetOptions(aCx, JS_GetOptions(aCx) | JSOPTION_DONT_REPORT_UNCAUGHT);

    jsval val;
    PRBool success = JS_ExecuteScript(aCx, global, script, &val);

    JS_SetOptions(aCx, oldOpts);

    if (!success) {
      return NS_ERROR_FAILURE;
    }
  }
  return NS_OK;
}
Esempio n. 6
0
JSContext *
js_newctx(JSErrorReporter er)
{
  JSContext *cx = JS_NewContext(runtime, 8192);

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

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

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

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

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

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

  /* Create the global object here */
  //  JS_SetGlobalObject(global_context, global_object);
  //  this is done in init_class / JS_InitStandardClasses.
  obj = JS_NewObject(cx, &global_class, NULL, NULL);
  init_class();
  JS_EndRequest(cx);
  // deassociate this context from the creating thread
  // so that it can be used in other threads
  // https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_NewContext
  JS_ClearContextThread(cx);
  /** register SIGINT signal */
  //   signal(SIGINT, js_sigint_handler);
}
Esempio n. 8
0
File: flim.c Progetto: mrdg/flim
void initialize_js(struct flim *flim)
{
    flim->js_runtime = JS_NewRuntime(8L * 1024L * 1024L);
    flim->js_context = JS_NewContext(flim->js_runtime, 8192);
    JS_SetOptions(flim->js_context, JSOPTION_VAROBJFIX | JSOPTION_METHODJIT);
    JS_SetVersion(flim->js_context, JSVERSION_LATEST);
    JS_SetErrorReporter(flim->js_context, report_error);

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

    eval_file("runtime/flim.js");
    eval_file("runtime/underscore.js");
}
Esempio n. 9
0
File: lwjs.c Progetto: fsky/webqq
lwqq_js_t* lwqq_js_init()
{
    lwqq_js_t* h = s_malloc0(sizeof(*h));
    h->runtime = JS_NewRuntime(8L*1024L*1024L);
    h->context = JS_NewContext(h->runtime, 16*1024);
    JS_SetOptions(h->context, 
	JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);
    JS_SetErrorReporter(h->context, report_error);
#ifdef MOZJS_185
    h->global = JS_NewCompartmentAndGlobalObject(h->context, &global_class, NULL);
#else
    h->global = JS_NewGlobalObject(h->context,&global_class,NULL);
#endif
    JS_InitStandardClasses(h->context, h->global);
    return h;
}
Esempio n. 10
0
/*----------------------------------------------------------------------------*
 *                           Scripter descriptor                              *
 *----------------------------------------------------------------------------*/
static void * _egueb_script_js_sm_scripter_new(void)
{
	Egueb_Script_Js_Sm_Scripter *thiz;

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

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

	_egueb_script_js_sm_init_global_object(thiz);
	return thiz;
}
Esempio n. 11
0
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;
}
Esempio n. 12
0
RuntimeContext::RuntimeContext(SharedPtr<Runtime>& runtime, int size) : _runtime(runtime), _context(NULL)
{
	_context = JS_NewContext(*runtime, size);
	if ( _context != NULL )
	{
		JS_SetErrorReporter(_context, &RuntimeContext::errorReporter);
		JS_BeginRequest(_context);
		JS_SetOptions(_context, JSOPTION_XML /* | JSOPTION_VAROBJFIX */);
		JS_SetVersion(_context, JSVERSION_1_8);

		//if ( m_configuration->GetBranchLimit() > 0 )
		//{
		//  JS_SetBranchCallback(cx, Engine::BranchCallback);
		//  JS_ToggleOptions(cx, JSOPTION_NATIVE_BRANCH_CALLBACK);
		//}
		JS_EndRequest(_context);
	}
}
Esempio n. 13
0
/*
 * call-seq:
 *   native_initialize(options={})
 *
 * Initializes the native spidermonkey values.
 */
static VALUE
initialize_native(VALUE self, VALUE rb_runtime, VALUE UNUSED(options))
{
  JohnsonContext* context;
  JohnsonRuntime* runtime;

  Data_Get_Struct(self, JohnsonContext, context);
  Data_Get_Struct(rb_runtime, JohnsonRuntime, runtime);

  if ((context->js = JS_NewContext(runtime->js, 8192L)))
  {
    // See if the runtime already has a shared global object.
    JSObject* global = runtime->global;

    // If it does, use it. If not,
    if (!global)
      // create one of our global objects.
      global = johnson_create_global_object(context->js);

    // Manually set the context's global object.
    JS_SetGlobalObject(context->js, global);
    JS_SetErrorReporter(context->js, report_js_error);
    JS_SetBranchCallback(context->js, branch_callback);
    JS_SetContextPrivate(context->js, (void *)self);

    JS_SetOptions(context->js, JS_GetOptions(context->js)
        | JSOPTION_DONT_REPORT_UNCAUGHT
#ifdef JSOPTION_VAROBJFIX
        | JSOPTION_VAROBJFIX
#endif
// #ifdef JSOPTION_XML
//         | JSOPTION_XML
// #endif
        );

    // Success.
    return init_spidermonkey_extensions(context, self);
  }

  if (context->js) JS_DestroyContext(context->js);

  rb_raise(rb_eRuntimeError, "Failed to initialize SpiderMonkey context");
}
Esempio n. 14
0
JSContext * InitializeSpiderMonkey() {

	runtime = JS_NewRuntime(jsRuntimeSize);
	JSContext * context = JS_NewContext(runtime, jsStackSize);

	JS_SetOptions(context,
					JSOPTION_VAROBJFIX |
					JSOPTION_JIT |
					JSOPTION_METHODJIT |
					JSOPTION_COMPILE_N_GO
					);

	JS_SetVersion(context, JSVERSION_LATEST);

	JS_SetErrorReporter(context, reportError);

	return context;

}
Esempio n. 15
0
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);
}
Esempio n. 16
0
  SafeCallGuard(JSContext *cx, nsIPrincipal *principal)
    : cx(cx) {
    nsIScriptSecurityManager_1_9_2 *ssm = XPCWrapper::GetSecurityManager();
    if (ssm) {
      // Note: We pass null as the target frame pointer because we know that
      // we're about to set aside the frame chain.
      nsresult rv = ssm->PushContextPrincipal(cx, nsnull, principal);
      if (NS_FAILED(rv)) {
        NS_WARNING("Not allowing call because we're out of memory");
        JS_ReportOutOfMemory(cx);
        this->cx = nsnull;
        return;
      }
    }

    js_SaveAndClearRegExpStatics(cx, &statics, &tvr, &tvr2);
    fp = JS_SaveFrameChain(cx);
    options =
      JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_DONT_REPORT_UNCAUGHT);
  }
Esempio n. 17
0
JSObject*
Core_initialize (JSContext *cx, const char* path)
{
    JS_BeginRequest(cx);
    JS_SetOptions(cx, JSOPTION_VAROBJFIX|JSOPTION_JIT|JSOPTION_XML);
    JS_SetVersion(cx, JS_StringToVersion("1.8"));

    JSObject* object = JS_NewObject(cx, &Core_class, NULL, NULL);

    if (object && JS_InitStandardClasses(cx, object)) {
        JS_DefineFunctions(cx, object, Core_methods);

        JS_EnterLocalRootScope(cx);

        // Properties
        jsval property;

        std::string rootPath = __Core_getRootPath(cx, path);
        jsval paths[] = {
            STRING_TO_JSVAL(JS_NewString(cx, JS_strdup(cx, rootPath.c_str()), rootPath.length())),
            STRING_TO_JSVAL(JS_NewString(cx, JS_strdup(cx, __LJS_LIBRARY_PATH__), strlen(__LJS_LIBRARY_PATH__)))
        };
        property = OBJECT_TO_JSVAL(JS_NewArrayObject(cx, 2, paths));
        JS_SetProperty(cx, object, "__PATH__", &property);

        property = STRING_TO_JSVAL(JS_NewString(cx, JS_strdup(cx, __LJS_VERSION__), strlen(__LJS_VERSION__)));
        JS_SetProperty(cx, object, "__VERSION__", &property);

        property = OBJECT_TO_JSVAL(object);
        JS_SetProperty(cx, object, "Program", &property);

        JS_LeaveLocalRootScope(cx);
        JS_EndRequest(cx);

        if (__Core_include(cx, __LJS_LIBRARY_PATH__ "/Core")) {
            return object;
        }
    }

    return NULL;
}
Esempio n. 18
0
bool ScriptEngine_StartUp()
{
	SetScriptFolder();

	bool bOk = true;

	bOk =
		NULL != (g_JsRt = JS_NewRuntime(1L * 1024L * 1024L, JS_USE_HELPER_THREADS))
		&& NULL != (g_JsCx = JS_NewContext(g_JsRt, 8192))
		&& (
			JS_SetOptions(g_JsCx, JSOPTION_VAROBJFIX),
			JS_SetErrorReporter(g_JsCx, reportError),
			true
		)
	
		// . (global):
		&& NULL != (g_JsGlobal = NewGlobalObject(g_JsCx))
	;
	
	if(bOk)
	{
		JSAutoCompartment ac(g_JsCx, g_JsGlobal);
		JS_SetGlobalObject(g_JsCx, g_JsGlobal);

		//char * loadInitScript = "load(scriptFolder+'AfxGoldSrcInit.js');";
		//jsval rval;
		//bOk = bOk && JS_EvaluateScript(g_JsCx, JS_GetGlobalForScopeChain(g_JsCx), loadInitScript, strlen(loadInitScript), NULL, 0, &rval);
	}

	if(!bOk)
	{
		MessageBox(0, "Failed to init scripting engine.", "Error", MB_OK|MB_ICONERROR);
		ScriptEngine_ShutDown();
	}

	g_JsRunning = bOk;

	return bOk;
}
Esempio n. 19
0
int main(int argc, const char *argv[])
{
	/* Create a JS runtime. */
	JSRuntime *rt = JS_NewRuntime(8L * 1024L * 1024L, JS_NO_HELPER_THREADS);
	if (!rt)
		return 1;

	/* Create a context. */
	JSContext *cx = JS_NewContext(rt, 8192);
	if (!cx)
		return 2;
	JS_SetOptions(cx, JSOPTION_VAROBJFIX);
	JS_SetErrorReporter(cx, reportError);

	int status = run(cx);

	JS_DestroyContext(cx);
	JS_DestroyRuntime(rt);

	/* Shut down the JS engine. */
	JS_ShutDown();

	return status;
}
Esempio n. 20
0
    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;
    }
Esempio n. 21
0
bool CompileFile(const std::string &inputFilePath, const std::string &outputFilePath) {
    bool result = false;
    std::string ofp;
    if (!outputFilePath.empty()) {
        ofp = outputFilePath;
    }
    else {
        ofp = RemoveFileExt(inputFilePath) + BYTE_CODE_FILE_EXT;
    }
    
    if (!JS_Init())
        return false;
    
    std::cout << "Input file: " << inputFilePath << std::endl;
    JSRuntime * runtime = JS_NewRuntime(10 * 1024 * 1024, JS_NO_HELPER_THREADS);

    JSContext *cx = JS_NewContext(runtime, 10240);
    JS_SetOptions(cx, JSOPTION_TYPE_INFERENCE);
    
    JS::CompartmentOptions options;
    options.setVersion(JSVERSION_LATEST);
    
    JS::RootedObject global(cx, JS_NewGlobalObject(cx, &GlobalClass, NULL, JS::DontFireOnNewGlobalHook, options));
    
    JS_SetErrorReporter(cx, &ReportError);
    
    {
        JSAutoCompartment ac(cx, global);
    
        if (JS_InitStandardClasses(cx, global)) {
            
            JS_InitReflect(cx, global);
            
            JS_FireOnNewGlobalObject(cx, global);
            
            JS::CompileOptions options(cx);
            options.setUTF8(true);
            options.setSourcePolicy(JS::CompileOptions::NO_SOURCE);
            std::cout << "Compiling ..." << std::endl;
            
            JS::RootedScript script(cx, JS::Compile(cx, global, options, inputFilePath.c_str()));
            
            if (script) {
                void *data = NULL;
                uint32_t length = 0;
                std::cout << "Encoding ..." << std::endl;
                data = JS_EncodeScript(cx, script, &length);
                
                if (data) {
                    if (WriteFile(ofp, data, length)) {
                        std::cout << "Done! " << "Output file: " << ofp << std::endl;
                        result = true;
                    }
                }
            }
            else
            {
                std::cout << "Compiled " << inputFilePath << " fails!" << std::endl;
            }
        }
        else
        {
            std::cout << "JS_InitStandardClasses failed! " << std::endl;
        }
    }
    if (cx) {
        JS_DestroyContext(cx);
        cx = NULL;
    }
    if (runtime) {
        JS_DestroyRuntime(runtime);
        runtime = NULL;
    }
    
    JS_ShutDown();
    
    return result;
}
Esempio n. 22
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;
}
Esempio n. 23
0
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);
}
Esempio n. 24
0
/*
 * 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;
}
Esempio n. 25
0
/* void CompileFile (in nsILocalFile aFile, in PRBool strict); */
NS_IMETHODIMP nsXPCToolsCompiler::CompileFile(nsILocalFile *aFile, PRBool strict)
{
    // use the xpccallcontext stuff to get the current JSContext
    
    // get the xpconnect service
    nsresult rv;
    nsCOMPtr<nsIXPConnect> xpc(do_GetService(nsIXPConnect::GetCID(), &rv));
    if(NS_FAILED(rv))
        return NS_ERROR_FAILURE;

    // get the xpconnect native call context
    nsCOMPtr<nsIXPCNativeCallContext> callContext;
    xpc->GetCurrentNativeCallContext(getter_AddRefs(callContext));
    if(!callContext)
        return NS_ERROR_FAILURE;

    // verify that we are being called from JS (i.e. the current call is
    // to this object - though we don't verify that it is to this exact method)
    nsCOMPtr<nsISupports> callee;
    callContext->GetCallee(getter_AddRefs(callee));
    if(!callee || callee.get() != (nsISupports*)this)
        return NS_ERROR_FAILURE;

    // Get JSContext of current call
    JSContext* cx;
    rv = callContext->GetJSContext(&cx);
    if(NS_FAILED(rv) || !cx)
        return NS_ERROR_FAILURE;

    FILE* handle;
    if(NS_FAILED(aFile->OpenANSIFileDesc("r", &handle)))
        return NS_ERROR_FAILURE;

    JSObject* glob = JS_NewObject(cx, &global_class, NULL, NULL);
    if (!glob)
        return NS_ERROR_FAILURE;
    if (!JS_InitStandardClasses(cx, glob))
        return NS_ERROR_FAILURE;

    nsCAutoString path;
    if(NS_FAILED(aFile->GetNativePath(path)))
        return NS_ERROR_FAILURE;

    uint32 oldoptions = JS_GetOptions(cx);
    JS_SetOptions(cx, JSOPTION_WERROR | (strict ? JSOPTION_STRICT : 0));
    JSErrorReporter older = JS_SetErrorReporter(cx, ErrorReporter);
    JSExceptionState *es =JS_SaveExceptionState(cx);

    if(!JS_CompileFileHandle(cx, glob, path.get(), handle))
    {
        jsval v;
        JSErrorReport* report;
        if(JS_GetPendingException(cx, &v) &&
           nsnull != (report = JS_ErrorFromException(cx, v)))
        {
            JSString* str;
            const char* msg = "Error";
            str = JS_ValueToString(cx, v);
            if(str)
                msg = JS_GetStringBytes(str);
            printf("%s [%s,%d]\n\n",
                    msg,
                    report->filename, 
                    (int)report->lineno);            
        }
        else
        {
            printf("no script and no error report!\n");
        }
        
    }    
    JS_RestoreExceptionState(cx, es);
    JS_SetErrorReporter(cx, older);
    JS_SetOptions(cx, oldoptions);
        
    return NS_OK;
}
Esempio n. 26
0
PyObject*
Context_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)
{
    Context* self = NULL;
    Runtime* runtime = NULL;
    PyObject* global = NULL;
    PyObject* access = NULL;
    int strict = 0;
    uint32_t jsopts;

    char* keywords[] = {"runtime", "glbl", "access", "strict", NULL};

    if(!PyArg_ParseTupleAndKeywords(
        args, kwargs,
        "O!|OOI",
        keywords,
        RuntimeType, &runtime,
        &global,
        &access,
        &strict
    )) goto error;

    if(global == Py_None) global = NULL;
    if(access == Py_None) access = NULL;
    strict &= 1;  /* clamp at 1 */

    if(global != NULL && !PyMapping_Check(global))
    {
        PyErr_SetString(PyExc_TypeError,
                            "Global handler must provide item access.");
        goto error;
    }

    if(access != NULL && !PyCallable_Check(access))
    {
        PyErr_SetString(PyExc_TypeError,
                            "Access handler must be callable.");
        goto error;
    }

    self = (Context*) type->tp_alloc(type, 0);
    if(self == NULL) goto error;

    // Tracking what classes we've installed in
    // the context.
    self->classes = (PyDictObject*) PyDict_New();
    if(self->classes == NULL) goto error;

    self->objects = (PySetObject*) PySet_New(NULL);
    if(self->objects == NULL) goto error;

    self->cx = JS_NewContext(runtime->rt, 8192);
    if(self->cx == NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Failed to create JSContext.");
        goto error;
    }

    JS_BeginRequest(self->cx);

    /*
     *  Notice that we don't add a ref to the Python context for
     *  the copy stored on the JSContext*. I'm pretty sure this
     *  would cause a cyclic dependancy that would prevent
     *  garbage collection from happening on either side of the
     *  bridge.
     *
     */
    JS_SetContextPrivate(self->cx, self);

    // Setup the root of the property lookup doodad.
    self->root = JS_NewObject(self->cx, &js_global_class, NULL, NULL);
    if(self->root == NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Error creating root object.");
        goto error;
    }

    if(!JS_InitStandardClasses(self->cx, self->root))
    {
        PyErr_SetString(PyExc_RuntimeError, "Error initializing JS VM.");
        goto error;
    }

    // Don't setup the global handler until after the standard classes
    // have been initialized.
    // XXX: Does anyone know if finalize is called if new fails?
    if(global != NULL) Py_INCREF(global);
    self->global = global;

    if(access != NULL) Py_INCREF(access);
    self->access = access;

    // Setup counters for resource limits
    self->branch_count = 0;
    self->max_time = 0;
    self->start_time = 0;
    self->max_heap = 0;

    JS_SetBranchCallback(self->cx, branch_cb);
    JS_SetErrorReporter(self->cx, report_error_cb);

    jsopts = JS_GetOptions(self->cx);
    jsopts |= JSOPTION_VAROBJFIX;
    if (strict) {
        jsopts |= JSOPTION_STRICT;
    } else {
        jsopts &= ~JSOPTION_STRICT;
    }
    JS_SetOptions(self->cx, jsopts);
    
    Py_INCREF(runtime);
    self->rt = runtime;

    goto success;

error:
    if(self != NULL && self->cx != NULL) JS_EndRequest(self->cx);
    Py_XDECREF(self);
    self = NULL;

success:
    if(self != NULL && self->cx != NULL) JS_EndRequest(self->cx);
    return (PyObject*) self;
}
Esempio n. 27
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, &params, &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;
}
Esempio n. 28
0
static GObject*
gjs_context_constructor (GType                  type,
                         guint                  n_construct_properties,
                         GObjectConstructParam *construct_params)
{
    GObject *object;
    GjsContext *js_context;
    guint32 options_flags;
    JSVersion js_version;

    object = (* G_OBJECT_CLASS (gjs_context_parent_class)->constructor) (type,
                                                                         n_construct_properties,
                                                                         construct_params);

    js_context = GJS_CONTEXT(object);

    if (js_context->runtime == NULL) {
        js_context->runtime = JS_NewRuntime(32*1024*1024 /* max bytes */);
        if (js_context->runtime == NULL)
            gjs_fatal("Failed to create javascript runtime");
        JS_SetGCParameter(js_context->runtime, JSGC_MAX_BYTES, 0xffffffff);
        js_context->we_own_runtime = TRUE;
        gjs_runtime_init(js_context->runtime);
    }

    js_context->context = JS_NewContext(js_context->runtime, 8192 /* stack chunk size */);
    if (js_context->context == NULL)
        gjs_fatal("Failed to create javascript context");

    JS_BeginRequest(js_context->context);

    /* same as firefox, see discussion at
     * https://bugzilla.mozilla.org/show_bug.cgi?id=420869 */
    JS_SetScriptStackQuota(js_context->context, 100*1024*1024);

    /* JSOPTION_DONT_REPORT_UNCAUGHT: Don't send exceptions to our
     * error report handler; instead leave them set.  This allows us
     * to get at the exception object.
     *
     * JSOPTION_STRICT: Report warnings to error reporter function.
     */
    options_flags = JSOPTION_DONT_REPORT_UNCAUGHT | JSOPTION_STRICT;

    if (!g_getenv("GJS_DISABLE_JIT")) {
        gjs_debug(GJS_DEBUG_CONTEXT, "Enabling JIT");
        options_flags |= JSOPTION_METHODJIT;
    }

    JS_SetOptions(js_context->context,
                  JS_GetOptions(js_context->context) | options_flags);

    JS_SetLocaleCallbacks(js_context->context, &gjs_locale_callbacks);

    JS_SetErrorReporter(js_context->context, gjs_error_reporter);

    /* set ourselves as the private data */
    JS_SetContextPrivate(js_context->context, js_context);

    js_version = JS_StringToVersion(js_context->jsversion_string);
    /* It doesn't make sense to throw here; just use the default if we
     * don't know.
     */
    if (js_version == JSVERSION_UNKNOWN)
        js_version = JSVERSION_DEFAULT;
    /* Set the version if we need to. */
    if (js_version != JSVERSION_DEFAULT && JS_GetVersion(js_context->context) != js_version) {
        gjs_debug(GJS_DEBUG_CONTEXT,
                  "Changing JavaScript version to %s from %s",
                  JS_VersionToString(js_version),
                  JS_VersionToString(JS_GetVersion(js_context->context)));

        JS_SetVersion(js_context->context, js_version);
    }

    if (!gjs_init_context_standard(js_context->context))
        gjs_fatal("Failed to initialize context");
    js_context->global = JS_GetGlobalObject(js_context->context);

    if (!JS_DefineProperty(js_context->context, js_context->global,
                           "window", OBJECT_TO_JSVAL(js_context->global),
                           NULL, NULL,
                           JSPROP_READONLY | JSPROP_PERMANENT))
        gjs_fatal("No memory to export global object as 'window'");

    /* Define a global function called log() */
    if (!JS_DefineFunction(js_context->context, js_context->global,
                           "log",
                           (JSNative)gjs_log,
                           1, GJS_MODULE_PROP_FLAGS))
        gjs_fatal("Failed to define log function");

    if (!JS_DefineFunction(js_context->context, js_context->global,
                           "logError",
                           (JSNative)gjs_log_error,
                           2, GJS_MODULE_PROP_FLAGS))
        gjs_fatal("Failed to define logError function");

    /* Define global functions called print() and printerr() */
    if (!JS_DefineFunction(js_context->context, js_context->global,
                           "print",
                           (JSNative)gjs_print,
                           3, GJS_MODULE_PROP_FLAGS))
        gjs_fatal("Failed to define print function");
    if (!JS_DefineFunction(js_context->context, js_context->global,
                           "printerr",
                           (JSNative)gjs_printerr,
                           4, GJS_MODULE_PROP_FLAGS))
        gjs_fatal("Failed to define printerr function");

    /* We need to know what the default context is, since it's the context whose
     * global object is used to load imported JS modules. We currently say that
     * it's the context of the runtime's owner, but if we needed to support
     * externally created runtimes, we could define it in some other fashion.
     */
    if (js_context->we_own_runtime) {
        gjs_runtime_set_default_context(js_context->runtime, js_context->context);
    } else {
        if (gjs_runtime_get_default_context(js_context->runtime) == NULL)
            gjs_fatal("GjsContext created for a runtime not owned by GJS");
    }

    /* We create the global-to-runtime root importer with the
     * passed-in search path. If someone else already created
     * the root importer, this is a no-op.
     */
    if (!gjs_create_root_importer(js_context->context,
                                  js_context->search_path ?
                                  (const char**) js_context->search_path :
                                  NULL,
                                  TRUE))
        gjs_fatal("Failed to create root importer");

    /* Now copy the global root importer (which we just created,
     * if it didn't exist) to our global object
     */
    if (!gjs_define_root_importer(js_context->context,
                                  js_context->global,
                                  "imports"))
        gjs_fatal("Failed to point 'imports' property at root importer");

    if (js_context->we_own_runtime) {
        js_context->profiler = gjs_profiler_new(js_context->runtime);
    }

    if (!gjs_is_registered_native_module(js_context->context, NULL, "gi"))
        gjs_register_native_module("gi", gjs_define_gi_stuff, GJS_NATIVE_SUPPLIES_MODULE_OBJ);

    /* For GjsDBus */
    {
        char *priv_typelib_dir = g_build_filename (PKGLIBDIR, "girepository-1.0", NULL);
        g_irepository_prepend_search_path(priv_typelib_dir);
        g_free (priv_typelib_dir);
    }

    if (js_context->gc_notifications_enabled)
        JS_SetGCCallback(js_context->context, gjs_on_context_gc);

    JS_EndRequest(js_context->context);

    g_static_mutex_lock (&contexts_lock);
    all_contexts = g_list_prepend(all_contexts, object);
    g_static_mutex_unlock (&contexts_lock);

    return object;
}
Esempio n. 29
0
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;
}
Esempio n. 30
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;
}