Пример #1
0
static JSBool edjsdb_Construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) {
    JSBool ok = JS_TRUE;
    JSObject *proto_obj = NULL;
    JSObject *ret_obj = NULL;
    edjsdb_private *p = NULL;
    JSString *type = NULL;
    char *mod_name = NULL;
    char *mod_path = NULL;
    struct stat *file_stat = NULL;
    JSBool (*db_driver_init)(JSContext *, JSObject *) = NULL;
    edjs_private *edjs_p = NULL;
    jsval path_val = JSVAL_VOID;
    JSObject *path_obj = NULL;


    JSFunctionSpec my_methods[] = {
        {"connect", edjsdb_connect, 1, JSPROP_ENUMERATE, 0},
        {"close", edjsdb_close, 0, 0, 0},
        {"query", edjsdb_query, 1, 0, 0},
        {"exec", edjsdb_exec, 1, 0, 0},
        {"createSequence", edjsdb_create_sequence, 1, 0, 0},
        {"dropSequence", edjsdb_drop_sequence, 1, 0, 0}, 
        {"listSequences", edjsdb_list_sequences, 0, 0, 0}, 
        {"nextID", edjsdb_next_id, 1, 0, 0},
        {"currentID", edjsdb_current_id, 1, 0, 0},
        {"quote", edjsdb_quote, 1, 0, 0},
        {0, 0, 0, 0, 0}
    };

    if (argc != 1) {
        //report error
        goto error;
    }

    JS_AddRoot(cx, &type);

    proto_obj = JS_NewObject(cx, NULL, NULL, NULL);
    if (NULL == proto_obj) {
        //throw error
        goto error;
    }
    *rval = OBJECT_TO_JSVAL(proto_obj); //root proto_obj

    if (JS_FALSE == JS_DefineFunctions(cx, proto_obj, my_methods)) {
        //report error
        goto error;
    }

    ret_obj = JS_NewObject(cx, &edjsdb_class, proto_obj, NULL);//JS_ConstructObjectWithArguments(cx, &edjsdb_class, NULL, NULL, argc, argv);

    if (NULL == ret_obj) {
        //throw error
        goto error;
    }
    *rval = OBJECT_TO_JSVAL(ret_obj); //root ret_obj

    p = (edjsdb_private *)EDJS_malloc(cx, sizeof(edjsdb_private));
    if (NULL == p) {
        goto error;
    }

    p->db_connection = NULL;
    p->lib_handle = NULL;
    p->finalize_func = edjsdb_finalize_stub;
    p->connect_func = edjsdb_connect_stub;
    p->close_func = edjsdb_close_stub;
    p->query_func = edjsdb_func_stub;
    p->exec_func = edjsdb_func_stub;
    p->create_sequence_func = edjsdb_func_stub;
    p->drop_sequence_func = edjsdb_func_stub;
    p->list_sequences_func = edjsdb_func_stub;
    p->next_id_func = edjsdb_func_stub;
    p->current_id_func = edjsdb_func_stub;
    p->quote_func = edjsdb_func_stub;


    if (JS_FALSE == JS_SetPrivate(cx, ret_obj, p)) {
        //report error
        goto error;
    }

    if (JS_FALSE == JS_DefineProperty(cx, ret_obj, "type", argv[0], NULL, NULL, JSPROP_ENUMERATE | JSPROP_READONLY)) {
        //report error
        goto error;
    }

    type = JS_ValueToString(cx, *argv);
    if (NULL == type) {
        //report error
        goto error;
    }

    mod_name = (char *)EDJS_malloc(cx, (7 + strlen(JS_GetStringBytes(type))) * sizeof(char)); //7 for db_.so\0
    strcpy(mod_name, "db_");
    strcat(mod_name, JS_GetStringBytes(type));
    strcat(mod_name, ".so");

    edjs_p = (edjs_private *)JS_GetContextPrivate(cx);

    if (JS_FALSE == JS_GetProperty(cx, edjs_p->settings_obj, "include_path", &path_val)) {
        //EDJS_ERR(cx, EDJSERR_GET_PROPERTY, "EDJS", "include_path");
        goto error;
    }

    path_obj = JSVAL_TO_OBJECT(path_val);

    if (JS_FALSE == EDJS_ResolveFile(cx, path_obj, NULL, mod_name, &mod_path, &file_stat)) {
        goto error;
    }

    if (NULL == mod_path) {
        //EDJS_ERR(cx, EDJSERR_FILENAME_RESOLVE, JS_GetStringBytes(include_str));
        goto error;
    }

    p->lib_handle = dlopen(mod_path, RTLD_NOW);
    char *dl_error = NULL;

    //if (NULL == p->lib_handle) {
    if ((dl_error = dlerror()) != NULL) {
        p->lib_handle = NULL;
        JS_ReportError(cx, dl_error);
        goto error;
    }


    db_driver_init = dlsym(p->lib_handle, "edjsdb_driver_instance_init");

    //    if (NULL == db_driver_init) {
    if ((dl_error = dlerror()) != NULL) {
        JS_ReportError(cx, dl_error);
        //JS_ReportError(cx, "failed to load edjsdb_driver_instance_init");
        goto error;
    }

    ok = db_driver_init(cx, ret_obj);
    if (JS_FALSE == ok) {
        JS_ReportError(cx, "driver failed its init method");
        goto error;
    }


    goto finish;
 error:
    ok = JS_FALSE;
    *rval = JSVAL_VOID;

 finish:
    JS_RemoveRoot(cx, &type);
    return ok;
}
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;
}
Пример #3
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;
}
Пример #4
0
int
js_plugin_load(const char *id, const char *url, char *errbuf, size_t errlen)
{
  char *sbuf;
  size_t size;
  JSContext *cx;
  js_plugin_t *jsp;
  JSObject *pobj, *gobj;
  JSScript *s;
  char path[PATH_MAX];
  jsval val;
  fa_handle_t *ref;
  
  ref = fa_reference(url);

  if((sbuf = fa_load(url, &size, NULL, errbuf, errlen, NULL)) == NULL) {
    fa_unreference(ref);
    return -1;
  }

  cx = js_newctx(err_reporter);
  JS_BeginRequest(cx);

  /* Remove any plugin with same URL */
  LIST_FOREACH(jsp, &js_plugins, jsp_link)
    if(!strcmp(jsp->jsp_id, id))
      break;
  if(jsp != NULL)
    js_plugin_unload0(cx, jsp);

  jsp = calloc(1, sizeof(js_plugin_t));
  jsp->jsp_url = strdup(url);
  jsp->jsp_id  = strdup(id);
  jsp->jsp_ref = ref;
  
  LIST_INSERT_HEAD(&js_plugins, jsp, jsp_link);

  gobj = JS_NewObject(cx, &global_class, NULL, NULL);
  JS_InitStandardClasses(cx, gobj);

  JS_DefineProperty(cx, gobj, "showtime", OBJECT_TO_JSVAL(showtimeobj),
		    NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT);

  /* Plugin object */
  pobj = JS_NewObject(cx, &plugin_class, NULL, gobj);
  JS_AddNamedRoot(cx, &pobj, "plugin");

  JS_SetPrivate(cx, pobj, jsp);

  JS_DefineFunctions(cx, pobj, plugin_functions);


  val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, url));
  JS_SetProperty(cx, pobj, "url", &val);

  if(!fa_parent(path, sizeof(path), url)) {
    val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, path));
    JS_SetProperty(cx, pobj, "path", &val);
  }

  JS_DefineProperty(cx, pobj, "URIRouting", BOOLEAN_TO_JSVAL(1),
		    NULL, jsp_setEnableURIRoute, JSPROP_PERMANENT);
  jsp->jsp_enable_uri_routing = 1;

  JS_DefineProperty(cx, pobj, "search", BOOLEAN_TO_JSVAL(1),
		    NULL, jsp_setEnableSearch, JSPROP_PERMANENT);
  jsp->jsp_enable_search = 1;

  jsp->jsp_protect_object = 1;

  s = JS_CompileScript(cx, pobj, sbuf, size, url, 1);
  free(sbuf);

  if(s != NULL) {
    JSObject *sobj = JS_NewScriptObject(cx, s);
    jsval result;

    JS_AddNamedRoot(cx, &sobj, "script");
    JS_ExecuteScript(cx, pobj, s, &result);
    JS_RemoveRoot(cx, &sobj);
  }

  JS_RemoveRoot(cx, &pobj);
  JS_EndRequest(cx);
  JS_GC(cx);
  JS_DestroyContext(cx);
  return 0;
}
Пример #5
0
JSBool
ncurses_initialize (JSContext* cx)
{
    JSObject* object = JS_DefineObject(
        cx, JS_GetGlobalObject(cx),
        ncurses_class.name, &ncurses_class, NULL, 
        JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE
    );

    if (object) {
        JS_DefineFunctions(cx, object, ncurses_methods);

        jsval property;

        JSObject* Buffering   = JS_NewObject(cx, NULL, NULL, NULL);
        jsval     jsBuffering = OBJECT_TO_JSVAL(Buffering);
        JS_SetProperty(cx, object, "Buffering", &jsBuffering);
            property = INT_TO_JSVAL(1);
            JS_SetProperty(cx, Buffering, "Normal", &property);
            property = INT_TO_JSVAL(2);
            JS_SetProperty(cx, Buffering, "Raw", &property);
            property = INT_TO_JSVAL(3);
            JS_SetProperty(cx, Buffering, "CBreak", &property);

        JSObject* Colors   = JS_NewObject(cx, NULL, NULL, NULL);
        jsval     jsColors = OBJECT_TO_JSVAL(Colors);
        JS_SetProperty(cx, object, "Colors", &jsColors);
            property = INT_TO_JSVAL(-1);
            JS_SetProperty(cx, Colors, "Normal", &property);
            property = INT_TO_JSVAL(COLOR_BLACK);
            JS_SetProperty(cx, Colors, "Black", &property);
            property = INT_TO_JSVAL(COLOR_RED);
            JS_SetProperty(cx, Colors, "Red", &property);
            property = INT_TO_JSVAL(COLOR_GREEN);
            JS_SetProperty(cx, Colors, "Green", &property);
            property = INT_TO_JSVAL(COLOR_YELLOW);
            JS_SetProperty(cx, Colors, "Yellow", &property);
            property = INT_TO_JSVAL(COLOR_BLUE);
            JS_SetProperty(cx, Colors, "Blue", &property);
            property = INT_TO_JSVAL(COLOR_MAGENTA);
            JS_SetProperty(cx, Colors, "Magenta", &property);
            property = INT_TO_JSVAL(COLOR_CYAN);
            JS_SetProperty(cx, Colors, "Cyan", &property);
            property = INT_TO_JSVAL(COLOR_WHITE);
            JS_SetProperty(cx, Colors, "White", &property);

        JSObject* Attributes   = JS_NewObject(cx, NULL, NULL, NULL);
        jsval     jsAttributes = OBJECT_TO_JSVAL(Attributes);
        JS_SetProperty(cx, object, "Attributes", &jsAttributes);
            property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight)
            JS_SetProperty(cx, Attributes, "Normal", &property);
            property = INT_TO_JSVAL(A_BLINK); // Blinking
            JS_SetProperty(cx, Attributes, "Blink", &property);
            property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold
            JS_SetProperty(cx, Attributes, "Bold", &property);
            property = INT_TO_JSVAL(A_DIM); // Half bright
            JS_SetProperty(cx, Attributes, "Dim", &property);
            property = INT_TO_JSVAL(A_REVERSE); // Reverse video
            JS_SetProperty(cx, Attributes, "Reverse", &property);
            property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal.
            JS_SetProperty(cx, Attributes, "Standout", &property);
            property = INT_TO_JSVAL(A_UNDERLINE); // Underlining
            JS_SetProperty(cx, Attributes, "Underline", &property);
            property = INT_TO_JSVAL(A_PROTECT); // Protected mode
            JS_SetProperty(cx, Attributes, "Protect", &property);
            property = INT_TO_JSVAL(A_INVIS);
            JS_SetProperty(cx, Attributes, "Invisible", &property);

        JSObject* Cursor   = JS_NewObject(cx, NULL, NULL, NULL);
        jsval     jsCursor = OBJECT_TO_JSVAL(Cursor);
        JS_SetProperty(cx, object, "Cursor", &jsCursor);
            property = INT_TO_JSVAL(0);
            JS_SetProperty(cx, Cursor, "Invisible", &property);
            property = INT_TO_JSVAL(1);
            JS_SetProperty(cx, Cursor, "Normal", &property);
            property = INT_TO_JSVAL(2);
            JS_SetProperty(cx, Cursor, "Visible", &property);

        JSObject* Keys   = JS_NewObject(cx, NULL, NULL, NULL);
        jsval     jsKeys = OBJECT_TO_JSVAL(Keys);
        JS_SetProperty(cx, object, "Keys", &jsKeys);
            property = INT_TO_JSVAL(KEY_BREAK);
            JS_SetProperty(cx, Keys, "Break", &property);
            property = INT_TO_JSVAL(KEY_DOWN);
            JS_SetProperty(cx, Keys, "Down", &property);
            property = INT_TO_JSVAL(KEY_UP);
            JS_SetProperty(cx, Keys, "Up", &property);
            property = INT_TO_JSVAL(KEY_LEFT);
            JS_SetProperty(cx, Keys, "Left", &property);
            property = INT_TO_JSVAL(KEY_RIGHT);
            JS_SetProperty(cx, Keys, "Right", &property);
            property = INT_TO_JSVAL(KEY_HOME);
            JS_SetProperty(cx, Keys, "Home", &property);
            property = INT_TO_JSVAL(KEY_BACKSPACE);
            JS_SetProperty(cx, Keys, "Backspace", &property);
            property = OBJECT_TO_JSVAL(JS_GetFunctionObject(
                JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F")
            ));
            JS_SetProperty(cx, Keys, "F", &property);
            property = INT_TO_JSVAL(KEY_DL);
            JS_SetProperty(cx, Keys, "DeleteLine", &property);
            property = INT_TO_JSVAL(KEY_IL);
            JS_SetProperty(cx, Keys, "InsertLine", &property);
            property = INT_TO_JSVAL(KEY_DC);
            JS_SetProperty(cx, Keys, "DeleteChar", &property);
            property = INT_TO_JSVAL(KEY_IC);
            JS_SetProperty(cx, Keys, "EnterInsertMode", &property);
            property = INT_TO_JSVAL(KEY_EIC);
            JS_SetProperty(cx, Keys, "EndInsertMode", &property);
            property = INT_TO_JSVAL(KEY_CLEAR);
            JS_SetProperty(cx, Keys, "Clear", &property);
            property = INT_TO_JSVAL(KEY_EOS);
            JS_SetProperty(cx, Keys, "EndOfScreen", &property);
            property = INT_TO_JSVAL(KEY_EOL);
            JS_SetProperty(cx, Keys, "EndOfLine", &property);
            property = INT_TO_JSVAL(KEY_SF);
            JS_SetProperty(cx, Keys, "ScrollForward", &property);
            property = INT_TO_JSVAL(KEY_SR);
            JS_SetProperty(cx, Keys, "ScrollBackward", &property);
            property = INT_TO_JSVAL(KEY_NPAGE);
            JS_SetProperty(cx, Keys, "NextPage", &property);
            property = INT_TO_JSVAL(KEY_PPAGE);
            JS_SetProperty(cx, Keys, "PreviousPage", &property);
            property = INT_TO_JSVAL(KEY_STAB);
            JS_SetProperty(cx, Keys, "SetTab", &property);
            property = INT_TO_JSVAL(KEY_CTAB);
            JS_SetProperty(cx, Keys, "ClearTab", &property);
            property = INT_TO_JSVAL(KEY_CATAB);
            JS_SetProperty(cx, Keys, "ClearAllTabs", &property);
            property = INT_TO_JSVAL(KEY_ENTER);
            JS_SetProperty(cx, Keys, "Enter", &property);
            property = INT_TO_JSVAL(KEY_SRESET);
            JS_SetProperty(cx, Keys, "SoftReset", &property);
            property = INT_TO_JSVAL(KEY_RESET);
            JS_SetProperty(cx, Keys, "Reset", &property);
            property = INT_TO_JSVAL(KEY_PRINT);
            JS_SetProperty(cx, Keys, "Print", &property);
            property = INT_TO_JSVAL(KEY_LL);
            JS_SetProperty(cx, Keys, "Bottom", &property);
            property = INT_TO_JSVAL(KEY_A1);
            JS_SetProperty(cx, Keys, "UpperLeft", &property);
            property = INT_TO_JSVAL(KEY_A3);
            JS_SetProperty(cx, Keys, "UpperRight", &property);
            property = INT_TO_JSVAL(KEY_B2);
            JS_SetProperty(cx, Keys, "Center", &property);
            property = INT_TO_JSVAL(KEY_C1);
            JS_SetProperty(cx, Keys, "LowerLeft", &property);
            property = INT_TO_JSVAL(KEY_C3);
            JS_SetProperty(cx, Keys, "LowerRight", &property);
            property = INT_TO_JSVAL(KEY_BTAB);
            JS_SetProperty(cx, Keys, "BackTab", &property);
            property = INT_TO_JSVAL(KEY_BEG);
            JS_SetProperty(cx, Keys, "Beginning", &property);
            property = INT_TO_JSVAL(KEY_CANCEL);
            JS_SetProperty(cx, Keys, "Cancel", &property);
            property = INT_TO_JSVAL(KEY_CLOSE);
            JS_SetProperty(cx, Keys, "Close", &property);
            property = INT_TO_JSVAL(KEY_COMMAND);
            JS_SetProperty(cx, Keys, "Command", &property);
            property = INT_TO_JSVAL(KEY_COPY);
            JS_SetProperty(cx, Keys, "Copy", &property);
            property = INT_TO_JSVAL(KEY_CREATE);
            JS_SetProperty(cx, Keys, "Create", &property);
            property = INT_TO_JSVAL(KEY_END);
            JS_SetProperty(cx, Keys, "End", &property);
            property = INT_TO_JSVAL(KEY_EXIT);
            JS_SetProperty(cx, Keys, "Exit", &property);
            property = INT_TO_JSVAL(KEY_FIND);
            JS_SetProperty(cx, Keys, "Find", &property);
            property = INT_TO_JSVAL(KEY_HELP);
            JS_SetProperty(cx, Keys, "Help", &property);
            property = INT_TO_JSVAL(KEY_MARK);
            JS_SetProperty(cx, Keys, "Mark", &property);
            property = INT_TO_JSVAL(KEY_MESSAGE);
            JS_SetProperty(cx, Keys, "Message", &property);
            property = INT_TO_JSVAL(KEY_MOUSE);
            JS_SetProperty(cx, Keys, "Mouse", &property);
            property = INT_TO_JSVAL(KEY_MOVE);
            JS_SetProperty(cx, Keys, "Move", &property);
            property = INT_TO_JSVAL(KEY_NEXT);
            JS_SetProperty(cx, Keys, "Next", &property);
            property = INT_TO_JSVAL(KEY_OPEN);
            JS_SetProperty(cx, Keys, "Open", &property);
            property = INT_TO_JSVAL(KEY_OPTIONS);
            JS_SetProperty(cx, Keys, "Options", &property);
            property = INT_TO_JSVAL(KEY_PREVIOUS);
            JS_SetProperty(cx, Keys, "Previous", &property);
            property = INT_TO_JSVAL(KEY_REDO);
            JS_SetProperty(cx, Keys, "Redo", &property);
            property = INT_TO_JSVAL(KEY_REFERENCE);
            JS_SetProperty(cx, Keys, "Reference", &property);
            property = INT_TO_JSVAL(KEY_REFRESH);
            JS_SetProperty(cx, Keys, "Refresh", &property);
            property = INT_TO_JSVAL(KEY_REPLACE);
            JS_SetProperty(cx, Keys, "Replace", &property);
            property = INT_TO_JSVAL(KEY_RESIZE);
            JS_SetProperty(cx, Keys, "Resize", &property);
            property = INT_TO_JSVAL(KEY_RESTART);
            JS_SetProperty(cx, Keys, "Restart", &property);
            property = INT_TO_JSVAL(KEY_RESUME);
            JS_SetProperty(cx, Keys, "Resume", &property);
            property = INT_TO_JSVAL(KEY_SAVE);
            JS_SetProperty(cx, Keys, "Save", &property);
            property = INT_TO_JSVAL(KEY_SELECT);
            JS_SetProperty(cx, Keys, "Select", &property);
            property = INT_TO_JSVAL(KEY_SUSPEND);
            JS_SetProperty(cx, Keys, "Suspend", &property);
            property = INT_TO_JSVAL(KEY_UNDO);
            JS_SetProperty(cx, Keys, "Undo", &property);
            JSObject* Shifted   = JS_NewObject(cx, NULL, NULL, NULL);
            jsval     jsShifted = OBJECT_TO_JSVAL(Shifted);
            JS_SetProperty(cx, Keys, "Shifted", &jsShifted);
                property = INT_TO_JSVAL(KEY_SBEG);
                JS_SetProperty(cx, Shifted, "Beginning", &property);
                property = INT_TO_JSVAL(KEY_SCANCEL);
                JS_SetProperty(cx, Shifted, "Cancel", &property);
                property = INT_TO_JSVAL(KEY_SCOMMAND);
                JS_SetProperty(cx, Shifted, "Command", &property);
                property = INT_TO_JSVAL(KEY_SCOPY);
                JS_SetProperty(cx, Shifted, "Copy", &property);
                property = INT_TO_JSVAL(KEY_SCREATE);
                JS_SetProperty(cx, Shifted, "Create", &property);
                property = INT_TO_JSVAL(KEY_SDC);
                JS_SetProperty(cx, Shifted, "DeleteChar", &property);
                property = INT_TO_JSVAL(KEY_SDL);
                JS_SetProperty(cx, Shifted, "DeleteLine", &property);
                property = INT_TO_JSVAL(KEY_SEND);
                JS_SetProperty(cx, Shifted, "End", &property);
                property = INT_TO_JSVAL(KEY_SEOL);
                JS_SetProperty(cx, Shifted, "EndOfLine", &property);
                property = INT_TO_JSVAL(KEY_SEXIT);
                JS_SetProperty(cx, Shifted, "Exit", &property);
                property = INT_TO_JSVAL(KEY_SFIND);
                JS_SetProperty(cx, Shifted, "Find", &property);
                property = INT_TO_JSVAL(KEY_SHELP);
                JS_SetProperty(cx, Shifted, "Help", &property);
                property = INT_TO_JSVAL(KEY_SHOME);
                JS_SetProperty(cx, Shifted, "Home", &property);
                property = INT_TO_JSVAL(KEY_SIC);
                JS_SetProperty(cx, Shifted, "EnterInsertMode", &property);
                property = INT_TO_JSVAL(KEY_SLEFT);
                JS_SetProperty(cx, Shifted, "Left", &property);
                property = INT_TO_JSVAL(KEY_SMESSAGE);
                JS_SetProperty(cx, Shifted, "Message", &property);
                property = INT_TO_JSVAL(KEY_SMOVE);
                JS_SetProperty(cx, Shifted, "Move", &property);
                property = INT_TO_JSVAL(KEY_SNEXT);
                JS_SetProperty(cx, Shifted, "Next", &property);
                property = INT_TO_JSVAL(KEY_SOPTIONS);
                JS_SetProperty(cx, Shifted, "Options", &property);
                property = INT_TO_JSVAL(KEY_SPREVIOUS);
                JS_SetProperty(cx, Shifted, "Previous", &property);
                property = INT_TO_JSVAL(KEY_SPRINT);
                JS_SetProperty(cx, Shifted, "Print", &property);
                property = INT_TO_JSVAL(KEY_SREDO);
                JS_SetProperty(cx, Shifted, "Redo", &property);
                property = INT_TO_JSVAL(KEY_SREPLACE);
                JS_SetProperty(cx, Shifted, "Replace", &property);
                property = INT_TO_JSVAL(KEY_SRIGHT);
                JS_SetProperty(cx, Shifted, "Right", &property);
                property = INT_TO_JSVAL(KEY_SRSUME);
                JS_SetProperty(cx, Shifted, "Resume", &property);
                property = INT_TO_JSVAL(KEY_SSAVE);
                JS_SetProperty(cx, Shifted, "Save", &property);
                property = INT_TO_JSVAL(KEY_SSUSPEND);
                JS_SetProperty(cx, Shifted, "Suspend", &property);
                property = INT_TO_JSVAL(KEY_SUNDO);
                JS_SetProperty(cx, Shifted, "Undo", &property);

        return JS_TRUE;
    }

    return JS_FALSE;
}
Пример #6
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;
}
Пример #7
0
void JsExecutionContext::init_class() {

  /* Initialize the built-in JS objects and the global object
   * As a side effect, JS_InitStandardClasses establishes obj as
   * the global object for cx, if one is not already established. */
  JS_InitStandardClasses(cx, obj);

  /* Declare shell functions */
  if (!JS_DefineFunctions(cx, obj, global_functions)) {
    JS_EndRequest(cx);
      error("JsParser :: error defining global functions");
	return ;
  }

  ///////////////////////////////////////////////////////////
  // Initialize classes

  JSObject *object_proto; // reminder for inher.
  JSObject *layer_object; // used in REGISTER_CLASS macro
  // Screen (in C++ ViewPort) has only one class type
  // all implementations are masked behind the factory
  REGISTER_CLASS("Screen",
    screen_class,
    screen_constructor,
    screen_properties,
    screen_methods,
    NULL);

  REGISTER_CLASS("Parameter",
    parameter_class,
    parameter_constructor,
    parameter_properties,
    parameter_methods,
    NULL);

  REGISTER_CLASS("Layer",
    layer_class,
    layer_constructor,
    layer_properties,
    layer_methods,
    NULL);
  object_proto = layer_object; // following registrations inherit from parent class Layer

  REGISTER_CLASS("GeometryLayer",
    geometry_layer_class,
    geometry_layer_constructor,
    NULL,
    geometry_layer_methods,
    object_proto);

  REGISTER_CLASS("GeneratorLayer",
    generator_layer_class,
    generator_layer_constructor,
    NULL,
    generator_layer_methods,
    object_proto);

  REGISTER_CLASS("ImageLayer",
    image_layer_class,
    image_layer_constructor,
    NULL,
    image_layer_methods,
    object_proto);

#ifdef WITH_FLASH
  REGISTER_CLASS("FlashLayer",
    flash_layer_class,
    flash_layer_constructor,
    NULL,
    flash_layer_methods,
    object_proto);
#endif

#ifdef WITH_GOOM
  REGISTER_CLASS("GoomLayer",
    goom_layer_class,
    goom_layer_constructor,
    NULL, // properties
    goom_layer_methods,
    object_proto);
#endif

#ifdef WITH_AUDIO
  REGISTER_CLASS("AudioJack",
    js_audio_jack_class,
    js_audio_jack_constructor,
    NULL, // properties
    js_audio_jack_methods,
    object_proto);
#endif

  REGISTER_CLASS("CamLayer",
    cam_layer_class,
    cam_layer_constructor,
    cam_layer_properties,
    cam_layer_methods,
    object_proto);

// #ifdef WITH_FFMPEG
//   REGISTER_CLASS("MovieLayer",
//     video_layer_class,
//     video_layer_constructor,
//     NULL, // properties
//     video_layer_methods,
//     object_proto);
// #endif

#ifdef WITH_AVIFILE
  REGISTER_CLASS("MovieLayer",
    avi_layer_class,
    avi_layer_constructor,
    NULL, // properties
    avi_layer_methods,
    object_proto);

#endif

#if defined WITH_TEXTLAYER
  REGISTER_CLASS("TextLayer",
    txt_layer_class,
    txt_layer_constructor,
    NULL, // properties
    txt_layer_methods,
    object_proto);
#endif

#ifdef WITH_XGRAB
  REGISTER_CLASS("XGrabLayer",
    js_xgrab_class,
    js_xgrab_constructor,
    NULL, // properties
    js_xgrab_methods,
    object_proto);
#endif

#ifdef WITH_CAIRO
  REGISTER_CLASS("VectorLayer",
    vector_layer_class,
    vector_layer_constructor,
    vector_layer_properties,
    vector_layer_methods,
    object_proto);
#endif

  REGISTER_CLASS("Filter",
    filter_class,
    filter_constructor,
    filter_properties,
    filter_methods,
    NULL);

// controller classes
  REGISTER_CLASS("Controller",
    js_ctrl_class,
    NULL,
    NULL, // properties
    js_ctrl_methods,
    NULL);
  object_proto = layer_object;

  REGISTER_CLASS("KeyboardController",
    js_kbd_ctrl_class,
    js_kbd_ctrl_constructor,
    NULL, // properties
    js_kbd_ctrl_methods,
    object_proto);

  REGISTER_CLASS("MouseController",
    js_mouse_ctrl_class,
    js_mouse_ctrl_constructor,
    NULL, // properties
    js_mouse_ctrl_methods,
    object_proto);

  REGISTER_CLASS("JoystickController",
    js_joy_ctrl_class,
    js_joy_ctrl_constructor,
    NULL, // properties
    js_joy_ctrl_methods,
    object_proto);

  REGISTER_CLASS("TriggerController",
    js_trigger_ctrl_class,
    js_trigger_ctrl_constructor,
    NULL, // properties
    js_trigger_ctrl_methods,
    object_proto);

  REGISTER_CLASS("ViMoController",
    js_vimo_ctrl_class,
    js_vimo_ctrl_constructor,
    NULL, // properties
    js_vimo_ctrl_methods,
    object_proto);

#ifdef WITH_MIDI
  REGISTER_CLASS("MidiController",
    js_midi_ctrl_class,
    js_midi_ctrl_constructor,
    NULL, // properties
    js_midi_ctrl_methods,
    object_proto);
#endif

  REGISTER_CLASS("OscController",
    js_osc_ctrl_class,
    js_osc_ctrl_constructor,
    NULL, // properties
    js_osc_ctrl_methods,
    object_proto);

#ifdef WITH_CWIID
  REGISTER_CLASS("WiiController",
    js_wii_ctrl_class,
    js_wii_ctrl_constructor,
    NULL, // properties
    js_wii_ctrl_methods,
    object_proto);
#endif

#ifdef WITH_OGGTHEORA
// encoder class
  REGISTER_CLASS("VideoEncoder",
    js_vid_enc_class,
    js_vid_enc_constructor,
    NULL, // properties
    js_vid_enc_methods,
    NULL);
#endif

  //JS_DefineProperties(global_context, layer_object, layer_properties);
  return;
}
Пример #8
0
JSURL *
lm_NewURL(JSContext *cx, MochaDecoder *decoder, LO_AnchorData *anchor_data,
          JSObject *document)
{
    JSObject *obj;
    JSURL *url;
    JSString *str;

    if (!decoder->url_prototype) {
	obj = JS_InitClass(cx, decoder->window_object, 
			   decoder->event_receiver_prototype, &lm_url_class, 
			   Url, 0, url_props, NULL, NULL, NULL);
	if (!obj)
	    return NULL;
	decoder->url_prototype = obj;
    }

    url = JS_malloc(cx, sizeof *url);
    if (!url)
	return NULL;
    XP_BZERO(url, sizeof *url);

    obj = JS_NewObject(cx, &lm_url_class, decoder->url_prototype, 
                       lm_GetOuterObject(decoder));
    if (!obj || !JS_SetPrivate(cx, obj, url)) {
	JS_free(cx, url);
	return NULL;
    }

    if (!JS_DefineFunctions(cx, obj, url_methods))
	return NULL;

    url->url_decoder = HOLD_BACK_COUNT(decoder);
    url->url_type = FORM_TYPE_NONE;
    url->index = URL_NOT_INDEXED;
    url->url_object = obj;

    str = JS_NewStringCopyZ(cx, (char *) anchor_data->anchor);
    if (!str)
	return NULL;
    url->href = str;
    if (!JS_AddNamedRoot(cx, &url->href, "url.href"))
	return NULL;

    if (anchor_data->target) {
	str = JS_NewStringCopyZ(cx, (char *) anchor_data->target);
	if (!str)
	    return NULL;
	url->target = str;
    }
    if (!JS_AddNamedRoot(cx, &url->target, "url.target"))
	return NULL;

    if (anchor_data->element && anchor_data->element->type == LO_TEXT) {
	str = lm_LocalEncodingToStr(decoder->window_context, 
		(char *) anchor_data->element->lo_text.text);
	if (!str)
	    return NULL;
	url->text = str;
    }
    if (!JS_AddNamedRoot(cx, &url->text, "url.text"))
	return NULL;

    return url;
}
Пример #9
0
JSObject*
Library::Create(JSContext* cx, Value path_, const JSCTypesCallbacks* callbacks)
{
    RootedValue path(cx, path_);
    RootedObject libraryObj(cx, JS_NewObject(cx, &sLibraryClass));
    if (!libraryObj)
        return nullptr;

    // initialize the library
    JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(nullptr));

    // attach API functions
    if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions))
        return nullptr;

    if (!path.isString()) {
        JS_ReportError(cx, "open takes a string argument");
        return nullptr;
    }

    PRLibSpec libSpec;
    RootedFlatString pathStr(cx, JS_FlattenString(cx, path.toString()));
    if (!pathStr)
        return nullptr;
    AutoStableStringChars pathStrChars(cx);
    if (!pathStrChars.initTwoByte(cx, pathStr))
        return nullptr;
