static bool extractSourceInformationFromException(JSC::ExecState* exec, JSObject* exceptionObject, int* lineNumber, int* columnNumber, String* sourceURL)
{
    VM& vm = exec->vm();
    auto scope = DECLARE_CATCH_SCOPE(vm);

    // FIXME: <http://webkit.org/b/115087> Web Inspector: Should not need to evaluate JavaScript handling exceptions
    JSValue lineValue = exceptionObject->getDirect(vm, Identifier::fromString(exec, "line"));
    JSValue columnValue = exceptionObject->getDirect(vm, Identifier::fromString(exec, "column"));
    JSValue sourceURLValue = exceptionObject->getDirect(vm, Identifier::fromString(exec, "sourceURL"));
    
    bool result = false;
    if (lineValue && lineValue.isNumber()
        && sourceURLValue && sourceURLValue.isString()) {
        *lineNumber = int(lineValue.toNumber(exec));
        *columnNumber = columnValue && columnValue.isNumber() ? int(columnValue.toNumber(exec)) : 0;
        *sourceURL = sourceURLValue.toWTFString(exec);
        result = true;
    } else if (ErrorInstance* error = jsDynamicCast<ErrorInstance*>(vm, exceptionObject)) {
        unsigned unsignedLine;
        unsigned unsignedColumn;
        result = getLineColumnAndSource(error->stackTrace(), unsignedLine, unsignedColumn, *sourceURL);
        *lineNumber = static_cast<int>(unsignedLine);
        *columnNumber = static_cast<int>(unsignedColumn);
    }
    
    if (sourceURL->isEmpty())
        *sourceURL = "undefined"_s;
    
    scope.clearException();
    return result;
}
Пример #2
0
PassRefPtr<ScriptCallStack> createScriptCallStackFromException(JSC::ExecState* exec, JSC::JSValue& exception, size_t maxStackSize)
{
    Vector<ScriptCallFrame> frames;
    RefCountedArray<StackFrame> stackTrace = exec->vm().exceptionStack();
    for (size_t i = 0; i < stackTrace.size() && i < maxStackSize; i++) {
        if (!stackTrace[i].callee && frames.size())
            break;

        unsigned line;
        unsigned column;
        stackTrace[i].computeLineAndColumn(line, column);
        String functionName = stackTrace[i].friendlyFunctionName(exec);
        frames.append(ScriptCallFrame(functionName, stackTrace[i].sourceURL, line, column));
    }

    // FIXME: <http://webkit.org/b/115087> Web Inspector: WebCore::reportException should not evaluate JavaScript handling exceptions
    // Fallback to getting at least the line and sourceURL from the exception if it has values and the exceptionStack doesn't.
    if (frames.size() > 0) {
        const ScriptCallFrame& firstCallFrame = frames.first();
        JSObject* exceptionObject = exception.toObject(exec);
        if (exception.isObject() && firstCallFrame.sourceURL().isEmpty()) {
            JSValue lineValue = exceptionObject->getDirect(exec->vm(), Identifier(exec, "line"));
            int lineNumber = lineValue && lineValue.isNumber() ? int(lineValue.toNumber(exec)) : 0;
            JSValue columnValue = exceptionObject->getDirect(exec->vm(), Identifier(exec, "column"));
            int columnNumber = columnValue && columnValue.isNumber() ? int(columnValue.toNumber(exec)) : 0;
            JSValue sourceURLValue = exceptionObject->getDirect(exec->vm(), Identifier(exec, "sourceURL"));
            String exceptionSourceURL = sourceURLValue && sourceURLValue.isString() ? sourceURLValue.toString(exec)->value(exec) : ASCIILiteral("undefined");
            frames[0] = ScriptCallFrame(firstCallFrame.functionName(), exceptionSourceURL, lineNumber, columnNumber);
        }
    }

    return ScriptCallStack::create(frames);
}
static RefPtr<IDBKey> createIDBKeyFromValue(ExecState& exec, JSValue value, Vector<JSArray*>& stack)
{
    VM& vm = exec.vm();
    if (value.isNumber() && !std::isnan(value.toNumber(&exec)))
        return IDBKey::createNumber(value.toNumber(&exec));

    if (value.isString())
        return IDBKey::createString(asString(value)->value(&exec));

    if (value.inherits<DateInstance>(vm)) {
        auto dateValue = valueToDate(exec, value);
        if (!std::isnan(dateValue))
            return IDBKey::createDate(dateValue);
    }

    if (value.isObject()) {
        JSObject* object = asObject(value);
        if (auto* array = jsDynamicCast<JSArray*>(vm, object)) {
            size_t length = array->length();

            if (stack.contains(array))
                return nullptr;

            if (stack.size() >= maximumDepth)
                return nullptr;

            stack.append(array);

            Vector<RefPtr<IDBKey>> subkeys;
            for (size_t i = 0; i < length; i++) {
                JSValue item = array->getIndex(&exec, i);
                RefPtr<IDBKey> subkey = createIDBKeyFromValue(exec, item, stack);
                if (!subkey)
                    subkeys.append(IDBKey::createInvalid());
                else
                    subkeys.append(subkey);
            }

            stack.removeLast();
            return IDBKey::createArray(subkeys);
        }

        if (auto* arrayBuffer = jsDynamicCast<JSArrayBuffer*>(vm, value))
            return IDBKey::createBinary(*arrayBuffer);

        if (auto* arrayBufferView = jsDynamicCast<JSArrayBufferView*>(vm, value))
            return IDBKey::createBinary(*arrayBufferView);
    }
    return nullptr;
}
Пример #4
0
void reportException(ExecState* exec, JSValue exception, CachedScript* cachedScript)
{
    if (isTerminatedExecutionException(exception))
        return;

    Interpreter::ErrorHandlingMode mode(exec);

    RefPtr<ScriptCallStack> callStack(createScriptCallStackFromException(exec, exception, ScriptCallStack::maxCallStackSizeToCapture));
    exec->clearException();
    exec->clearSupplementaryExceptionInfo();

    JSDOMGlobalObject* globalObject = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject());
    if (JSDOMWindow* window = jsDynamicCast<JSDOMWindow*>(globalObject)) {
        if (!window->impl()->isCurrentlyDisplayedInFrame())
            return;
    }

    int lineNumber = 0;
    int columnNumber = 0;
    String exceptionSourceURL;
    if (callStack->size()) {
        const ScriptCallFrame& frame = callStack->at(0);
        lineNumber = frame.lineNumber();
        columnNumber = frame.columnNumber();
        exceptionSourceURL = frame.sourceURL();
    } else {
        // There may not be an exceptionStack for a <script> SyntaxError. Fallback to getting at least the line and sourceURL from the exception.
        JSObject* exceptionObject = exception.toObject(exec);
        JSValue lineValue = exceptionObject->getDirect(exec->vm(), Identifier(exec, "line"));
        lineNumber = lineValue && lineValue.isNumber() ? int(lineValue.toNumber(exec)) : 0;
        JSValue columnValue = exceptionObject->getDirect(exec->vm(), Identifier(exec, "column"));
        columnNumber = columnValue && columnValue.isNumber() ? int(columnValue.toNumber(exec)) : 0;
        JSValue sourceURLValue = exceptionObject->getDirect(exec->vm(), Identifier(exec, "sourceURL"));
        exceptionSourceURL = sourceURLValue && sourceURLValue.isString() ? sourceURLValue.toString(exec)->value(exec) : ASCIILiteral("undefined");
    }

    String errorMessage;
    if (ExceptionBase* exceptionBase = toExceptionBase(exception))
        errorMessage = exceptionBase->message() + ": "  + exceptionBase->description();
    else {
        // FIXME: <http://webkit.org/b/115087> Web Inspector: WebCore::reportException should not evaluate JavaScript handling exceptions
        // If this is a custon exception object, call toString on it to try and get a nice string representation for the exception.
        errorMessage = exception.toString(exec)->value(exec);
        exec->clearException();
        exec->clearSupplementaryExceptionInfo();
    }

    ScriptExecutionContext* scriptExecutionContext = globalObject->scriptExecutionContext();
    scriptExecutionContext->reportException(errorMessage, lineNumber, columnNumber, exceptionSourceURL, callStack->size() ? callStack : 0, cachedScript);
}
Пример #5
0
static inline T toSmallerUInt(ExecState* exec, JSValue value, IntegerConversionConfiguration configuration)
{
    typedef IntTypeLimits<T> LimitsTrait;
    // Fast path if the value is already a 32-bit unsigned integer in the right range.
    if (value.isUInt32()) {
        uint32_t d = value.asUInt32();
        if (d <= LimitsTrait::maxValue)
            return static_cast<T>(d);
        if (configuration == EnforceRange) {
            throwTypeError(exec);
            return 0;
        }
        return static_cast<T>(d);
    }

    double x = value.toNumber(exec);
    if (exec->hadException())
        return 0;

    if (configuration == EnforceRange)
        return enforceRange(exec, x, 0, LimitsTrait::maxValue);

    if (std::isnan(x) || std::isinf(x) || !x)
        return 0;

    x = x < 0 ? -floor(fabs(x)) : floor(fabs(x));
    return static_cast<T>(fmod(x, LimitsTrait::numberOfValues));
}
Пример #6
0
// http://www.w3.org/TR/WebIDL/#es-byte
int8_t toInt8(ExecState* exec, JSValue value, IntegerConversionConfiguration configuration)
{
    // Fast path if the value is already a 32-bit signed integer in the right range.
    if (value.isInt32()) {
        int32_t d = value.asInt32();
        if (d >= kMinInt8 && d <= kMaxInt8)
            return static_cast<int8_t>(d);
        if (configuration == EnforceRange) {
            throwTypeError(exec);
            return 0;
        }
        d %= 256;
        return static_cast<int8_t>(d > kMaxInt8 ? d - 256 : d);
    }

    double x = value.toNumber(exec);
    if (exec->hadException())
        return 0;

    if (configuration == EnforceRange)
        return enforceRange(exec, x, kMinInt8, kMaxInt8);

    if (std::isnan(x) || std::isinf(x) || !x)
        return 0;

    x = x < 0 ? -floor(fabs(x)) : floor(fabs(x));
    x = fmod(x, 256); // 2^8.

    return static_cast<int8_t>(x > kMaxInt8 ? x - 256 : x);
}
static EncodedJSValue JSC_HOST_CALL IntlDateTimeFormatFuncFormatDateTime(ExecState* state)
{
    // 12.3.4 DateTime Format Functions (ECMA-402 2.0)
    // 1. Let dtf be the this value.
    // 2. Assert: Type(dtf) is Object and dtf has an [[initializedDateTimeFormat]] internal slot whose value is true.
    IntlDateTimeFormat* format = jsCast<IntlDateTimeFormat*>(state->thisValue());

    JSValue date = state->argument(0);
    double value;

    // 3. If date is not provided or is undefined, then
    if (date.isUndefined()) {
        // a. Let x be %Date_now%().
        value = JSValue::decode(dateNow(state)).toNumber(state);
    } else {
        // 4. Else
        // a. Let x be ToNumber(date).
        value = date.toNumber(state);
        // b. ReturnIfAbrupt(x).
        if (state->hadException())
            return JSValue::encode(jsUndefined());
    }

    // 5. Return FormatDateTime(dtf, x).
    return JSValue::encode(format->format(*state, value));
}
Пример #8
0
static inline double normalizeHighWaterMark(ExecState& exec, JSObject& strategy)
{
    JSValue jsHighWaterMark = getPropertyFromObject(exec, strategy, "highWaterMark");

    if (exec.hadException())
        return 0;

    if (jsHighWaterMark.isUndefined())
        return 1;

    double highWaterMark = jsHighWaterMark.toNumber(&exec);

    if (exec.hadException())
        return 0;

    if (std::isnan(highWaterMark)) {
        throwVMError(&exec, createTypeError(&exec, ASCIILiteral("Value is NaN")));
        return 0;
    }
    if (highWaterMark < 0) {
        throwVMError(&exec, createRangeError(&exec, ASCIILiteral("Not a positive value")));
        return 0;
    }
    return highWaterMark;
}
Пример #9
0
// ECMA 15.9.3
JSObject* constructDate(ExecState* exec, JSGlobalObject* globalObject, JSValue newTarget, const ArgList& args)
{
    VM& vm = exec->vm();
    int numArgs = args.size();

    double value;

    if (numArgs == 0) // new Date() ECMA 15.9.3.3
        value = NORMAL_OR_DETERMINISTIC_FUNCTION(jsCurrentTime(), deterministicCurrentTime(globalObject));
    else if (numArgs == 1) {
        if (args.at(0).inherits(DateInstance::info()))
            value = asDateInstance(args.at(0))->internalNumber();
        else {
            JSValue primitive = args.at(0).toPrimitive(exec);
            if (primitive.isString())
                value = parseDate(vm, primitive.getString(exec));
            else
                value = primitive.toNumber(exec);
        }
    } else
        value = millisecondsFromComponents(exec, args, WTF::LocalTime);

    Structure* dateStructure = InternalFunction::createSubclassStructure(exec, newTarget, globalObject->dateStructure());

    return DateInstance::create(vm, dateStructure, value);
}
Пример #10
0
double JSObject::toNumber(ExecState *exec) const
{
  JSValue *prim = toPrimitive(exec,NumberType);
  if (exec->hadException()) // should be picked up soon in nodes.cpp
    return 0.0;
  return prim->toNumber(exec);
}
Пример #11
0
JSValue JSWebSocket::close(ExecState* exec)
{
    // FIXME: We should implement [Clamp] for IDL binding code generator, and
    // remove this custom method.
    WebSocket* webSocket = static_cast<WebSocket*>(impl());
    size_t argumentCount = exec->argumentCount();
    int code = WebSocketChannel::CloseEventCodeNotSpecified;
    String reason = "";
    if (argumentCount >= 1) {
        JSValue v = exec->argument(0);
        double x = v.toNumber(exec);
        double maxValue = static_cast<double>(std::numeric_limits<uint16_t>::max());
        double minValue = static_cast<double>(std::numeric_limits<uint16_t>::min());
        if (isnan(x))
            x = 0.0;
        else
            x = clampTo(x, minValue, maxValue);
        code = clampToInteger(x);
        if (argumentCount >= 2) {
            reason = ustringToString(exec->argument(1).toString(exec)->value(exec));
            if (exec->hadException()) {
                setDOMException(exec, SYNTAX_ERR);
                return jsUndefined();
            }
        }
    }
    ExceptionCode ec = 0;
    webSocket->close(code, reason, ec);
    setDOMException(exec, ec);
    return jsUndefined();
}
Пример #12
0
// http://www.w3.org/TR/WebIDL/#es-octet
uint8_t toUInt8(ExecState* exec, JSValue value, IntegerConversionConfiguration configuration)
{
    // Fast path if the value is already a 32-bit unsigned integer in the right range.
    if (value.isUInt32()) {
        uint32_t d = value.asUInt32();
        if (d <= kMaxUInt8)
            return static_cast<uint8_t>(d);
        if (configuration == EnforceRange) {
            throwTypeError(exec);
            return 0;
        }
        return static_cast<uint8_t>(d % 256); // 2^8.
    }

    double x = value.toNumber(exec);
    if (exec->hadException())
        return 0;

    if (configuration == EnforceRange)
        return enforceRange(exec, x, 0, kMaxUInt8);

    if (std::isnan(x) || std::isinf(x) || !x)
        return 0;

    x = x < 0 ? -floor(fabs(x)) : floor(fabs(x));
    return static_cast<uint8_t>(fmod(x, 256)); // 2^8.
}
Пример #13
0
double JSObject::toNumber(ExecState* exec) const
{
    JSValue primitive = toPrimitive(exec, PreferNumber);
    if (exec->hadException()) // should be picked up soon in Nodes.cpp
        return 0.0;
    return primitive.toNumber(exec);
}
void setJSHTMLMeterElementOptimum(ExecState* exec, JSObject* thisObject, JSValue value)
{
    JSHTMLMeterElement* castedThis = static_cast<JSHTMLMeterElement*>(thisObject);
    HTMLMeterElement* imp = static_cast<HTMLMeterElement*>(castedThis->impl());
    ExceptionCode ec = 0;
    imp->setOptimum(value.toNumber(exec), ec);
    setDOMException(exec, ec);
}
Пример #15
0
int main(int argc, char **argv)
{
    // expecting a filename
    if (argc < 2) {
        fprintf(stderr, "You have to specify at least one filename\n");
        return -1;
    }
    
    bool ret = true;
    {
        JSLock lock;
        
        // create interpreter w/ global object
        Global* global = new Global();
        RefPtr<Interpreter> interp = new Interpreter(global);
        ExecState *exec = interp->globalExec();
        
        MyObject *myObject = (MyObject *)_NPN_CreateObject (NPP(0), myFunctionPtrs);
        
// FIXME
//        global->put(exec, Identifier("myInterface"), Instance::createRuntimeObject(Instance::CLanguage, (void *)myObject));
        
        for (int i = 1; i < argc; i++) {
            const char *code = readJavaScriptFromFile(argv[i]);
            
            if (code) {
                // run
                Completion comp(interp->evaluate("", 0, code));
                
                if (comp.complType() == Throw) {
                    JSValue *exVal = comp.value();
                    char *msg = exVal->toString(exec).ascii();
                    int lineno = -1;
                    if (exVal->type() == ObjectType) {
                        JSValue *lineVal = exVal->getObject()->get(exec, Identifier("line"));
                        if (lineVal->type() == NumberType)
                            lineno = int(lineVal->toNumber(exec));
                    }
                    if (lineno != -1)
                        fprintf(stderr,"Exception, line %d: %s\n",lineno,msg);
                    else
                        fprintf(stderr,"Exception: %s\n",msg);
                    ret = false;
                }
                else if (comp.complType() == ReturnValue) {
                    char *msg = comp.value()->toString(interp->globalExec()).ascii();
                    fprintf(stderr,"Return value: %s\n",msg);
                }
            }
        }
                
        _NPN_ReleaseObject ((NPObject *)myObject);
        
    } // end block, so that Interpreter and global get deleted
    
    return ret ? 0 : 3;
}
Пример #16
0
// http://www.w3.org/TR/WebIDL/#es-unsigned-long
uint32_t toUInt32EnforceRange(ExecState* exec, JSValue value)
{
    if (value.isUInt32())
        return value.asUInt32();

    double x = value.toNumber(exec);
    if (exec->hadException())
        return 0;
    return enforceRange(exec, x, 0, kMaxUInt32);
}
Пример #17
0
// ECMA 15.9.3
JSObject* constructDate(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args)
{
    VM& vm = exec->vm();
    int numArgs = args.size();

    double value;

    if (numArgs == 0) // new Date() ECMA 15.9.3.3
        value = jsCurrentTime();
    else if (numArgs == 1) {
        if (args.at(0).inherits(DateInstance::info()))
            value = asDateInstance(args.at(0))->internalNumber();
        else {
            JSValue primitive = args.at(0).toPrimitive(exec);
            if (primitive.isString())
                value = parseDate(vm, primitive.getString(exec));
            else
                value = primitive.toNumber(exec);
        }
    } else {
        double doubleArguments[7] = {
            args.at(0).toNumber(exec), 
            args.at(1).toNumber(exec), 
            args.at(2).toNumber(exec), 
            args.at(3).toNumber(exec), 
            args.at(4).toNumber(exec), 
            args.at(5).toNumber(exec), 
            args.at(6).toNumber(exec)
        };
        if (!std::isfinite(doubleArguments[0])
            || !std::isfinite(doubleArguments[1])
            || (numArgs >= 3 && !std::isfinite(doubleArguments[2]))
            || (numArgs >= 4 && !std::isfinite(doubleArguments[3]))
            || (numArgs >= 5 && !std::isfinite(doubleArguments[4]))
            || (numArgs >= 6 && !std::isfinite(doubleArguments[5]))
            || (numArgs >= 7 && !std::isfinite(doubleArguments[6])))
            value = QNaN;
        else {
            GregorianDateTime t;
            int year = JSC::toInt32(doubleArguments[0]);
            t.setYear((year >= 0 && year <= 99) ? (year + 1900) : year);
            t.setMonth(JSC::toInt32(doubleArguments[1]));
            t.setMonthDay((numArgs >= 3) ? JSC::toInt32(doubleArguments[2]) : 1);
            t.setHour(JSC::toInt32(doubleArguments[3]));
            t.setMinute(JSC::toInt32(doubleArguments[4]));
            t.setSecond(JSC::toInt32(doubleArguments[5]));
            t.setIsDST(-1);
            double ms = (numArgs >= 7) ? doubleArguments[6] : 0;
            value = gregorianDateTimeToMS(vm, t, ms, false);
        }
    }

    return DateInstance::create(vm, globalObject->dateStructure(), value);
}
Пример #18
0
JSLR_API bool _cdecl JSTryConvertToNumber(JSContextRef ctx, JSValueRef value, double* result)
{
	ExecState* exec = toJS(ctx);
	JSValue jsValue = toJS(exec, value);
	if (jsValue.isNumber())
	{
		*result = jsValue.toNumber(exec);
		return true;
	}
	return false;
}
// ECMA 15.9.3
JSObject* constructDate(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args)
{
    int numArgs = args.size();

    double value;

    if (numArgs == 0) // new Date() ECMA 15.9.3.3
        value = jsCurrentTime();
    else if (numArgs == 1) {
        if (args.at(0).inherits(&DateInstance::s_info))
            value = asDateInstance(args.at(0))->internalNumber();
        else {
            JSValue primitive = args.at(0).toPrimitive(exec);
            if (primitive.isString())
                value = parseDate(exec, primitive.getString(exec));
            else
                value = primitive.toNumber(exec);
        }
    } else {
        double doubleArguments[7] = {
            args.at(0).toNumber(exec),
            args.at(1).toNumber(exec),
            args.at(2).toNumber(exec),
            args.at(3).toNumber(exec),
            args.at(4).toNumber(exec),
            args.at(5).toNumber(exec),
            args.at(6).toNumber(exec)
        };
        if (isnan(doubleArguments[0])
                || isnan(doubleArguments[1])
                || (numArgs >= 3 && isnan(doubleArguments[2]))
                || (numArgs >= 4 && isnan(doubleArguments[3]))
                || (numArgs >= 5 && isnan(doubleArguments[4]))
                || (numArgs >= 6 && isnan(doubleArguments[5]))
                || (numArgs >= 7 && isnan(doubleArguments[6])))
            value = NaN;
        else {
            GregorianDateTime t;
            int year = JSC::toInt32(doubleArguments[0]);
            t.year = (year >= 0 && year <= 99) ? year : year - 1900;
            t.month = JSC::toInt32(doubleArguments[1]);
            t.monthDay = (numArgs >= 3) ? JSC::toInt32(doubleArguments[2]) : 1;
            t.hour = JSC::toInt32(doubleArguments[3]);
            t.minute = JSC::toInt32(doubleArguments[4]);
            t.second = JSC::toInt32(doubleArguments[5]);
            t.isDST = -1;
            double ms = (numArgs >= 7) ? doubleArguments[6] : 0;
            value = gregorianDateTimeToMS(exec, t, ms, false);
        }
    }

    return new (exec) DateInstance(exec, globalObject->dateStructure(), value);
}
Пример #20
0
static RefPtr<DeviceMotionData::RotationRate> readRotationRateArgument(JSValue value, ExecState& state)
{
    if (value.isUndefinedOrNull())
        return nullptr;

    // Given the above test, this will always yield an object.
    JSObject* object = value.toObject(&state);

    JSValue alphaValue = object->get(&state, Identifier::fromString(&state, "alpha"));
    if (state.hadException())
        return nullptr;
    bool canProvideAlpha = !alphaValue.isUndefinedOrNull();
    double alpha = alphaValue.toNumber(&state);
    if (state.hadException())
        return nullptr;

    JSValue betaValue = object->get(&state, Identifier::fromString(&state, "beta"));
    if (state.hadException())
        return nullptr;
    bool canProvideBeta = !betaValue.isUndefinedOrNull();
    double beta = betaValue.toNumber(&state);
    if (state.hadException())
        return nullptr;

    JSValue gammaValue = object->get(&state, Identifier::fromString(&state, "gamma"));
    if (state.hadException())
        return nullptr;
    bool canProvideGamma = !gammaValue.isUndefinedOrNull();
    double gamma = gammaValue.toNumber(&state);
    if (state.hadException())
        return nullptr;

    if (!canProvideAlpha && !canProvideBeta && !canProvideGamma)
        return nullptr;

    return DeviceMotionData::RotationRate::create(canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma);
}
Пример #21
0
static RefPtr<DeviceMotionData::Acceleration> readAccelerationArgument(JSValue value, ExecState& state)
{
    if (value.isUndefinedOrNull())
        return nullptr;

    // Given the above test, this will always yield an object.
    JSObject* object = value.toObject(&state);

    JSValue xValue = object->get(&state, Identifier::fromString(&state, "x"));
    if (state.hadException())
        return nullptr;
    bool canProvideX = !xValue.isUndefinedOrNull();
    double x = xValue.toNumber(&state);
    if (state.hadException())
        return nullptr;

    JSValue yValue = object->get(&state, Identifier::fromString(&state, "y"));
    if (state.hadException())
        return nullptr;
    bool canProvideY = !yValue.isUndefinedOrNull();
    double y = yValue.toNumber(&state);
    if (state.hadException())
        return nullptr;

    JSValue zValue = object->get(&state, Identifier::fromString(&state, "z"));
    if (state.hadException())
        return nullptr;
    bool canProvideZ = !zValue.isUndefinedOrNull();
    double z = zValue.toNumber(&state);
    if (state.hadException())
        return nullptr;

    if (!canProvideX && !canProvideY && !canProvideZ)
        return nullptr;

    return DeviceMotionData::Acceleration::create(canProvideX, x, canProvideY, y, canProvideZ, z);
}
static RefPtr<IDBKey> createIDBKeyFromValue(ExecState* exec, JSValue value, Vector<JSArray*>& stack)
{
    if (value.isNumber() && !std::isnan(value.toNumber(exec)))
        return IDBKey::createNumber(value.toNumber(exec));
    if (value.isString())
        return IDBKey::createString(value.toString(exec)->value(exec));
    if (value.inherits(DateInstance::info()) && !std::isnan(valueToDate(exec, value)))
        return IDBKey::createDate(valueToDate(exec, value));
    if (value.isObject()) {
        JSObject* object = asObject(value);
        if (isJSArray(object) || object->inherits(JSArray::info())) {
            JSArray* array = asArray(object);
            size_t length = array->length();

            if (stack.contains(array))
                return nullptr;
            if (stack.size() >= maximumDepth)
                return nullptr;
            stack.append(array);

            Vector<RefPtr<IDBKey>> subkeys;
            for (size_t i = 0; i < length; i++) {
                JSValue item = array->getIndex(exec, i);
                RefPtr<IDBKey> subkey = createIDBKeyFromValue(exec, item, stack);
                if (!subkey)
                    subkeys.append(IDBKey::createInvalid());
                else
                    subkeys.append(subkey);
            }

            stack.removeLast();
            return IDBKey::createArray(subkeys);
        }
    }
    return nullptr;
}
Пример #23
0
void setJSPannerNodeConeOuterGain(ExecState* exec, EncodedJSValue thisValue, EncodedJSValue encodedValue)
{
    JSValue value = JSValue::decode(encodedValue);
    UNUSED_PARAM(exec);
    JSPannerNode* castedThis = jsDynamicCast<JSPannerNode*>(JSValue::decode(thisValue));
    if (!castedThis) {
        throwVMTypeError(exec);
        return;
    }
    PannerNode& impl = castedThis->impl();
    double nativeValue(value.toNumber(exec));
    if (exec->hadException())
        return;
    impl.setConeOuterGain(nativeValue);
}
Пример #24
0
EXPORT
double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
{
    JSLock lock;
    JSValue* jsValue = toJS(value);
    ExecState* exec = toJS(ctx);

    double number = jsValue->toNumber(exec);
    if (exec->hadException()) {
        if (exception)
            *exception = toRef(exec->exception());
        exec->clearException();
        number = NaN;
    }
    return number;
}
Пример #25
0
// ECMA 15.4.5.1
void JSArray::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
    JSArray* thisObject = jsCast<JSArray*>(cell);

    if (propertyName == exec->propertyNames().length) {
        unsigned newLength = value.toUInt32(exec);
        if (value.toNumber(exec) != static_cast<double>(newLength)) {
            exec->vm().throwException(exec, createRangeError(exec, ASCIILiteral("Invalid array length")));
            return;
        }
        thisObject->setLength(exec, newLength, slot.isStrictMode());
        return;
    }

    JSObject::put(thisObject, exec, propertyName, value, slot);
}
Пример #26
0
double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
{
    if (!ctx) {
        ASSERT_NOT_REACHED();
        return PNaN;
    }
    ExecState* exec = toJS(ctx);
    JSLockHolder locker(exec);

    JSValue jsValue = toJS(exec, value);

    double number = jsValue.toNumber(exec);
    if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
        number = PNaN;
    return number;
}
Пример #27
0
double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
{
    ExecState* exec = toJS(ctx);
    APIEntryShim entryShim(exec);

    JSValue jsValue = toJS(exec, value);

    double number = jsValue.toNumber(exec);
    if (exec->hadException()) {
        if (exception)
            *exception = toRef(exec, exec->exception());
        exec->clearException();
        number = NaN;
    }
    return number;
}
void JSHTMLOptionsCollection::setLength(ExecState& state, JSValue value)
{
    ExceptionCode ec = 0;
    unsigned newLength = 0;
    double lengthValue = value.toNumber(&state);
    if (!std::isnan(lengthValue) && !std::isinf(lengthValue)) {
        if (lengthValue < 0.0)
            ec = INDEX_SIZE_ERR;
        else if (lengthValue > static_cast<double>(UINT_MAX))
            newLength = UINT_MAX;
        else
            newLength = static_cast<unsigned>(lengthValue);
    }
    if (!ec)
        wrapped().setLength(newLength, ec);
    setDOMException(&state, ec);
}
Пример #29
0
// ECMA 15.9.3
JSObject* constructDate(ExecState* exec, const ArgList& args)
{
    int numArgs = args.size();

    double value;

    if (numArgs == 0) // new Date() ECMA 15.9.3.3
        value = getCurrentUTCTime();
    else if (numArgs == 1) {
        if (args.at(exec, 0)->isObject(&DateInstance::info))
            value = asDateInstance(args.at(exec, 0))->internalNumber();
        else {
            JSValue* primitive = args.at(exec, 0)->toPrimitive(exec);
            if (primitive->isString())
                value = parseDate(primitive->getString());
            else
                value = primitive->toNumber(exec);
        }
    } else {
        if (isnan(args.at(exec, 0)->toNumber(exec))
                || isnan(args.at(exec, 1)->toNumber(exec))
                || (numArgs >= 3 && isnan(args.at(exec, 2)->toNumber(exec)))
                || (numArgs >= 4 && isnan(args.at(exec, 3)->toNumber(exec)))
                || (numArgs >= 5 && isnan(args.at(exec, 4)->toNumber(exec)))
                || (numArgs >= 6 && isnan(args.at(exec, 5)->toNumber(exec)))
                || (numArgs >= 7 && isnan(args.at(exec, 6)->toNumber(exec))))
            value = NaN;
        else {
          GregorianDateTime t;
          int year = args.at(exec, 0)->toInt32(exec);
          t.year = (year >= 0 && year <= 99) ? year : year - 1900;
          t.month = args.at(exec, 1)->toInt32(exec);
          t.monthDay = (numArgs >= 3) ? args.at(exec, 2)->toInt32(exec) : 1;
          t.hour = args.at(exec, 3)->toInt32(exec);
          t.minute = args.at(exec, 4)->toInt32(exec);
          t.second = args.at(exec, 5)->toInt32(exec);
          t.isDST = -1;
          double ms = (numArgs >= 7) ? args.at(exec, 6)->toNumber(exec) : 0;
          value = gregorianDateTimeToMS(t, ms, false);
        }
    }

    DateInstance* result = new (exec) DateInstance(exec->lexicalGlobalObject()->dateStructure());
    result->setInternalValue(jsNumber(exec, timeClip(value)));
    return result;
}
Пример #30
0
// http://www.w3.org/TR/WebIDL/#es-unsigned-long-long
uint64_t toUInt64(ExecState* exec, JSValue value, IntegerConversionConfiguration configuration)
{
    if (value.isUInt32())
        return value.asUInt32();

    double x = value.toNumber(exec);
    if (exec->hadException())
        return 0;

    if (configuration == EnforceRange)
        return enforceRange(exec, x, 0, kJSMaxInteger);

    // Map NaNs and +/-Infinity to 0; convert finite values modulo 2^64.
    unsigned long long n;
    doubleToInteger(x, n);
    return n;
}