void
InitGlobalObjectOptions(JS::CompartmentOptions& aOptions,
                        nsIPrincipal* aPrincipal)
{
    bool shouldDiscardSystemSource = ShouldDiscardSystemSource();
    bool extraWarningsForSystemJS = ExtraWarningsForSystemJS();

    bool isSystem = nsContentUtils::IsSystemPrincipal(aPrincipal);

    if (isSystem) {
        // Make sure [SecureContext] APIs are visible:
        aOptions.creationOptions().setSecureContext(true);
    }

    short status = aPrincipal->GetAppStatus();

    // Enable the ECMA-402 experimental formatToParts in certified apps.
    if (status == nsIPrincipal::APP_STATUS_CERTIFIED) {
        aOptions.creationOptions()
                .setExperimentalDateTimeFormatFormatToPartsEnabled(true);
    }

    if (shouldDiscardSystemSource) {
        bool discardSource = isSystem ||
                             (status == nsIPrincipal::APP_STATUS_PRIVILEGED ||
                              status == nsIPrincipal::APP_STATUS_CERTIFIED);

        aOptions.behaviors().setDiscardSource(discardSource);
    }

    if (extraWarningsForSystemJS) {
        if (isSystem)
            aOptions.behaviors().extraWarningsOverride().set(true);
    }
}
Esempio n. 2
0
void
InitGlobalObjectOptions(JS::CompartmentOptions& aOptions,
                        nsIPrincipal* aPrincipal)
{
    bool shouldDiscardSystemSource = ShouldDiscardSystemSource();
    bool extraWarningsForSystemJS = ExtraWarningsForSystemJS();

    bool isSystem = nsContentUtils::IsSystemPrincipal(aPrincipal);

    if (isSystem) {
        // Make sure [SecureContext] APIs are visible:
        aOptions.creationOptions().setSecureContext(true);

#if 0 // TODO: Reenable in Bug 1288653
        // Enable the ECMA-402 experimental formatToParts in any chrome page
        aOptions.creationOptions()
                .setExperimentalDateTimeFormatFormatToPartsEnabled(true);
#endif
    }

    if (shouldDiscardSystemSource) {
        bool discardSource = isSystem;

        aOptions.behaviors().setDiscardSource(discardSource);
    }

    if (extraWarningsForSystemJS) {
        if (isSystem)
            aOptions.behaviors().extraWarningsOverride().set(true);
    }
}
Esempio n. 3
0
bool
DedicatedWorkerGlobalScope::WrapGlobalObject(JSContext* aCx,
                                             JS::MutableHandle<JSObject*> aReflector)
{
  mWorkerPrivate->AssertIsOnWorkerThread();
  MOZ_ASSERT(!mWorkerPrivate->IsSharedWorker());

  JS::CompartmentOptions options;
  mWorkerPrivate->CopyJSCompartmentOptions(options);

  const bool usesSystemPrincipal = mWorkerPrivate->UsesSystemPrincipal();

  // Note that xpc::ShouldDiscardSystemSource() and
  // xpc::ExtraWarningsForSystemJS() read prefs that are cached on the main
  // thread. This is benignly racey.
  const bool discardSource = usesSystemPrincipal &&
                             xpc::ShouldDiscardSystemSource();
  const bool extraWarnings = usesSystemPrincipal &&
                             xpc::ExtraWarningsForSystemJS();

  JS::CompartmentBehaviors& behaviors = options.behaviors();
  behaviors.setDiscardSource(discardSource)
           .extraWarningsOverride().set(extraWarnings);

  const bool sharedMemoryEnabled = xpc::SharedMemoryEnabled();

  JS::CompartmentCreationOptions& creationOptions = options.creationOptions();
  creationOptions.setSharedMemoryAndAtomicsEnabled(sharedMemoryEnabled);

  return DedicatedWorkerGlobalScopeBinding::Wrap(aCx, this, this,
                                                 options,
                                                 GetWorkerPrincipal(),
                                                 true, aReflector);
}
Esempio n. 4
0
JSCompartment::JSCompartment(Zone* zone, const JS::CompartmentOptions& options = JS::CompartmentOptions())
  : creationOptions_(options.creationOptions()),
    behaviors_(options.behaviors()),
    zone_(zone),
    runtime_(zone->runtimeFromAnyThread()),
    principals_(nullptr),
    isSystem_(false),
    isAtomsCompartment_(false),
    isSelfHosting(false),
    marked(true),
    warnedAboutExprClosure(false),
    warnedAboutStringGenericsMethods(0),
#ifdef DEBUG
    firedOnNewGlobalObject(false),
