Exemplo n.º 1
0
JS_STATIC_DLL_CALLBACK(JSBool) js__load(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
{
    uintN i;
    JSString * str;
    const char * filename;
    JSScript * script;
    JSBool ok;
    jsval result;

    for (i = 0; i < argc; i++) {
        str = JS_ValueToString(cx, argv[i]);
        if (!str) return JS_FALSE;
        argv[i] = STRING_TO_JSVAL(str);
        filename = JS_GetStringBytes(str);
        script = JS_CompileFile(cx, obj, filename);
        if (!script) {
            ok = JS_FALSE;
        } else {
            ok = JS_ExecuteScript(cx, obj, script, &result);
            JS_DestroyScript(cx, script);
        }
        if (!ok) return JS_FALSE;
    }
    return JS_TRUE;
}
Exemplo n.º 2
0
static JSBool
Load(JSContext *cx, uintN argc, jsval *vp)
{
    uintN i;
    JSString *str;
    jsval result;

    JSObject *obj = JS_THIS_OBJECT(cx, vp);
    if (!obj)
        return JS_FALSE;

    jsval *argv = JS_ARGV(cx, vp);
    for (i = 0; i < argc; i++) {
        str = JS_ValueToString(cx, argv[i]);
        if (!str)
            return JS_FALSE;
        argv[i] = STRING_TO_JSVAL(str);
        JSAutoByteString filename(cx, str);
        if (!filename)
            return false;
        JSScript *script = JS_CompileFile(cx, obj, filename.ptr());
        if (!script || !JS_ExecuteScript(cx, obj, script, &result))
            return false;
    }
    JS_SET_RVAL(cx, vp, JSVAL_VOID);
    return JS_TRUE;
}
Exemplo n.º 3
0
qq_jso_t* qq_js_load(qq_js_t* js,const char* file)
{
    JSObject* global = JS_GetGlobalObject(js->context);
    JSObject* script = JS_CompileFile(js->context, global, file);
    JS_ExecuteScript(js->context, global, script, NULL);
    return (qq_jso_t*)script;
}
Exemplo n.º 4
0
Arquivo: lwjs.c Projeto: fsky/webqq
lwqq_jso_t* lwqq_js_load(lwqq_js_t* js,const char* file)
{
    JSObject* global = JS_GetGlobalObject(js->context);
#ifdef MOZJS_185
    JSObject* script = JS_CompileFile(js->context, global, file);
#else
    JSScript* script = JS_CompileUTF8File(js->context,global,file);
#endif
    JS_ExecuteScript(js->context, global, script, NULL);
    return (lwqq_jso_t*)script;
}
JSBool systemInclude(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{// begin systemInclude
	// default return value
	*rval = BOOLEAN_TO_JSVAL(false);
	if(argc != 1)
		return JS_FALSE;
	if(JSVAL_IS_STRING(argv[0]) == false)
		return JS_FALSE;

	struct stat sbFileInfo;
	const char *pIncludeFile = JS_GetStringBytes(JSVAL_TO_STRING(argv[0]));
	// make sure we haven't included this already to avoid a recursive
	// dependency loop
	char *pTempStr = new char[PATH_MAX+1];
	if(realpath(pIncludeFile,pTempStr) == NULL)
	{// begin can't resolve path
		JS_ReportError(cx, "include() can't resolve the path of \"%s\".", pIncludeFile);
		return JS_FALSE;
	}// end can't resolve path

	std::string sRealPath = pTempStr;
	if(stat(sRealPath.c_str() , &sbFileInfo) != 0)
	{// begin can't stat file
		JS_ReportError(cx, "include() Can't stat \"%s\" errno(%i).", sRealPath.c_str(), errno);
		return JS_FALSE;
	}// end can't stat file

	for(int i = 0;i < g_vIncludes.size();i++)
	{// begin check previous includes
		if(g_vIncludes[i] == sRealPath)
		{// begin found
			printf("include() Warning: Duplicated include of \"%s\"...ignoring.\n",sRealPath.c_str());
			return JS_TRUE;
		}// end found
	}// end check previous includes
	g_vIncludes.push_back(sRealPath);

	JSScript *pJSScript = JS_CompileFile(cx, obj, sRealPath.c_str());
	jsval lastRval;
	if(pJSScript != NULL)
	{// begin execute external file
		JSBool ok = JS_ExecuteScript(cx, obj, pJSScript, &lastRval);
		JS_DestroyScript(cx,pJSScript);
		*rval = BOOLEAN_TO_JSVAL(ok);
	}// end execute external file
	else
	{// begin error including
		JS_ReportError(cx, "include() Cannot compile file \"%s\"", pIncludeFile);
		return JS_FALSE;
	}// end error including
	return JS_TRUE;
}// end systemInclude
Exemplo n.º 6
0
static JSBool
Load(JSContext *cx, uintN argc, jsval *vp)
{
    SG_context *pCtx = NULL;
    JSObject *thisobj = JS_THIS_OBJECT(cx, vp);
    jsval *argv = JS_ARGV(cx, vp);
    uintN i;
    if (!thisobj)
        return JS_FALSE;

	SG_context__alloc(&pCtx);
	if (pCtx==NULL)
		return JS_FALSE;

    for (i = 0; i < argc; i++) {
        JSString *str = JS_ValueToString(cx, argv[i]);
        char *filename = NULL;
    	uint32 oldopts;
    	JSObject *scriptObj;
        if (!str) {
        	SG_CONTEXT_NULLFREE(pCtx);
            return JS_FALSE;
        }
        argv[i] = STRING_TO_JSVAL(str);
        sg_jsglue__jsstring_to_sz(pCtx, cx, str, &filename);
        if (SG_context__has_err(pCtx)) {
        	SG_CONTEXT_NULLFREE(pCtx);
            return JS_FALSE;
        }
        errno = 0;
        oldopts = JS_GetOptions(cx);
        JS_SetOptions(cx, oldopts | JSOPTION_COMPILE_N_GO | JSOPTION_NO_SCRIPT_RVAL);
        scriptObj = JS_CompileFile(cx, thisobj, filename);
        SG_NULLFREE(pCtx, filename);
        JS_SetOptions(cx, oldopts);
        if (!scriptObj) {
        	SG_CONTEXT_NULLFREE(pCtx);
            return JS_FALSE;
        }

        if (!compileOnly && !JS_ExecuteScript(cx, thisobj, scriptObj, NULL)) {
        	SG_CONTEXT_NULLFREE(pCtx);
            return JS_FALSE;
        }
    }

	SG_CONTEXT_NULLFREE(pCtx);
    return JS_TRUE;
}
bool parseECMAScript(const char *name)
{// begin parseECMAScript
	jsval rval;
	uintN lineno = 0;
        jscu=0;
	printf("Spidermonkey compiling \"%s\"\n",name);
	JSScript *pJSScript = JS_CompileFile(g_pCx, g_pObject, name);
	if(pJSScript != NULL)
	{// begin execute external file
		printf("Spidermonkey executing \"%s\"\n",name);
		JSBool ok = JS_ExecuteScript(g_pCx, g_pObject, pJSScript, &rval);
		JS_DestroyScript(g_pCx,pJSScript);
	}// end execute external file
        A_Resync();
        return jscu;
                        
}// end parseECMAScript
Exemplo n.º 8
0
/**
 * Load a JavaScript file
 *
 * @param cx the JavaScript context
 * @param global the global JavaScript object (not used)
 * @param filename the file name to load
 * @return a JavaScript Object on success, NULL if an errro occurred
 */
JSObject * loadZooApiFile(JSContext *cx,JSObject  *global, char* filename){
  struct stat api_status;
  int s=stat(filename, &api_status);
  if(s==0){
    jsval rval;
    JSObject *script = JS_CompileFile(cx, JS_GetGlobalObject(cx), filename);
    if(script!=NULL){
      (void)JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, &rval);
#ifdef JS_DEBUG
      fprintf(stderr,"**************\n%s correctly loaded\n**************\n",filename);
#endif
      return script;
    }
#ifdef JS_DEBUG
    else
      fprintf(stderr,"\n**************\nUnable to run %s\n**************\n",filename);
#endif
  }
#ifdef JS_DEBUG
  else
    fprintf(stderr,"\n**************\nUnable to load %s\n**************\n",filename);
#endif
  return NULL;
}
Exemplo n.º 9
0
long sbbs_t::js_execfile(const char *cmd, const char* startup_dir, JSObject* scope)
{
	char*		p;
	char*		args=NULL;
	char*		fname;
	int			argc=0;
	char		cmdline[MAX_PATH+1];
	char		path[MAX_PATH+1];
	JSObject*	js_scope=scope;
	JSObject*	js_script=NULL;
	jsval		rval;
	int32		result=0;

	if(js_cx==NULL) {
		errormsg(WHERE,ERR_CHK,"JavaScript support",0);
		errormsg(WHERE,ERR_EXEC,cmd,0);
		return -1;
	}

	SAFECOPY(cmdline,cmd);
	p=strchr(cmdline,' ');
	if(p!=NULL) {
		*p=0;
		args=p+1;
	}
	fname=cmdline;

	path[0]=0;
	if(strcspn(fname,"/\\")==strlen(fname)) {
		if(startup_dir!=NULL && *startup_dir)
			SAFEPRINTF3(path,"%s%s%s",startup_dir,fname,js_ext(fname));
		if(path[0]==0 || !fexistcase(path)) {
			SAFEPRINTF3(path,"%s%s%s",cfg.mods_dir,fname,js_ext(fname));
			if(cfg.mods_dir[0]==0 || !fexistcase(path))
				SAFEPRINTF3(path,"%s%s%s",cfg.exec_dir,fname,js_ext(fname));
		}
	} else
		SAFECOPY(path,fname);

	if(!fexistcase(path)) {
		errormsg(WHERE,ERR_OPEN,path,O_RDONLY);
		return -1;
	}

	JS_BEGINREQUEST(js_cx);
	if(js_scope==NULL)
		js_scope=JS_NewObject(js_cx, NULL, NULL, js_glob);

	if(js_scope!=NULL) {

		JSObject* argv=JS_NewArrayObject(js_cx, 0, NULL);

		JS_DefineProperty(js_cx, js_scope, "argv", OBJECT_TO_JSVAL(argv)
			,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);

		/* TODO: Handle quoted "one arg" syntax here? */
		if(args!=NULL && argv!=NULL) {
			while(*args) {
				p=strchr(args,' ');
				if(p!=NULL)
					*p=0;
				while(*args && *args==' ') args++; /* Skip spaces */
				JSString* arg = JS_NewStringCopyZ(js_cx, args);
				if(arg==NULL)
					break;
				jsval val=STRING_TO_JSVAL(arg);
				if(!JS_SetElement(js_cx, argv, argc, &val))
					break;
				argc++;
				if(p==NULL)	/* last arg */
					break;
				args+=(strlen(args)+1);
			}
		}
		JS_DefineProperty(js_cx, js_scope, "argc", INT_TO_JSVAL(argc)
			,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);

		JS_ClearPendingException(js_cx);

		js_script=JS_CompileFile(js_cx, js_scope, path);
	}

	if(js_scope==NULL || js_script==NULL) {
		JS_ReportPendingException(js_cx);	/* Added Feb-2-2006, rswindell */
		JS_ENDREQUEST(js_cx);
		errormsg(WHERE,"compiling",path,0);
		return -1;
	}

	if(scope==NULL) {
		js_callback.counter=0;	// Reset loop counter

#if JS_VERSION>180
		JS_SetOperationCallback(js_cx, js_OperationCallback);
#else
		JS_SetBranchCallback(js_cx, js_BranchCallback);
#endif

		js_PrepareToExecute(js_cx, js_glob, path, startup_dir);
	}
	JS_ExecuteScript(js_cx, js_scope, js_script, &rval);

	if(scope==NULL) {
		JS_GetProperty(js_cx, js_scope, "exit_code", &rval);
		if(rval!=JSVAL_VOID)
			JS_ValueToInt32(js_cx,rval,&result);

		js_EvalOnExit(js_cx, js_scope, &js_callback);
	}

	JS_ReportPendingException(js_cx);	/* Added Dec-4-2005, rswindell */

	JS_DestroyScript(js_cx, js_script);

	if(scope==NULL)
		JS_ClearScope(js_cx, js_scope);

	JS_GC(js_cx);

	JS_ENDREQUEST(js_cx);

	return(result);
}
Exemplo n.º 10
0
/**
 * Load a JavaScript file then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by value as JavaScript
 * Objects.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param inputs the maps containing the inputs
 * @param outputs the maps containing the outputs
 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1 
 *  if the service failed to load or throw error at runtime.
 */
int zoo_js_support(maps** main_conf,map* request,service* s,maps **inputs,maps **outputs)
{
  /*maps* main=*main_conf;
  maps* _inputs=*inputs;
  maps* _outputs=*outputs;*/

  /* The class of the global object. */
  JSClass global_class= {
    "global", JSCLASS_GLOBAL_FLAGS,
    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
    JSCLASS_NO_OPTIONAL_MEMBERS
  };

  /* JS variables. */
  JSRuntime *rt;
  JSContext *cx;
  JSObject  *global;

  /* Create a JS runtime. */
  rt = JS_NewRuntime(8L * 1024L * 1024L);
  if (rt == NULL)
    return 1;
  
  /* Create a context. */
  cx = JS_NewContext(rt,8192);
  if (cx == NULL){
    return 1;
  }
  JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
  JS_SetVersion(cx, JSVERSION_LATEST);
  JS_SetErrorReporter(cx, reportError);

  /* Create the global object. */
  global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);

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

  /* Define specific function and global variable to share with JS runtime
   */
  jsval tmp=INT_TO_JSVAL(3);
  if (!JS_SetProperty(cx, global, "SERVICE_SUCCEEDED", &tmp))
    return 1;
  tmp=INT_TO_JSVAL(4);
  if (!JS_SetProperty(cx, global, "SERVICE_FAILED", &tmp))
    return 1;
  if (!JS_DefineFunction(cx, global, "ZOORequest", JSRequest, 4, 0))
    return 1;
  if (!JS_DefineFunction(cx, global, "ZOOTranslate", JSTranslate, 4, 0))
    return 1;
  if (!JS_DefineFunction(cx, global, "ZOOUpdateStatus", JSUpdateStatus, 2, 0))
    return 1;
  if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0))
    return 1;  
  if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0))
    return 1;

  /**
   * Add private context object
   */
  void* cxPrivate = request;
  JS_SetContextPrivate(cx,cxPrivate);

  map* tmpm1=getMap(request,"metapath");
  char ntmp[1024];
  map* cwdMap=getMapFromMaps(*main_conf,"main","servicePath");
  if(cwdMap!=NULL)
    sprintf(ntmp,"%s",cwdMap->value);
  else
    getcwd(ntmp,1024);

  /**
   * Load the first part of the ZOO-API
   */
  char *api0=(char*)malloc((strlen(ntmp)+17)*sizeof(char));
  sprintf(api0,"%s/ZOO-proj4js.js",ntmp);
