Esempio n. 1
0
bool
eval(const char* asciiChars, bool mutedErrors, JS::MutableHandleValue rval)
{
    size_t len = strlen(asciiChars);
    mozilla::UniquePtr<char16_t[]> chars(new char16_t[len+1]);
    for (size_t i = 0; i < len; ++i)
        chars[i] = asciiChars[i];
    chars[len] = 0;

    JS::RootedObject global(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
    CHECK(global);
    JSAutoCompartment ac(cx, global);
    CHECK(JS_InitStandardClasses(cx, global));


    JS::CompileOptions options(cx);
    options.setMutedErrors(mutedErrors)
           .setFileAndLine("", 0);

    return JS::Evaluate(cx, options, chars.get(), len, rval);
}
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;
}
Esempio n. 3
0
JSObject * JSAPITest::createGlobal(JSPrincipals *principals)
{
    /* Create the global object. */
    JS::CompartmentOptions options;
    options.setVersion(JSVERSION_LATEST);
    global = JS_NewGlobalObject(cx, getGlobalClass(), principals, JS::FireOnNewGlobalHook, options);
    if (!global)
        return nullptr;
    JS::AddNamedObjectRoot(cx, &global, "test-global");
    JS::HandleObject globalHandle = JS::HandleObject::fromMarkedLocation(global.unsafeGet());
    JSAutoCompartment ac(cx, globalHandle);

    /* Populate the global object with the standard globals, like Object and
       Array. */
    if (!JS_InitStandardClasses(cx, globalHandle)) {
        global = nullptr;
        JS::RemoveObjectRoot(cx, &global);
    }

    return global;
}
bool
eval(const char *asciiChars, JSPrincipals *principals, JSPrincipals *originPrincipals, jsval *rval)
{
    size_t len = strlen(asciiChars);
    jschar *chars = new jschar[len+1];
    for (size_t i = 0; i < len; ++i)
        chars[i] = asciiChars[i];
    chars[len] = 0;

    JS::RootedObject global(cx, JS_NewGlobalObject(cx, getGlobalClass(), principals, JS::FireOnNewGlobalHook));
    CHECK(global);
    JSAutoCompartment ac(cx, global);
    CHECK(JS_InitStandardClasses(cx, global));
    bool ok = JS_EvaluateUCScriptForPrincipalsVersionOrigin(cx, global,
                                                            principals,
                                                            originPrincipals,
                                                            chars, len, "", 0, rval,
                                                            JSVERSION_DEFAULT);
    delete[] chars;
    return ok;
}
Esempio n. 5
0
static JSObject *
NewGlobalObject(JSContext *cx)
{
    JS::RootedObject glob(cx, JS_NewGlobalObject(cx, &AfxGlobal_class, NULL, JS::CompartmentOptions()));
    if(!glob)
        return NULL;

    {
        JSAutoCompartment ac(cx, glob);

        if(!JS_InitStandardClasses(cx, glob))
            return NULL;

		if(!JS_DefineFunctions(cx, glob, AfxGlobal_functions))
			return NULL;

        if (!JS_DefineProperties(cx, glob, AfxGlobal_properties))
            return NULL;
    }

    return glob;
}
Esempio n. 6
0
JSObject* newDelegate()
{
    static const js::Class delegateClass = {
        "delegate",
        JSCLASS_GLOBAL_FLAGS | JSCLASS_HAS_RESERVED_SLOTS(1),
        nullptr, /* addProperty */
        nullptr, /* delProperty */
        nullptr, /* getProperty */
        nullptr, /* setProperty */
        nullptr, /* enumerate */
        nullptr, /* resolve */
        nullptr, /* mayResolve */
        nullptr, /* convert */
        nullptr, /* finalize */
        nullptr, /* call */
        nullptr, /* hasInstance */
        nullptr, /* construct */
        JS_GlobalObjectTraceHook,
        JS_NULL_CLASS_SPEC,
        {
            nullptr,
            nullptr,
            false,
            nullptr,
            DelegateObjectMoved
        },
        JS_NULL_OBJECT_OPS
    };

    /* Create the global object. */
    JS::CompartmentOptions options;
    options.setVersion(JSVERSION_LATEST);
    JS::RootedObject global(cx);
    global = JS_NewGlobalObject(cx, Jsvalify(&delegateClass), nullptr, JS::FireOnNewGlobalHook,
                                options);
    JS_SetReservedSlot(global, 0, JS::Int32Value(42));

    return global;
}
Esempio n. 7
0
bool Context::initialize()
{
  JS_SetErrorReporter(_jsctx, reportError);

  /* Enter a request before running anything in the context */
  JSAutoRequest ar(_jsctx);

  /* Create the global object in a new compartment. */
  _global = JS_NewGlobalObject(_jsctx, &global_class, nullptr);
  if (_global)
    return false;

  /* Set the context's global */
  JSAutoCompartment ac(_jsctx, _global);
  JS_SetGlobalObject(_jsctx, _global);

  /* Populate the global object with the standard globals, like Object and Array. */
  if (!JS_InitStandardClasses(_jsctx, _global)) {
    return false;
  }

  return true;
}
Esempio n. 8
0
  nsresult Init()
  {
    mRuntime = JS_NewRuntime(sRuntimeHeapSize, JS_NO_HELPER_THREADS);
    NS_ENSURE_TRUE(mRuntime, NS_ERROR_OUT_OF_MEMORY);

    /*
     * Not setting this will cause JS_CHECK_RECURSION to report false
     * positives
     */
    JS_SetNativeStackQuota(mRuntime, 128 * sizeof(size_t) * 1024); 

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

    JSAutoRequest ar(mContext);

    JS::CompartmentOptions options;
    options.setZone(JS::SystemZone)
           .setVersion(JSVERSION_LATEST);
    mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr,
                                 JS::DontFireOnNewGlobalHook, options);
    NS_ENSURE_TRUE(mGlobal, NS_ERROR_OUT_OF_MEMORY);
    JS::Rooted<JSObject*> global(mContext, mGlobal);

    JSAutoCompartment ac(mContext, global);
    js::SetDefaultObjectForContext(mContext, global);
    JS_InitStandardClasses(mContext, global);

    JS_SetErrorReporter(mContext, PACErrorReporter);

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

    JS_FireOnNewGlobalObject(mContext, global);

    return NS_OK;
  }
  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;
  }