#ifdef XP_WIN
    // On Windows, converting to native charset may corrupt path string.
    // So, we have to use Unicode path directly.
    char16ptr_t pathChars = pathStrChars.twoByteChars();
    libSpec.value.pathname_u = pathChars;
    libSpec.type = PR_LibSpec_PathnameU;
#else
    // Convert to platform native charset if the appropriate callback has been
    // provided.
    char* pathBytes;
    if (callbacks && callbacks->unicodeToNative) {
        pathBytes =
            callbacks->unicodeToNative(cx, pathStrChars.twoByteChars(), pathStr->length());
        if (!pathBytes)
            return nullptr;

    } else {
        // Fallback: assume the platform native charset is UTF-8. This is true
        // for Mac OS X, Android, and probably Linux.
        size_t nbytes =
            GetDeflatedUTF8StringLength(cx, pathStrChars.twoByteChars(), pathStr->length());
        if (nbytes == (size_t) -1)
            return nullptr;

        pathBytes = static_cast<char*>(JS_malloc(cx, nbytes + 1));
        if (!pathBytes)
            return nullptr;

        ASSERT_OK(DeflateStringToUTF8Buffer(cx, pathStrChars.twoByteChars(),
                                            pathStr->length(), pathBytes, &nbytes));
        pathBytes[nbytes] = 0;
    }

    libSpec.value.pathname = pathBytes;
    libSpec.type = PR_LibSpec_Pathname;
