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

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

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

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

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

  /* create some privacy for us */
  if (!JS_SetPrivate(THIS->ctx, global, THIS))
    Pike_error("Could not set the private storage for the global object\n");
    
  pop_n_elems(args);
}
JSInterpreter::JSInterpreter() {
        /* Create a JS runtime. You always need at least one runtime per process. */
        rt = JS_NewRuntime(8 * 1024 * 1024);
        if (rt == NULL)
            throw * new std::runtime_error("Can't create JS runtime.");

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

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

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

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

    }
Ejemplo n.º 3
0
void JavaScriptEngine::Start() {

	globalRuntime = JS_NewRuntime(32L * 1024L * 1024L);
	if (globalRuntime == NULL) {
		LogInfo(TAG, "(globalRuntime == NULL)");
		return;
	}
	globalContext = JS_NewContext(globalRuntime, 8192);
	if (globalContext == NULL) {
		LogInfo(TAG, "(globalContext == NULL)");
		return;
	}
	JS_SetOptions(globalContext, JSOPTION_VAROBJFIX);
	JS_SetVersion(globalContext, JSVERSION_LATEST);
	JS_SetErrorReporter(globalContext, ReportError);
	globalObject = JS_NewCompartmentAndGlobalObject(globalContext,
			&globalClass, NULL);
	if (globalObject == NULL) {
		LogInfo(TAG, "(globalObject == NULL)");
		return;
	}
	if (!JS_InitStandardClasses(globalContext, globalObject)) {
		LogInfo(TAG, "(!JS_InitStandardClasses(globalContext, global))");
		return;
	}
	BindingGlobalObject();
	BindingObject();
	RunScript("index.js");
}
void TraceMonkeyEngine::init()
{
    Logging::log(Logging::DEBUG, "TraceMonkeyEngine::init\r\n");
    INDENT_LOG(Logging::DEBUG);

    assert(runtime == NULL);

    runtime = JS_NewRuntime(8L * 1024L * 1024L); // Force GC after X MB.
    if (runtime == NULL)
    {
        Logging::log(Logging::ERROR, "Cannot create TraceMonkey runtime\r\n");
        assert(0);
    }

    /* Create a context. */
    context = JS_NewContext(runtime, 8192);
    if (context == NULL)
    {
        Logging::log(Logging::ERROR, "Cannot create TraceMonkey runtime\r\n");
        assert(0);
    }

    JS_SetOptions(context, JSOPTION_VAROBJFIX);
    JS_SetVersion(context, JSVERSION_ECMA_3);
    JS_SetErrorReporter(context, reportError);

    // Create the global object. Store it locally for a while until it is usable by others
    JSObject* _global = JS_NewObject(context, &global_class, NULL, NULL);
    if (_global == NULL)
    {
        Logging::log(Logging::ERROR, "Cannot create TraceMonkey runtime\r\n");
        assert(0);
    }

    /* Populate the global object with the standard globals,
       like Object and Array. */
    if (!JS_InitStandardClasses(context, _global))
    {
        Logging::log(Logging::ERROR, "Cannot create TraceMonkey runtime\r\n");
        assert(0);
    }

    // Create our internal wrappers

    globalValue = ScriptValuePtr(new TraceMonkeyValue( this, true, OBJECT_TO_JSVAL(_global) ));
    global = _global; // Now that globalValue is set, it is usable by others, so reveal it

    // JITting
//    JS_ToggleOptions(context, JSOPTION_JIT); // Might be buggy, wait for 1.8 to release

// JS_MaybeGC - call during idle time in the main loop? Or other method?

// Use JS_SetContextPrivate and JS_GetContextPrivate to associate application-specific data with a context.
//  - Useful for security checks, once we have a context for the system and sandboxed contexts
//    for user scripts

    // Debugging features

    JS_SetGCZeal(context, 2); // XXX This is 'extremely high' - make a parameter, see MDC docs
}
Ejemplo n.º 5
0
   // PD_TRACE_DECLARE_FUNCTION ( SDB_SCOPE_INIT, "Scope::init" )
   BOOLEAN Scope::init()
   {
      BOOLEAN ret = FALSE ;
      PD_TRACE_ENTRY ( SDB_SCOPE_INIT );

      SDB_ASSERT( globalEngine, "Script engine has not been initialized" );
      SDB_ASSERT( ! _context && ! _global, "Can't init a scope twice" );

      _context = JS_NewContext( globalEngine->_runtime, 1024 * 1024 ) ;
      VERIFY( _context );

      JS_SetOptions( _context, JSOPTION_VAROBJFIX );
      JS_SetVersion( _context, JSVERSION_LATEST );
      JS_SetErrorReporter( _context, sdbReportError );

      _global = JS_NewCompartmentAndGlobalObject( _context, &global_class, NULL );
      VERIFY( _global );

      VERIFY( JS_InitStandardClasses( _context, _global ) );

      VERIFY( InitDbClasses( _context, _global ) ) ;

      VERIFY ( SDB_OK == evalInitScripts ( this ) ) ;

      ret = TRUE ;

   done :
      PD_TRACE_EXIT ( SDB_SCOPE_INIT );
      return ret ;
   error :
      goto done ;
   }
