コード例 #1
0
// From native type to jsval
jsval int32_to_jsval( JSContext *cx, int32_t number )
{
    return INT_TO_JSVAL(number);
}
コード例 #2
0
JSProperty *
js_SetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
    JSRuntime *rt;
    JSScope *scope, *protoScope;
    JSProperty *prop, *protoProp;
    PRHashNumber hash;
    JSSymbol *sym, *protoSym;
    JSObject *proto, *assignobj;
    jsval pval, aval, rval;
    jsint slot;
    JSErrorReporter older;
    JSString *str;

    rt = cx->runtime;
    PR_ASSERT(JS_IS_RUNTIME_LOCKED(rt));

#ifdef SCOPE_TABLE_NOTYET
    /* XXX hash recompute */
    /* XXX protoProp->getter, protoProp->setter, protoProp->flags */
    scope = js_MutateScope(cx, obj, id, getter, setter, flags, &prop);
#endif
    scope = js_GetMutableScope(cx, obj);
    if (!scope)
	return NULL;

    /* Handle old bug that treated empty string as zero index. */
    CHECK_FOR_FUNNY_INDEX(id);

    hash = js_HashValue(id);
    sym = scope->ops->lookup(cx, scope, id, hash);
    if (sym) {
	prop = sym_property(sym);
#if JS_HAS_OBJ_WATCHPOINT
	if (!prop) {
	    /*
	     * Deleted property place-holder, could have a watchpoint that
	     * holds the deleted-but-watched property.
	     */
	    prop = js_FindWatchPoint(rt, obj, js_IdToValue(id));
	}
#endif
    } else {
	prop = NULL;
    }

    if (!prop) {
	/* Find a prototype property with the same id. */
	proto = OBJ_GET_PROTO(obj);
	protoProp = NULL;
	while (proto) {
	    protoScope = (JSScope *)proto->map;
	    protoSym = protoScope->ops->lookup(cx, protoScope, id, hash);
	    if (protoSym) {
		protoProp = sym_property(protoSym);
		if (protoProp)
		    break;
	    }
	    proto = OBJ_GET_PROTO(proto);
	}

	/* Make a new property descriptor with the right heritage. */
	if (protoProp) {
	    prop = js_NewProperty(cx, scope, id,
				  protoProp->getter, protoProp->setter,
				  protoProp->flags | JSPROP_ENUMERATE);
	    prop->id = protoProp->id;
	} else {
	    prop = js_NewProperty(cx, scope, id,
				  scope->map.clasp->getProperty,
				  scope->map.clasp->setProperty,
				  JSPROP_ENUMERATE);
	}
	if (!prop)
	    return NULL;

	if (!obj->map->clasp->addProperty(cx, obj, prop->id, vp)) {
	    js_DestroyProperty(cx, prop);
	    return NULL;
	}

	/* Initialize new properties to undefined. */
	obj->slots[prop->slot] = JSVAL_VOID;

	if (sym) {
	    /* Null-valued symbol left behind from a delete operation. */
	    sym->entry.value = js_HoldProperty(cx, prop);
	}
    }

    if (!sym) {
	/* Need a new symbol as well as a new property. */
	sym = scope->ops->add(cx, scope, id, prop);
	if (!sym)
	    return NULL;
#if JS_BUG_AUTO_INDEX_PROPS
	{
	    jsval id2 = INT_TO_JSVAL(prop->slot - JSSLOT_START);
	    if (!scope->ops->add(cx, scope, id2, prop)) {
		scope->ops->remove(cx, scope, id);
		return NULL;
	    }
	    PROPERTY_CACHE_FILL(cx, &rt->propertyCache, obj, id2, prop);
	}
#endif
	PROPERTY_CACHE_FILL(cx, &rt->propertyCache, obj, id, prop);
    }

    /* Get the current property value from its slot. */
    PR_ASSERT(prop->slot < obj->map->freeslot);
    slot = prop->slot;
    pval = obj->slots[slot];

    /* Evil overloaded operator assign() hack. */
    if (JSVAL_IS_OBJECT(pval)) {
	assignobj = JSVAL_TO_OBJECT(pval);
	if (assignobj) {
	    older = JS_SetErrorReporter(cx, NULL);
	    if (js_GetProperty(cx, assignobj, (jsval)rt->atomState.assignAtom,
			       &aval) &&
		JSVAL_IS_FUNCTION(aval) &&
		js_Call(cx, assignobj, aval, 1, vp, &rval)) {
		*vp = rval;
		JS_SetErrorReporter(cx, older);
		prop->flags |= JSPROP_ASSIGNHACK;
		return prop;
	    }
	    JS_SetErrorReporter(cx, older);
	}
    }

    /* Check for readonly *after* the assign() hack. */
    if (prop->flags & JSPROP_READONLY) {
	if (!JSVERSION_IS_ECMA(cx->version)) {
	    str = js_ValueToSource(cx, js_IdToValue(id));
	    if (str) {
		JS_ReportError(cx, "%s is read-only",
			       JS_GetStringBytes(str));
	    }
	}
	return NULL;
    }

    /* Let the setter modify vp before copying from it to obj->slots[slot]. */
    if (!prop->setter(cx, obj, prop->id, vp))
	return NULL;
    GC_POKE(cx, pval);
    obj->slots[slot] = *vp;

    /* Setting a property makes it enumerable. */
    prop->flags |= JSPROP_ENUMERATE;
    return prop;
}
コード例 #3
0
JSBool js_multiplayer_bot_get_skill(JSContext *cx,JSObject *j_obj,jsval id,jsval *vp)
{
	*vp=INT_TO_JSVAL(server.skill);
	return(JS_TRUE);
}
コード例 #4
0
-#if defined(XP_MACOSX)
+#if defined(XP_DARWIN)
 #include "copyfile.h"
-#endif // defined(XP_MACOSX)
+#endif // defined(XP_DARWIN)
 
 #if defined(XP_WIN)
 #include <windows.h>
@@ -564,10 +568,10 @@ static const dom::ConstantSpec gLibcProp
   // The size of |fsblkcnt_t|.
   { "OSFILE_SIZEOF_FSBLKCNT_T", INT_TO_JSVAL(sizeof (fsblkcnt_t)) },
 
-#if !defined(ANDROID)
+#if !defined(ANDROID) && (defined(__NetBSD_) && (__NetBSD_Version__ < 600000000))
   // The size of |posix_spawn_file_actions_t|.
   { "OSFILE_SIZEOF_POSIX_SPAWN_FILE_ACTIONS_T", INT_TO_JSVAL(sizeof (posix_spawn_file_actions_t)) },