#ifdef JS_DEBUG
  fprintf(stderr,"Trying to load %s\n",api0);
#endif
  JSObject *api_script1=loadZooApiFile(cx,global,api0);
  free(api0);
  fflush(stderr);

  char *api1=(char*)malloc((strlen(ntmp)+13)*sizeof(char));
  sprintf(api1,"%s/ZOO-api.js",ntmp);
#ifdef JS_DEBUG
  fprintf(stderr,"Trying to load %s\n",api1);
#endif
  JSObject *api_script2=loadZooApiFile(cx,global,api1);
  free(api1);
  fflush(stderr);

  /* Your application code here. This may include JSAPI calls
     to create your own custom JS objects and run scripts. */
  //maps* out=*outputs;
  int res=SERVICE_FAILED;
  //maps* mc=*main_conf;
  map* tmpm2=getMap(s->content,"serviceProvider");

  char *filename=(char*)malloc(strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+3);
  sprintf(filename,"%s/%s/%s",ntmp,tmpm1->value,tmpm2->value);
  filename[strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+2]=0;
#ifdef JS_DEBUG
  fprintf(stderr,"FILENAME %s\n",filename);
#endif
  struct stat file_status;
  stat(filename, &file_status);
  //char *source=(char*)malloc(file_status.st_size);
  //uint16 lineno;
  jsval rval;
  JSBool ok ;
  JSObject *script = JS_CompileFile(cx, global, filename);
  if(script!=NULL){
    (void)JS_ExecuteScript(cx, global, script, &rval);
  }
  else{
    char tmp1[1024];
    sprintf(tmp1,"Unable to load JavaScript file %s",filename);
    free(filename);
    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
    JS_MaybeGC(cx);
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return -1;
  }
  

  /* Call a function in obj's scope. */
  jsval argv[3];
  JSObject *jsargv1=JSObject_FromMaps(cx,*main_conf);
  argv[0] = OBJECT_TO_JSVAL(jsargv1);
  JSObject *jsargv2=JSObject_FromMaps(cx,*inputs);
  argv[1] = OBJECT_TO_JSVAL(jsargv2);
  JSObject *jsargv3=JSObject_FromMaps(cx,*outputs);
  argv[2] = OBJECT_TO_JSVAL(jsargv3);
  jsval rval1=JSVAL_NULL;