Ejemplo n.º 6
0
ContextCallback(JSContext *cx, uintN contextOp)
{
    if (contextOp == JSCONTEXT_NEW) {
        JS_SetErrorReporter(cx, my_ErrorReporter);
        JS_SetVersion(cx, JSVERSION_LATEST);
    }
    return JS_TRUE;
}
Ejemplo n.º 7
0
Version(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    if (argc > 0 && JSVAL_IS_INT(argv[0]))
        *rval = INT_TO_JSVAL(JS_SetVersion(cx, JSVersion(JSVAL_TO_INT(argv[0]))));
    else
        *rval = INT_TO_JSVAL(JS_GetVersion(cx));
    return JS_TRUE;
}
Ejemplo n.º 8
0
void SG_jscore__new_context(SG_context * pCtx, JSContext ** pp_cx, JSObject ** pp_glob,
	const SG_vhash * pServerConfig)
{
	JSContext * cx = NULL;
	JSObject * glob = NULL;

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

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

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

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

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

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

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

    SG_jsglue__set_sg_context(pCtx, cx);

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

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

	*pp_cx = cx;
	*pp_glob = glob;

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

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

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

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

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

 
    /* Your application code here. This may include JSAPI calls
     * to create your own custom JavaScript objects and to run scripts.
     *
     * The following example code creates a literal JavaScript script,
     * evaluates it, and prints the result to stdout.
     *
     * Errors are conventionally saved in a JSBool variable named ok.
     */
	
	JS_DefineFunction(cx,global,"print",&js_print,0,0);
	
	// execJsFile(cx,"t.js");
	
	// testObj(cx);
	
	beforeTest(cx);
	execJsFile(cx,"t4.js");
	test(cx);
    
 
    /* End of your application code */
 
    /* Clean things up and shut down SpiderMonkey. */
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return 0;
}
Ejemplo n.º 10
0
static void ctx_compile(INT32 args)
{
  JSScript           *compiled;
  struct pike_string *script;
  jsval               rval;
  INT32               version = -1, oldversion = -1;

  if (!THIS->ctx) {
    pop_n_elems(args);
    push_int(0);
    return;
  }
    
  switch(args) {
      case 2:
        get_all_args("compile", args, "%S%i", &script, &version);
        break;

      case 1:
        get_all_args("compile", args, "%S", &script);
        break;

      default:
        Pike_error("Not enough arguments\n");
  }

  if (version != -1)
    oldversion = JS_SetVersion(THIS->ctx, version);
    
  /* TODO: filename should indicate the actual location of the script */
  compiled = JS_CompileScript(THIS->ctx, global,
                               script->str, script->len,
                              "Caudium/js", &rval);

  if (oldversion != -1)
    JS_SetVersion(THIS->ctx, oldversion);
    
  pop_n_elems(args);
    
  if (!compiled) {
    push_int(-1);
    return;
  }
}
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;
}
Ejemplo n.º 12
0
bool CompileFile(const std::string &inputFilePath, const std::string &outputFilePath) {
    bool result = false;
    std::string ofp;
    if (!outputFilePath.empty()) {
        ofp = outputFilePath;
    }
    else {
        ofp = RemoveFileExt(inputFilePath) + BYTE_CODE_FILE_EXT;
    }
    std::cout << "Input file: " << inputFilePath << std::endl;
    JSRuntime * runtime = JS_NewRuntime(10 * 1024 * 1024, JS_NO_HELPER_THREADS);
    JSContext *context = JS_NewContext(runtime, 10240);
    JS_SetOptions(context, JSOPTION_TYPE_INFERENCE);
    JS_SetVersion(context, JSVERSION_LATEST);
    JS_SetOptions(context, JS_GetOptions(context) & ~JSOPTION_METHODJIT);
    JS_SetOptions(context, JS_GetOptions(context) & ~JSOPTION_METHODJIT_ALWAYS);
	JSObject* global = JS_NewGlobalObject(context, &GlobalClass, NULL);
    JS_SetErrorReporter(context, &ReportError);
	if (JS_InitStandardClasses(context, global)) {

        JS::CompileOptions options(context);
        options.setUTF8(true);
        options.setSourcePolicy(JS::CompileOptions::NO_SOURCE);
        js::RootedObject rootedObject(context, global);
        std::cout << "Compiling ..." << std::endl;
        JSScript *script = JS::Compile(context, rootedObject, options, inputFilePath.c_str());
        if (script) {
            void *data = NULL;
            uint32_t length = 0;
            std::cout << "Encoding ..." << std::endl;
            data = JS_EncodeScript(context, script, &length);
            if (data) {
                if (WriteFile(ofp, data, length)) {
                    std::cout << "Done! " << "Output file: " << ofp << std::endl;
                    result = true;
                }
            }
        }
        
    }
    if (context) {
        JS_DestroyContext(context);
        context = NULL;
    }
    if (runtime) {
        JS_DestroyRuntime(runtime);
        runtime = NULL;
    }
    return result;
}
Ejemplo n.º 13
0
Archivo: flim.c Proyecto: 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");
}
Ejemplo n.º 14
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;
}
Ejemplo n.º 15
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);
	}
}
Ejemplo n.º 16
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;

}
Ejemplo n.º 17
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);
}
Ejemplo n.º 18
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;
}
  nsresult Init()
  {
    mRuntime = JS_NewRuntime(sRuntimeHeapSize, JS_NO_HELPER_THREADS);
    NS_ENSURE_TRUE(mRuntime, NS_ERROR_OUT_OF_MEMORY);

    mContext = JS_NewContext(mRuntime, 0);
    NS_ENSURE_TRUE(mContext, NS_ERROR_OUT_OF_MEMORY);

    JSAutoRequest ar(mContext);

    mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr);
    NS_ENSURE_TRUE(mGlobal, NS_ERROR_OUT_OF_MEMORY);

    JS_SetGlobalObject(mContext, mGlobal);
    JS_InitStandardClasses(mContext, mGlobal);

    JS_SetVersion(mContext, JSVERSION_LATEST);
    JS_SetErrorReporter(mContext, PACErrorReporter);

    if (!JS_DefineFunctions(mContext, mGlobal, PACGlobalFunctions))
      return NS_ERROR_FAILURE;

    return NS_OK;
  }