-#endif // !defined(ANDROID)
+#endif // !defined(ANDROID) && NetBSD 5.*
 
   // Defining |dirent|.
   // Size
@@ -627,7 +631,7 @@ static const dom::ConstantSpec gLibcProp
 
   { "OSFILE_SIZEOF_STATVFS", INT_TO_JSVAL(sizeof (struct statvfs)) },
 
-  { "OSFILE_OFFSETOF_STATVFS_F_BSIZE", INT_TO_JSVAL(offsetof (struct statvfs, f_bsize)) },
+  { "OSFILE_OFFSETOF_STATVFS_F_FRSIZE", INT_TO_JSVAL(offsetof (struct statvfs, f_frsize)) },
   { "OSFILE_OFFSETOF_STATVFS_F_BAVAIL", INT_TO_JSVAL(offsetof (struct statvfs, f_bavail)) },
 
 #endif // defined(XP_UNIX)
コード例 #5
0
  INT_CONSTANT(S_IFREG),
  INT_CONSTANT(S_IFLNK),
  INT_CONSTANT(S_IFSOCK),
#endif // defined(S_IFIFO)

  // Constants used to define data structures
  //
  // Many data structures have different fields/sizes/etc. on
  // various OSes / versions of the same OS / platforms. For these
  // data structures, we need to compute and export from C the size
  // and, if necessary, the offset of fields, so as to be able to
  // define the structure in JS.

#if defined(XP_UNIX)
  // The size of |mode_t|.
  { "OSFILE_SIZEOF_MODE_T", INT_TO_JSVAL(sizeof (mode_t)) },

  // The size of |gid_t|.
  { "OSFILE_SIZEOF_GID_T", INT_TO_JSVAL(sizeof (gid_t)) },

  // The size of |uid_t|.
  { "OSFILE_SIZEOF_UID_T", INT_TO_JSVAL(sizeof (uid_t)) },

  // The size of |time_t|.
  { "OSFILE_SIZEOF_TIME_T", INT_TO_JSVAL(sizeof (time_t)) },

  // Defining |dirent|.
  // Size
  { "OSFILE_SIZEOF_DIRENT", INT_TO_JSVAL(sizeof (dirent)) },

  // Offset of field |d_name|.