#ifdef JS_DEBUG
  fprintf(stderr, "object %p\n", (void *) argv[2]);
#endif

  ok = JS_CallFunctionName(cx, global, s->name, 3, argv, &rval1);

#ifdef JS_DEBUG
  fprintf(stderr, "object %p\n", (void *) argv[2]);
#endif

  JSObject *d;
  if (ok==JS_TRUE && JSVAL_IS_OBJECT(rval1)==JS_TRUE) {
#ifdef JS_DEBUG
    fprintf(stderr,"Function run sucessfully !\n");
#endif
    /* Should get a number back from the service function call. */
    ok = JS_ValueToObject(cx, rval1, &d);
  }else{
    /* Unable to run JS function */
    char tmp1[1024];
    if(strlen(dbg)==0)
      sprintf(dbg,"No result was found after the function call");
    sprintf(tmp1,"Unable to run %s from the JavaScript file %s : \n %s",s->name,filename,dbg);
#ifdef JS_DEBUG
    fprintf(stderr,"%s",tmp1);
#endif
    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
    free(filename);
    JS_MaybeGC(cx);
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    // Should return -1 here but the unallocation won't work from zoo_service_loader.c line 1847
    return -1;
  }

  //jsval t=OBJECT_TO_JSVAL(d);
  if(JS_IsArrayObject(cx,d)){
#ifdef JS_DEBUG
    fprintf(stderr,"An array was returned !\n");
#endif
    jsuint	 len;
    if((JS_GetArrayLength(cx, d, &len)==JS_FALSE)){
#ifdef JS_DEBUG
      fprintf(stderr,"outputs array is empty\n");
#endif
    }
    jsval tmp1;
    JSBool hasResult=JS_GetElement(cx,d,0,&tmp1);
    res=JSVAL_TO_INT(tmp1);
#ifdef JS_DEBUG
    fprintf(stderr," * %d * \n",res);
#endif
    if(res==SERVICE_SUCCEEDED){
      jsval tmp2;
      JSBool hasElement=JS_GetElement(cx,d,1,&tmp2);
      if(hasElement==JS_TRUE){
	freeMaps(outputs);
	free(*outputs);
	*outputs=mapsFromJSObject(cx,tmp2);
      }
    }else{
      jsval tmp3;
      JSBool hasConf=JS_GetElement(cx,d,1,&tmp3);
      if(hasConf==JS_TRUE){
	freeMaps(main_conf);
	free(*main_conf);
	*main_conf=mapsFromJSObject(cx,tmp3);
      }
    }

  }
  else{
#ifdef JS_DEBUG
    fprintf(stderr,"The service didn't return an array !\n");
#endif
    /**
     * Extract result
     */
    jsval tmp1;
    JSBool hasResult=JS_GetProperty(cx,d,"result",&tmp1);
    res=JSVAL_TO_INT(tmp1);

#ifdef JS_DEBUG
    fprintf(stderr," * %d * \n",res);
#endif
    /**
     * Extract outputs when available.
     */
    jsval tmp2;
    JSBool hasElement=JS_GetProperty(cx,d,"outputs",&tmp2);
    if(!JSVAL_IS_VOID(tmp2) && hasElement==JS_TRUE){
      freeMaps(outputs);
      free(*outputs);    
      *outputs=mapsFromJSObject(cx,tmp2);
    }
    JS_MaybeGC(cx);
#ifdef JS_DEBUG
    if(JSVAL_IS_VOID(tmp2))
      fprintf(stderr,"No outputs property returned\n");
    else{
      if(JS_IsArrayObject(cx,JSVAL_TO_OBJECT(tmp2)))
	fprintf(stderr,"outputs is an array as expected\n");
      else
	fprintf(stderr,"outputs is not an array as expected\n");
    }
    JS_MaybeGC(cx);
#endif

    /**
     * Extract conf when available.
     */
    jsval tmp3;
    JSBool hasConf=JS_GetProperty(cx,d,"conf",&tmp3);
    if(!JSVAL_IS_VOID(tmp3) && hasConf==JS_TRUE){
      freeMaps(main_conf);
      free(*main_conf);
      *main_conf=mapsFromJSObject(cx,tmp3);
    }
    JS_MaybeGC(cx);

#ifdef JS_DEBUG
    dumpMaps(*outputs);
#endif
  }
  /* Cleanup. */
  JS_MaybeGC(cx);
  JS_DestroyContext(cx);
  JS_DestroyRuntime(rt);
  JS_ShutDown();
  free(filename);