Ejemplo n.º 20
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);
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
0
static int
ProcessArgs(JSContext *cx, JSObject *obj, char **argv, int argc)
{
    const char rcfilename[] = "xpcshell.js";
    FILE *rcfile;
    int i, j, length;
    JSObject *argsObj;
    char *filename = NULL;
    JSBool isInteractive = JS_TRUE;
    JSBool forceTTY = JS_FALSE;

    rcfile = fopen(rcfilename, "r");
    if (rcfile) {
        printf("[loading '%s'...]\n", rcfilename);
        ProcessFile(cx, obj, rcfilename, rcfile, JS_FALSE);
    }

    /*
     * Scan past all optional arguments so we can create the arguments object
     * before processing any -f options, which must interleave properly with
     * -v and -w options.  This requires two passes, and without getopt, we'll
     * have to keep the option logic here and in the second for loop in sync.
     */
    for (i = 0; i < argc; i++) {
        if (argv[i][0] != '-' || argv[i][1] == '\0') {
            ++i;
            break;
        }
        switch (argv[i][1]) {
          case 'v':
          case 'f':
          case 'e':
            ++i;
            break;
          default:;
        }
    }

    /*
     * Create arguments early and define it to root it, so it's safe from any
     * GC calls nested below, and so it is available to -f <file> arguments.
     */
    argsObj = JS_NewArrayObject(cx, 0, NULL);
    if (!argsObj)
        return 1;
    if (!JS_DefineProperty(cx, obj, "arguments", OBJECT_TO_JSVAL(argsObj),
                           NULL, NULL, 0)) {
        return 1;
    }

    length = argc - i;
    for (j = 0; j < length; j++) {
        JSString *str = JS_NewStringCopyZ(cx, argv[i++]);
        if (!str)
            return 1;
        if (!JS_DefineElement(cx, argsObj, j, STRING_TO_JSVAL(str),
                              NULL, NULL, JSPROP_ENUMERATE)) {
            return 1;
        }
    }

    for (i = 0; i < argc; i++) {
        if (argv[i][0] != '-' || argv[i][1] == '\0') {
            filename = argv[i++];
            isInteractive = JS_FALSE;
            break;
        }
        switch (argv[i][1]) {
        case 'v':
            if (++i == argc) {
                return usage();
            }
            JS_SetVersion(cx, JSVersion(atoi(argv[i])));
            break;
        case 'W':
            reportWarnings = JS_FALSE;
            break;
        case 'w':
            reportWarnings = JS_TRUE;
            break;
        case 's':
            JS_ToggleOptions(cx, JSOPTION_STRICT);
            break;
        case 'x':
            JS_ToggleOptions(cx, JSOPTION_XML);
            break;
        case 'P':
            if (JS_GET_CLASS(cx, JS_GetPrototype(cx, obj)) != &global_class) {
                JSObject *gobj;

                if (!JS_SealObject(cx, obj, JS_TRUE))
                    return JS_FALSE;
                gobj = JS_NewObject(cx, &global_class, NULL, NULL);
                if (!gobj)
                    return JS_FALSE;
                if (!JS_SetPrototype(cx, gobj, obj))
                    return JS_FALSE;
                JS_SetParent(cx, gobj, NULL);
                JS_SetGlobalObject(cx, gobj);
                obj = gobj;
            }
            break;
        case 'f':
            if (++i == argc) {
                return usage();
            }
            Process(cx, obj, argv[i], JS_FALSE);
            /*
             * XXX: js -f foo.js should interpret foo.js and then
             * drop into interactive mode, but that breaks test
             * harness. Just execute foo.js for now.
             */
            isInteractive = JS_FALSE;
            break;
        case 'i':
            isInteractive = forceTTY = JS_TRUE;
            break;
        case 'e':
        {
            jsval rval;

            if (++i == argc) {
                return usage();
            }

            JS_EvaluateScript(cx, obj, argv[i], strlen(argv[i]), 
                              "-e", 1, &rval);

            isInteractive = JS_FALSE;
            break;
        }
        case 'C':
            compileOnly = JS_TRUE;
            isInteractive = JS_FALSE;
            break;
#ifdef MOZ_SHARK
        case 'k':
            JS_ConnectShark();
            break;
#endif
        default:
            return usage();
        }
    }

    if (filename || isInteractive)
        Process(cx, obj, filename, forceTTY);
    return gExitCode;
}
Ejemplo n.º 23
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;
}
Ejemplo n.º 24
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;
}
Ejemplo n.º 25
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;
}
Ejemplo n.º 26
0
NS_IMETHODIMP nsJSSh::Init()
{
  nsCOMPtr<nsIScriptSecurityManager> ssm = do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
  if (!ssm) {
    NS_ERROR("failed to get script security manager");
    return NS_ERROR_FAILURE;
  }

  ssm->GetSystemPrincipal(getter_AddRefs(mPrincipal));
  if (!mPrincipal) {
    NS_ERROR("failed to get system principal");
    return NS_ERROR_FAILURE;
  }
  
  nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
  if (!xpc) {
    NS_ERROR("failed to get xpconnect service");
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIJSRuntimeService> rtsvc = do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
  // get the JSRuntime from the runtime svc
  if (!rtsvc) {
    NS_ERROR("failed to get nsJSRuntimeService");
    return NS_ERROR_FAILURE;
  }
  
  JSRuntime *rt = nsnull;
  if (NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt) {
    NS_ERROR("failed to get JSRuntime from nsJSRuntimeService");
    return NS_ERROR_FAILURE;
  }
  
  mJSContext = JS_NewContext(rt, 8192);
  if (!mJSContext) {
    NS_ERROR("JS_NewContext failed");
    return NS_ERROR_FAILURE;
  }

  JSAutoRequest ar(mJSContext);

  // Enable e4x:
  JS_SetOptions(mJSContext, JS_GetOptions(mJSContext) | JSOPTION_XML);
  
  // Always use the latest js version
  JS_SetVersion(mJSContext, JSVERSION_LATEST);
  
  mContextStack = do_GetService("@mozilla.org/js/xpc/ContextStack;1");
  if (!mContextStack) {
    NS_ERROR("failed to get the nsThreadJSContextStack service");
    return NS_ERROR_FAILURE;
  }
  
  JS_SetErrorReporter(mJSContext, my_ErrorReporter);

  nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
  xpc->InitClassesWithNewWrappedGlobal(mJSContext, (nsIJSSh*)this,
                                       NS_GET_IID(nsISupports),
                                       PR_TRUE,
                                       getter_AddRefs(holder));
  if (!holder) {
    NS_ERROR("global initialization failed");
    return NS_ERROR_FAILURE;
  }
  
  holder->GetJSObject(&mGlobal);
  if (!mGlobal) {
    NS_ERROR("bad global object");
    return NS_ERROR_FAILURE;
  }
  mContextObj = mGlobal;
  
  if (!JS_DefineFunctions(mJSContext, mGlobal, global_functions)) {
    NS_ERROR("failed to initialise global functions");
    return NS_ERROR_FAILURE;
  }
  
  if (!mStartupURI.IsEmpty())
    LoadURL(mStartupURI.get());
  
  return NS_OK;
}
Ejemplo n.º 27
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;
}
Ejemplo n.º 28
0
int SDL_main(int argc, char **argv) {

    bool referenceMode = false;
    bool javaScriptMode = false;
    char* scripts [32];
    int scriptCount = 0;
    char* args;

    int o = 0;
    while ((o = getopt (argc, argv, "rjs:a:")) != -1) {
        switch (o) {
        case 'r':
            referenceMode = true;
            break;
        case 'j':
            javaScriptMode = true;
            break;
        case 's':
            scripts[scriptCount++] = optarg;
            break;
        case 'a':
            args = optarg;
            break;
        case '?':
            printf("[-r] [-s FILE] [-a ARGUMENTS]\n");
            break;
        }
    }

	if (referenceMode) {
        Avc avc(args);
        avc.Play();
	} else if (javaScriptMode) {
        /* JS variables. */
        JSRuntime *rt;
        JSContext *cx;
        JSObject *global;

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

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

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

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

        if (!JS_DefineFunctions(cx, global, globalFunctions))
            return JS_FALSE;

        for (int i = 0; i < scriptCount; i++) {
            JSScript *script = JS_CompileFile(cx, global, scripts[i]);
            if (script == NULL)
                return 1;

            jsval rval;
            JSBool result = JS_ExecuteScript(cx, global, script, &rval);
            if (!result) {
                printf("Cannot execute script %s", scripts[i]);
            }
        }

        /* Cleanup. */
        JS_DestroyContext(cx);
        JS_DestroyRuntime(rt);
        JS_ShutDown();
	}
	return 0;
}
Ejemplo n.º 29
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;
    }