コード例 #6
0
ファイル: nsJSFile.cpp プロジェクト: rn10950/RetroZilla
//
// Native method FileMacAlias
//
JSBool PR_CALLBACK
InstallFileOpFileMacAlias(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  nsInstall *nativeThis =
    GetNativeThis(cx, obj, argv);
  if (!nativeThis)
    return JS_FALSE;

  PRInt32          nativeRet;
  nsAutoString     sourceLeaf, aliasLeaf;
  JSObject         *jsoSourceFolder, *jsoAliasFolder;
  nsInstallFolder  *nsifSourceFolder, *nsifAliasFolder;
  nsresult         rv1 = NS_OK, rv2 = NS_OK;
  
  *rval = JSVAL_NULL;

  if(argc >= 3)
  {
    // public int FileMacAlias( InstallFolder aSourceFolder,
    //                          String        aSourceName,
    //                          InstallFolder aAliasFolder );
    // where
    //      aSourceFolder -- the folder of the installed file from Get*Folder() APIs
    //      aSourceName   -- the installed file's name
    //      aAliasFolder  -- the folder of the new alias from Get*Folder() APIs
    //
    // NOTE: 
    //      The destination alias name is aSourceName + " alias" (Mac-like behavior). 
    //      
    //      returns SUCCESS for successful scheduling of operation
    //              UNEXPECTED_ERROR for failure
    
    if (argv[0] == JSVAL_NULL || !JSVAL_IS_OBJECT(argv[0]) ||  // InstallFolder aSourceFolder
        argv[2] == JSVAL_NULL || !JSVAL_IS_OBJECT(argv[2]))    // InstallFolder aAliasFolder
    {
        *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
        return JS_TRUE;
    }

    jsoSourceFolder = JSVAL_TO_OBJECT(argv[0]);
    jsoAliasFolder  = JSVAL_TO_OBJECT(argv[2]);
    if ((!JS_InstanceOf(cx, jsoSourceFolder, &FileSpecObjectClass, nsnull)) ||
        (!JS_InstanceOf(cx, jsoAliasFolder,  &FileSpecObjectClass, nsnull)))
    {
        *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
        return JS_TRUE;
    }

    nsifSourceFolder = (nsInstallFolder *) JS_GetPrivate(cx, jsoSourceFolder);
    nsifAliasFolder  = (nsInstallFolder *) JS_GetPrivate(cx, jsoAliasFolder);
    if (!nsifSourceFolder || !nsifAliasFolder)
    {
        *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
        return JS_TRUE;
    }

    // make copies of the InstallFolders leaving originals uncontaminated
    nsCOMPtr<nsIFile> iFileSourceOrig = nsifSourceFolder->GetFileSpec(); 
    nsCOMPtr<nsIFile> iFileAliasOrig  = nsifAliasFolder->GetFileSpec();
    nsCOMPtr<nsIFile> iFileSource;
    nsCOMPtr<nsIFile> iFileAlias;
    rv1 = iFileSourceOrig->Clone(getter_AddRefs(iFileSource));
    rv2 = iFileAliasOrig->Clone(getter_AddRefs(iFileAlias));
    if (NS_FAILED(rv1) || NS_FAILED(rv2))
    {
        *rval = INT_TO_JSVAL(nsInstall::UNEXPECTED_ERROR);
        return JS_TRUE;
    }
    
    ConvertJSValToStr(sourceLeaf, cx, argv[1]);
    rv1 = iFileSource->Append(sourceLeaf);
        
    // public int FileMacAlias( InstallFolder aSourceFolder,
    //                          String        aSourceFileName,
    //                          InstallFolder aAliasFolder,
    //                          String        aAliasName );
    // where
    //      aSourceFolder -- the folder of the installed file from Get*Folder() APIs
    //      aSourceName   -- the installed file's name
    //      aAliasFolder  -- the folder of the new alias from Get*Folder() APIs
    //      aAliasName    -- the actual name of the new alias
    //      
    //      returns SUCCESS for successful scheduling of operation
    //              UNEXPECTED_ERROR for failure
    
    if (argc >= 4) 
    {
        ConvertJSValToStr(aliasLeaf, cx, argv[3]);
    }
    else
    {
    	aliasLeaf = sourceLeaf;
        aliasLeaf.AppendLiteral(" alias");   // XXX use GetResourcedString(id)
    }
    
    rv2 = iFileAlias->Append(aliasLeaf);
	if (NS_FAILED(rv1) || NS_FAILED(rv2))
	{
		*rval = INT_TO_JSVAL(nsInstall::UNEXPECTED_ERROR);
		return JS_TRUE;
	}

    if(NS_OK != nativeThis->FileOpFileMacAlias(iFileSource, iFileAlias, &nativeRet))
    {
        *rval = INT_TO_JSVAL(nsInstall::UNEXPECTED_ERROR);
        return JS_TRUE;
    }

    *rval = INT_TO_JSVAL(nativeRet);
  }
  else
  {
    JS_ReportError(cx, "Function FileMacAlias requires 3 or 4 parameters");
    return JS_TRUE;
  }

  return JS_TRUE;
}
コード例 #7
0
ファイル: jsexn.c プロジェクト: edrikL/gears
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;
        JSNativeFunction *fun;
        JSObject *funobj;
        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. */
        NATIVE_FUN_SET_CLASS(fun, &js_ErrorClass);

        /* Extract the constructor object. */
        funobj = &fun->base.object;

        /* Make the prototype and constructor links. */
        if (!js_SetClassPrototype(cx, funobj, 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, funobj))
            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];
}
コード例 #8
0
ファイル: context.cpp プロジェクト: carriercomm/jspp-2
void Context::ToJSArg(JS::Value *val, int arg) const
{
  *val = INT_TO_JSVAL(arg);
}
コード例 #9
0
ファイル: PJS_Reflection.c プロジェクト: gitpan/JSP
/* Converts perl values to equivalent JS values */
JSBool
PJS_ReflectPerl2JS(
    pTHX_ 
    JSContext *cx,
    JSObject *pobj,
    SV *ref,
    jsval *rval
) {
    PJS_Context *pcx = PJS_GET_CONTEXT(cx);
    JSObject *newobj = NULL;

    if(++pcx->svconv % 2000 == 0) {
	JSErrorReporter older;
	ENTER; SAVETMPS; /* Scope for finalizers */
	older = JS_SetErrorReporter(cx, NULL);
	if(pcx->svconv > 10000) {
	    JS_GC(cx);
	    pcx->svconv = 0;
	} else JS_MaybeGC(cx);
	JS_SetErrorReporter(cx, older);
	FREETMPS; LEAVE;
    }
    if(SvROK(ref)) {
	MAGIC *mg;
	/* First check old jsvisitors */
	if((newobj = PJS_IsPerlVisitor(aTHX_ pcx, SvRV(ref)))) {
	    PJS_DEBUG("Old jsvisitor returns\n");
	    *rval = OBJECT_TO_JSVAL(newobj);
	    return JS_TRUE;
	}

	if(SvMAGICAL(SvRV(ref)) && (mg = mg_find(SvRV(ref), PERL_MAGIC_tied))
	   && mg->mg_obj && sv_derived_from(mg->mg_obj, PJS_BOXED_PACKAGE)) {
	    PJS_DEBUG1("A magical ref %s, shortcircuit!\n", SvPV_nolen((SV*)mg->mg_obj));
	    ref = mg->mg_obj;
	}

	if(sv_derived_from(ref, PJS_BOXED_PACKAGE)) {
	    SV **fref = av_fetch((AV *)SvRV(SvRV(ref)), 2, 0);
	    assert(sv_derived_from(*fref, PJS_RAW_JSVAL));
	    *rval = (jsval)SvIV(SvRV(*fref));
	    return JS_TRUE;
	}

	if(sv_derived_from(ref, PJS_BOOLEAN)) {
	    *rval = SvTRUE(SvRV(ref)) ? JSVAL_TRUE : JSVAL_FALSE;
	    return JS_TRUE;
	}
	
	if(sv_isobject(ref)) {
	    newobj = PJS_NewPerlObject(aTHX_ cx, pobj, ref); 
	    if(newobj) {
		*rval = OBJECT_TO_JSVAL(newobj);
		return JS_TRUE;
	    }
	    return JS_FALSE;
	}
    }

    SvGETMAGIC(ref);

    if(!SvOK(ref)) /* undef */
        *rval = JSVAL_VOID;
    else if(SvIOK(ref) || SvIOKp(ref)) {
        if(SvIV(ref) <= JSVAL_INT_MAX)
            *rval = INT_TO_JSVAL(SvIV(ref));
        else JS_NewDoubleValue(cx, (double) SvIV(ref), rval);
    }
    else if(SvNOK(ref)) 
        JS_NewDoubleValue(cx, SvNV(ref), rval);
    else if(SvPOK(ref) || SvPOKp(ref)) {
        STRLEN len;
        char *str;
	SV *temp=NULL;
	if(SvREADONLY(ref)) {
	    temp = newSVsv(ref);
	    str = PJS_SvPV(temp, len);
	} else str = PJS_SvPV(ref, len);
	JSString *jstr = ((int)len >= 0)
	    ? JS_NewStringCopyN(cx, str, len)
	    : JS_NewUCStringCopyN(cx, (jschar *)str, -(int)len);
	sv_free(temp);
	if(!jstr) return JS_FALSE;
        *rval = STRING_TO_JSVAL(jstr);
    }
    else if(SvROK(ref)) { /* Plain reference */
        I32 type = SvTYPE(SvRV(ref));

        if(type == SVt_PVHV)
	    newobj = PJS_NewPerlHash(aTHX_ cx, pobj, ref);
	else if(type == SVt_PVAV)
	    newobj = PJS_NewPerlArray(aTHX_ cx, pobj, ref);
        else if(type == SVt_PVCV)
            newobj = PJS_NewPerlSub(aTHX_ cx, pobj, ref);            
	else
	    newobj = PJS_NewPerlScalar(aTHX_ cx, pobj, ref);
	if(!newobj) return JS_FALSE;
	*rval = OBJECT_TO_JSVAL(newobj);
    }
    else {
        warn("I have no idea what perl send us (it's of type %i), I'll pretend it's undef", SvTYPE(ref));
        *rval = JSVAL_VOID;
    }

    return JS_TRUE;
}
コード例 #10
0
static JSBool fade( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval )
{
   *rval = JSVAL_FALSE ;
   if( ( 5 == argc ) 
       && 
       JSVAL_IS_OBJECT( argv[0] )
       && 
       JSVAL_IS_OBJECT( argv[1] )
       && 
       JSVAL_IS_INT( argv[2] )
       && 
       JSVAL_IS_INT( argv[3] )
       && 
       JSVAL_IS_INT( argv[4] ) )
   {
      JSObject *thisObj = JS_NewObject( cx, &jsFadeClass_, NULL, NULL );

      if( thisObj )
      {
         *rval = OBJECT_TO_JSVAL( thisObj ); // root
         JSObject *const src = JSVAL_TO_OBJECT( argv[0] );
         JSObject *const dest = JSVAL_TO_OBJECT( argv[1] );
         jsval lhWidth, lhHeight,
               rhWidth, rhHeight ;
         if( JS_GetProperty( cx, src, "width", &lhWidth )
             &&
             JS_GetProperty( cx, src, "height", &lhHeight )
             &&
             JS_GetProperty( cx, dest, "width", &rhWidth )
             &&
             JS_GetProperty( cx, dest, "height", &rhHeight ) )
         {
            if( ( JSVAL_TO_INT( lhWidth ) == JSVAL_TO_INT( rhWidth ) )
                &&
                ( JSVAL_TO_INT( lhHeight ) == JSVAL_TO_INT( rhHeight ) ) )
            {
               int const duration = JSVAL_TO_INT( argv[2] );
               if( 0 < duration )
               {
                  int const x = JSVAL_TO_INT( argv[3] );
                  int const y = JSVAL_TO_INT( argv[4] );
                  fbDevice_t &fbDev = getFB();
                  if( ( 0 <= x ) && ( 0 <= y ) 
                      &&
                      ( fbDev.getWidth() > x )
                      &&
                      ( fbDev.getHeight() > y ) )
                  {
                     for( int i = 0 ; i < argc ; i++ )
                        JS_DefineProperty( cx, thisObj, 
                                           fadeProperties_[i].name, 
                                           argv[i], 0, 0,  JSPROP_ENUMERATE|JSPROP_PERMANENT|JSPROP_READONLY );
                     unsigned long const tickNow = now_ms();
                     JS_DefineProperty( cx, thisObj, fadeProperties_[argc].name, INT_TO_JSVAL( tickNow ),
                                        0, 0,  JSPROP_ENUMERATE|JSPROP_PERMANENT|JSPROP_READONLY );
                  }
               }
               else
                  JS_ReportError( cx, "duration must be > 0" );
            }
            else
               JS_ReportError( cx, "fade: images must be the same size\n"
                                   "%d/%d, %d/%d\n",
                               JSVAL_TO_INT( lhWidth ), JSVAL_TO_INT( rhWidth ),
                               JSVAL_TO_INT( lhHeight ), JSVAL_TO_INT( rhHeight ) );
         }
         else
            JS_ReportError( cx, "fade: getting image sizes" );
      }
      else
         JS_ReportError( cx, "Error allocating fade" );
   }
   else
      JS_ReportError( cx, "Usage : new fade( srcImg, destImg, durationMs );" );
      
   return JS_TRUE ;

}
コード例 #11
0
JSBool systemExecute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{// begin systemExecute
	// default return value
	*rval = INT_TO_JSVAL(-1);

	if(argc != 3)
		return JS_FALSE;
	if(JSVAL_IS_STRING(argv[0]) == false || JSVAL_IS_OBJECT(argv[1]) == false || JSVAL_IS_BOOLEAN(argv[2]) == false)
		return JS_FALSE;

	char *pExecutable = JS_GetStringBytes(JSVAL_TO_STRING(argv[0]));
	JSObject *pArgs = JSVAL_TO_OBJECT(argv[1]);
	bool bWait = JSVAL_TO_BOOLEAN(argv[2]);
	int status = 0;
	jsuint nArgsLength = 0;
	jsval jsValue;
	struct stat sbFileInfo;

	if(JS_IsArrayObject(cx, pArgs) == false)
		return JS_FALSE;

	JS_GetArrayLength(cx,pArgs,&nArgsLength);
	char **args = new char *[JSVAL_TO_INT(nArgsLength)+2];
	args[0] = pExecutable;
	args[JSVAL_TO_INT(nArgsLength)+1] = NULL;

	for(jsuint i = 1;i <= nArgsLength;i++)
	{
		if(JS_GetElement(cx, pArgs, i, &jsValue) == JS_FALSE)
		{// begin failure to get item
			JS_ReportError(cx, "exec() JS_GetElement failed to get an array item.");
			return JS_FALSE;
		}// end failure to get item
		args[JSVAL_TO_INT(i)] = JS_GetStringBytes(JSVAL_TO_STRING(jsValue));
	}
	if(getuid() == 0)
	{// begin running as root
		JS_ReportError(cx, "exec() disallowed while running as root.");
		return JS_FALSE;
	}// end running as root
	if(stat(pExecutable , &sbFileInfo) != 0)
	{// begin can't stat file
		JS_ReportError(cx, "exec() Can't stat \"%s\" errno(%i).", pExecutable, errno);
		return JS_FALSE;
	}// end can't stat file
	if((sbFileInfo.st_mode & S_ISUID) == S_ISUID || (sbFileInfo.st_mode & S_ISGID) == S_ISGID)
	{// begin setuid/setgid files disallowed
		JS_ReportError(cx, "exec() disallowed execution of \"%s\" since it is a setuid/setgid file.", pExecutable);
		return JS_FALSE;
	}// end setuid/setgid files disallowed

        enterLock();
	// clear file descriptor table of forked process and fork
#if defined( __linux__) || defined(__macosx__) || defined(__APPLE__)
	pid_t pidRtn = fork();
#elif defined(__FreeBSD__) || defined(__OpenBSD__)
	pid_t pidRtn = rfork(RFPROC|RFCFDG);
#endif
	if(pidRtn == 0)
	{// begin child process
#if defined( __linux__) || defined(__macosx__) || defined(__APPLE__)
		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
#endif
		char **pEnv = environ;
		//char *pEnv[] = {NULL};
		execve(pExecutable,args,pEnv);
		printf("Error: execve failure errno(%d)\n",errno);
		_exit(errno);
	}// end child process
	else if(bWait && pidRtn != -1)
	{// begin wait for execution to finish
		printf("Waiting on pid %d...",pidRtn);
		do
		{// begin wait for child
			waitpid(pidRtn,&status,WUNTRACED);
		}// end wait for child
		while(WIFEXITED(status) == false && WIFSIGNALED(status) == false);
		printf("Done...\n");
	}// end wait for execution to finish
	else if(pidRtn == -1)
	{// begin rfork failure
		printf("Error: execve failure errno(%d)\n",errno);
	}// end rfork failure
        leaveLock();

	// cleanup
	delete []args;
	if(pidRtn != -1)
		*rval = INT_TO_JSVAL(WEXITSTATUS(status));	// success return child's exit status
	else
		*rval = INT_TO_JSVAL(-1);	// failure
	return JS_TRUE;
}// end systemExecute
コード例 #12
0
ファイル: MPQStats.cpp プロジェクト: ds-hwang/d2bs
DWORD FillBaseStat(JSContext* cx, jsval *argv, INT table, INT row, INT column, char* szTable, char* szStat)
{
	if(szTable)
	{
		table = -1;
		for(int i = 0; BaseStatTable[i].pTable != NULL; i++)
			if(!_strcmpi(szTable, BaseStatTable[i].szTableName))
			{
				table = i;
				break;
			}

		if(table == -1)
			return false;
	}

	BinField* pTable = BaseStatTable[table].pTable;

	if(szStat)
	{
		column = -1;
		for(int i = 0; i < BaseStatTable[table].wTableSize; i++)
			if(!_strcmpi(szStat, pTable[i].szFieldName))
			{
				column = i;
				break;
			}

		if(column == -1)
			return false;
	}

	if(column > BaseStatTable[table].wTableSize)
		return FALSE;

	DWORD dwBuffer = 0;
	WORD wBuffer = 0;
	char* szBuffer = NULL;
	DWORD dwHelperSize = pTable[column+1].dwFieldOffset - pTable[column].dwFieldOffset;
	if(dwHelperSize > 4)
		dwHelperSize = 4;

	switch(pTable[column].eFieldType)
	{
		case FIELDTYPE_DATA_ASCII:
			szBuffer = new char[(pTable[column].dwFieldLength + 1)];
			memset(szBuffer, NULL, pTable[column].dwFieldLength + 1);
			if(!FillBaseStat(table, row, column, szBuffer, pTable[column].dwFieldLength+1))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szBuffer));
			delete[] szBuffer;
			return TRUE;

		case FIELDTYPE_DATA_DWORD:
		case FIELDTYPE_CALC_TO_DWORD:
		case FIELDTYPE_NAME_TO_DWORD:
		case FIELDTYPE_DATA_DWORD_2:
		case FIELDTYPE_UNKNOWN_11:
			if(!FillBaseStat(table, row, column, &dwBuffer, sizeof(DWORD)))
				(*argv) = JSVAL_VOID;
			else
				JS_NewNumberValue(cx, (jsdouble)dwBuffer, argv);
			return TRUE;

		case FIELDTYPE_NAME_TO_INDEX_2:
		case FIELDTYPE_NAME_TO_WORD_2:
		case FIELDTYPE_NAME_TO_INDEX:
		case FIELDTYPE_NAME_TO_WORD:
		case FIELDTYPE_KEY_TO_WORD:
		case FIELDTYPE_DATA_WORD:
		case FIELDTYPE_CODE_TO_WORD:
			if(!FillBaseStat(table, row, column, &wBuffer, sizeof(WORD)))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = INT_TO_JSVAL(wBuffer);
			return TRUE;

		case FIELDTYPE_CODE_TO_BYTE:
		case FIELDTYPE_DATA_BYTE_2:
		case FIELDTYPE_DATA_BYTE:
			if(!FillBaseStat(table, row, column, &dwBuffer, dwHelperSize))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = INT_TO_JSVAL(dwBuffer);
			return TRUE;

		case FIELDTYPE_DATA_BIT:
			if(!FillBaseStat(table, row, column, &dwBuffer, sizeof(DWORD)))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = BOOLEAN_TO_JSVAL(!!dwBuffer);
			return TRUE;

		case FIELDTYPE_ASCII_TO_CODE:
		case FIELDTYPE_DATA_RAW:
			szBuffer = new char[5];
			memset(szBuffer, NULL, 5);
			if(!FillBaseStat(table, row, column, szBuffer, 5))
				(*argv) = JSVAL_VOID;
			else
				(*argv) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szBuffer));
			delete[] szBuffer;
			return TRUE;

		case FIELDTYPE_MONSTER_COMPS:
			// ..? :E
			return FALSE;
	}
	return FALSE;
}
コード例 #13
0
ファイル: jsj_convert.c プロジェクト: chemeris/sipxecs
/*
 * Convert a JS value to a Java value of the given type signature.  The cost
 * variable is incremented if coercion is required, e.g. the source value is
 * a string, but the target type is a boolean.
 *
 * Returns JS_FALSE if no conversion is possible, either because the jsval has
 * a type that is wholly incompatible with the Java value, or because a scalar
 * jsval can't be represented in a variable of the target type without loss of
 * precision, e.g. the source value is "4.2" but the destination type is byte.
 * If conversion is not possible and java_value is non-NULL, the JS error
 * reporter is called with an appropriate message.
 */  