#endif

    PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, 0);

    if (!library) {
        char* error = (char*) JS_malloc(cx, PR_GetErrorTextLength() + 1);
        if (error)
            PR_GetErrorText(error);

#ifdef XP_WIN
        JS_ReportError(cx, "couldn't open library %hs: %s", pathChars, error);
#else
        JS_ReportError(cx, "couldn't open library %s: %s", pathBytes, error);
        JS_free(cx, pathBytes);
#endif
        JS_free(cx, error);
        return nullptr;
    }

#ifndef XP_WIN
    JS_free(cx, pathBytes);
#endif

    // stash the library
    JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(library));

    return libraryObj;
}
Пример #10
0
JSObject *
js_InitExceptionClasses(JSContext *cx, JSObject *obj)
{
    JSObject *obj_proto, *protos[JSEXN_LIMIT];
    int i;

    /*
     * If lazy class initialization occurs for any Error subclass, then all
     * classes are initialized, starting with Error.  To avoid reentry and
     * redundant initialization, we must not pass a null proto parameter to
     * js_NewObject below, when called for the Error superclass.  We need to
     * ensure that Object.prototype is the proto of Error.prototype.
     *
     * See the equivalent code to ensure that parent_proto is non-null when
     * JS_InitClass calls js_NewObject, in jsapi.c.
     */
    if (!js_GetClassPrototype(cx, obj, INT_TO_JSID(JSProto_Object),
                              &obj_proto)) {
        return NULL;
    }

    if (!js_EnterLocalRootScope(cx))
        return NULL;

    /* Initialize the prototypes first. */
    for (i = 0; exceptions[i].name != 0; i++) {
        JSAtom *atom;
        JSFunction *fun;
        JSString *nameString;
        int protoIndex = exceptions[i].protoIndex;

        /* Make the prototype for the current constructor name. */
        protos[i] = js_NewObject(cx, &js_ErrorClass,
                                 (protoIndex != JSEXN_NONE)
                                 ? protos[protoIndex]
                                 : obj_proto,
                                 obj, 0);
        if (!protos[i])
            break;

        /* So exn_finalize knows whether to destroy private data. */
        STOBJ_SET_SLOT(protos[i], JSSLOT_PRIVATE, JSVAL_VOID);

        /* Make a constructor function for the current name. */
        atom = cx->runtime->atomState.classAtoms[exceptions[i].key];
        fun = js_DefineFunction(cx, obj, atom, exceptions[i].native, 3, 0);
        if (!fun)
            break;

        /* Make this constructor make objects of class Exception. */
        FUN_CLASP(fun) = &js_ErrorClass;

        /* Make the prototype and constructor links. */
        if (!js_SetClassPrototype(cx, FUN_OBJECT(fun), protos[i],
                                  JSPROP_READONLY | JSPROP_PERMANENT)) {
            break;
        }

        /* proto bootstrap bit from JS_InitClass omitted. */
        nameString = JS_NewStringCopyZ(cx, exceptions[i].name);
        if (!nameString)
            break;

        /* Add the name property to the prototype. */
        if (!JS_DefineProperty(cx, protos[i], js_name_str,
                               STRING_TO_JSVAL(nameString),
                               NULL, NULL,
                               JSPROP_ENUMERATE)) {
            break;
        }

        /* Finally, stash the constructor for later uses. */
        if (!js_SetClassObject(cx, obj, exceptions[i].key, FUN_OBJECT(fun)))
            break;
    }

    js_LeaveLocalRootScope(cx);
    if (exceptions[i].name)
        return NULL;

    /*
     * Add an empty message property.  (To Exception.prototype only,
     * because this property will be the same for all the exception
     * protos.)
     */
    if (!JS_DefineProperty(cx, protos[0], js_message_str,
                           STRING_TO_JSVAL(cx->runtime->emptyString),
                           NULL, NULL, JSPROP_ENUMERATE)) {
        return NULL;
    }
    if (!JS_DefineProperty(cx, protos[0], js_fileName_str,
                           STRING_TO_JSVAL(cx->runtime->emptyString),
                           NULL, NULL, JSPROP_ENUMERATE)) {
        return NULL;
    }
    if (!JS_DefineProperty(cx, protos[0], js_lineNumber_str,
                           INT_TO_JSVAL(0),
                           NULL, NULL, JSPROP_ENUMERATE)) {
        return NULL;
    }

    /*
     * Add methods only to Exception.prototype, because ostensibly all
     * exception types delegate to that.
     */
    if (!JS_DefineFunctions(cx, protos[0], exception_methods))
        return NULL;

    return protos[0];
}
/*
 * "Steal" calls to netscape.security.PrivilegeManager.enablePrivilege,
 * et al. so that code that worked with 4.0 can still work.
 */