#endif
    global_(nullptr),
    enterCompartmentDepth(0),
    globalHolds(0),
    performanceMonitoring(runtime_),
    data(nullptr),
    realmData(nullptr),
    allocationMetadataBuilder(nullptr),
    lastAnimationTime(0),
    regExps(),
    arraySpeciesLookup(),
    globalWriteBarriered(0),
    detachedTypedObjects(0),
    objectMetadataState(ImmediateMetadata()),
    selfHostingScriptSource(nullptr),
    objectMetadataTable(nullptr),
    innerViews(zone),
    lazyArrayBuffers(nullptr),
    wasm(zone),
    nonSyntacticLexicalEnvironments_(nullptr),
    gcIncomingGrayPointers(nullptr),
    debugModeBits(0),
    validAccessPtr(nullptr),
    randomKeyGenerator_(runtime_->forkRandomKeyGenerator()),
    scriptCountsMap(nullptr),
    scriptNameMap(nullptr),
    debugScriptMap(nullptr),
    debugEnvs(nullptr),
    enumerators(nullptr),
    compartmentStats_(nullptr),
    scheduledForDestruction(false),
    maybeAlive(true),
    jitCompartment_(nullptr),
    mappedArgumentsTemplate_(nullptr),
    unmappedArgumentsTemplate_(nullptr),
    iterResultTemplate_(nullptr),
    lcovOutput()
{
    PodArrayZero(sawDeprecatedLanguageExtension);
    runtime_->numCompartments++;
    MOZ_ASSERT_IF(creationOptions_.mergeable(),
                  creationOptions_.invisibleToDebugger());
}
Esempio n. 5
0
JSCompartment::JSCompartment(Zone* zone, const JS::CompartmentOptions& options = JS::CompartmentOptions())
  : creationOptions_(options.creationOptions()),
    behaviors_(options.behaviors()),
    zone_(zone),
    runtime_(zone->runtimeFromMainThread()),
    principals_(nullptr),
    isSystem_(false),
    isSelfHosting(false),
    marked(true),
    warnedAboutExprClosure(false),
#ifdef DEBUG
    firedOnNewGlobalObject(false),