JSBool
jsj_ConvertJSValueToJavaValue(JSContext *cx, JNIEnv *jEnv, jsval v_arg,
                              JavaSignature *signature,
                              int *cost, jvalue *java_value, JSBool *is_local_refp)
{
    JavaSignatureChar type;
    jsval v;
    JSBool success = JS_FALSE;

    /* Initialize to default case, in which no new Java object is
       synthesized to perform the conversion and, therefore, no JNI local
       references are being held. */
    *is_local_refp = JS_FALSE;   
    
    type = signature->type;
    v = v_arg;
    switch (type) {
    case JAVA_SIGNATURE_BOOLEAN:
        if (!JSVAL_IS_BOOLEAN(v)) {
            if (!JS_ConvertValue(cx, v, JSTYPE_BOOLEAN, &v))
                goto conversion_error;
            if (JSVAL_IS_VOID(v))
                goto conversion_error;
            (*cost)++;
        }
        if (java_value)
            java_value->z = (jboolean)(JSVAL_TO_BOOLEAN(v) == JS_TRUE);
        break;

    case JAVA_SIGNATURE_SHORT:
        JSVAL_TO_INTEGRAL_JVALUE(short, s, jshort, v, java_value);
        break;

    case JAVA_SIGNATURE_BYTE:
        JSVAL_TO_INTEGRAL_JVALUE(byte, b, jbyte, v, java_value);
        break;

    case JAVA_SIGNATURE_CHAR:
        /* A one-character string can be converted into a character */
        if (JSVAL_IS_STRING(v) && (JS_GetStringLength(JSVAL_TO_STRING(v)) == 1)) {
            v = INT_TO_JSVAL(*JS_GetStringChars(JSVAL_TO_STRING(v)));
        }
        JSVAL_TO_INTEGRAL_JVALUE(char, c, jchar, v, java_value);
        break;

    case JAVA_SIGNATURE_INT:
        JSVAL_TO_INTEGRAL_JVALUE(int, i, jint, v, java_value);
        break;

    case JAVA_SIGNATURE_LONG:
#if defined(XP_MAC) || (defined(XP_OS2) && !defined(HAVE_LONG_LONG))
        JSVAL_TO_JLONG_JVALUE(j, jlong, v, java_value);
#else
        JSVAL_TO_INTEGRAL_JVALUE(long, j, jlong, v, java_value);
#endif
        break;
    
    case JAVA_SIGNATURE_FLOAT:
        if (!JSVAL_IS_NUMBER(v)) {
            if (!JS_ConvertValue(cx, v, JSTYPE_NUMBER, &v))
                goto conversion_error;
            (*cost)++;
        }
        if (java_value) {
            if (JSVAL_IS_INT(v))
                java_value->f = (jfloat) JSVAL_TO_INT(v);
            else
                java_value->f = (jfloat) *JSVAL_TO_DOUBLE(v);
        }
        break;

    case JAVA_SIGNATURE_DOUBLE:
        if (!JSVAL_IS_NUMBER(v)) {
            if (!JS_ConvertValue(cx, v, JSTYPE_NUMBER, &v))
                goto conversion_error;
            (*cost)++;
        }
        if (java_value) {
            if (JSVAL_IS_INT(v))
                java_value->d = (jdouble) JSVAL_TO_INT(v);
            else
                java_value->d = (jdouble) *JSVAL_TO_DOUBLE(v);
        }
        break;

    /* Non-primitive (reference) type */
    default:
        JS_ASSERT(IS_REFERENCE_TYPE(type));
        if (!jsj_ConvertJSValueToJavaObject(cx, jEnv, v, signature, cost,
            &java_value->l, is_local_refp))
            goto conversion_error;
        break;

    case JAVA_SIGNATURE_UNKNOWN:
    case JAVA_SIGNATURE_VOID:
        JS_ASSERT(0);
        return JS_FALSE;
    }

    /* Success */
    return JS_TRUE;

numeric_conversion_error:
    success = JS_TRUE;
    /* Fall through ... */

conversion_error:

    if (java_value) {
        const char *jsval_string;
        const char *class_name;
        JSString *jsstr;

        jsval_string = NULL;
        jsstr = JS_ValueToString(cx, v_arg);
        if (jsstr)
            jsval_string = JS_GetStringBytes(jsstr);
        if (!jsval_string)
            jsval_string = "";
        
        class_name = jsj_ConvertJavaSignatureToHRString(cx, signature);
        JS_ReportErrorNumber(cx, jsj_GetErrorMessage, NULL, 
                             JSJMSG_CANT_CONVERT_JS, jsval_string,
                             class_name);

        return JS_FALSE;
    }
    return success;
}
コード例 #14
0
ファイル: rpmxar-js.c プロジェクト: cmjonze/rpm5_tarballs
static JSBool
rpmxar_enumerate(JSContext *cx, JSObject *obj, JSIterateOp op,
		  jsval *statep, jsid *idp)
{
    void * ptr = JS_GetInstancePrivate(cx, obj, &rpmxarClass, NULL);
    rpmxar xar = ptr;
    int ix = 0;

_ENUMERATE_DEBUG_ENTRY(_debug < 0);

    switch (op) {
    case JSENUMERATE_INIT:
    case JSENUMERATE_INIT_ALL:
	if (idp)
	    *idp = JSVAL_ZERO;
	*statep = INT_TO_JSVAL(ix);
if (_debug)
fprintf(stderr, "\tINIT xar %p\n", xar);
        break;
    case JSENUMERATE_NEXT:
	ix = JSVAL_TO_INT(*statep);
	if (!rpmxarNext(xar)) {
	    const char * path = rpmxarPath(xar);
	    struct stat * st = xmalloc(sizeof(*st));
	    JSObject * arr = JS_NewArrayObject(cx, 0, NULL);
	    JSBool ok = JS_AddRoot(cx, &arr);
	    JSObject * o;
	    jsval v;

	    v = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, path));
	    ok = JS_SetElement(cx, arr, 0, &v);
	    if (!rpmxarStat(xar, st)
	     && (o = JS_NewObject(cx, &rpmstClass, NULL, NULL)) != NULL
             && JS_SetPrivate(cx, o, (void *)st))
		v = OBJECT_TO_JSVAL(o);
	    else {
		st = _free(st);
		v = JSVAL_NULL;
	    }
	    ok = JS_SetElement(cx, arr, 1, &v);

	    v = OBJECT_TO_JSVAL(arr);
	    ok = JS_DefineElement(cx, obj, ix, v, NULL, NULL, JSPROP_ENUMERATE);

	    (void) JS_RemoveRoot(cx, &arr);
if (_debug)
fprintf(stderr, "\tNEXT xar %p[%u] \"%s\"\n", xar, ix, path);
	    path = _free(path);
	    JS_ValueToId(cx, *statep, idp);
	    *statep = INT_TO_JSVAL(ix+1);
	} else
	    *idp = JSVAL_VOID;
	if (!JSID_IS_VOID(*idp))
            break;
        /*@fallthrough@*/
    case JSENUMERATE_DESTROY:
	ix = JSVAL_TO_INT(*statep);
	(void) JS_DefineProperty(cx, obj, "length", INT_TO_JSVAL(ix),
			NULL, NULL, JSPROP_ENUMERATE);