#ifdef JS_DEBUG
  fprintf(stderr,"Returned value %d\n",res);
#endif
  return res;
}
Exemplo n.º 11
0
static void
Process(JSContext *cx, JSObject *obj, char *filename, JSBool forceTTY)
{
	SG_context * pCtx = NULL;
	char * sz = NULL;
	
    JSBool ok, hitEOF;
    JSObject *script;
    jsval result;
    JSString *str;
    char buffer[4096];
    char *bufp;
    int lineno;
    int startline;

    SetContextOptions(cx);

    if (!forceTTY && filename != NULL && strlen(filename) != 0) {
        script = JS_CompileFile(cx, obj, filename);
        if (script) {
            if (!compileOnly)
                (void)JS_ExecuteScript(cx, obj, script, &result);
        }

        return;
    }

	(void)SG_context__alloc(&pCtx);

    /* It's an interactive filehandle; drop into read-eval-print loop. */
    lineno = 1;
    hitEOF = JS_FALSE;
    do {
        bufp = buffer;
        *bufp = '\0';

        /*
         * Accumulate lines until we get a 'compilable unit' - one that either
         * generates an error (before running out of source) or that compiles
         * cleanly.  This should be whenever we get a complete statement that
         * coincides with the end of a line.
         */
        startline = lineno;
        do {
            if (!GetLine(pCtx, cx, bufp, (SG_uint32)(sizeof(buffer)-(bufp-buffer)), stdin, startline == lineno ? "vscript> " : "")) {
                hitEOF = JS_TRUE;
                break;
            }
            bufp += strlen(bufp);
            lineno++;
        } while (!JS_BufferIsCompilableUnit(cx, obj, buffer, strlen(buffer)));

        /* Clear any pending exception from previous failed compiles.  */
        JS_ClearPendingException(cx);
        script = JS_CompileScript(cx, obj, buffer, strlen(buffer), "typein",
                                  startline);
        if (script) {
            if (!compileOnly) {
                ok = JS_ExecuteScript(cx, obj, script, &result);
                if (ok && !JSVAL_IS_VOID(result)) {
                    str = JS_ValueToString(cx, result);
                    if (str)
                    {
                    	SG_ERR_IGNORE(  sg_jsglue__jsstring_to_sz(pCtx, cx, str, &sz)  );
                        fprintf(gOutFile, "%s\n", sz);
                        SG_NULLFREE(pCtx, sz);
                    }
                }
            }
        }
    } while (!hitEOF && !gQuitting);
    SG_CONTEXT_NULLFREE(pCtx);
    fprintf(gOutFile, "\n");
    return;
}
Exemplo n.º 12
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;
}