int runWithContext()

in src/couch/priv/couch_js/102/main.cpp [245:309]


int runWithContext(JSContext* cx, couch_args* args) {
    JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_BASELINE_ENABLE, 0);
    JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_ION_ENABLE, 0);

    if (!JS::InitSelfHostedCode(cx))
        return 1;

    JS::SetWarningReporter(cx, couch_error);
    JS::SetOutOfMemoryCallback(cx, couch_oom, NULL);
    JS_SetContextPrivate(cx, args);
    JS_SetSecurityCallbacks(cx, &security_callbacks);

    JS::RealmOptions options;
    // we need this in the query server error handling
    options.creationOptions().setToSourceEnabled(enableToSource);
    JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr,
                                                   JS::FireOnNewGlobalHook, options));
    if (!global)
        return 1;

    JSAutoRealm ar(cx, global);

    if(!JS::InitRealmStandardClasses(cx))
        return 1;

    if(couch_load_funcs(cx, global, global_functions) != true)
        return 1;

    for(int i = 0 ; args->scripts[i] ; i++) {
        const char* filename = args->scripts[i];

        // Compile and run
        JS::CompileOptions options(cx);
        JS::RootedScript script(cx);

        script = JS::CompileUtf8Path(cx, options, filename);
        if (!script) {
            JS::RootedValue exc(cx);
            if(!JS_GetPendingException(cx, &exc)) {
                fprintf(stderr, "Failed to compile file: %s\n", filename);
            } else {
                JS::RootedObject exc_obj(cx, &exc.toObject());
                JSErrorReport* report = JS_ErrorFromException(cx, exc_obj);
                couch_error(cx, report);
            }
            return 1;
        }

        JS::RootedValue result(cx);
        if(JS_ExecuteScript(cx, script, &result) != true) {
            JS::RootedValue exc(cx);
            if(!JS_GetPendingException(cx, &exc)) {
                fprintf(stderr, "Failed to execute script.\n");
            } else {
                JS::RootedObject exc_obj(cx, &exc.toObject());
                JSErrorReport* report = JS_ErrorFromException(cx, exc_obj);
                couch_error(cx, report);
            }
        }

        // Give the GC a chance to run.
        JS_MaybeGC(cx);
    }
    return 0;
}