void
CacheIRSpewer::valueProperty(LockGuard<Mutex>&, const char* name, const Value& v)
{
    MOZ_ASSERT(enabled());
    JSONPrinter& j = json.ref();

    j.beginObjectProperty(name);

    const char* type = InformalValueTypeName(v);
    if (v.isInt32())
        type = "int32";
    j.property("type", type);

    if (v.isInt32()) {
        j.property("value", v.toInt32());
    } else if (v.isDouble()) {
        j.floatProperty("value", v.toDouble(), 3);
    } else if (v.isString() || v.isSymbol()) {
        JSString* str = v.isString() ? v.toString() : v.toSymbol()->description();
        if (str && str->isLinear()) {
            j.beginStringProperty("value");
            QuoteString(output, &str->asLinear());
            j.endStringProperty();
        }
    } else if (v.isObject()) {
        j.formatProperty("value", "%p (shape: %p)", &v.toObject(),
                         v.toObject().maybeShape());
    }

    j.endObject();
}
Example #2
0
bool AssetPack::initialize(const Json::Value &root) {
	if (!root.isObject()) return false;
	Value version = root["Version"];
	Value gameName = root["GameName"];
	Value defaultSave = root["EntityLocationsFile"];
	Value assetRoot = root["Assets"];
	
	if (!version.isConvertibleTo(ValueType::realValue)) return false;
	if (!gameName.isString()) return false;
	if (!defaultSave.isString()) return false;
	if (!assetRoot.isArray()) return false;

	this->version = version.asDouble();
	this->gameName = gameName.asString();
	this->defaultSaveFile = defaultSave.asString();
	this->assetRoot = assetRoot;
	Value assetName;
	for (Value asset : assetRoot) {
		if (!asset.isObject()) continue;
		assetName = asset["Name"];
		if (!assetName.isString()) continue;
		if (assetValues.find(assetName.asString()) != assetValues.end()) {
			cout << "Asset pack contains duplicated asset: " << assetName.asString() <<". Ignoring duplicate." << endl;
			continue;
		}
		assetValues[assetName.asString()] = asset;
	}
	return true;
}
static bool
DumpHeapComplete(JSContext *cx, unsigned argc, jsval *vp)
{
    CallArgs args = CallArgsFromVp(argc, vp);

    DumpHeapNurseryBehaviour nurseryBehaviour = js::IgnoreNurseryObjects;
    FILE *dumpFile = nullptr;

    unsigned i = 0;
    if (argc > i) {
        Value v = args[i];
        if (v.isString()) {
            JSString *str = v.toString();
            bool same = false;
            if (!JS_StringEqualsAscii(cx, str, "collectNurseryBeforeDump", &same))
                return false;
            if (same) {
                nurseryBehaviour = js::CollectNurseryBeforeDump;
                ++i;
            }
        }
    }

    if (argc > i) {
        Value v = args[i];
        if (v.isString()) {
            if (!fuzzingSafe) {
                JSString *str = v.toString();
                JSAutoByteString fileNameBytes;
                if (!fileNameBytes.encodeLatin1(cx, str))
                    return false;
                const char *fileName = fileNameBytes.ptr();
                dumpFile = fopen(fileName, "w");
                if (!dumpFile) {
                    JS_ReportError(cx, "can't open %s", fileName);
                    return false;
                }
            }
            ++i;
        }
    }

    if (i != argc) {
        JS_ReportError(cx, "bad arguments passed to dumpHeapComplete");
        return false;
    }

    js::DumpHeapComplete(JS_GetRuntime(cx), dumpFile ? dumpFile : stdout, nurseryBehaviour);

    if (dumpFile)
        fclose(dumpFile);

    JS_SET_RVAL(cx, vp, JSVAL_VOID);
    return true;
}
    CompletionType evaluate()
    {
        Value* value = getScopeChain()->get("iid");
        if (!value->isString())
        {
            throw getErrorInstance("TypeError");
        }

        const char* iid = value->toString().c_str();

        Reflect::Interface interface;
        try
        {
            interface = es::getInterface(iid);
        }
        catch (...)
        {
            throw getErrorInstance("TypeError");
        }

        // Construct Interface Object
        ObjectValue* object = new ObjectValue;
        object->setCode(new InterfaceConstructor(object, iid));
        object->setPrototype(prototype);
        return CompletionType(CompletionType::Return, object, "");
    }
 std::pair<size_t, bool> StreamWriter<StreamType>::append_value(const Value& v)
 {
     std::pair<size_t, bool> k(0, false);
     if(v.isNull())
         k = append_null();
     else if(v.isBool())
         k = append_bool(v);
     else if(v.isChar())
         k = append_char(v);
     else if(v.isSignedInteger())
         k = append_signedInt(v);
     else if(v.isUnsignedInteger())
         k = append_unsignedInt(v);
     else if(v.isFloat())
         k = append_float(v);
     else if(v.isString())
         k = append_string(v);
     //else if(v.isBinary())
     //    k = append_binary(v); //currently not supported
     else if(v.isArray())
         k = append_array(v);
     else if(v.isObject())
         k = append_object(v);
     return k;
 }