#endif
    global_(nullptr),
    enterCompartmentDepth(0),
    performanceMonitoring(runtime_),
    data(nullptr),
    allocationMetadataBuilder(nullptr),
    lastAnimationTime(0),
    regExps(runtime_),
    globalWriteBarriered(0),
    detachedTypedObjects(0),
    objectMetadataState(ImmediateMetadata()),
    propertyTree(thisForCtor()),
    baseShapes(zone, BaseShapeSet()),
    initialShapes(zone, InitialShapeSet()),
    selfHostingScriptSource(nullptr),
    objectMetadataTable(nullptr),
    lazyArrayBuffers(nullptr),
    wasmInstances(zone, WasmInstanceObjectSet()),
    nonSyntacticLexicalScopes_(nullptr),
    gcIncomingGrayPointers(nullptr),
    debugModeBits(0),
    watchpointMap(nullptr),
    scriptCountsMap(nullptr),
    debugScriptMap(nullptr),
    debugScopes(nullptr),
    enumerators(nullptr),
    compartmentStats_(nullptr),
    scheduledForDestruction(false),
    maybeAlive(true),
    jitCompartment_(nullptr),
    mappedArgumentsTemplate_(nullptr),
    unmappedArgumentsTemplate_(nullptr),
    lcovOutput()
{
    PodArrayZero(sawDeprecatedLanguageExtension);
    runtime_->numCompartments++;
    MOZ_ASSERT_IF(creationOptions_.mergeable(),
                  creationOptions_.invisibleToDebugger());
}
Esempio n. 6
0
int
main(int argc, const char** argv)
{
    if (!JS_Init()) return 1;
    JSContext* cx = checkPtr(JS_NewContext(1024 * 1024));

    JS_SetGCParameter(cx, JSGC_MAX_BYTES, 0xffffffff);
    JS_SetNativeStackQuota(cx, 5000000);

    checkBool(JS::InitSelfHostedCode(cx));
    JS::SetWarningReporter(cx, reportWarning);

    JSAutoRequest ar(cx);

    /* Create the global object. */
    JS::CompartmentOptions options;
    options.behaviors().setVersion(JSVERSION_LATEST);

    RootedObject global(cx, checkPtr(JS_NewGlobalObject(cx, &global_class,
                        nullptr, JS::FireOnNewGlobalHook, options)));
    JSAutoCompartment ac(cx, global);

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

    argv++;
    while (*argv) {
        const char* name = *argv++;
        GDBFragment* fragment;
        for (fragment = GDBFragment::allFragments; fragment; fragment = fragment->next) {
            if (strcmp(fragment->name(), name) == 0) {
                fragment->run(cx, argv);
                break;
            }
        }
        if (!fragment) {
            fprintf(stderr, "Unrecognized fragment name: %s\n", name);
            exit(1);
        }
    }

    return 0;
}
Esempio n. 7
0
static void
CreateGlobalAndRunTest(JSRuntime* rt, JSContext* cx)
{
  static const JSClass GlobalClass = {
    "global", JSCLASS_GLOBAL_FLAGS,
    nullptr, nullptr, nullptr, nullptr,
    nullptr, nullptr, nullptr, nullptr,
    nullptr, nullptr, nullptr,
    JS_GlobalObjectTraceHook
  };

  JS::CompartmentOptions options;
  options.behaviors().setVersion(JSVERSION_LATEST);
  JS::PersistentRootedObject global(cx);
  global = JS_NewGlobalObject(cx, &GlobalClass, nullptr, JS::FireOnNewGlobalHook, options);
  ASSERT_TRUE(global != nullptr);

  JSCompartment *oldCompartment = JS_EnterCompartment(cx, global);

  typedef Heap<JSObject*> ElementT;

  {
    nsTArray<ElementT>* array = new nsTArray<ElementT>(InitialElements);
    RunTest(rt, cx, array);
    delete array;
  }

  {
    FallibleTArray<ElementT>* array = new FallibleTArray<ElementT>(InitialElements);
    RunTest(rt, cx, array);
    delete array;
  }

  {
    AutoTArray<ElementT, InitialElements> array;
    RunTest(rt, cx, &array);
  }

  JS_LeaveCompartment(cx, oldCompartment);
}
Esempio n. 8
0
bool
XPCShellEnvironment::Init()
{
    nsresult rv;

    // unbuffer stdout so that output is in the correct order; note that stderr
    // is unbuffered by default
    setbuf(stdout, 0);

    AutoSafeJSContext cx;

    mGlobalHolder.init(cx);

    nsCOMPtr<nsIXPConnect> xpc =
      do_GetService(nsIXPConnect::GetCID());
    if (!xpc) {
        NS_ERROR("failed to get nsXPConnect service!");
        return false;
    }

    nsCOMPtr<nsIPrincipal> principal;
    nsCOMPtr<nsIScriptSecurityManager> securityManager =
        do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
    if (NS_SUCCEEDED(rv) && securityManager) {
        rv = securityManager->GetSystemPrincipal(getter_AddRefs(principal));
        if (NS_FAILED(rv)) {
            fprintf(stderr, "+++ Failed to obtain SystemPrincipal from ScriptSecurityManager service.\n");
        }
    } else {
        fprintf(stderr, "+++ Failed to get ScriptSecurityManager service, running without principals");
    }

    RefPtr<BackstagePass> backstagePass;
    rv = NS_NewBackstagePass(getter_AddRefs(backstagePass));
    if (NS_FAILED(rv)) {
        NS_ERROR("Failed to create backstage pass!");
        return false;
    }

    JS::CompartmentOptions options;
    options.creationOptions().setSystemZone();
    options.behaviors().setVersion(JSVERSION_LATEST);
    if (xpc::SharedMemoryEnabled())
        options.creationOptions().setSharedMemoryAndAtomicsEnabled(true);

    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    rv = xpc->InitClassesWithNewWrappedGlobal(cx,
                                              static_cast<nsIGlobalObject *>(backstagePass),
                                              principal, 0,
                                              options,
                                              getter_AddRefs(holder));
    if (NS_FAILED(rv)) {
        NS_ERROR("InitClassesWithNewWrappedGlobal failed!");
        return false;
    }

    JS::Rooted<JSObject*> globalObj(cx, holder->GetJSObject());
    if (!globalObj) {
        NS_ERROR("Failed to get global JSObject!");
        return false;
    }
    JSAutoCompartment ac(cx, globalObj);

    backstagePass->SetGlobalObject(globalObj);

    JS::Rooted<Value> privateVal(cx, PrivateValue(this));
    if (!JS_DefineProperty(cx, globalObj, "__XPCShellEnvironment",
                           privateVal,
                           JSPROP_READONLY | JSPROP_PERMANENT,
                           JS_STUBGETTER, JS_STUBSETTER) ||
        !JS_DefineFunctions(cx, globalObj, gGlobalFunctions) ||
        !JS_DefineProfilingFunctions(cx, globalObj))
    {
        NS_ERROR("JS_DefineFunctions failed!");
        return false;
    }

    mGlobalHolder = globalObj;

    FILE* runtimeScriptFile = fopen(kDefaultRuntimeScriptFilename, "r");
    if (runtimeScriptFile) {
        fprintf(stdout, "[loading '%s'...]\n", kDefaultRuntimeScriptFilename);
        ProcessFile(cx, kDefaultRuntimeScriptFilename,
                    runtimeScriptFile, false);
        fclose(runtimeScriptFile);
    }

    return true;
}