/* -*-  Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Test that heap snapshots walk the compartment boundaries correctly.

#include "DevTools.h"

DEF_TEST(DoesntCrossCompartmentBoundaries, {
    // Create a new global to get a new compartment.
    JS::CompartmentOptions options;
    JS::RootedObject newGlobal(cx, JS_NewGlobalObject(cx,
                                                      getGlobalClass(),
                                                      nullptr,
                                                      JS::FireOnNewGlobalHook,
                                                      options));
    ASSERT_TRUE(newGlobal);
    JSCompartment* newCompartment = nullptr;
    {
      JSAutoCompartment ac(cx, newGlobal);
      ASSERT_TRUE(JS_InitStandardClasses(cx, newGlobal));
      newCompartment = js::GetContextCompartment(cx);
    }
    ASSERT_TRUE(newCompartment);
    ASSERT_NE(newCompartment, compartment);

    // Our set of target compartments is only the pre-existing compartment and
    // does not include the new compartment.
    JS::CompartmentSet targetCompartments;
    ASSERT_TRUE(targetCompartments.init());
Esempio n. 11
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. 12
0
static JSDContext*
_newJSDContext(JSRuntime*         jsrt, 
               JSD_UserCallbacks* callbacks, 
               void*              user,
               JSObject*          scopeobj)
{
    JSDContext* jsdc = NULL;
    JSCompartment *oldCompartment = NULL;
    JSBool ok;

    if( ! jsrt )
        return NULL;

    if( ! _validateUserCallbacks(callbacks) )
        return NULL;

    jsdc = (JSDContext*) calloc(1, sizeof(JSDContext));
    if( ! jsdc )
        goto label_newJSDContext_failure;

    if( ! JSD_INIT_LOCKS(jsdc) )
        goto label_newJSDContext_failure;

    JS_INIT_CLIST(&jsdc->links);

    jsdc->jsrt = jsrt;

    if( callbacks )
        memcpy(&jsdc->userCallbacks, callbacks, callbacks->size);
    
    jsdc->user = user;

#ifdef JSD_HAS_DANGEROUS_THREAD
    jsdc->dangerousThread = _dangerousThread;
#endif

    JS_INIT_CLIST(&jsdc->threadsStates);
    JS_INIT_CLIST(&jsdc->sources);
    JS_INIT_CLIST(&jsdc->removedSources);

    jsdc->sourceAlterCount = 1;

    if( ! jsd_CreateAtomTable(jsdc) )
        goto label_newJSDContext_failure;

    if( ! jsd_InitObjectManager(jsdc) )
        goto label_newJSDContext_failure;

    if( ! jsd_InitScriptManager(jsdc) )
        goto label_newJSDContext_failure;

    jsdc->dumbContext = JS_NewContext(jsdc->jsrt, 256);
    if( ! jsdc->dumbContext )
        goto label_newJSDContext_failure;

    JS_BeginRequest(jsdc->dumbContext);
    JS_SetOptions(jsdc->dumbContext, JS_GetOptions(jsdc->dumbContext));

    jsdc->glob = JS_NewGlobalObject(jsdc->dumbContext, &global_class, NULL);

    if( ! jsdc->glob )
        goto label_newJSDContext_failure;

    oldCompartment = JS_EnterCompartment(jsdc->dumbContext, jsdc->glob);

    if ( ! JS_AddNamedObjectRoot(jsdc->dumbContext, &jsdc->glob, "JSD context global") )
        goto label_newJSDContext_failure;

    ok = JS_InitStandardClasses(jsdc->dumbContext, jsdc->glob);

    JS_LeaveCompartment(jsdc->dumbContext, oldCompartment);
    if( ! ok )
        goto label_newJSDContext_failure;

    JS_EndRequest(jsdc->dumbContext);

    jsdc->data = NULL;
    jsdc->inited = JS_TRUE;

    JSD_LOCK();
    JS_INSERT_LINK(&jsdc->links, &_jsd_context_list);
    JSD_UNLOCK();

    return jsdc;

label_newJSDContext_failure:
    if( jsdc ) {
        if ( jsdc->dumbContext && jsdc->glob )
            JS_RemoveObjectRootRT(JS_GetRuntime(jsdc->dumbContext), &jsdc->glob);
        jsd_DestroyObjectManager(jsdc);
        jsd_DestroyAtomTable(jsdc);
        if( jsdc->dumbContext )
            JS_EndRequest(jsdc->dumbContext);
        free(jsdc);
    }
    return NULL;
}
Esempio n. 13
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;
}
JSObject* createTestGlobal()
{
    JS::CompartmentOptions options;
    return JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook, options);
}
Esempio n. 15
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);
}
int main(int argc, const char *argv[])
{
	static JSFunctionSpec myjs_global_functions[]={
		JS_FS("rand",myjs_rand,0,0),
		JS_FS("srand",myjs_srand,0,0),
		JS_FS("system",myjs_system,0,0),
		JS_FS_END
	};
	
    /* 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;
    
	
	if(!JS_DefineFunctions(cx,global,myjs_global_functions))
		return JS_FALSE;
 
    /* 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.
     */
    char *script = "var a=ss;";
    jsval rval;
    JSString *str;
    JSBool ok;
    const char *filename = "noname";
    uint32_t lineno = 0;
 
    ok = JS_EvaluateScript(cx, global, script, strlen(script),
                           filename, lineno, &rval);
    if (!ok)
        return 1;
 
    str = JS_ValueToString(cx, rval);
    printf("%s\n", JS_EncodeString(cx, str));
 
    /* End of your application code */
 
    /* Clean things up and shut down SpiderMonkey. */
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return 0;
}
Esempio n. 17
0
nsresult
SaveProfileTask::Run() {
  // Get file path
#if defined(SPS_PLAT_arm_android) && !defined(MOZ_WIDGET_GONK)
  nsCString tmpPath;
  tmpPath.AppendPrintf("/sdcard/profile_%i_%i.txt", XRE_GetProcessType(), getpid());
#else
  nsCOMPtr<nsIFile> tmpFile;
  nsAutoCString tmpPath;
  if (NS_FAILED(NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tmpFile)))) {
    LOG("Failed to find temporary directory.");
    return NS_ERROR_FAILURE;
  }
  tmpPath.AppendPrintf("profile_%i_%i.txt", XRE_GetProcessType(), getpid());

  nsresult rv = tmpFile->AppendNative(tmpPath);
  if (NS_FAILED(rv))
    return rv;

  rv = tmpFile->GetNativePath(tmpPath);
  if (NS_FAILED(rv))
    return rv;