Example #6
0
bool DeviceGroup::open(const char *key, PolyDriver& poly,
                       yarp::os::Searchable& config, const char *comment) {

    Value *name;
    if (config.check(key,name,comment)) {
        if (name->isString()) {
            // maybe user isn't doing nested configuration
            yarp::os::Property p;
            p.setMonitor(config.getMonitor(),
                         name->toString().c_str()); // pass on any monitoring
            p.fromString(config.toString());
            p.put("device",name->toString());
            p.unput("subdevice");
            p.unput("wrapped");
            poly.open(p);
        } else {
            Bottle subdevice = config.findGroup(key).tail();
            poly.open(subdevice);
        }
        if (!poly.isValid()) {
            printf("cannot make <%s>\n", name->toString().c_str());
            return false;
        }
    } else {
        printf("\"--%s <name>\" not set\n", key);
        return false;
    }
    return true;
}
Example #7
0
Tuple::Tuple(Value value)
{ 
    if (!value.isTuple() && !value.isString())
        throw RunError("non-tuple value in tuple constructor");

    tuple = value;
}
Example #8
0
 int String::compare(const Value& v) {
     if (v.isString()) {
         return _value.compare(v.toString());
     } else {
         return toNumber() - v.toNumber();
     }
 }
Example #9
0
static JSAtom *
ToAtomSlow(ExclusiveContext *cx, typename MaybeRooted<Value, allowGC>::HandleType arg)
{
    JS_ASSERT(!arg.isString());

    Value v = arg;
    if (!v.isPrimitive()) {
        if (!cx->shouldBeJSContext() || !allowGC)
            return NULL;
        RootedValue v2(cx, v);
        if (!ToPrimitive(cx->asJSContext(), JSTYPE_STRING, &v2))
            return NULL;
        v = v2;
    }

    if (v.isString())
        return AtomizeString<allowGC>(cx, v.toString());
    if (v.isInt32())
        return Int32ToAtom<allowGC>(cx, v.toInt32());
    if (v.isDouble())
        return NumberToAtom<allowGC>(cx, v.toDouble());
    if (v.isBoolean())
        return v.toBoolean() ? cx->names().true_ : cx->names().false_;
    if (v.isNull())
        return cx->names().null;
    return cx->names().undefined;
}
Example #10
0
bool
Library::Name(JSContext* cx, unsigned argc, Value* vp)
{
  CallArgs args = CallArgsFromVp(argc, vp);
  if (args.length() != 1) {
    JS_ReportErrorASCII(cx, "libraryName takes one argument");
    return false;
  }

  Value arg = args[0];
  JSString* str = nullptr;
  if (arg.isString()) {
    str = arg.toString();
  } else {
    JS_ReportErrorASCII(cx, "name argument must be a string");
    return false;
  }

  AutoString resultString;
  AppendString(resultString, DLL_PREFIX);
  AppendString(resultString, str);
  AppendString(resultString, DLL_SUFFIX);

  JSString* result = JS_NewUCStringCopyN(cx, resultString.begin(),
                                         resultString.length());
  if (!result)
    return false;

  args.rval().setString(result);
  return true;
}
static JSBool
DumpHeapComplete(JSContext *cx, unsigned argc, jsval *vp)
{
    const char *fileName = NULL;
    JSAutoByteString fileNameBytes;
    if (argc > 0) {
        Value v = JS_ARGV(cx, vp)[0];
        if (v.isString()) {
            JSString *str = v.toString();
            if (!fileNameBytes.encodeLatin1(cx, str))
                return false;
            fileName = fileNameBytes.ptr();
        }
    }

    FILE *dumpFile;
    if (!fileName) {
        dumpFile = stdout;
    } else {
        dumpFile = fopen(fileName, "w");
        if (!dumpFile) {
            JS_ReportError(cx, "can't open %s", fileName);
            return false;
        }
    }

    js::DumpHeapComplete(JS_GetRuntime(cx), dumpFile);

    fclose(dumpFile);

    JS_SET_RVAL(cx, vp, JSVAL_VOID);
    return true;
}
Example #12
0
static HashNumber
HashValue(const Value& v, const mozilla::HashCodeScrambler& hcs)
{
    // HashableValue::setValue normalizes values so that the SameValue relation
    // on HashableValues is the same as the == relationship on
    // value.asRawBits(). So why not just return that? Security.
    //
    // To avoid revealing GC of atoms, string-based hash codes are computed
    // from the string contents rather than any pointer; to avoid revealing
    // addresses, pointer-based hash codes are computed using the
    // HashCodeScrambler.

    if (v.isString())
        return v.toString()->asAtom().hash();
    if (v.isSymbol()) {
        Symbol* sym = v.toSymbol();
        if (sym->isWellKnownSymbol())
            return HashNumber(sym->code());
        if (sym->code() == SymbolCode::InSymbolRegistry)
            return sym->description()->hash();
        return hcs.scramble(v.asRawBits());
    }
    if (v.isObject())
        return hcs.scramble(v.asRawBits());

    MOZ_ASSERT(!v.isGCThing(), "do not reveal pointers via hash codes");
    return v.asRawBits();
}
Example #13
0
JSON_STATUS CXBMCOperations::StartSlideshow(const CStdString &method, ITransportLayer *transport, IClient *client, const Value &parameterObject, Value &result)
{
  CStdString exec = "slideShow(";

  if (parameterObject.isString())
    exec += parameterObject.asString();
  else if (parameterObject.isObject() && parameterObject.isMember("directory") && parameterObject["directory"].isString())
  {
    exec += parameterObject["directory"].asString();

    if (parameterObject.get("random", true).asBool())
      exec += ", random";
    else
      exec += ", notrandom";

    if (parameterObject.get("recursive", true).asBool())
      exec += ", recursive";
  }
  else
    return InvalidParams;

  exec += ")";
  ThreadMessage msg = { TMSG_EXECUTE_BUILT_IN, (DWORD)0, (DWORD)0, exec };
  g_application.getApplicationMessenger().SendMessage(msg);

  return ACK;
}
Example #14
0
static bool
CloneValue(JSContext *cx, const Value &selfHostedValue, MutableHandleValue vp, CloneMemory &clonedObjects)
{
    if (selfHostedValue.isObject()) {
        JSObject *selfHostedObject = &selfHostedValue.toObject();
        RootedObject clone(cx, CloneObject(cx, selfHostedObject, clonedObjects));
        if (!clone)
            return false;
        vp.setObject(*clone);
    } else if (selfHostedValue.isBoolean() || selfHostedValue.isNumber() || selfHostedValue.isNullOrUndefined()) {
        // Nothing to do here: these are represented inline in the value.
        vp.set(selfHostedValue);
    } else if (selfHostedValue.isString()) {
        if (!selfHostedValue.toString()->isFlat())
            MOZ_CRASH();
        JSFlatString *selfHostedString = &selfHostedValue.toString()->asFlat();
        RootedString clone(cx, js_NewStringCopyN<CanGC>(cx,
                                                        selfHostedString->chars(),
                                                        selfHostedString->length()));
        if (!clone)
            return false;
        vp.setString(clone);
    } else {
        MOZ_ASSUME_UNREACHABLE("Self-hosting CloneValue can't clone given value.");
    }
    return true;
}
Example #15
0
//
// Function: GESTEP
//
Value func_gestep(valVector args, ValueCalc *calc, FuncExtra *)
{
    Value x = args[0];
    Value y = Value(0.0);
    if (args.count() == 2)
        y = args[1];

    if (x.isString() || y.isString())
        return Value::errorNUM();

    int result = 0;
    if (calc->greater(x, y) || calc->approxEqual(x, y))
        result = 1;

    return Value(result);
}
Example #16
0
bool ServerSerial::open(Searchable& prop)
{
    verb = (prop.check("verbose",Value(0),"Specifies if the device is in verbose mode (0/1).").asInt())>0;
    if (verb)
        printf("running with verbose output\n");

    Value *name;
    if (prop.check("subdevice",name,"name of specific control device to wrap")) {
        printf("Subdevice %s\n", name->toString().c_str());
        if (name->isString()) {
            // maybe user isn't doing nested configuration
            Property p;
            p.setMonitor(prop.getMonitor(),
                            "subdevice"); // pass on any monitoring
            p.fromString(prop.toString());
            p.put("device",name->toString());
            poly.open(p);
        } else {
            Bottle subdevice = prop.findGroup("subdevice").tail();
            poly.open(subdevice);
        }
        if (!poly.isValid()) {
            printf("cannot make <%s>\n", name->toString().c_str());
        }
    } else {
        printf("\"--subdevice <name>\" not set for server_serial\n");
        return false;
    }

    if (!poly.isValid()) {
        return false;
    }

    ConstString rootName =
        prop.check("name",Value("/serial"),
                    "prefix for port names").asString().c_str();

    command_buffer.attach(toDevice);
    reply_buffer.attach(fromDevice);

    command_buffer.useCallback(callback_impl);

    toDevice.open((rootName+"/in").c_str());
    fromDevice.open((rootName+"/out").c_str());



    if (poly.isValid())
        poly.view(serial);

    if(serial != NULL) {
        start();
        return true;
    }

    printf("subdevice <%s> doesn't look like a serial port (no appropriate interfaces were acquired)\n",
                    name->toString().c_str());

    return false;
}
Example #17
0
// Function: DCOUNT
Value func_dcount(valVector args, ValueCalc *calc, FuncExtra *)
{
    Value database = args[0];
    Value conditions = args[2];
    int fieldIndex = getFieldIndex(calc, args[1], database);

    DBConditions conds(calc, database, conditions);

    int rows = database.rows() - 1;  // first row contains column names
    int count = 0;
    for (int r = 0; r < rows; ++r)
        if (conds.matches(r)) {
            // fieldIndex is optional, if no field is specified count all rows matching the conditions
            if (fieldIndex < 0)
                count++;
            else {
                Value val = database.element(fieldIndex, r + 1);
                // include this value in the result
                if ((!val.isEmpty()) && (!val.isBoolean()) && (!val.isString()))
                    count++;
            }
        }

    return Value(count);
}
Example #18
0
js::ToBooleanSlow(const Value &v)
{
    if (v.isString())
        return v.toString()->length() != 0;

    JS_ASSERT(v.isObject());
    return !EmulatesUndefined(&v.toObject());
}
Example #19
0
void CFileItemHandler::FillDetails(ISerializable* info, CFileItemPtr item, const Value& fields, Value &result)
{
  if (info == NULL || fields.size() == 0)
    return;

  CVariant data;
  info->Serialize(data);

  Value serialization;
  data.toJsonValue(serialization);

  for (unsigned int i = 0; i < fields.size(); i++)
  {
    CStdString field = fields[i].asString();

    if (item)
    {
      if (item->IsAlbum() && item->HasProperty(field))
      {
        if (field == "album_rating")
          result[field] = item->GetPropertyInt(field);
        else
          result[field] = item->GetProperty(field);

        continue;
      }

      if (field == "fanart")
      {
        CStdString cachedFanArt = item->GetCachedFanart();
        if (!cachedFanArt.IsEmpty())
        {
          result["fanart"] = cachedFanArt.c_str();
          continue;
        }
      }
    }

    if (serialization.isMember(field))
    {
      Value value = serialization[field];
      if (!value.isString() || (value.isString() && !value.asString().empty()))
        result[field] = value;
    }
  }
}
Example #20
0
void TEMPLATE::set_foo( const Value &value, index_t, int, const index_t* )
{
  if( !value.isString() )
  {
    throw Exception() << "Param 'foo' must be set with string.";
  }

  m_foo = value.getString();
}
Example #21
0
static bool
Str(JSContext* cx, const Value& v, StringifyContext* scx)
{
    /* Step 11 must be handled by the caller. */
    MOZ_ASSERT(!IsFilteredValue(v));

    JS_CHECK_RECURSION(cx, return false);

    /*
     * This method implements the Str algorithm in ES5 15.12.3, but:
     *
     *   * We move property retrieval (step 1) into callers to stream the
     *     stringification process and avoid constantly copying strings.
     *   * We move the preprocessing in steps 2-4 into a helper function to
     *     allow both JO and JA to use this method.  While JA could use it
     *     without this move, JO must omit any |undefined|-valued property per
     *     so it can't stream out a value using the Str method exactly as
     *     defined by ES5.
     *   * We move step 11 into callers, again to ease streaming.
     */

    /* Step 8. */
    if (v.isString())
        return Quote(cx, scx->sb, v.toString());

    /* Step 5. */
    if (v.isNull())
        return scx->sb.append("null");

    /* Steps 6-7. */
    if (v.isBoolean())
        return v.toBoolean() ? scx->sb.append("true") : scx->sb.append("false");

    /* Step 9. */
    if (v.isNumber()) {
        if (v.isDouble()) {
            if (!IsFinite(v.toDouble()))
                return scx->sb.append("null");
        }

        return NumberValueToStringBuffer(cx, v, scx->sb);
    }

    /* Step 10. */
    MOZ_ASSERT(v.isObject());
    RootedObject obj(cx, &v.toObject());

    scx->depth++;
    bool ok;
    if (IsArray(obj, cx))
        ok = JA(cx, obj, scx);
    else
        ok = JO(cx, obj, scx);
    scx->depth--;

    return ok;
}
Example #22
0
void JSException::buildMessage(JSContextRef ctx, JSValueRef exn, JSStringRef sourceURL, const char* errorMsg) {
  std::ostringstream msgBuilder;
  if (errorMsg && strlen(errorMsg) > 0) {
    msgBuilder << errorMsg << ": ";
  }

  Object exnObject = Value(ctx, exn).asObject();
  Value exnMessage = exnObject.getProperty("message");
  msgBuilder << (exnMessage.isString() ? exnMessage : (Value)exnObject).toString().str();

  // The null/empty-ness of source tells us if the JS came from a
  // file/resource, or was a constructed statement.  The location
  // info will include that source, if any.
  std::string locationInfo = sourceURL != nullptr ? String::ref(ctx, sourceURL).str() : "";
  auto line = exnObject.getProperty("line");
  if (line != nullptr && line.isNumber()) {
    if (locationInfo.empty() && line.asInteger() != 1) {
      // If there is a non-trivial line number, but there was no
      // location info, we include a placeholder, and the line
      // number.
      locationInfo = folly::to<std::string>("<unknown file>:", line.asInteger());
    } else if (!locationInfo.empty()) {
      // If there is location info, we always include the line
      // number, regardless of its value.
      locationInfo += folly::to<std::string>(":", line.asInteger());
    }
  }

  if (!locationInfo.empty()) {
    msgBuilder << " (" << locationInfo << ")";
  }

  auto exceptionText = msgBuilder.str();
  LOG(ERROR) << "Got JS Exception: " << exceptionText;
  msg_ = std::move(exceptionText);

  Value jsStack = exnObject.getProperty("stack");
  if (jsStack.isString()) {
    auto stackText = jsStack.toString().str();
    LOG(ERROR) << "Got JS Stack: " << stackText;
    stack_ = std::move(stackText);
  }
}
Example #23
0
static HashNumber
HashValue(const Value& v)
{
    // HashableValue::setValue normalizes values so that the SameValue relation
    // on HashableValues is the same as the == relationship on
    // value.data.asBits.
    if (v.isString())
        return v.toString()->asAtom().hash();
    return v.asRawBits();
}
JSON_STATUS CPlaylistOperations::Destroy(const CStdString &method, ITransportLayer *transport, IClient *client, const Value &parameterObject, Value &result)
{
  if (!parameterObject.isString())
    return InvalidParams;

  CSingleLock lock(VirtualCriticalSection);
  VirtualPlaylists.erase(parameterObject.asString());

  return ACK;
}
Example #25
0
	string run(const url& url_) throw (bad_alloc) {
		vector<Value> args;
		args.push_back(glb.newString(url_.to_string()));
		args.push_back(glb.newString(url_.get_host()));

		Value res = glb.call("FindProxyForURL", args);
		if (res.isString() && !res.isException())
			return res.toString();
		return "";
	}