if (_debug)
fprintf(stderr, "\tFINI xar %p[%u]\n", xar, ix);
	*statep = JSVAL_NULL;
        break;
    }
    return JS_TRUE;
}
コード例 #15
0
jsval long_to_jsval(JSContext* cx, long v)
{
    return INT_TO_JSVAL(v);
}
コード例 #16
0
ファイル: system.c プロジェクト: PofigNaNik/gjs
JSBool
gjs_js_define_system_stuff(JSContext *context,
                           JSObject  *module)
{
    GjsContext *gjs_context;
    char *program_name;
    jsval value;
    JSBool retval;

    if (!JS_DefineFunction(context, module,
                           "addressOf",
                           (JSNative) gjs_address_of,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module,
                           "refcount",
                           (JSNative) gjs_refcount,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module,
                           "breakpoint",
                           (JSNative) gjs_breakpoint,
                           0, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module,
                           "gc",
                           (JSNative) gjs_gc,
                           0, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module,
                           "exit",
                           (JSNative) gjs_exit,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    retval = JS_FALSE;

    gjs_context = JS_GetContextPrivate(context);
    g_object_get(gjs_context,
                 "program-name", &program_name,
                 NULL);

    if (!gjs_string_from_utf8(context, program_name,
                              -1, &value))
        goto out;

    /* The name is modeled after program_invocation_name,
       part of the glibc */
    if (!JS_DefineProperty(context, module,
                           "programInvocationName",
                           value,
                           JS_PropertyStub,
                           JS_StrictPropertyStub,
                           GJS_MODULE_PROP_FLAGS | JSPROP_READONLY))
        goto out;

    if (!JS_DefineProperty(context, module,
                           "version",
                           INT_TO_JSVAL(GJS_VERSION),
                           JS_PropertyStub,
                           JS_StrictPropertyStub,
                           GJS_MODULE_PROP_FLAGS | JSPROP_READONLY))
        goto out;

    retval = JS_TRUE;

 out:
    g_free(program_name);

    return retval;
}
コード例 #17
0
ファイル: nsJSFile.cpp プロジェクト: rn10950/RetroZilla
//
// Native method FileWindowsShortcut
//
JSBool PR_CALLBACK
InstallFileOpFileWindowsShortcut(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  nsInstall *nativeThis =
    GetNativeThis(cx, obj, argv);
  if (!nativeThis)
    return JS_FALSE;

  PRInt32 nativeRet;
  nsAutoString b0;
  nsAutoString b1;
  nsAutoString b2;
  nsAutoString b3;
  nsAutoString b4;
  nsAutoString b5;
  nsCOMPtr<nsILocalFile> nsfsB0;
  nsCOMPtr<nsILocalFile> nsfsB1;
  nsCOMPtr<nsILocalFile> nsfsB3;
  nsCOMPtr<nsILocalFile> nsfsB5;
  PRInt32      b6;

  //JSObject *jsObj;
  //nsInstallFolder *folder;

  *rval = JSVAL_NULL;

  if(argc >= 7)
  {
    //  public int FileWindowsShortcut(String aTarget,
    //                                 String aShortcutPath,
    //                                 String aDescription,
    //                                 String aWorkingPath,
    //                                 String aParams,
    //                                 String aIcon,
    //                                 Number aIconId);


    ConvertJSValToStr(b0, cx, argv[0]);
    NS_NewLocalFile(b0, PR_TRUE, getter_AddRefs(nsfsB0));
    ConvertJSValToStr(b1, cx, argv[1]);
    NS_NewLocalFile(b1, PR_TRUE, getter_AddRefs(nsfsB1));
    ConvertJSValToStr(b2, cx, argv[2]);
    ConvertJSValToStr(b3, cx, argv[3]);
    NS_NewLocalFile(b3, PR_TRUE, getter_AddRefs(nsfsB3));
    ConvertJSValToStr(b4, cx, argv[4]);
    ConvertJSValToStr(b5, cx, argv[5]);
    NS_NewLocalFile(b5, PR_TRUE, getter_AddRefs(nsfsB5));

    if(JSVAL_IS_NULL(argv[6]))
    {
      b6 = 0;
    }
    else
    {
      b6 = JSVAL_TO_INT(argv[6]);
    }

    if(NS_OK != nativeThis->FileOpFileWindowsShortcut(nsfsB0, nsfsB1, b2, nsfsB3, b4, nsfsB5, b6, &nativeRet))
    {
      return JS_TRUE;
    }

    *rval = INT_TO_JSVAL(nativeRet);
  }
  else
  {
    JS_ReportError(cx, "Function FileWindowsShortcut requires 7 parameters");
    return JS_TRUE;
  }

  return JS_TRUE;
}
コード例 #18
0
/**
 * This method is called when getting a Property from HTMLTableRowElement
 */
static JSBool jhtml_tablerow_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
  #if (WEBC_SUPPORT_TABLES)
	HTMLElement *pElem = (HTMLElement *) jhutil_GetPrivate(cx, obj);
	HTMLTableRow *pTableRow = (pElem)? (HTMLTableRow *) pElem : 0;
	WebcJSScript *jsscr = (WebcJSScript *) jhutil_GetContextPrivate(cx);
	WebcJSDocumentContext *jsmgr = (jsscr)? jsscr->GetJSMgr() : 0;
	if (!pTableRow || !jsmgr)
		return JS_TRUE;

	JSString *jsstr = 0;
	switch (JSVAL_TO_INT(id))
	{
		case HTMLTABLEROWELEMENT_ROWINDEX:
			*vp = INT_TO_JSVAL(pTableRow->RowIndex());
		case HTMLTABLEROWELEMENT_SECTIONROWINDEX:
			//this is not implimented in our browser
			break;
		case HTMLTABLEROWELEMENT_ALIGN:
			switch (pTableRow->GetTextAlign())
			{
				case TU_ALIGN_LEFT:
					jsstr = JS_InternString(cx, "left");
					break;
				case TU_ALIGN_RIGHT:
					jsstr = JS_InternString(cx, "right");
					break;
				case TU_ALIGN_CENTER:
					jsstr = JS_InternString(cx, "center");
					break;
//				case TU_ALIGN_JUSTIFY:
//					jsstr = JS_InternString(cx, "justify");
//					break;
			}
			if (!jsstr)
				jsstr = JS_InternString(cx, "undefined");
			*vp = STRING_TO_JSVAL(jsstr);
			return JS_TRUE;
		case HTMLTABLEROWELEMENT_BGCOLOR:
			//this has been deprecated
			break;
		case HTMLTABLEROWELEMENT_CH:
			//this is not implemented in our browser
			break;
		case HTMLTABLEROWELEMENT_CHOFF:
			//this is not implemented in our browser
			break;
		case HTMLTABLEROWELEMENT_VALIGN:
			switch (pTableRow->GetVAlign())
			{
				case TU_VALIGN_TOP:
					jsstr = JS_InternString(cx, "top");
					break;
				case TU_VALIGN_MIDDLE:
					jsstr = JS_InternString(cx, "center");
					break;
				case TU_VALIGN_BOTTOM:
					jsstr = JS_InternString(cx, "bottom");
					break;
				case TU_VALIGN_BASELINE:
					jsstr = JS_InternString(cx, "baseline");
					break;
				default:
					jsstr = JS_InternString(cx, "undefined");
					break;
			}
			*vp = STRING_TO_JSVAL(jsstr);
			return JS_TRUE;
	}//end switch
	return JS_TRUE;
  #else // WEBC_SUPPORT_TABLES
    return JS_FALSE;
  #endif // WEBC_SUPPORT_TABLES
}
コード例 #19
0
ファイル: nsJSFile.cpp プロジェクト: rn10950/RetroZilla
//
// Native method FileCopy
//
JSBool PR_CALLBACK
InstallFileOpFileCopy(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  nsInstall *nativeThis =
    GetNativeThis(cx, obj, argv);
  if (!nativeThis)
    return JS_FALSE;

  PRInt32 nativeRet;
  JSObject *jsSrcObj, *jsTargetObj;
  nsInstallFolder *srcFolder, *targetFolder;

  *rval = INT_TO_JSVAL(nsInstall::UNEXPECTED_ERROR);

  if(argc >= 2)
  {
    //  public int FileCopy (nsInstallFolder aSourceFolder,
    //                       nsInstallFolder aTargetFolder);

    if (argv[0] == JSVAL_NULL || !JSVAL_IS_OBJECT(argv[0])) //argv[0] MUST be a jsval
    {
      *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
      return JS_TRUE;
    }

    if (argv[1] == JSVAL_NULL || !JSVAL_IS_OBJECT(argv[1])) //argv[1] MUST be a jsval
    {
      *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
      return JS_TRUE;
    }

    jsSrcObj = JSVAL_TO_OBJECT(argv[0]);
    jsTargetObj = JSVAL_TO_OBJECT(argv[1]);

    if (!JS_InstanceOf(cx, jsSrcObj, &FileSpecObjectClass, nsnull))
    {
      *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
      return JS_TRUE;
    }
    if (!JS_InstanceOf(cx, jsTargetObj, &FileSpecObjectClass, nsnull))
    {
      *rval = INT_TO_JSVAL(nsInstall::INVALID_ARGUMENTS);
      return JS_TRUE;
    }

    srcFolder = (nsInstallFolder*)JS_GetPrivate(cx, jsSrcObj);
    targetFolder = (nsInstallFolder*)JS_GetPrivate(cx, jsTargetObj);
    PRInt32 tempRet;
    tempRet = nativeThis->FileOpFileCopy(*srcFolder, *targetFolder, &nativeRet);

    if(!srcFolder || !targetFolder || NS_OK != tempRet)
    {
      return JS_TRUE;
    }

    *rval = INT_TO_JSVAL(nativeRet);
  }
  else
  {
    JS_ReportError(cx, "Function FileCopy requires 2 parameters");
    return JS_TRUE;
  }

  return JS_TRUE;
}
コード例 #20
0
ファイル: task.cpp プロジェクト: BenitoJedai/jslibs
bool
TheTask(JSContext *cx, TaskPrivate *pv) {

	bool ok;
	jsval argv[3] = { JSVAL_NULL }; // argv[0] is rval and code

	JSObject *globalObj;
	globalObj = JL_GetGlobal(cx);
	ASSERT( globalObj );

	// no need to mutex this because this and the constructor are the only places that access pv->serializedCode.
	ok = UnserializeJsval(cx, pv->serializedCode, &argv[0]);
	SerializerFree(&pv->serializedCode);
	JL_CHK( ok );

	JSFunction *fun;
	fun = JS_ValueToFunction(cx, argv[0]);
	JL_CHK( fun );
/*
	JSObject *funObj;
	funObj = JS_GetFunctionObject(fun);
	ASSERT( funObj );
	// JL_CHK( JS_SetParent(cx, funObj, globalObj) ); // re-scope the function
	ASSERT( JS_GetParent(funObj) );
*/

	size_t index;
	index = 0;

	for (;;) {

		JL_CHK( JLSemaphoreAcquire(pv->requestSem) ); // -1 // wait for a request

		JLMutexAcquire(pv->mutex); // --
		if ( pv->end ) { // manage the end of the thread

			JLMutexRelease(pv->mutex); // ++
			break;
		}

		SerializedData *serializedRequest;
		serializedRequest = (SerializedData*)QueueShift(&pv->requestList);
		pv->pendingRequestCount--;
		pv->processingRequestCount++; // = 1;
		JLMutexRelease(pv->mutex); // ++

		ASSERT( serializedRequest );
		ok = UnserializeJsval(cx, serializedRequest, &argv[1]);
		SerializerFree(&serializedRequest);
		JL_CHK( ok );

		argv[2] = INT_TO_JSVAL(index++);

		ok = JS_CallFunction(cx, globalObj, fun, COUNTOF(argv)-1, argv+1, argv);
		if ( ok ) {

			SerializedData *serializedResponse;
			SerializerCreate(&serializedResponse);
			JL_CHK( SerializeJsval(cx, serializedResponse, &argv[0]) );

			JLMutexAcquire(pv->mutex); // --
			QueuePush(&pv->responseList, serializedResponse);
			pv->pendingResponseCount++;
			pv->processingRequestCount--;
			JLMutexRelease(pv->mutex); // ++
		} else {

			jsval ex;
			if ( JL_IsExceptionPending(cx) ) { // manageable error

				ok = JS_GetPendingException(cx, &ex);
				JS_ClearPendingException(cx);
				JL_CHK( ok );
			} else {

				ex = JSVAL_VOID; // unknown exception
			}

			SerializedData *serializedException;
			SerializerCreate(&serializedException);
			JL_CHK( SerializeJsval(cx, serializedException, &ex) );

			JLMutexAcquire(pv->mutex); // --
			QueuePush(&pv->exceptionList, serializedException);
			QueuePush(&pv->responseList, NULL); // signals an exception
			pv->pendingResponseCount++;
			pv->processingRequestCount--;
			JLMutexRelease(pv->mutex); // ++
		}

		ASSERT( pv->processingRequestCount == 0 );

		JLSemaphoreRelease(pv->responseSem); // +1 // signals a response
		JLEventTrigger(pv->responseEvent);
	}

	return true;
	JL_BAD;
}