NS_IMETHODIMP 
nsSecurityNameSet::InitializeNameSet(nsIScriptContext* aScriptContext)
{
    JSContext* cx = aScriptContext->GetNativeContext();
    JSObject *global = JS_ObjectToInnerObject(cx, JS_GetGlobalObject(cx));

    // We hide enablePrivilege behind a pref because it has been altered in a
    // way that makes it fundamentally insecure to use in production. Mozilla
    // uses this pref during automated testing to support legacy test code that
    // uses enablePrivilege. If you're not doing test automation, you _must_ not
    // flip this pref, or you will be exposing all your users to security
    // vulnerabilities.
    if (!mozilla::Preferences::GetBool("security.enablePrivilege.enable_for_tests"))
        return NS_OK;

    /*
     * Find Object.prototype's class by walking up the global object's
     * prototype chain.
     */
    JSObject *obj = global;
    JSObject *proto;
    JSAutoRequest ar(cx);
    while ((proto = JS_GetPrototype(obj)) != nullptr)
        obj = proto;
    JSClass *objectClass = JS_GetClass(obj);

    JS::Value v;
    if (!JS_GetProperty(cx, global, "netscape", &v))
        return NS_ERROR_FAILURE;

    JSObject *securityObj;
    if (v.isObject()) {
        /*
         * "netscape" property of window object exists; get the
         * "security" property.
         */
        obj = &v.toObject();
        if (!JS_GetProperty(cx, obj, "security", &v) || !v.isObject())
            return NS_ERROR_FAILURE;
        securityObj = &v.toObject();
    } else {
        /* define netscape.security object */
        obj = JS_DefineObject(cx, global, "netscape", objectClass, nullptr, 0);
        if (obj == nullptr)
            return NS_ERROR_FAILURE;
        securityObj = JS_DefineObject(cx, obj, "security", objectClass,
                                      nullptr, 0);
        if (securityObj == nullptr)
            return NS_ERROR_FAILURE;
    }

    /* Define PrivilegeManager object with the necessary "static" methods. */
    obj = JS_DefineObject(cx, securityObj, "PrivilegeManager", objectClass,
                          nullptr, 0);
    if (obj == nullptr)
        return NS_ERROR_FAILURE;

    return JS_DefineFunctions(cx, obj, PrivilegeManager_static_methods)
           ? NS_OK
           : NS_ERROR_FAILURE;
}
Пример #12
0
static void
js_sub_query(subtitle_provider_t *SP, sub_scanner_t *ss, int score,
	     int autosel)
{
  js_subprovider_t *sp = (js_subprovider_t *)SP;

  JSContext *cx = js_newctx(NULL);
  JS_BeginRequest(cx);

  if(ss != NULL) {
    JSObject *obj = JS_NewObject(cx, &subreq_class, NULL, NULL);

    JS_AddNamedRoot(cx, &obj, "subscanner");

    if(sp->sp_jsp != NULL)
      usage_inc_plugin_counter(sp->sp_jsp->jsp_id, "subsearch", 1);

    js_sub_job_t *jsj = malloc(sizeof(js_sub_job_t));
    jsj->jsj_ss = ss;
    jsj->jsj_score = score;
    jsj->jsj_autosel = autosel;
    sub_scanner_retain(ss);
    JS_SetPrivate(cx, obj, jsj);

    JS_DefineFunctions(cx, obj, sub_functions);

    js_set_prop_rstr(cx, obj, "title", ss->ss_title);
    js_set_prop_rstr(cx, obj, "imdb", ss->ss_imdbid);

    if(ss->ss_season > 0)
      js_set_prop_int(cx, obj, "season", ss->ss_season);

    if(ss->ss_year > 0)
      js_set_prop_int(cx, obj, "year", ss->ss_year);

    if(ss->ss_episode > 0)
      js_set_prop_int(cx, obj, "episode", ss->ss_episode);

    if(ss->ss_fsize > 0)
      js_set_prop_dbl(cx, obj, "filesize", ss->ss_fsize);

    if(ss->ss_hash_valid) {
      char str[64];
      snprintf(str, sizeof(str), "%016" PRIx64, ss->ss_opensub_hash);
      js_set_prop_str(cx, obj, "opensubhash", str);

      bin2hex(str, sizeof(str), ss->ss_subdbhash, 16);
      js_set_prop_str(cx, obj, "subdbhash", str);
    }

    if(ss->ss_duration > 0)
      js_set_prop_int(cx, obj, "duration", ss->ss_duration);

    jsval result;
    jsval arg = OBJECT_TO_JSVAL(obj);
    JS_CallFunctionValue(cx, NULL, sp->sp_func, 1, &arg, &result);

    JS_RemoveRoot(cx, &obj);
  }
  js_subprovider_release(cx, sp);
  JS_DestroyContext(cx);
}
Пример #13
0
static inline bool
Define(JSContext* cx, JSObject* obj, JSFunctionSpec* spec) {
  return JS_DefineFunctions(cx, obj, spec);
}
Пример #14
0
 JSBool
 ejsfile_LTX_onLoad(JSContext *cx, JSObject *module)
 {
   if (!JS_DefineFunctions(cx, module, file_static_methods)) return JS_FALSE;
   return JS_TRUE;
 }