Example #26
0
bool Value::sameValue(Value other) const {
    if (val == other.val)
        return true;
    if (isString() && other.isString())
        return stringValue()->isEqualTo(other.stringValue());
    if (isInteger() && other.isDouble())
        return int_32 ? (double(int_32) == other.doubleValue()) : (other.val == 0);
    if (isDouble() && other.isInteger())
        return other.int_32 ? (doubleValue() == double(other.int_32)) : (val == 0);
    return false;
}
std::string Reference::extractReference(const Value &value)
{
	if (value.isString()) {
		return value.toString();
	} else if (value.isObject()) {
		if (value.hasMember("$ref") && value["$ref"].isString()) {
			return value["$ref"].toString();
		}
	}
	return std::string();
}
Example #28
0
Node::Node(Value value)
{
    if (value.isObject())
        construct(&value.toObject());
    else if (value.isString())
        construct(value.toString());
    else if (value.isSymbol())
        construct(value.toSymbol());
    else
        construct<void>(nullptr);
}
TEST(YAMLUtilsTest, toValueTestByte)
{
  const char* s1 = "this is a string";
  Value v = YAMLUtils::toValue(s1, NTA_BasicType_Byte);
  EXPECT_TRUE(!v.isScalar()) << "assertion !v.isScalar() failed at "
    << __FILE__ << ":" << __LINE__ ;
  EXPECT_TRUE(v.isString()) << "assertion v.isScalar() failed at "
    << __FILE__ << ":" << __LINE__ ;
  ASSERT_EQ(v.getType(), NTA_BasicType_Byte);
  std::string s = *v.getString();
  EXPECT_STREQ(s1, s.c_str());
}
Example #30
0
ReturnedValue Lookup::getterGeneric(Lookup *l, ExecutionEngine *engine, const Value &object)
{
    if (Object *o = object.asObject())
        return o->getLookup(l);

    Object *proto;
    switch (object.type()) {
    case Value::Undefined_Type:
    case Value::Null_Type:
        return engine->throwTypeError();
    case Value::Boolean_Type:
        proto = engine->booleanPrototype.asObject();
        break;
    case Value::Managed_Type: {
        Q_ASSERT(object.isString());
        proto = engine->stringPrototype.asObject();
        Scope scope(engine);
        ScopedString name(scope, engine->currentContext()->compilationUnit->runtimeStrings[l->nameIndex]);
        if (name->equals(engine->id_length)) {
            // special case, as the property is on the object itself
            l->getter = stringLengthGetter;
            return stringLengthGetter(l, engine, object);
        }
        break;
    }
    case Value::Integer_Type:
    default: // Number
        proto = engine->numberPrototype.asObject();
    }

    PropertyAttributes attrs;
    ReturnedValue v = l->lookup(object, proto, &attrs);
    if (v != Primitive::emptyValue().asReturnedValue()) {
        l->type = object.type();
        l->proto = proto;
        if (attrs.isData()) {
            if (l->level == 0)
                l->getter = Lookup::primitiveGetter0;
            else if (l->level == 1)
                l->getter = Lookup::primitiveGetter1;
            return v;
        } else {
            if (l->level == 0)
                l->getter = Lookup::primitiveGetterAccessor0;
            else if (l->level == 1)
                l->getter = Lookup::primitiveGetterAccessor1;
            return v;
        }
    }

    return Encode::undefined();
}