Expected<T, DatabaseError> InMemoryDatabase::getValue(const std::string& domain, const std::string& key) { debug_only::verifyTrue(is_open_, "database is not open"); if (!is_open_) { return createError(DatabaseError::DbIsNotOpen, "Database is closed"); } auto storage_iter = storage_.find(domain); if (storage_iter == storage_.end()) { return domainNotFoundError(domain); } std::lock_guard<std::mutex> lock(storage_iter->second->getMutex()); auto result = storage_iter->second->get(key); if (result) { DataType value = result.take(); if (value.type() == typeid(T)) { return boost::get<T>(value); } else { auto error = createError(DatabaseError::KeyNotFound, "Requested wrong type for: ") << domain << ":" << key << " stored type: " << value.type().name() << " requested type " << boost::core::demangle(typeid(T).name()); LOG(ERROR) << error.getFullMessageRecursive(); debug_only::fail(error.getFullMessageRecursive().c_str()); return std::move(error); } } return result.takeError(); }
// VERSION major[.minor] Error parseVersion(uint32_t *Major, uint32_t *Minor) { read(); if (Tok.K != Identifier) return createError("identifier expected, but got " + Tok.Value); StringRef V1, V2; std::tie(V1, V2) = Tok.Value.split('.'); if (V1.getAsInteger(10, *Major)) return createError("integer expected, but got " + Tok.Value); if (V2.empty()) *Minor = 0; else if (V2.getAsInteger(10, *Minor)) return createError("integer expected, but got " + Tok.Value); return Error::success(); }
JSObject* ScriptExecutable::prepareForExecutionImpl( ExecState* exec, JSFunction* function, JSScope* scope, CodeSpecializationKind kind) { VM& vm = exec->vm(); DeferGC deferGC(vm.heap); if (vm.getAndClearFailNextNewCodeBlock()) return createError(exec->callerFrame(), ASCIILiteral("Forced Failure")); JSObject* exception = 0; CodeBlock* codeBlock = newCodeBlockFor(kind, function, scope, exception); if (!codeBlock) { RELEASE_ASSERT(exception); return exception; } if (Options::validateBytecode()) codeBlock->validate(); if (Options::useLLInt()) setupLLInt(vm, codeBlock); else setupJIT(vm, codeBlock); installCode(*codeBlock->vm(), codeBlock, codeBlock->codeType(), codeBlock->specializationKind()); return 0; }
static RefPtr<CryptoAlgorithmParameters> createAesCbcParams(ExecState* exec, JSValue value) { if (!value.isObject()) { throwTypeError(exec); return nullptr; } JSValue iv = getProperty(exec, value.getObject(), "iv"); if (exec->hadException()) return nullptr; auto result = adoptRef(*new CryptoAlgorithmAesCbcParams); CryptoOperationData ivData; if (!cryptoOperationDataFromJSValue(exec, iv, ivData)) { ASSERT(exec->hadException()); return nullptr; } if (ivData.second != 16) { exec->vm().throwException(exec, createError(exec, "AES-CBC initialization data must be 16 bytes")); return nullptr; } memcpy(result->iv.data(), ivData.first, ivData.second); return WTFMove(result); }
void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, ScriptValue* exception) { if (isExecutionForbidden()) return; initScriptIfNeeded(); JSLock lock(SilenceAssertionsOnly); ExecState* exec = m_workerContextWrapper->globalExec(); m_workerContextWrapper->globalData().timeoutChecker.start(); JSValue evaluationException; JSC::evaluate(exec, exec->dynamicGlobalObject()->globalScopeChain(), sourceCode.jsSourceCode(), m_workerContextWrapper.get(), &evaluationException); m_workerContextWrapper->globalData().timeoutChecker.stop(); if ((evaluationException && isTerminatedExecutionException(evaluationException)) || m_workerContextWrapper->globalData().terminator.shouldTerminate()) { forbidExecution(); return; } if (evaluationException) { String errorMessage; int lineNumber = 0; String sourceURL = sourceCode.url().string(); if (m_workerContext->sanitizeScriptError(errorMessage, lineNumber, sourceURL)) *exception = ScriptValue(*m_globalData, throwError(exec, createError(exec, errorMessage.impl()))); else *exception = ScriptValue(*m_globalData, evaluationException); } }
void QtField::setValueToInstance(ExecState* exec, const Instance* inst, JSValue aValue) const { if (m_type == ChildObject) // QtScript doesn't allow setting to a named child return; const QtInstance* instance = static_cast<const QtInstance*>(inst); QObject* obj = instance->getObject(); if (obj) { QMetaType::Type argtype = QMetaType::Void; if (m_type == MetaProperty) #if HAVE(QT5) argtype = (QMetaType::Type) m_property.userType(); #else argtype = (QMetaType::Type) QMetaType::type(m_property.typeName()); #endif // dynamic properties just get any QVariant QVariant val = convertValueToQVariant(exec, aValue, argtype, 0); if (m_type == MetaProperty) { if (m_property.isWritable()) m_property.write(obj, val); } #ifndef QT_NO_PROPERTIES else if (m_type == DynamicProperty) obj->setProperty(m_dynamicProperty.constData(), val); #endif } else { QString msg = QString(QLatin1String("cannot access member `%1' of deleted QObject")).arg(QLatin1String(name())); throwError(exec, createError(exec, msg.toLatin1().constData())); } }
// Shared implementation used by test and exec. bool RegExpObject::match(ExecState* exec) { RegExpConstructor* regExpConstructor = exec->lexicalGlobalObject()->regExpConstructor(); UString input = !exec->argumentCount() ? regExpConstructor->input() : exec->argument(0).toString(exec); if (input.isNull()) { throwError(exec, createError(exec, makeString("No input to ", toString(exec), "."))); return false; } if (!regExp()->global()) { int position; int length; regExpConstructor->performMatch(d->regExp.get(), input, 0, position, length); return position >= 0; } if (d->lastIndex < 0 || d->lastIndex > input.length()) { d->lastIndex = 0; return false; } int position; int length = 0; regExpConstructor->performMatch(d->regExp.get(), input, static_cast<int>(d->lastIndex), position, length); if (position < 0) { d->lastIndex = 0; return false; } d->lastIndex = position + length; return true; }
void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, ScriptValue* exception) { if (isExecutionForbidden()) return; initScriptIfNeeded(); ExecState* exec = m_workerContextWrapper->globalExec(); JSLockHolder lock(exec); JSValue evaluationException; JSC::evaluate(exec, sourceCode.jsSourceCode(), m_workerContextWrapper.get(), &evaluationException); if ((evaluationException && isTerminatedExecutionException(evaluationException)) || m_workerContextWrapper->vm().watchdog.didFire()) { forbidExecution(); return; } if (evaluationException) { String errorMessage; int lineNumber = 0; String sourceURL = sourceCode.url().string(); if (m_workerContext->sanitizeScriptError(errorMessage, lineNumber, sourceURL, sourceCode.cachedScript())) *exception = ScriptValue(*m_vm, throwError(exec, createError(exec, errorMessage.impl()))); else *exception = ScriptValue(*m_vm, evaluationException); } }
JSValue* createStackOverflowError(ExecState* exec) { //Note by Arpit Baldeva:07/16/09. Added this assert to indicate to the users that the JavaScript has exceeded //statck size. This is because EAWebkit users can explicitly set the stack size for JavaScript usage. ASSERT_WITH_MESSAGE(false, "JavaScript Stack overflowed. Please increase the stack size"); return createError(exec, RangeError, "Maximum call stack size exceeded."); }
JSValue IntlNumberFormat::formatNumber(ExecState& state, double number) { VM& vm = state.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 11.3.4 FormatNumber abstract operation (ECMA-402 2.0) if (!m_initializedNumberFormat) return throwTypeError(&state, scope, "Intl.NumberFormat.prototype.format called on value that's not an object initialized as a NumberFormat"_s); // Map negative zero to positive zero. if (!number) number = 0.0; UErrorCode status = U_ZERO_ERROR; Vector<UChar, 32> buffer(32); auto length = unum_formatDouble(m_numberFormat.get(), number, buffer.data(), buffer.size(), nullptr, &status); if (status == U_BUFFER_OVERFLOW_ERROR) { buffer.grow(length); status = U_ZERO_ERROR; unum_formatDouble(m_numberFormat.get(), number, buffer.data(), length, nullptr, &status); } if (U_FAILURE(status)) return throwException(&state, scope, createError(&state, "Failed to format a number."_s)); return jsString(&state, String(buffer.data(), length)); }
JSValue QtField::valueFromInstance(ExecState* exec, const Instance* inst) const { const QtInstance* instance = static_cast<const QtInstance*>(inst); QObject* obj = instance->getObject(); if (obj) { QVariant val; if (m_type == MetaProperty) { if (m_property.isReadable()) val = m_property.read(obj); else return jsUndefined(); } else if (m_type == ChildObject) val = QVariant::fromValue((QObject*) m_childObject.data()); #ifndef QT_NO_PROPERTIES else if (m_type == DynamicProperty) val = obj->property(m_dynamicProperty); #endif JSValueRef exception = 0; JSValueRef jsValue = convertQVariantToValue(toRef(exec), inst->rootObject(), val, &exception); if (exception) return exec->vm().throwException(exec, toJS(exec, exception)); return toJS(exec, jsValue); } QString msg = QString(QLatin1String("cannot access member `%1' of deleted QObject")).arg(QLatin1String(name())); return exec->vm().throwException(exec, createError(exec, msg.toLatin1().constData())); }
void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, NakedPtr<JSC::Exception>& returnedException) { if (isExecutionForbidden()) return; initScriptIfNeeded(); ExecState* exec = m_workerGlobalScopeWrapper->globalExec(); JSLockHolder lock(exec); JSC::evaluate(exec, sourceCode.jsSourceCode(), m_workerGlobalScopeWrapper->globalThis(), returnedException); VM& vm = exec->vm(); if ((returnedException && isTerminatedExecutionException(returnedException)) || isTerminatingExecution()) { forbidExecution(); return; } if (returnedException) { String errorMessage; int lineNumber = 0; int columnNumber = 0; String sourceURL = sourceCode.url().string(); if (m_workerGlobalScope->sanitizeScriptError(errorMessage, lineNumber, columnNumber, sourceURL, sourceCode.cachedScript())) { vm.throwException(exec, createError(exec, errorMessage.impl())); returnedException = vm.exception(); vm.clearException(); } } }
Poco::JSON::Object::Ptr ClusterQueueManagerMapper::suspend() { createCommand(MQCMD_SUSPEND_Q_MGR_CLUSTER); // Required parameters addParameter<std::string>(MQCA_CLUSTER_NAME, "ClusterName"); addParameter<std::string>(MQCA_CLUSTER_NAMELIST, "ClusterNamelist"); // Optional parameters addParameter<std::string>(MQCACF_COMMAND_SCOPE, "CommandScope"); addAttributeList(MQIACF_MODE, "Mode"); PCF::Vector commandResponse; execute(commandResponse); if ( commandResponse.size() > 0 ) { PCF::Vector::iterator it = commandResponse.begin(); if ( (*it)->getReasonCode() != MQRC_NONE ) { return createError(**it); } } return new Poco::JSON::Object(); }
static Expected<StringRef> getDynamicStrTab(const ELFFile<ELFT> *Elf) { auto DynamicEntriesOrError = Elf->dynamicEntries(); if (!DynamicEntriesOrError) return DynamicEntriesOrError.takeError(); for (const typename ELFT::Dyn &Dyn : *DynamicEntriesOrError) { if (Dyn.d_tag == ELF::DT_STRTAB) { auto MappedAddrOrError = Elf->toMappedAddr(Dyn.getPtr()); if (!MappedAddrOrError) consumeError(MappedAddrOrError.takeError()); return StringRef(reinterpret_cast<const char *>(*MappedAddrOrError)); } } // If the dynamic segment is not present, we fall back on the sections. auto SectionsOrError = Elf->sections(); if (!SectionsOrError) return SectionsOrError.takeError(); for (const typename ELFT::Shdr &Sec : *SectionsOrError) { if (Sec.sh_type == ELF::SHT_DYNSYM) return Elf->getStringTableForSymtab(Sec); } return createError("dynamic string table not found"); }
JSValue JSNPObject::callConstructor(ExecState* exec) { ASSERT_GC_OBJECT_INHERITS(this, &s_info); if (!m_npObject) return throwInvalidAccessError(exec); size_t argumentCount = exec->argumentCount(); Vector<NPVariant, 8> arguments(argumentCount); // Convert all arguments to NPVariants. for (size_t i = 0; i < argumentCount; ++i) m_objectMap->convertJSValueToNPVariant(exec, exec->argument(i), arguments[i]); // Calling NPClass::construct will call into plug-in code, and there's no telling what the plug-in can do. // (including destroying the plug-in). Because of this, we make sure to keep the plug-in alive until // the call has finished. NPRuntimeObjectMap::PluginProtector protector(m_objectMap); bool returnValue; NPVariant result; VOID_TO_NPVARIANT(result); { JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly); returnValue = m_npObject->_class->construct(m_npObject, arguments.data(), argumentCount, &result); NPRuntimeObjectMap::moveGlobalExceptionToExecState(exec); } if (!returnValue) throwError(exec, createError(exec, "Error calling method on NPObject.")); JSValue value = m_objectMap->convertNPVariantToJSValue(exec, globalObject(), result); releaseNPVariantValue(&result); return value; }
// ECMA 8.6.2.2 void JSObject::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot) { ASSERT(value); ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(this)); if (propertyName == exec->propertyNames().underscoreProto) { // Setting __proto__ to a non-object, non-null value is silently ignored to match Mozilla. if (!value.isObject() && !value.isNull()) return; if (!setPrototypeWithCycleCheck(value)) throwError(exec, createError(exec, "cyclic __proto__ value")); return; } // Check if there are any setters or getters in the prototype chain JSValue prototype; for (JSObject* obj = this; !obj->structure()->hasGetterSetterProperties(); obj = asObject(prototype)) { prototype = obj->prototype(); if (prototype.isNull()) { putDirectInternal(exec->globalData(), propertyName, value, 0, true, slot); return; } } unsigned attributes; JSCell* specificValue; if ((m_structure->get(propertyName, attributes, specificValue) != WTF::notFound) && attributes & ReadOnly) return; for (JSObject* obj = this; ; obj = asObject(prototype)) { if (JSValue gs = obj->getDirect(propertyName)) { if (gs.isGetterSetter()) { JSObject* setterFunc = asGetterSetter(gs)->setter(); if (!setterFunc) { throwSetterError(exec); return; } CallData callData; CallType callType = setterFunc->getCallData(callData); MarkedArgumentBuffer args; args.append(value); call(exec, setterFunc, callType, callData, this, args); return; } // If there's an existing property on the object or one of its // prototypes it should be replaced, so break here. break; } prototype = obj->prototype(); if (prototype.isNull()) break; } putDirectInternal(exec->globalData(), propertyName, value, 0, true, slot); return; }
GTEST_TEST(ExpectedTest, nested_errors_example) { const auto msg = std::string{"Write a good error message"}; auto firstFailureSource = [&msg]() -> Expected<std::vector<int>, TestError> { return createError(TestError::Semantic, msg); }; auto giveMeNestedError = [&]() -> Expected<std::vector<int>, TestError> { auto ret = firstFailureSource(); ret.isError(); return createError(TestError::Runtime, msg, ret.takeError()); }; auto ret = giveMeNestedError(); EXPECT_FALSE(ret); ASSERT_TRUE(ret.isError()); EXPECT_EQ(ret.getErrorCode(), TestError::Runtime); ASSERT_TRUE(ret.getError().hasUnderlyingError()); EXPECT_PRED2(stringContains, ret.getError().getFullMessage(), msg); }
GTEST_TEST(ExpectedTest, error_takeOr_with_rvalue_as_an_argument) { auto value = int{312}; auto callable = []() -> Expected<int, TestError> { return createError(TestError::Logical, "error message"); }; value = callable().takeOr(value); EXPECT_EQ(value, 312); }
JSValue IntlCollator::compareStrings(ExecState& state, StringView x, StringView y) { // 10.3.4 CompareStrings abstract operation (ECMA-402 2.0) if (!m_collator) { createCollator(state); if (!m_collator) return state.vm().throwException(&state, createError(&state, ASCIILiteral("Failed to compare strings."))); } UErrorCode status = U_ZERO_ERROR; UCharIterator iteratorX = createIterator(x); UCharIterator iteratorY = createIterator(y); auto result = ucol_strcollIter(m_collator, &iteratorX, &iteratorY, &status); if (U_FAILURE(status)) return state.vm().throwException(&state, createError(&state, ASCIILiteral("Failed to compare strings."))); return jsNumber(result); }
Expected<StorageType, DatabaseError> InMemoryStorage<StorageType>::get( const std::string& key) const { auto iter = storage_.find(key); if (iter != storage_.end()) { return iter->second; } return createError(DatabaseError::KeyNotFound, "Can't find value for key ") << key; }
GitCredentialResponse GitCredentialResponse::createForDefault() { git_cred *cred; if (git_cred_default_new(&cred) < 0) { return createError(); } else { return GitCredentialResponse(cred); } }
GitCredentialResponse GitCredentialResponse::createForUsername(const QString &username) { git_cred *cred; if (git_cred_username_new(&cred, username.toLocal8Bit().constData()) < 0) { return createError(); } else { return GitCredentialResponse(cred); } }
GitCredentialResponse GitCredentialResponse::createForUsernamePassword(const QString &username, const QString &password) { git_cred *cred; if (git_cred_userpass_plaintext_new(&cred, username.toLocal8Bit().constData(), password.toLocal8Bit().constData()) < 0) { return createError(); } else { return GitCredentialResponse(cred); } }
void NPRuntimeObjectMap::moveGlobalExceptionToExecState(ExecState* exec) { if (globalExceptionString().isNull()) return; { JSLockHolder lock(exec); exec->vm().throwException(exec, createError(exec, globalExceptionString())); } globalExceptionString() = String(); }
GitCredentialResponse GitCredentialResponse::createForSSHKey(const QString &username, const QString &pubkeyPath, const QString &privkeyPath, const QString &passthrase) { git_cred *cred; if (git_cred_ssh_key_new(&cred, username.toLocal8Bit().constData(), pubkeyPath.toLocal8Bit().constData(), privkeyPath.toLocal8Bit().constData(), passthrase.toLocal8Bit().constData()) < 0) { return createError(); } else { return GitCredentialResponse(cred); } }
Error parseExport() { COFFShortExport E; E.Name = Tok.Value; read(); if (Tok.K == Equal) { read(); if (Tok.K != Identifier) return createError("identifier expected, but got " + Tok.Value); E.ExtName = E.Name; E.Name = Tok.Value; } else { unget(); } if (Machine == IMAGE_FILE_MACHINE_I386) { if (!isDecorated(E.Name, MingwDef)) E.Name = (std::string("_").append(E.Name)); if (!E.ExtName.empty() && !isDecorated(E.ExtName, MingwDef)) E.ExtName = (std::string("_").append(E.ExtName)); } for (;;) { read(); if (Tok.K == Identifier && Tok.Value[0] == '@') { Tok.Value.drop_front().getAsInteger(10, E.Ordinal); read(); if (Tok.K == KwNoname) { E.Noname = true; } else { unget(); } continue; } if (Tok.K == KwData) { E.Data = true; continue; } if (Tok.K == KwConstant) { E.Constant = true; continue; } if (Tok.K == KwPrivate) { E.Private = true; continue; } unget(); Info.Exports.push_back(E); return Error::success(); } }
GTEST_TEST(ExpectedTest, error__takeOr_with_user_defined_class) { class SomeTestClass { public: explicit SomeTestClass(const std::string& prefix, const std::string& sufix) : text{prefix + " - " + sufix} {} std::string text; }; auto callable = []() -> Expected<SomeTestClass, TestError> { return createError(TestError::Semantic, "error message"); }; EXPECT_EQ(callable().takeOr(SomeTestClass("427 BC", "347 BC")).text, "427 BC - 347 BC"); }
EncodedJSValue JSC_HOST_CALL jsConsolePrototypeFunctionDebug(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); JSConsole* castedThis = static_cast<JSConsole*>(asObject(thisValue)); Console* imp = static_cast<Console*>(castedThis->impl()); unsigned count = exec->argumentCount(); Vector<NPVariant, 8> cArgs(count); unsigned i; for (i = 0; i < count; i++) JSC::Bindings::convertValueToNPVariant(exec, exec->argument(i), &cArgs[i]); // Invoke the 'C' method. bool retval = true; NPVariant resultVariant; VOID_TO_NPVARIANT(resultVariant); { JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly); //ASSERT(JSC::Bindings::globalExceptionString().isNull()); NPInvokeFunctionPtr ptr = (NPInvokeFunctionPtr)(imp->frame()->page()->chrome()->client()->getJavascriptCallCppCallback()); retval = ptr(0, 0, cArgs.data(), count, &resultVariant); //CInstance::moveGlobalExceptionToExecState(exec); } if (!retval) throwError(exec, createError(exec, "Error calling method on NPObject.")); for (i = 0; i < count; i++) _NPN_ReleaseVariantValue(&cArgs[i]); JSValue resultValue = JSC::Bindings::convertNPVariantToValue(exec, &resultVariant, 0); _NPN_ReleaseVariantValue(&resultVariant); return resultValue; // JSValue thisValue = exec->hostThisValue(); // if (!thisValue.inherits(&JSConsole::s_info)) // return throwVMTypeError(exec); // JSConsole* castedThis = static_cast<JSConsole*>(asObject(thisValue)); // Console* imp = static_cast<Console*>(castedThis->impl()); // RefPtr<ScriptArguments> scriptArguments(createScriptArguments(exec, 0)); // size_t maxStackSize = imp->shouldCaptureFullStackTrace() ? ScriptCallStack::maxCallStackSizeToCapture : 1; // RefPtr<ScriptCallStack> callStack(createScriptCallStack(exec, maxStackSize)); // // imp->debug(scriptArguments, callStack); // return JSValue::encode(jsUndefined()); }
// Call this only if you know that exception fuzzing is enabled. void doExceptionFuzzing(ExecState* exec, const char* where, void* returnPC) { ASSERT(Options::useExceptionFuzz()); DeferGCForAWhile deferGC(exec->vm().heap); s_numberOfExceptionFuzzChecks++; unsigned fireTarget = Options::fireExceptionFuzzAt(); if (fireTarget == s_numberOfExceptionFuzzChecks) { printf("JSC EXCEPTION FUZZ: Throwing fuzz exception with call frame %p, seen in %s and return address %p.\n", exec, where, returnPC); exec->vm().throwException( exec, createError(exec, ASCIILiteral("Exception Fuzz"))); } }
Expected<int32_t, DatabaseError> Database::getInt32(const std::string& domain, const std::string& key) { Expected<std::string, DatabaseError> string_value = getString(domain, key); if (string_value) { auto value = tryTo<int32_t>(*string_value); if (value) { return *value; } else { return createError(DatabaseError::FailToReadData, "Failed to convert string to int", value.takeError()); } } else { return string_value.takeError(); } }