Пример #15
0
JSObject*
Library::Create(JSContext* cx, jsval path, JSCTypesCallbacks* callbacks)
{
  JSObject* libraryObj = JS_NewObject(cx, &sLibraryClass, NULL, NULL);
  if (!libraryObj)
    return NULL;
  js::AutoObjectRooter root(cx, libraryObj);

  // initialize the library
  if (!JS_SetReservedSlot(cx, libraryObj, SLOT_LIBRARY, PRIVATE_TO_JSVAL(NULL)))
    return NULL;

  // attach API functions
  if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions))
    return NULL;

  if (!JSVAL_IS_STRING(path)) {
    JS_ReportError(cx, "open takes a string argument");
    return NULL;
  }

  PRLibSpec libSpec;
  JSFlatString* pathStr = JS_FlattenString(cx, JSVAL_TO_STRING(path));
  if (!pathStr)
    return NULL;
#ifdef XP_WIN
  // On Windows, converting to native charset may corrupt path string.
  // So, we have to use Unicode path directly.
  const PRUnichar* pathChars = JS_GetFlatStringChars(pathStr);
  if (!pathChars)
    return NULL;

  libSpec.value.pathname_u = pathChars;
  libSpec.type = PR_LibSpec_PathnameU;
#else
  // Convert to platform native charset if the appropriate callback has been
  // provided.
  char* pathBytes;
  if (callbacks && callbacks->unicodeToNative) {
    pathBytes = 
      callbacks->unicodeToNative(cx, pathStr->chars(), pathStr->length());
    if (!pathBytes)
      return NULL;

  } else {
    // Fallback: assume the platform native charset is UTF-8. This is true
    // for Mac OS X, Android, and probably Linux.
    size_t nbytes =
      GetDeflatedUTF8StringLength(cx, pathStr->chars(), pathStr->length());
    if (nbytes == (size_t) -1)
      return NULL;

    pathBytes = static_cast<char*>(JS_malloc(cx, nbytes + 1));
    if (!pathBytes)
      return NULL;

    ASSERT_OK(DeflateStringToUTF8Buffer(cx, pathStr->chars(),
                pathStr->length(), pathBytes, &nbytes));
    pathBytes[nbytes] = 0;
  }

  libSpec.value.pathname = pathBytes;
  libSpec.type = PR_LibSpec_Pathname;
#endif

  PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, 0);
#ifndef XP_WIN
  JS_free(cx, pathBytes);
#endif
  if (!library) {
    JS_ReportError(cx, "couldn't open library");
    return NULL;
  }

  // stash the library
  if (!JS_SetReservedSlot(cx, libraryObj, SLOT_LIBRARY,
         PRIVATE_TO_JSVAL(library)))
    return NULL;

  return libraryObj;
}
Пример #16
0
 virtual void initClasses(JSContext * theContext,
                          JSObject *theGlobalObject) {
     JS_DefineFunctions(theContext, theGlobalObject, jslib::JSHashingFunctions::Functions());
     jslib::createFunctionDocumentation("HashingFunctions", jslib::JSHashingFunctions::Functions());
 }