#endif

  // Create a JSContext to run a JSObjectBuilder :(
  // Based on XPCShellEnvironment
  JSRuntime *rt;
  JSContext *cx;
  nsCOMPtr<nsIJSRuntimeService> rtsvc
    = do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
  if (!rtsvc || NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt) {
    LOG("failed to get RuntimeService");
    return NS_ERROR_FAILURE;;
  }

  cx = JS_NewContext(rt, 8192);
  if (!cx) {
    LOG("Failed to get context");
    return NS_ERROR_FAILURE;
  }

  {
    JSAutoRequest ar(cx);
    static const JSClass c = {
      "global", JSCLASS_GLOBAL_FLAGS,
      JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
      JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub
    };
    JSObject *obj = JS_NewGlobalObject(cx, &c, nullptr, JS::FireOnNewGlobalHook);

    std::ofstream stream;
    stream.open(tmpPath.get());
    if (stream.is_open()) {
      JSAutoCompartment autoComp(cx, obj);
      JSObject* profileObj = profiler_get_profile_jsobject(cx);
      JS::Rooted<JS::Value> val(cx, OBJECT_TO_JSVAL(profileObj));
      JS_Stringify(cx, &val, JS::NullPtr(), JS::NullHandleValue, WriteCallback, &stream);
      stream.close();
      LOGF("Saved to %s", tmpPath.get());
    } else {
      LOG("Fail to open profile log file.");
    }
  }
  JS_DestroyContext(cx);

  return NS_OK;
}
Esempio n. 18
0
// static
JSObject*
SimpleGlobalObject::Create(GlobalType globalType, JS::Handle<JS::Value> proto)
{
    // We can't root our return value with our AutoJSAPI because the rooting
    // analysis thinks ~AutoJSAPI can GC.  So we need to root in a scope outside
    // the lifetime of the AutoJSAPI.
    JS::Rooted<JSObject*> global(RootingCx());

    {   // Scope to ensure the AutoJSAPI destructor runs before we end up returning
        AutoJSAPI jsapi;
        jsapi.Init();
        JSContext* cx = jsapi.cx();

        JS::CompartmentOptions options;
        options.creationOptions()
        .setInvisibleToDebugger(true)
        // Put our SimpleGlobalObjects in the system zone, so we won't create
        // lots of zones for what are probably very short-lived
        // compartments.  This should help them be GCed quicker and take up
        // less memory before they're GCed.
        .setZone(JS::SystemZone);

        if (NS_IsMainThread()) {
            nsCOMPtr<nsIPrincipal> principal = nsNullPrincipal::Create();
            options.creationOptions().setTrace(xpc::TraceXPCGlobal);
            global = xpc::CreateGlobalObject(cx, js::Jsvalify(&SimpleGlobalClass),
                                             nsJSPrincipals::get(principal),
                                             options);
        } else {
            global = JS_NewGlobalObject(cx, js::Jsvalify(&SimpleGlobalClass),
                                        nullptr,
                                        JS::DontFireOnNewGlobalHook, options);
        }

        if (!global) {
            jsapi.ClearException();
            return nullptr;
        }

        JSAutoCompartment ac(cx, global);

        // It's important to create the nsIGlobalObject for our new global before we
        // start trying to wrap things like the prototype into its compartment,
        // because the wrap operation relies on the global having its
        // nsIGlobalObject already.
        RefPtr<SimpleGlobalObject> globalObject =
            new SimpleGlobalObject(global, globalType);

        // Pass on ownership of globalObject to |global|.
        JS_SetPrivate(global, globalObject.forget().take());

        if (proto.isObjectOrNull()) {
            JS::Rooted<JSObject*> protoObj(cx, proto.toObjectOrNull());
            if (!JS_WrapObject(cx, &protoObj)) {
                jsapi.ClearException();
                return nullptr;
            }

            if (!JS_SplicePrototype(cx, global, protoObj)) {
                jsapi.ClearException();
                return nullptr;
            }
        } else if (!proto.isUndefined()) {
            // Bogus proto.
            return nullptr;
        }

        JS_FireOnNewGlobalObject(cx, global);
    }

    return global;
}
Esempio n. 19
0
char* launchApp(char *appName,int isMenu){
	static int nruns = 0;
	char* tmp = NULL,*script = NULL, *addrBack = NULL;
	if(appName){
		static JSContext *cx = NULL;
		static JSObject *gl = NULL;
		script = fileToString(LIBRARY);
		if(!(cx = JS_NewContext(runtime, 8192))){
			fprint(stderr,"Problem creating runtime\n");
			exit(EXIT_FAILURE);
		}
		JS_SetErrorReporter(cx, reportError);
		//if(!(gl = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL))){
		
		static struct JSPrincipals def_principles = {0};
		if(!(gl = JS_NewGlobalObject(cx, &global_class, NULL))){
			fprint(stderr,"Problem creating global object\n");
			exit(EXIT_FAILURE);
		}
		JSCompartment *cmp = JS_EnterCompartment(cx, gl);
		
		if (!(JS_InitStandardClasses(cx, gl))){
			fprint(stderr,"Problem creating standard classes\n");
			exit(EXIT_FAILURE);
		}
		if(!JS_DefineFunctions(cx, gl, jsFunctions)){
			fprint(stderr,"Unable to load native functions\n");
			exit(EXIT_FAILURE);
		}
		globalObject = gl;
		char *pathToFile = NULL;
		if(isMenu){
			pathToFile = (char*)malloc(1+strlen(MENU_DIR));
			strcpy(pathToFile,MENU_DIR);
		} else {
			pathToFile = (char*)malloc(strlen(appName) + 1 + strlen(GAMES_DIR));
			strcpy(pathToFile,GAMES_DIR);
			strcat(pathToFile,appName);
			//strcat(pathToFile,"/");
		}
		
		
		JSBool ran = JS_FALSE;
		jsval retVal;
		
		obj.chrootPath = pathToFile;
		
		JS_SetPrivate(cx,gl,&obj);
		
		SDL_FlushEvents(); //clear queue of events before starting a new app.
		if(isMenu && 0 == nruns) {
			//define the property first_run = true;
			JS_DefineProperty(cx,JS_GetGlobalObject(cx),"first_run",BOOLEAN_TO_JSVAL(JS_TRUE),NULL,NULL,0);
		}
		
		if(script){
			loadBaseClasses(appName,pathToFile,cx); //appName is without the extension, appPath needs the directory to chroot
			ran = JS_EvaluateScript(cx, gl, script, strlen(script) , LIBRARY,0, &retVal);
		}
		nruns++;
		
		clearModules(cx);
		JS_GC(JS_GetRuntime(cx));
		JS_LeaveCompartment(cx,cmp);
		//The user requested to quit.
		if(SDL_QuitRequested()){
			if(script)free(script);
			exitProgram(cx);
			exit(EXIT_SUCCESS);
		}

		if(isMenu && (ran == JS_FALSE)){
			if(script) free(script);
			exitProgram(cx);
			exit(EXIT_FAILURE);
		}
		if(ran != JS_FALSE){
			if(JSVAL_IS_STRING(retVal)){
				addrBack = JS_EncodeString(cx,JSVAL_TO_STRING(retVal));
				tmp = (char*)malloc(strlen(addrBack) +1);
				strcpy(tmp,addrBack);
				JS_free(cx,addrBack);
				addrBack = tmp;
			} 
			if(JSVAL_IS_BOOLEAN(retVal) && isMenu){
				if(script) free(script);
				if(pathToFile) free(pathToFile);
				exitProgram(cx);
				exit(EXIT_SUCCESS);
			}
		} else {
			addrBack = NULL;
		}
		if(script) free(script);
		if(pathToFile) free(pathToFile);
		JS_DestroyContext(cx);
		return addrBack;
	}
}
JSObject *createTestGlobal()
{
    JS::CompartmentOptions options;
    options.setVersion(JSVERSION_LATEST);
    return JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook, options);
}