Ejemplo n.º 30
0
static int
ProcessArgs(JSContext *cx, JSObject *obj, char **argv, int argc)
{
    int i, j, length;
    JSObject *argsObj;
    char *filename = NULL;
    JSBool isInteractive = JS_TRUE;
    JSBool forceTTY = JS_FALSE;

    /*
     * Scan past all optional arguments so we can create the arguments object
     * before processing any -f options, which must interleave properly with
     * -v and -w options.  This requires two passes, and without getopt, we'll
     * have to keep the option logic here and in the second for loop in sync.
     */
    for (i = 0; i < argc; i++) {
        if (argv[i][0] != '-' || argv[i][1] == '\0') {
            ++i;
            break;
        }
        switch (argv[i][1]) {
          case 'b':
          case 'c':
          case 'f':
          case 'e':
          case 'v':
          case 'S':
            ++i;
            break;
          default:;
        }
    }

    /*
     * Create arguments early and define it to root it, so it's safe from any
     * GC calls nested below, and so it is available to -f <file> arguments.
     */
    argsObj = JS_NewArrayObject(cx, 0, NULL);
    if (!argsObj)
        return 1;
    if (!JS_DefineProperty(cx, obj, "arguments", OBJECT_TO_JSVAL(argsObj),
                           NULL, NULL, 0)) {
        return 1;
    }

    length = argc - i;
    for (j = 0; j < length; j++) {
        JSString *str = JS_NewStringCopyZ(cx, argv[i++]);
        if (!str)
            return 1;
        if (!JS_DefineElement(cx, argsObj, j, STRING_TO_JSVAL(str),
                              NULL, NULL, JSPROP_ENUMERATE)) {
            return 1;
        }
    }

    for (i = 0; i < argc; i++) {
        if (argv[i][0] != '-' || argv[i][1] == '\0') {
            filename = argv[i++];
            isInteractive = JS_FALSE;
            break;
        }

        switch (argv[i][1]) {
        case 'v':
            if (++i == argc)
                return usage();

            JS_SetVersion(cx, (JSVersion) atoi(argv[i]));
            break;

        case 'w':
            reportWarnings = JS_TRUE;
            break;

        case 'W':
            reportWarnings = JS_FALSE;
            break;

        case 's':
            JS_ToggleOptions(cx, JSOPTION_STRICT);
            break;

        case 'E':
            JS_ToggleOptions(cx, JSOPTION_RELIMIT);
            break;

        case 'x':
            JS_ToggleOptions(cx, JSOPTION_XML);
            break;

        case 'o':
            if (++i == argc)
                return usage();

            for (j = 0; js_options[j].name; ++j) {
                if (strcmp(js_options[j].name, argv[i]) == 0) {
                    JS_ToggleOptions(cx, js_options[j].flag);
                    break;
                }
            }
            break;

        case 'c':
            /* set stack chunk size */
            gStackChunkSize = atoi(argv[++i]);
            break;

        case 'f':
            if (++i == argc)
                return usage();

            Process(cx, obj, argv[i], JS_FALSE);

            /*
             * XXX: js -f foo.js should interpret foo.js and then
             * drop into interactive mode, but that breaks the test
             * harness. Just execute foo.js for now.
             */
            isInteractive = JS_FALSE;
            break;

        case 'e':
        {
            jsval rval;

            if (++i == argc)
                return usage();

            /* Pass a filename of -e to imitate PERL */
            JS_EvaluateScript(cx, obj, argv[i], SG_STRLEN(argv[i]),
                              "-e", 1, &rval);

            isInteractive = JS_FALSE;
            break;

        }
        case 'C':
            compileOnly = JS_TRUE;
            isInteractive = JS_FALSE;
            break;

        case 'i':
            isInteractive = forceTTY = JS_TRUE;
            break;

        case 'S':
            if (++i == argc)
                return usage();

            /* Set maximum stack size. */
            gMaxStackSize = atoi(argv[i]);
            break;

#ifdef MOZ_SHARK
        case 'k':
            JS_ConnectShark();
            break;
#endif
        default:
            return usage();
        }
    }

    if (filename || isInteractive)
        Process(cx, obj, filename, forceTTY);
    return gExitCode;
}