Пример #17
0
bool initJSDir( JSContext *cx, JSObject *glob )
{
   return JS_DefineFunctions( cx, glob, _functions);
}
Пример #18
0
Файл: jsexn.c Проект: artcom/y60
JSObject *
js_InitExceptionClasses(JSContext *cx, JSObject *obj)
{
    int i;
    JSObject *protos[JSEXN_LIMIT];

    /* Initialize the prototypes first. */
    for (i = 0; exceptions[i].name != 0; i++) {
        JSAtom *atom;
        JSFunction *fun;
        JSString *nameString;
        int protoIndex = exceptions[i].protoIndex;

        /* Make the prototype for the current constructor name. */
        protos[i] = js_NewObject(cx, &ExceptionClass,
                                 (protoIndex != JSEXN_NONE)
                                 ? protos[protoIndex]
                                 : NULL,
                                 obj);
        if (!protos[i])
            return NULL;

        /* So exn_finalize knows whether to destroy private data. */
        OBJ_SET_SLOT(cx, protos[i], JSSLOT_PRIVATE, JSVAL_VOID);

        atom = js_Atomize(cx, exceptions[i].name, strlen(exceptions[i].name), 0);
        if (!atom)
            return NULL;

        /* Make a constructor function for the current name. */
        fun = js_DefineFunction(cx, obj, atom, exceptions[i].native, 3, 0);
        if (!fun)
            return NULL;

        /* Make this constructor make objects of class Exception. */
        fun->clasp = &ExceptionClass;

        /* Make the prototype and constructor links. */
        if (!js_SetClassPrototype(cx, fun->object, protos[i],
                                  JSPROP_READONLY | JSPROP_PERMANENT)) {
            return NULL;
        }

        /* proto bootstrap bit from JS_InitClass omitted. */
        nameString = JS_NewStringCopyZ(cx, exceptions[i].name);
        if (!nameString)
            return NULL;

        /* Add the name property to the prototype. */
        if (!JS_DefineProperty(cx, protos[i], js_name_str,
                               STRING_TO_JSVAL(nameString),
                               NULL, NULL,
                               JSPROP_ENUMERATE)) {
            return NULL;
        }
    }

    /*
     * Add an empty message property.  (To Exception.prototype only,
     * because this property will be the same for all the exception
     * protos.)
     */
    if (!JS_DefineProperty(cx, protos[0], js_message_str,
                           STRING_TO_JSVAL(cx->runtime->emptyString),
                           NULL, NULL, JSPROP_ENUMERATE)) {
        return NULL;
    }
    if (!JS_DefineProperty(cx, protos[0], js_filename_str,
                           STRING_TO_JSVAL(cx->runtime->emptyString),
                           NULL, NULL, JSPROP_ENUMERATE)) {
        return NULL;
    }
    if (!JS_DefineProperty(cx, protos[0], js_lineno_str,
                           INT_TO_JSVAL(0),
                           NULL, NULL, JSPROP_ENUMERATE)) {
        return NULL;
    }

    /*
     * Add methods only to Exception.prototype, because ostensibly all
     * exception types delegate to that.
     */
    if (!JS_DefineFunctions(cx, protos[0], exception_methods))
        return NULL;

    return protos[0];
}
Пример #19
0
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);
  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;

  JSObject* 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 */
  JSObject* bindings = JS_DefineObject(cx, alpha, "bindings", NULL, NULL, 0);
  if (!JS_DefineFunctions(cx, bindings, binding_functions)) return 1;

  /* Set global on alpha */
  jsval global_val = OBJECT_TO_JSVAL(global);
  if (!JS_SetProperty(cx, alpha, "global", &global_val)) return 1;

  /* Set args on alpha */
  JSObject* args = JS_NewArrayObject(cx, 0, NULL);
  jsval args_val = OBJECT_TO_JSVAL(args);
  if (!JS_SetProperty(cx, alpha, "args", &args_val)) return 1;
  int index;
  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;
}
Пример #20
0
int main()
{
    JSRuntime *rt;
    JSContext *jscontext;
    JSObject *glob;
    nsresult rv;

    gErrFile = stderr;
    gOutFile = stdout;
    {
        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
        NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
        if(registrar)
            registrar->AutoRegister(nsnull);
    
        // get the JSRuntime from the runtime svc, if possible
        nsCOMPtr<nsIJSRuntimeService> rtsvc =
                 do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv);
        if(NS_FAILED(rv) || NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt)
            DIE("FAILED to get a JSRuntime");

        jscontext = JS_NewContext(rt, 8192);
        if(!jscontext)
            DIE("FAILED to create a JSContext");

        JS_SetErrorReporter(jscontext, my_ErrorReporter);

        nsCOMPtr<nsIXPConnect> xpc(do_GetService(nsIXPConnect::GetCID(), &rv));
        if(!xpc)
            DIE("FAILED to get xpconnect service\n");

        nsCOMPtr<nsIJSContextStack> cxstack =
                 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
        if(NS_FAILED(rv))
            DIE("FAILED to get the nsThreadJSContextStack service!\n");

        if(NS_FAILED(cxstack->Push(jscontext)))
            DIE("FAILED to push the current jscontext on the nsThreadJSContextStack service!\n");

        // XXX I'd like to replace this with code that uses a wrapped xpcom object
        // as the global object. The old TextXPC did this. The support for this
        // is not working now in the new xpconnect code.

        glob = JS_NewObject(jscontext, &global_class, NULL, NULL);
        if (!glob)
            DIE("FAILED to create global object");
        if (!JS_InitStandardClasses(jscontext, glob))
            DIE("FAILED to init standard classes");
        if (!JS_DefineFunctions(jscontext, glob, glob_functions))
            DIE("FAILED to define global functions");
        if (NS_FAILED(xpc->InitClasses(jscontext, glob)))
            DIE("FAILED to init xpconnect classes");

        /**********************************************/
        // run the tests...

        TestCategoryManmager();
        TestSecurityManager(jscontext, glob, xpc);
        TestArgFormatter(jscontext, glob, xpc);
        TestThreadJSContextStack(jscontext);

        /**********************************************/

        if(NS_FAILED(cxstack->Pop(nsnull)))
            DIE("FAILED to pop the current jscontext from the nsThreadJSContextStack service!\n");

        JS_ClearScope(jscontext, glob);
        JS_GC(jscontext);
        JS_GC(jscontext);
        JS_DestroyContext(jscontext);
        xpc->DebugDump(4);

        cxstack = nsnull;   // release service held by nsCOMPtr
        xpc     = nsnull;   // release service held by nsCOMPtr
        rtsvc   = nsnull;   // release service held by nsCOMPtr
    }
    rv = NS_ShutdownXPCOM( NULL );
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM FAILED");

    return 0;
}
Пример #21
0
JSObject *
js_InitExceptionClasses(JSContext *cx, JSObject *obj)
{
    jsval roots[3];
    JSObject *obj_proto, *error_proto;
    jsval empty;

    /*
     * If lazy class initialization occurs for any Error subclass, then all
     * classes are initialized, starting with Error.  To avoid reentry and
     * redundant initialization, we must not pass a null proto parameter to
     * js_NewObject below, when called for the Error superclass.  We need to
     * ensure that Object.prototype is the proto of Error.prototype.
     *
     * See the equivalent code to ensure that parent_proto is non-null when
     * JS_InitClass calls js_NewObject, in jsapi.c.
     */
    if (!js_GetClassPrototype(cx, obj, INT_TO_JSID(JSProto_Object),
                              &obj_proto)) {
        return NULL;
    }

    memset(roots, 0, sizeof(roots));
    JSAutoTempValueRooter tvr(cx, JS_ARRAY_LENGTH(roots), roots);

#ifdef __GNUC__
    error_proto = NULL;   /* quell GCC overwarning */
#endif

    /* Initialize the prototypes first. */
    for (intN i = JSEXN_ERR; i != JSEXN_LIMIT; i++) {
        JSObject *proto;
        JSProtoKey protoKey;
        JSAtom *atom;
        JSFunction *fun;

        /* Make the prototype for the current constructor name. */
        proto = js_NewObject(cx, &js_ErrorClass,
                             (i != JSEXN_ERR) ? error_proto : obj_proto,
                             obj);
        if (!proto)
            return NULL;
        if (i == JSEXN_ERR) {
            error_proto = proto;
            roots[0] = OBJECT_TO_JSVAL(proto);
        } else {
            // We cannot share the root for error_proto and other prototypes
            // as error_proto must be rooted until the function returns.
            roots[1] = OBJECT_TO_JSVAL(proto);
        }

        /* So exn_finalize knows whether to destroy private data. */
        proto->setPrivate(NULL);

        /* Make a constructor function for the current name. */
        protoKey = GetExceptionProtoKey(i);
        atom = cx->runtime->atomState.classAtoms[protoKey];
        fun = js_DefineFunction(cx, obj, atom, Exception, 3, 0);
        if (!fun)
            return NULL;
        roots[2] = OBJECT_TO_JSVAL(FUN_OBJECT(fun));

        /* Make this constructor make objects of class Exception. */
        FUN_CLASP(fun) = &js_ErrorClass;

        /* Make the prototype and constructor links. */
        if (!js_SetClassPrototype(cx, FUN_OBJECT(fun), proto,
                                  JSPROP_READONLY | JSPROP_PERMANENT)) {
            return NULL;
        }

        /* Add the name property to the prototype. */
        if (!JS_DefineProperty(cx, proto, js_name_str, ATOM_KEY(atom),
                               NULL, NULL, JSPROP_ENUMERATE)) {
            return NULL;
        }

        /* Finally, stash the constructor for later uses. */
        if (!js_SetClassObject(cx, obj, protoKey, FUN_OBJECT(fun)))
            return NULL;
    }

    /*
     * Set default values and add methods. We do it only for Error.prototype
     * as the rest of exceptions delegate to it.
     */
    empty = STRING_TO_JSVAL(cx->runtime->emptyString);
    if (!JS_DefineProperty(cx, error_proto, js_message_str, empty,
                           NULL, NULL, JSPROP_ENUMERATE) ||
        !JS_DefineProperty(cx, error_proto, js_fileName_str, empty,
                           NULL, NULL, JSPROP_ENUMERATE) ||
        !JS_DefineProperty(cx, error_proto, js_lineNumber_str, JSVAL_ZERO,
                           NULL, NULL, JSPROP_ENUMERATE) ||
        !JS_DefineFunctions(cx, error_proto, exception_methods)) {
        return NULL;
    }

    return error_proto;
}
Пример #22
0
bool initJSHyperlink( JSContext *cx, JSObject *glob )
{
   return JS_DefineFunctions( cx, glob, text_functions);
}
Пример #23
0
int ExecShellScript(const char * file, int argc, char** argv, JSContext * context, JSObject * env, jsval * vp) {

	register FILE * filep;
	register int c;

	filep = fopen(file, "rb");

	if (!filep) {

		JS_ReportError(context, "%s: %s", file, "No such file or directory");

		return 0;

	}

	if (getc(filep) == '#' && getc(filep) == '!') {

		c = 1;

		while (c != EOF && c != '\n') c = getc(filep);

		ungetc(c, filep);

	} else {
		fclose(filep);
		JS_ReportError(context, "%s: %s", file, "is not a shell script");
		return 0;
	}

	JSObject* argsObj = JS_NewArrayObject(context, 0, NULL);
	JS_DefineProperty(context, env, "parameter", OBJECT_TO_JSVAL(argsObj), NULL, NULL, 0);

	JSString* str = JS_NewStringCopyZ(context, file);
	JS_DefineElement(context, argsObj, 0, STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE);
	int i;
	for (i = 0; i < argc; i++) {
		str = JS_NewStringCopyZ(context, argv[i]);
		JS_DefineElement(context, argsObj, i + 1, STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE);
	}

	setenv(SMASH_RESOURCE_PATH_ENV_ID, GET_STRING_DEF(SMASH_RESOURCE_PATH), 0);

	JS_InitCTypesClass(context, env);
	JS_DefineFunctions(context, env, shell_functions);
	JS_DefineProperties(context, env, shell_properties);
	jsval fun;
	JS_GetProperty(context, env, "system", &fun);
	JS_DefineFunction(context, JSVAL_TO_OBJECT(fun), "read", ShellSystemRead, 1, JSPROP_ENUMERATE);
	JS_DefineFunction(context, JSVAL_TO_OBJECT(fun), "write", ShellSystemWrite, 2, JSPROP_ENUMERATE);
	jsval fun2;
	JS_GetProperty(context, env, "echo", &fun2);
	JS_DefineFunction(context, JSVAL_TO_OBJECT(fun2), "error", ShellEchoError, 1, JSPROP_ENUMERATE);
	jsval fun3;
	JS_GetProperty(context, env, "setFileContent", &fun3);
	JS_DefineFunction(context, JSVAL_TO_OBJECT(fun3), "append", ShellSetFileContentAppend, 2, JSPROP_ENUMERATE);

#ifdef SMASH_MAIN_LOADER
	//ExecScriptFile(context, env, GET_STRING_DEF(SMASH_MAIN_LOADER), NULL);
#endif

#ifdef SMASH_SHELL_LOADER
	ExecScriptFile(context, env, GET_STRING_DEF(SMASH_SHELL_LOADER), NULL);
#endif

	JSObject * jsTemp = JS_CompileFileHandle(context, env, file, filep);

	fclose(filep);

	if (jsTemp) {

		return JS_ExecuteScript(context, env, jsTemp, vp);

	} else {

		JS_ReportPendingException(context);

		return 1;

	}

}
Пример #24
0
int main(int argc, char ** argv)
{
    if (argc != 2) {
        printf("\nusage: %s script-filename\n\n", argv[0]);
        return -1;
    }

    // evaluate script file size
    struct stat s;
    memset(&s, 0, sizeof(s));
    if (stat(argv[1], &s)) {
        fprintf(stderr, "ERROR: cannot get stat from file '%s'\n", argv[1]);
        return -1;
    }

    // read script from file
    char * source = new char[s.st_size];
    std::ifstream f(argv[1]);
    f.read(source, s.st_size);
    f.close();

    JSClass global_class = {
        "global", 0,
        JS_PropertyStub, JS_PropertyStub,
        JS_PropertyStub, JS_PropertyStub,
        JS_EnumerateStub, JS_ResolveStub,
        JS_ConvertStub, JS_FinalizeStub
    };

    // setup environment
    JSRuntime * runtime = JS_NewRuntime(0x100000);
    JSContext * context = JS_NewContext(runtime, 0x1000);
    JSObject * global = JS_NewObject(context, &global_class, NULL, NULL);
    JS_InitStandardClasses(context, global);
    JS_SetErrorReporter(context, error_reporter);

    // register functions
    static JSFunctionSpec functions[] = {
        //  name            native           nargs
        {"load",        js__load,        1},
        {"print",       js__print,       0},
        {"hello_world", js__hello_world, 0},
        {NULL}
    };
    JS_DefineFunctions(context, global, functions);

    // execute script
    jsval ret;
    JSBool rc = JS_EvaluateScript(context, global,
                                  source, s.st_size,
                                  argv[1], 0,
                                  &ret);
    if (rc == JS_FALSE) {
        fprintf(stderr, "ERROR: rc=%d, filename:'%s'\n", rc, argv[1]);
    }

    // clean up
    delete[] source;
    JS_DestroyContext(context);
    JS_DestroyRuntime(runtime);
    JS_ShutDown();
    return 0;
}
nsresult
mozJSComponentLoader::GlobalForLocation(nsILocalFile *aComponent,
                                        JSObject **aGlobal,
                                        char **aLocation)
{
    nsresult rv;

    JSPrincipals* jsPrincipals = nsnull;
    JSCLContextHelper cx(mContext);

#ifndef XPCONNECT_STANDALONE
    rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
    NS_ENSURE_SUCCESS(rv, rv);

    JSPrincipalsHolder princHolder(mContext, jsPrincipals);
#endif

    nsCOMPtr<nsIXPCScriptable> backstagePass;
    rv = mRuntimeService->GetBackstagePass(getter_AddRefs(backstagePass));
    NS_ENSURE_SUCCESS(rv, rv);

    JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);

    nsCOMPtr<nsIXPConnect> xpc =
        do_GetService(kXPConnectServiceContractID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Make sure InitClassesWithNewWrappedGlobal() installs the
    // backstage pass as the global in our compilation context.
    JS_SetGlobalObject(cx, nsnull);

    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                              NS_GET_IID(nsISupports),
                                              nsIXPConnect::
                                                  FLAG_SYSTEM_GLOBAL_OBJECT,
                                              getter_AddRefs(holder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *global;
    rv = holder->GetJSObject(&global);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineFunctions(cx, global, gGlobalFun)) {
        return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
    rv = xpc->WrapNative(cx, global, aComponent,
                         NS_GET_IID(nsILocalFile),
                         getter_AddRefs(locationHolder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *locationObj;
    rv = locationHolder->GetJSObject(&locationObj);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineProperty(cx, global, "__LOCATION__",
                           OBJECT_TO_JSVAL(locationObj), nsnull, nsnull, 0)) {
        return NS_ERROR_FAILURE;
    }

    nsCAutoString nativePath;
    // Quick hack to unbust XPCONNECT_STANDALONE.
    // This leaves the jsdebugger with a non-URL pathname in the 
    // XPCONNECT_STANDALONE case - but at least it builds and runs otherwise.
    // See: http://bugzilla.mozilla.org/show_bug.cgi?id=121438
#ifdef XPCONNECT_STANDALONE
    localFile->GetNativePath(nativePath);
#else
    NS_GetURLSpecFromFile(aComponent, nativePath);
#endif

    // Before compiling the script, first check to see if we have it in
    // the fastload file.  Note: as a rule, fastload errors are not fatal
    // to loading the script, since we can always slow-load.
    nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);

    // Save the old state and restore it upon return
    FastLoadStateHolder flState(flSvc);
    PRBool fastLoading = PR_FALSE;

    if (NS_SUCCEEDED(rv)) {
        rv = StartFastLoad(flSvc);
        if (NS_SUCCEEDED(rv)) {
            fastLoading = PR_TRUE;
        }
    }

    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), nativePath);
    NS_ENSURE_SUCCESS(rv, rv);

    JSScript *script = nsnull;

    if (fastLoading) {
        rv = ReadScript(flSvc, nativePath.get(), uri, cx, &script);
        if (NS_SUCCEEDED(rv)) {
            LOG(("Successfully loaded %s from fastload\n", nativePath.get()));
            fastLoading = PR_FALSE; // no need to write out the script
        } else if (rv == NS_ERROR_NOT_AVAILABLE) {
            // This is ok, it just means the script is not yet in the
            // fastload file.
            rv = NS_OK;
        } else {
            LOG(("Failed to deserialize %s\n", nativePath.get()));

            // Remove the fastload file, it may be corrupted.
            LOG(("Invalid fastload file detected, removing it\n"));
            nsCOMPtr<nsIObjectOutputStream> objectOutput;
            flSvc->GetOutputStream(getter_AddRefs(objectOutput));
            if (objectOutput) {
                flSvc->SetOutputStream(nsnull);
                objectOutput->Close();
            }
            nsCOMPtr<nsIObjectInputStream> objectInput;
            flSvc->GetInputStream(getter_AddRefs(objectInput));
            if (objectInput) {
                flSvc->SetInputStream(nsnull);
                objectInput->Close();
            }
            if (mFastLoadFile) {
                mFastLoadFile->Remove(PR_FALSE);
            }
            fastLoading = PR_FALSE;
        }
    }


    if (!script || NS_FAILED(rv)) {
        // The script wasn't in the fastload cache, so compile it now.
        LOG(("Slow loading %s\n", nativePath.get()));

#ifdef HAVE_PR_MEMMAP
        PRInt64 fileSize;
        rv = aComponent->GetFileSize(&fileSize);
        if (NS_FAILED(rv))
            return rv;

        PRInt64 maxSize;
        LL_UI2L(maxSize, PR_UINT32_MAX);
        if (LL_CMP(fileSize, >, maxSize)) {
            NS_ERROR("file too large");
            return NS_ERROR_FAILURE;
        }

        PRFileDesc *fileHandle;
        rv = aComponent->OpenNSPRFileDesc(PR_RDONLY, 0, &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        // Make sure the file is closed, no matter how we return.
        FileAutoCloser fileCloser(fileHandle);

        PRFileMap *map = PR_CreateFileMap(fileHandle, fileSize,
                                          PR_PROT_READONLY);
        if (!map) {
            NS_ERROR("Failed to create file map");
            return NS_ERROR_FAILURE;
        }

        // Make sure the file map is closed, no matter how we return.
        FileMapAutoCloser mapCloser(map);

        PRUint32 fileSize32;
        LL_L2UI(fileSize32, fileSize);

        char *buf = static_cast<char*>(PR_MemMap(map, 0, fileSize32));
        if (!buf) {
            NS_WARNING("Failed to map file");
            return NS_ERROR_FAILURE;
        }

        script = JS_CompileScriptForPrincipals(cx, global,
                                               jsPrincipals,
                                               buf, fileSize32,
                                               nativePath.get(), 1);
        PR_MemUnmap(buf, fileSize32);

#else  /* HAVE_PR_MEMMAP */

        /**
         * No memmap implementation, so fall back to using
         * JS_CompileFileHandleForPrincipals().
         */

        FILE *fileHandle;
        rv = aComponent->OpenANSIFileDesc("r", &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        script = JS_CompileFileHandleForPrincipals(cx, global,
                                                   nativePath.get(),
                                                   fileHandle, jsPrincipals);

        /* JS will close the filehandle after compilation is complete. */

#endif /* HAVE_PR_MEMMAP */
    }
Пример #26
0
void runWebCallBacks(JSContext *cx){
	if(!curlHandle)
		return;
	int p;
	curl_multi_perform(curlHandle, &p);
	CURLMsg *msg = NULL;
	
	while( msg = curl_multi_info_read(curlHandle,&p)){
	
		if( msg->msg == CURLMSG_DONE ) {
			if( msg->data.result == CURLE_OK){
				JSObject *ob = NULL;
				ob = JS_NewObject(cx,&webRespClass,NULL,NULL);
				if(!ob){
					fprint(stderr,"Error creating http response javascript object\n");
					exit(EXIT_FAILURE);
				}
				JS_SetPrivate(cx,ob,msg);

				static JSFunctionSpec responseFuncSpec[3]= {
					JS_FS("toString", webRspData,0,0),
					JS_FS("getImage", webRspGetImg,0,0),
					//JS_FS("hasHeaderLine", webRspHL,0,0),
					JS_FS_END
				};
				if(!JS_DefineFunctions(cx, ob, responseFuncSpec))
					fprint(stderr,"Unable to create http response object\n");

				//Create an instance of webResponseObject, with private data set.
				jsval result;
				jsval oj = OBJECT_TO_JSVAL(ob);
				
				rqPrivate *rq = NULL;
				curl_easy_getinfo(msg->easy_handle,CURLINFO_PRIVATE,(char**)&rq);
				if(!rq){
					fprint(stderr,"Error retrieving data from the handle");
					exit( EXIT_FAILURE);
				}
			
				JS_CallFunctionValue(cx, NULL,rq->success, 1, &oj , &result);
				
			} else { /* Just return error string -> Cleanup now */
				char *errCode = (char*)curl_easy_strerror(msg->data.result);
				if(!errCode)
					errCode = "FAILED WITH NO REASON GIVEN";
				JSString *string;
				string =  JS_NewStringCopyZ(cx, errCode);
				jsval result, errString = STRING_TO_JSVAL(string);
				
				rqPrivate *rq = NULL;
				curl_easy_getinfo(msg->easy_handle,CURLINFO_PRIVATE,(char**)&rq);
				if(!rq){
					fprint(stderr,"Error retrieving data from the handle");
					exit( EXIT_FAILURE);
				}
				
				JS_CallFunctionValue(cx, NULL,rq->failure, 1, &errString, &result);
				curl_multi_remove_handle(curlHandle,msg->easy_handle);
				if(rq->data)
					free(rq->data);
				free(rq);
				curl_easy_cleanup(msg->easy_handle);
			}
		}
	}
}
Пример #27
0
JSBool
xpc_qsDefineQuickStubs(JSContext *cx, JSObject *proto, uintN flags,
                       PRUint32 ifacec, const nsIID **interfaces,
                       PRUint32 tableSize, const xpc_qsHashEntry *table)
{
    /*
     * Walk interfaces in reverse order to behave like XPConnect when a
     * feature is defined in more than one of the interfaces.
     *
     * XPCNativeSet::FindMethod returns the first matching feature it finds,
     * searching the interfaces forward.  Here, definitions toward the
     * front of 'interfaces' overwrite those toward the back.
     */
    PRBool definedProperty = PR_FALSE;
    for(uint32 i = ifacec; i-- != 0;)
    {
        const nsID &iid = *interfaces[i];
        const xpc_qsHashEntry *entry =
            LookupInterfaceOrAncestor(tableSize, table, iid);

        if(entry)
        {
            for(;;)
            {
                // Define quick stubs for attributes.
                const xpc_qsPropertySpec *ps = entry->properties;
                if(ps)
                {
                    for(; ps->name; ps++)
                    {
                        definedProperty = PR_TRUE;
                        if(!JS_DefineProperty(cx, proto, ps->name, JSVAL_VOID,
                                              ps->getter, ps->setter,
                                              flags | JSPROP_SHARED))
                            return JS_FALSE;
                    }
                }

                // Define quick stubs for methods.
                const xpc_qsFunctionSpec *fs = entry->functions;
                if(fs)
                {
                    for(; fs->name; fs++)
                    {
                        if(!JS_DefineFunction(
                               cx, proto, fs->name,
                               reinterpret_cast<JSNative>(fs->native),
                               fs->arity, flags | JSFUN_FAST_NATIVE))
                            return JS_FALSE;
                    }
                }

                const xpc_qsTraceableSpec *ts = entry->traceables;
                if(ts)
                {
                    for(; ts->name; ts++)
                    {
                        if(!JS_DefineFunction(
                               cx, proto, ts->name, ts->native, ts->arity,
                               flags | JSFUN_FAST_NATIVE | JSFUN_STUB_GSOPS |
                                       JSFUN_TRCINFO))
                            return JS_FALSE;
                    }
                }

                // Next.
                size_t j = entry->parentInterface;
                if(j == XPC_QS_NULL_INDEX)
                    break;
                entry = table + j;
            }
        }
    }

    static JSFunctionSpec getterfns[] = {
        JS_FN("__lookupGetter__", SharedLookupGetter, 1, 0),
        JS_FN("__lookupSetter__", SharedLookupSetter, 1, 0),
        JS_FN("__defineGetter__", SharedDefineGetter, 2, 0),
        JS_FN("__defineSetter__", SharedDefineSetter, 2, 0),
        JS_FS_END
    };

    if(definedProperty && !JS_DefineFunctions(cx, proto, getterfns))
        return JS_FALSE;

    return JS_TRUE;
}
Пример #28
0
JSObject *
GlobalObject::initFunctionAndObjectClasses(JSContext *cx)
{
    Rooted<GlobalObject*> self(cx, this);

    JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment);
    JS_ASSERT(isNative());

    /*
     * Calling a function from a cleared global triggers this (yeah, I know).
     * Uncomment this once bug 470510 is fixed (if that bug doesn't remove
     * isCleared entirely).
     */
    // JS_ASSERT(!isCleared());

    /* If cx has no global object, make this the global object. */
    if (!cx->globalObject)
        JS_SetGlobalObject(cx, self);

    RootedObject objectProto(cx);

    /*
     * Create |Object.prototype| first, mirroring CreateBlankProto but for the
     * prototype of the created object.
     */
    objectProto = NewObjectWithGivenProto(cx, &ObjectClass, NULL, self);
    if (!objectProto || !objectProto->setSingletonType(cx))
        return NULL;

    /*
     * The default 'new' type of Object.prototype is required by type inference
     * to have unknown properties, to simplify handling of e.g. heterogenous
     * objects in JSON and script literals.
     */
    if (!objectProto->setNewTypeUnknown(cx))
        return NULL;

    /* Create |Function.prototype| next so we can create other functions. */
    RootedFunction functionProto(cx);
    {
        JSObject *functionProto_ = NewObjectWithGivenProto(cx, &FunctionClass, objectProto, self);
        if (!functionProto_)
            return NULL;
        functionProto = functionProto_->toFunction();

        /*
         * Bizarrely, |Function.prototype| must be an interpreted function, so
         * give it the guts to be one.
         */
        JSObject *proto = js_NewFunction(cx, functionProto,
                                         NULL, 0, JSFUN_INTERPRETED, self, NULL);
        if (!proto)
            return NULL;
        JS_ASSERT(proto == functionProto);
        functionProto->flags |= JSFUN_PROTOTYPE;

        const char *rawSource = "() {\n}";
        size_t sourceLen = strlen(rawSource);
        jschar *source = InflateString(cx, rawSource, &sourceLen);
        if (!source)
            return NULL;
        ScriptSource *ss = cx->new_<ScriptSource>();
        if (!ss) {
            cx->free_(source);
            return NULL;
        }
        ScriptSourceHolder ssh(cx->runtime, ss);
        ss->setSource(source, sourceLen);

        CompileOptions options(cx);
        options.setNoScriptRval(true)
               .setVersion(JSVERSION_DEFAULT);
        Rooted<JSScript*> script(cx, JSScript::Create(cx,
                                                      /* enclosingScope = */ NullPtr(),
                                                      /* savedCallerFun = */ false,
                                                      options,
                                                      /* staticLevel = */ 0,
                                                      ss,
                                                      0,
                                                      ss->length()));
        if (!script || !JSScript::fullyInitTrivial(cx, script))
            return NULL;

        functionProto->initScript(script);
        functionProto->getType(cx)->interpretedFunction = functionProto;
        script->setFunction(functionProto);

        if (!functionProto->setSingletonType(cx))
            return NULL;

        /*
         * The default 'new' type of Function.prototype is required by type
         * inference to have unknown properties, to simplify handling of e.g.
         * CloneFunctionObject.
         */
        if (!functionProto->setNewTypeUnknown(cx))
            return NULL;
    }

    /* Create the Object function now that we have a [[Prototype]] for it. */
    RootedFunction objectCtor(cx);
    {
        JSObject *ctor = NewObjectWithGivenProto(cx, &FunctionClass, functionProto, self);
        if (!ctor)
            return NULL;
        objectCtor = js_NewFunction(cx, ctor, js_Object, 1, JSFUN_CONSTRUCTOR, self,
                                    CLASS_NAME(cx, Object));
        if (!objectCtor)
            return NULL;
    }

    /*
     * Install |Object| and |Object.prototype| for the benefit of subsequent
     * code that looks for them.
     */
    self->setObjectClassDetails(objectCtor, objectProto);

    /* Create |Function| so it and |Function.prototype| can be installed. */
    RootedFunction functionCtor(cx);
    {
        // Note that ctor is rooted purely for the JS_ASSERT at the end
        RootedObject ctor(cx, NewObjectWithGivenProto(cx, &FunctionClass, functionProto, self));
        if (!ctor)
            return NULL;
        functionCtor = js_NewFunction(cx, ctor, Function, 1, JSFUN_CONSTRUCTOR, self,
                                      CLASS_NAME(cx, Function));
        if (!functionCtor)
            return NULL;
        JS_ASSERT(ctor == functionCtor);
    }

    /*
     * Install |Function| and |Function.prototype| so that we can freely create
     * functions and objects without special effort.
     */
    self->setFunctionClassDetails(functionCtor, functionProto);

    /*
     * The hard part's done: now go back and add all the properties these
     * primordial values have.
     */
    if (!LinkConstructorAndPrototype(cx, objectCtor, objectProto) ||
        !DefinePropertiesAndBrand(cx, objectProto, NULL, object_methods))
    {
        return NULL;
    }

    /*
     * Add an Object.prototype.__proto__ accessor property to implement that
     * extension (if it's actually enabled).  Cache the getter for this
     * function so that cross-compartment [[Prototype]]-getting is implemented
     * in one place.
     */
    Rooted<JSFunction*> getter(cx, js_NewFunction(cx, NULL, ProtoGetter, 0, 0, self, NULL));
    if (!getter)
        return NULL;
#if JS_HAS_OBJ_PROTO_PROP
    Rooted<JSFunction*> setter(cx, js_NewFunction(cx, NULL, ProtoSetter, 0, 0, self, NULL));
    if (!setter)
        return NULL;
    RootedValue undefinedValue(cx, UndefinedValue());
    if (!objectProto->defineProperty(cx, cx->runtime->atomState.protoAtom, undefinedValue,
                                     JS_DATA_TO_FUNC_PTR(PropertyOp, getter.get()),
                                     JS_DATA_TO_FUNC_PTR(StrictPropertyOp, setter.get()),
                                     JSPROP_GETTER | JSPROP_SETTER | JSPROP_SHARED))
    {
        return NULL;
    }
#endif /* JS_HAS_OBJ_PROTO_PROP */
    self->setProtoGetter(getter);


    if (!DefinePropertiesAndBrand(cx, objectCtor, NULL, object_static_methods) ||
        !LinkConstructorAndPrototype(cx, functionCtor, functionProto) ||
        !DefinePropertiesAndBrand(cx, functionProto, NULL, function_methods) ||
        !DefinePropertiesAndBrand(cx, functionCtor, NULL, NULL))
    {
        return NULL;
    }

    /* Add the global Function and Object properties now. */
    jsid objectId = NameToId(CLASS_NAME(cx, Object));
    if (!self->addDataProperty(cx, objectId, JSProto_Object + JSProto_LIMIT * 2, 0))
        return NULL;
    jsid functionId = NameToId(CLASS_NAME(cx, Function));
    if (!self->addDataProperty(cx, functionId, JSProto_Function + JSProto_LIMIT * 2, 0))
        return NULL;

    /* Heavy lifting done, but lingering tasks remain. */

    /* ES5 15.1.2.1. */
    RootedId id(cx, NameToId(cx->runtime->atomState.evalAtom));
    JSObject *evalobj = js_DefineFunction(cx, self, id, IndirectEval, 1, JSFUN_STUB_GSOPS);
    if (!evalobj)
        return NULL;
    self->setOriginalEval(evalobj);

    /* ES5 13.2.3: Construct the unique [[ThrowTypeError]] function object. */
    RootedFunction throwTypeError(cx, js_NewFunction(cx, NULL, ThrowTypeError, 0, 0, self, NULL));
    if (!throwTypeError)
        return NULL;
    if (!throwTypeError->preventExtensions(cx))
        return NULL;
    self->setThrowTypeError(throwTypeError);

    RootedObject intrinsicsHolder(cx, JS_NewObject(cx, NULL, NULL, self));
    if (!intrinsicsHolder)
        return NULL;
    self->setIntrinsicsHolder(intrinsicsHolder);
    if (!JS_DefineFunctions(cx, intrinsicsHolder, intrinsic_functions))
        return NULL;

    /*
     * The global object should have |Object.prototype| as its [[Prototype]].
     * Eventually we'd like to have standard classes be there from the start,
     * and thus we would know we were always setting what had previously been a
     * null [[Prototype]], but right now some code assumes it can set the
     * [[Prototype]] before standard classes have been initialized.  For now,
     * only set the [[Prototype]] if it hasn't already been set.
     */
    if (self->shouldSplicePrototype(cx) && !self->splicePrototype(cx, objectProto))
        return NULL;

    /*
     * Notify any debuggers about the creation of the script for
     * |Function.prototype| -- after all initialization, for simplicity.
     */
    js_CallNewScriptHook(cx, functionProto->script(), functionProto);
    return functionProto;
}
Пример #29
0
 /*!
   \return JS_TRUE on success
 */
 JSBool
 ejsposix_LTX_onLoad(JSContext *cx, JSObject *util)
 {
   return JS_DefineFunctions(cx, util, static_methods);
 }