LibJS+LibWeb: Move the macro to convert ENOMEM to an exception to LibJS

Move the macro to LibJS and change it to return a throw completion
instead of a WebIDL exception. This will let us use this macro within
LibJS to handle OOM conditions.
This commit is contained in:
Timothy Flynn 2023-01-07 12:14:54 -05:00 committed by Linus Groh
parent ba97f6a0d3
commit d8044c5358
15 changed files with 118 additions and 93 deletions

View file

@ -11,10 +11,23 @@
#include <AK/Optional.h>
#include <AK/Try.h>
#include <AK/Variant.h>
#include <LibJS/Runtime/ErrorTypes.h>
#include <LibJS/Runtime/Value.h>
namespace JS {
#define TRY_OR_THROW_OOM(vm, expression) \
({ \
/* Ignore -Wshadow to allow nesting the macro. */ \
AK_IGNORE_DIAGNOSTIC("-Wshadow", \
auto _temporary_result = (expression)); \
if (_temporary_result.is_error()) { \
VERIFY(_temporary_result.error().code() == ENOMEM); \
return vm.throw_completion<JS::InternalError>(JS::ErrorType::OutOfMemory); \
} \
_temporary_result.release_value(); \
})
// 6.2.3 The Completion Record Specification Type, https://tc39.es/ecma262/#sec-completion-record-specification-type
class [[nodiscard]] Completion {
public:

View file

@ -110,6 +110,7 @@
"Object prototype must not be {} on a super property access") \
M(ObjectPrototypeWrongType, "Prototype must be an object or null") \
M(OptionIsNotValidValue, "{} is not a valid value for option {}") \
M(OutOfMemory, "Out of memory") \
M(OverloadResolutionFailed, "Overload resolution failed") \
M(PrivateFieldAlreadyDeclared, "Private field '{}' has already been declared") \
M(PrivateFieldDoesNotExistOnObject, "Private field '{}' does not exist on object") \

View file

@ -6,6 +6,7 @@
#include <AK/TypeCasts.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/PromiseCapability.h>
#include <LibWeb/Bindings/MainThreadVM.h>
@ -160,9 +161,9 @@ JS::NonnullGCPtr<JS::Promise> consume_body(JS::Realm& realm, BodyMixin const& ob
promise = body->fully_read_as_promise();
// 4. Let steps be to return the result of package data with the first argument given, type, and objects MIME type.
auto steps = [&realm, &object, type](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {
auto steps = [&vm, &realm, &object, type](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {
VERIFY(value.is_string());
auto bytes = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(value.as_string().deprecated_string().bytes()));
auto bytes = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(value.as_string().deprecated_string().bytes()));
return package_data(realm, move(bytes), type, object.mime_type_impl());
};

View file

@ -5,6 +5,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/Completion.h>
#include <LibWeb/Fetch/BodyInit.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/URL/URLSearchParams.h>
@ -29,6 +30,8 @@ WebIDL::ExceptionOr<Infrastructure::BodyWithType> safely_extract_body(JS::Realm&
// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm, BodyInitOrReadableBytes const& object, bool keepalive)
{
auto& vm = realm.vm();
// 1. Let stream be null.
JS::GCPtr<Streams::ReadableStream> stream;
@ -77,19 +80,19 @@ WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm,
},
[&](ReadonlyBytes bytes) -> WebIDL::ExceptionOr<void> {
// Set source to object.
source = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(bytes));
source = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(bytes));
return {};
},
[&](JS::Handle<JS::Object> const& buffer_source) -> WebIDL::ExceptionOr<void> {
// Set source to a copy of the bytes held by object.
source = TRY_OR_RETURN_OOM(realm, WebIDL::get_buffer_source_copy(*buffer_source.cell()));
source = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(*buffer_source.cell()));
return {};
},
[&](JS::Handle<URL::URLSearchParams> const& url_search_params) -> WebIDL::ExceptionOr<void> {
// Set source to the result of running the application/x-www-form-urlencoded serializer with objects list.
source = url_search_params->to_deprecated_string().to_byte_buffer();
// Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
type = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy("application/x-www-form-urlencoded;charset=UTF-8"sv.bytes()));
type = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("application/x-www-form-urlencoded;charset=UTF-8"sv.bytes()));
return {};
},
[&](DeprecatedString const& scalar_value_string) -> WebIDL::ExceptionOr<void> {
@ -97,7 +100,7 @@ WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm,
// Set source to the UTF-8 encoding of object.
source = scalar_value_string.to_byte_buffer();
// Set type to `text/plain;charset=UTF-8`.
type = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy("text/plain;charset=UTF-8"sv.bytes()));
type = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("text/plain;charset=UTF-8"sv.bytes()));
return {};
},
[&](JS::Handle<Streams::ReadableStream> const& stream) -> WebIDL::ExceptionOr<void> {

View file

@ -7,6 +7,7 @@
#include <AK/Base64.h>
#include <AK/Debug.h>
#include <AK/ScopeGuard.h>
#include <LibJS/Runtime/Completion.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Cookie/Cookie.h>
#include <LibWeb/DOM/Document.h>
@ -165,15 +166,15 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Infrastructure::FetchController>> fetch(JS:
}
// 3. Append (`Accept`, value) to requests header list.
auto header = TRY_OR_RETURN_OOM(realm, Infrastructure::Header::from_string_pair("Accept"sv, value.bytes()));
TRY_OR_RETURN_OOM(realm, request.header_list()->append(move(header)));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Accept"sv, value.bytes()));
TRY_OR_THROW_OOM(vm, request.header_list()->append(move(header)));
}
// 14. If requests header list does not contain `Accept-Language`, then user agents should append
// (`Accept-Language, an appropriate header value) to requests header list.
if (!request.header_list()->contains("Accept-Language"sv.bytes())) {
auto header = MUST(Infrastructure::Header::from_string_pair("Accept-Language"sv, "*"sv));
TRY_OR_RETURN_OOM(realm, request.header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, request.header_list()->append(move(header)));
}
// 15. If requests priority is null, then use requests initiator, destination, and render-blocking appropriately
@ -325,7 +326,7 @@ WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> main_fetch(JS::
request->use_cors_preflight()
|| (request->unsafe_request()
&& (!Infrastructure::is_cors_safelisted_method(request->method())
|| !TRY_OR_RETURN_OOM(realm, Infrastructure::get_cors_unsafe_header_names(request->header_list())).is_empty()))) {
|| !TRY_OR_THROW_OOM(vm, Infrastructure::get_cors_unsafe_header_names(request->header_list())).is_empty()))) {
// 1. Set requests response tainting to "cors".
request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
@ -402,11 +403,11 @@ WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> main_fetch(JS::
// -> "basic"
case Infrastructure::Request::ResponseTainting::Basic:
// basic filtered response
return TRY_OR_RETURN_OOM(realm, Infrastructure::BasicFilteredResponse::create(vm, *response));
return TRY_OR_THROW_OOM(vm, Infrastructure::BasicFilteredResponse::create(vm, *response));
// -> "cors"
case Infrastructure::Request::ResponseTainting::CORS:
// CORS filtered response
return TRY_OR_RETURN_OOM(realm, Infrastructure::CORSFilteredResponse::create(vm, *response));
return TRY_OR_THROW_OOM(vm, Infrastructure::CORSFilteredResponse::create(vm, *response));
// -> "opaque"
case Infrastructure::Request::ResponseTainting::Opaque:
// opaque filtered response
@ -517,7 +518,7 @@ WebIDL::ExceptionOr<void> fetch_response_handover(JS::Realm& realm, Infrastructu
// The user agent may decide to expose `Server-Timing` headers to non-secure contexts requests as well.
auto* client = fetch_params.request()->client();
if (!response.is_network_error() && client != nullptr && HTML::is_secure_context(*client)) {
auto server_timing_headers = TRY_OR_RETURN_OOM(realm, response.header_list()->get_decode_and_split("Server-Timing"sv.bytes()));
auto server_timing_headers = TRY_OR_THROW_OOM(vm, response.header_list()->get_decode_and_split("Server-Timing"sv.bytes()));
if (server_timing_headers.has_value())
timing_info->set_server_timing_headers(server_timing_headers.release_value());
}
@ -681,7 +682,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& r
auto response = Infrastructure::Response::create(vm);
response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
auto header = MUST(Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=utf-8"sv));
TRY_OR_RETURN_OOM(realm, response->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
response->set_body(MUST(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes())));
return PendingResponse::create(vm, request, response);
}
@ -697,7 +698,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& r
auto const& url = request->current_url();
auto data_or_error = url.data_payload_is_base64()
? decode_base64(url.data_payload())
: TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(url.data_payload().bytes()));
: TRY_OR_THROW_OOM(vm, ByteBuffer::copy(url.data_payload().bytes()));
// 2. If dataURLStruct is failure, then return a network error.
if (data_or_error.is_error())
@ -710,8 +711,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& r
// body is dataURLStructs body as a body.
auto response = Infrastructure::Response::create(vm);
response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
auto header = TRY_OR_RETURN_OOM(realm, Infrastructure::Header::from_string_pair("Content-Type"sv, mime_type));
TRY_OR_RETURN_OOM(realm, response->header_list()->append(move(header)));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Content-Type"sv, mime_type));
TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
response->set_body(TRY(Infrastructure::byte_sequence_as_body(realm, data_or_error.value().span())));
return PendingResponse::create(vm, request, response);
}
@ -1168,7 +1169,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
.name = MUST(ByteBuffer::copy("Content-Length"sv.bytes())),
.value = content_length_header_value.release_value(),
};
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
// FIXME: 10. If contentLength is non-null and httpRequests keepalive is true, then:
@ -1181,18 +1182,18 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
// 11. If httpRequests referrer is a URL, then:
if (http_request->referrer().has<AK::URL>()) {
// 1. Let referrerValue be httpRequests referrer, serialized and isomorphic encoded.
auto referrer_value = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(http_request->referrer().get<AK::URL>().serialize().bytes()));
auto referrer_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(http_request->referrer().get<AK::URL>().serialize().bytes()));
// 2. Append (`Referer`, referrerValue) to httpRequests header list.
auto header = Infrastructure::Header {
.name = MUST(ByteBuffer::copy("Referer"sv.bytes())),
.value = move(referrer_value),
};
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
// 12. Append a request `Origin` header for httpRequest.
TRY_OR_RETURN_OOM(realm, http_request->add_origin_header());
TRY_OR_THROW_OOM(vm, http_request->add_origin_header());
// FIXME: 13. Append the Fetch metadata headers for httpRequest.
@ -1201,9 +1202,9 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
if (!http_request->header_list()->contains("User-Agent"sv.bytes())) {
auto header = Infrastructure::Header {
.name = MUST(ByteBuffer::copy("User-Agent"sv.bytes())),
.value = TRY_OR_RETURN_OOM(realm, Infrastructure::default_user_agent_value()),
.value = TRY_OR_THROW_OOM(vm, Infrastructure::default_user_agent_value()),
};
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
// 15. If httpRequests cache mode is "default" and httpRequests header list contains `If-Modified-Since`,
@ -1225,7 +1226,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
&& !http_request->prevent_no_cache_cache_control_header_modification()
&& !http_request->header_list()->contains("Cache-Control"sv.bytes())) {
auto header = MUST(Infrastructure::Header::from_string_pair("Cache-Control"sv, "max-age=0"sv));
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
// 17. If httpRequests cache mode is "no-store" or "reload", then:
@ -1235,14 +1236,14 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
// httpRequests header list.
if (!http_request->header_list()->contains("Pragma"sv.bytes())) {
auto header = MUST(Infrastructure::Header::from_string_pair("Pragma"sv, "no-cache"sv));
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
// 2. If httpRequests header list does not contain `Cache-Control`, then append
// (`Cache-Control`, `no-cache`) to httpRequests header list.
if (!http_request->header_list()->contains("Cache-Control"sv.bytes())) {
auto header = MUST(Infrastructure::Header::from_string_pair("Cache-Control"sv, "no-cache"sv));
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
}
@ -1252,7 +1253,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
// Additionally, many servers mistakenly ignore `Range` headers if a non-identity encoding is accepted.
if (http_request->header_list()->contains("Range"sv.bytes())) {
auto header = MUST(Infrastructure::Header::from_string_pair("Accept-Encoding"sv, "identity"sv));
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
// 19. Modify httpRequests header list per HTTP. Do not append a given header if httpRequests header list
@ -1284,8 +1285,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
// 2. If cookies is not the empty string, then append (`Cookie`, cookies) to httpRequests header list.
if (!cookies.is_empty()) {
auto header = TRY_OR_RETURN_OOM(realm, Infrastructure::Header::from_string_pair("Cookie"sv, cookies));
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Cookie"sv, cookies));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
}
@ -1306,14 +1307,14 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet
else if (http_request->current_url().includes_credentials() && is_authentication_fetch == IsAuthenticationFetch::Yes) {
auto const& url = http_request->current_url();
auto payload = DeprecatedString::formatted("{}:{}", url.username(), url.password());
authorization_value = TRY_OR_RETURN_OOM(realm, encode_base64(payload.bytes())).to_deprecated_string();
authorization_value = TRY_OR_THROW_OOM(vm, encode_base64(payload.bytes())).to_deprecated_string();
}
// 4. If authorizationValue is non-null, then append (`Authorization`, authorizationValue) to
// httpRequests header list.
if (authorization_value.has_value()) {
auto header = TRY_OR_RETURN_OOM(realm, Infrastructure::Header::from_string_pair("Authorization"sv, *authorization_value));
TRY_OR_RETURN_OOM(realm, http_request->header_list()->append(move(header)));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Authorization"sv, *authorization_value));
TRY_OR_THROW_OOM(vm, http_request->header_list()->append(move(header)));
}
}
}
@ -1582,11 +1583,11 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> nonstandard_resource_load
if (auto const* body = request->body().get_pointer<Infrastructure::Body>()) {
TRY(body->source().visit(
[&](ByteBuffer const& byte_buffer) -> WebIDL::ExceptionOr<void> {
load_request.set_body(TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(byte_buffer)));
load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(byte_buffer)));
return {};
},
[&](JS::Handle<FileAPI::Blob> const& blob_handle) -> WebIDL::ExceptionOr<void> {
load_request.set_body(TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(blob_handle->bytes())));
load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob_handle->bytes())));
return {};
},
[](Empty) -> WebIDL::ExceptionOr<void> {

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Fetch/Headers.h>
@ -46,10 +47,12 @@ void Headers::visit_edges(JS::Cell::Visitor& visitor)
// https://fetch.spec.whatwg.org/#dom-headers-append
WebIDL::ExceptionOr<void> Headers::append(DeprecatedString const& name_string, DeprecatedString const& value_string)
{
auto& vm = this->vm();
// The append(name, value) method steps are to append (name, value) to this.
auto header = Infrastructure::Header {
.name = TRY_OR_RETURN_OOM(realm(), ByteBuffer::copy(name_string.bytes())),
.value = TRY_OR_RETURN_OOM(realm(), ByteBuffer::copy(value_string.bytes())),
.name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name_string.bytes())),
.value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(value_string.bytes())),
};
TRY(append(move(header)));
return {};
@ -64,7 +67,7 @@ WebIDL::ExceptionOr<void> Headers::delete_(DeprecatedString const& name_string)
// 1. If validating (name, ``) for headers returns false, then return.
// NOTE: Passing a dummy header value ought not to have any negative repercussions.
auto header = TRY_OR_RETURN_OOM(realm, Infrastructure::Header::from_string_pair(name, ""sv));
auto header = TRY_OR_THROW_OOM(realm.vm(), Infrastructure::Header::from_string_pair(name, ""sv));
if (!TRY(validate(header)))
return {};
@ -97,7 +100,7 @@ WebIDL::ExceptionOr<DeprecatedString> Headers::get(DeprecatedString const& name_
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid header name"sv };
// 2. Return the result of getting name from thiss header list.
auto byte_buffer = TRY_OR_RETURN_OOM(realm(), m_header_list->get(name));
auto byte_buffer = TRY_OR_THROW_OOM(vm(), m_header_list->get(name));
// FIXME: Teach BindingsGenerator about Optional<DeprecatedString>
return byte_buffer.has_value() ? DeprecatedString { byte_buffer->span() } : DeprecatedString {};
}
@ -119,16 +122,18 @@ WebIDL::ExceptionOr<bool> Headers::has(DeprecatedString const& name_string)
// https://fetch.spec.whatwg.org/#dom-headers-set
WebIDL::ExceptionOr<void> Headers::set(DeprecatedString const& name_string, DeprecatedString const& value_string)
{
// The set(name, value) method steps are:
auto& realm = this->realm();
auto& vm = realm.vm();
// The set(name, value) method steps are:
auto name = name_string.bytes();
auto value = value_string.bytes();
// 1. Normalize value.
auto normalized_value = TRY_OR_RETURN_OOM(realm, Infrastructure::normalize_header_value(value));
auto normalized_value = TRY_OR_THROW_OOM(vm, Infrastructure::normalize_header_value(value));
auto header = Infrastructure::Header {
.name = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(name)),
.name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name)),
.value = move(normalized_value),
};
@ -141,7 +146,7 @@ WebIDL::ExceptionOr<void> Headers::set(DeprecatedString const& name_string, Depr
return {};
// 4. Set (name, value) in thiss header list.
TRY_OR_RETURN_OOM(realm, m_header_list->set(move(header)));
TRY_OR_THROW_OOM(vm, m_header_list->set(move(header)));
// 5. If thiss guard is "request-no-cors", then remove privileged no-CORS request-headers from this.
if (m_guard == Guard::RequestNoCORS)
@ -190,8 +195,9 @@ JS::ThrowCompletionOr<void> Headers::for_each(ForEachCallback callback)
// https://fetch.spec.whatwg.org/#headers-validate
WebIDL::ExceptionOr<bool> Headers::validate(Infrastructure::Header const& header) const
{
// To validate a header (name, value) for a Headers object headers:
auto& realm = this->realm();
// To validate a header (name, value) for a Headers object headers:
auto const& [name, value] = header;
// 1. If name is not a header name or value is not a header value, then throw a TypeError.
@ -205,7 +211,7 @@ WebIDL::ExceptionOr<bool> Headers::validate(Infrastructure::Header const& header
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Headers object is immutable"sv };
// 3. If headerss guard is "request" and (name, value) is a forbidden request-header, then return false.
if (m_guard == Guard::Request && TRY_OR_RETURN_OOM(realm, Infrastructure::is_forbidden_request_header(header)))
if (m_guard == Guard::Request && TRY_OR_THROW_OOM(realm.vm(), Infrastructure::is_forbidden_request_header(header)))
return false;
// 4. If headerss guard is "response" and name is a forbidden response-header name, then return false.
@ -219,12 +225,14 @@ WebIDL::ExceptionOr<bool> Headers::validate(Infrastructure::Header const& header
// https://fetch.spec.whatwg.org/#concept-headers-append
WebIDL::ExceptionOr<void> Headers::append(Infrastructure::Header header)
{
// To append a header (name, value) to a Headers object headers, run these steps:
auto& realm = this->realm();
auto& vm = realm.vm();
// To append a header (name, value) to a Headers object headers, run these steps:
auto& [name, value] = header;
// 1. Normalize value.
value = TRY_OR_RETURN_OOM(realm, Infrastructure::normalize_header_value(value));
value = TRY_OR_THROW_OOM(vm, Infrastructure::normalize_header_value(value));
// 2. If validating (name, value) for headers returns false, then return.
if (!TRY(validate(header)))
@ -233,21 +241,21 @@ WebIDL::ExceptionOr<void> Headers::append(Infrastructure::Header header)
// 3. If headerss guard is "request-no-cors":
if (m_guard == Guard::RequestNoCORS) {
// 1. Let temporaryValue be the result of getting name from headerss header list.
auto temporary_value = TRY_OR_RETURN_OOM(realm, m_header_list->get(name));
auto temporary_value = TRY_OR_THROW_OOM(vm, m_header_list->get(name));
// 2. If temporaryValue is null, then set temporaryValue to value.
if (!temporary_value.has_value()) {
temporary_value = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(value));
temporary_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(value));
}
// 3. Otherwise, set temporaryValue to temporaryValue, followed by 0x2C 0x20, followed by value.
else {
TRY_OR_RETURN_OOM(realm, temporary_value->try_append(0x2c));
TRY_OR_RETURN_OOM(realm, temporary_value->try_append(0x20));
TRY_OR_RETURN_OOM(realm, temporary_value->try_append(value));
TRY_OR_THROW_OOM(vm, temporary_value->try_append(0x2c));
TRY_OR_THROW_OOM(vm, temporary_value->try_append(0x20));
TRY_OR_THROW_OOM(vm, temporary_value->try_append(value));
}
auto temporary_header = Infrastructure::Header {
.name = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(name)),
.name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name)),
.value = temporary_value.release_value(),
};
@ -257,7 +265,7 @@ WebIDL::ExceptionOr<void> Headers::append(Infrastructure::Header header)
}
// 4. Append (name, value) to headerss header list.
TRY_OR_RETURN_OOM(realm, m_header_list->append(move(header)));
TRY_OR_THROW_OOM(vm, m_header_list->append(move(header)));
// 5. If headerss guard is "request-no-cors", then remove privileged no-CORS request-headers from headers.
if (m_guard == Guard::RequestNoCORS)
@ -269,25 +277,27 @@ WebIDL::ExceptionOr<void> Headers::append(Infrastructure::Header header)
// https://fetch.spec.whatwg.org/#concept-headers-fill
WebIDL::ExceptionOr<void> Headers::fill(HeadersInit const& object)
{
auto& vm = realm().vm();
// To fill a Headers object headers with a given object object, run these steps:
return object.visit(
// 1. If object is a sequence, then for each header of object:
[this](Vector<Vector<DeprecatedString>> const& object) -> WebIDL::ExceptionOr<void> {
[&](Vector<Vector<DeprecatedString>> const& object) -> WebIDL::ExceptionOr<void> {
for (auto const& entry : object) {
// 1. If header's size is not 2, then throw a TypeError.
if (entry.size() != 2)
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Array must contain header key/value pair"sv };
// 2. Append (header[0], header[1]) to headers.
auto header = TRY_OR_RETURN_OOM(realm(), Infrastructure::Header::from_string_pair(entry[0], entry[1].bytes()));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair(entry[0], entry[1].bytes()));
TRY(append(move(header)));
}
return {};
},
// 2. Otherwise, object is a record, then for each key → value of object, append (key, value) to headers.
[this](OrderedHashMap<DeprecatedString, DeprecatedString> const& object) -> WebIDL::ExceptionOr<void> {
[&](OrderedHashMap<DeprecatedString, DeprecatedString> const& object) -> WebIDL::ExceptionOr<void> {
for (auto const& entry : object) {
auto header = TRY_OR_RETURN_OOM(realm(), Infrastructure::Header::from_string_pair(entry.key, entry.value));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair(entry.key, entry.value));
TRY(append(move(header)));
}
return {};

View file

@ -8,6 +8,7 @@
#include <AK/TypeCasts.h>
#include <AK/URLParser.h>
#include <LibJS/Heap/Heap.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
@ -126,15 +127,13 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::clone(JS::VM& vm) cons
{
// To clone a response response, run these steps:
auto& realm = *vm.current_realm();
// 1. If response is a filtered response, then return a new identical filtered response whose internal response is a clone of responses internal response.
if (is<FilteredResponse>(*this)) {
auto internal_response = TRY(static_cast<FilteredResponse const&>(*this).internal_response()->clone(vm));
if (is<BasicFilteredResponse>(*this))
return TRY_OR_RETURN_OOM(realm, BasicFilteredResponse::create(vm, internal_response));
return TRY_OR_THROW_OOM(vm, BasicFilteredResponse::create(vm, internal_response));
if (is<CORSFilteredResponse>(*this))
return TRY_OR_RETURN_OOM(realm, CORSFilteredResponse::create(vm, internal_response));
return TRY_OR_THROW_OOM(vm, CORSFilteredResponse::create(vm, internal_response));
if (is<OpaqueFilteredResponse>(*this))
return OpaqueFilteredResponse::create(vm, internal_response);
if (is<OpaqueRedirectFilteredResponse>(*this))

View file

@ -5,6 +5,7 @@
*/
#include <AK/URLParser.h>
#include <LibJS/Runtime/Completion.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/RequestPrototype.h>
#include <LibWeb/DOM/AbortSignal.h>
@ -174,13 +175,13 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::construct_impl(JS::Realm
// method
// requests method.
request->set_method(TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(input_request->method())));
request->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(input_request->method())));
// header list
// A copy of requests header list.
auto header_list_copy = Infrastructure::HeaderList::create(vm);
for (auto& header : *input_request->header_list())
TRY_OR_RETURN_OOM(realm, header_list_copy->append(header));
TRY_OR_THROW_OOM(vm, header_list_copy->append(header));
request->set_header_list(header_list_copy);
// unsafe-request flag
@ -365,7 +366,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::construct_impl(JS::Realm
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Method must not be one of CONNECT, TRACE, or TRACK"sv };
// 3. Normalize method.
method = TRY_OR_RETURN_OOM(realm, Infrastructure::normalize_method(method.bytes()));
method = TRY_OR_THROW_OOM(vm, Infrastructure::normalize_method(method.bytes()));
// 4. Set requests method to method.
request->set_method(MUST(ByteBuffer::copy(method.bytes())));

View file

@ -5,6 +5,7 @@
*/
#include <AK/URLParser.h>
#include <LibJS/Runtime/Completion.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Fetch/Enums.h>
@ -82,6 +83,8 @@ JS::NonnullGCPtr<Response> Response::create(JS::Realm& realm, JS::NonnullGCPtr<I
// https://fetch.spec.whatwg.org/#initialize-a-response
WebIDL::ExceptionOr<void> Response::initialize_response(ResponseInit const& init, Optional<Infrastructure::BodyWithType> const& body)
{
auto& vm = this->vm();
// 1. If init["status"] is not in the range 200 to 599, inclusive, then throw a RangeError.
if (init.status < 200 || init.status > 599)
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Status must be in range 200-599"sv };
@ -92,7 +95,7 @@ WebIDL::ExceptionOr<void> Response::initialize_response(ResponseInit const& init
m_response->set_status(init.status);
// 4. Set responses responses status message to init["statusText"].
m_response->set_status_message(TRY_OR_RETURN_OOM(realm(), ByteBuffer::copy(init.status_text.bytes())));
m_response->set_status_message(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(init.status_text.bytes())));
// 5. If init["headers"] exists, then fill responses headers with init["headers"].
if (init.headers.has_value())
@ -111,9 +114,9 @@ WebIDL::ExceptionOr<void> Response::initialize_response(ResponseInit const& init
if (body->type.has_value() && m_response->header_list()->contains("Content-Type"sv.bytes())) {
auto header = Infrastructure::Header {
.name = MUST(ByteBuffer::copy("Content-Type"sv.bytes())),
.value = TRY_OR_RETURN_OOM(realm(), ByteBuffer::copy(body->type->span())),
.value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(body->type->span())),
};
TRY_OR_RETURN_OOM(realm(), m_response->header_list()->append(move(header)));
TRY_OR_THROW_OOM(vm, m_response->header_list()->append(move(header)));
}
}
@ -185,8 +188,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::redirect(JS::VM& vm, D
auto value = parsed_url.serialize();
// 7. Append (`Location`, value) to responseObjects responses header list.
auto header = TRY_OR_RETURN_OOM(realm, Infrastructure::Header::from_string_pair("Location"sv, value));
TRY_OR_RETURN_OOM(realm, response_object->response()->header_list()->append(move(header)));
auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Location"sv, value));
TRY_OR_THROW_OOM(vm, response_object->response()->header_list()->append(move(header)));
// 8. Return responseObject.
return response_object;
@ -210,7 +213,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::json(JS::VM& vm, JS::V
// 4. Perform initialize a response given responseObject, init, and (body, "application/json").
auto body_with_type = Infrastructure::BodyWithType {
.body = move(body),
.type = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy("application/json"sv.bytes()))
.type = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("application/json"sv.bytes()))
};
TRY(response_object->initialize_response(init, move(body_with_type)));

View file

@ -7,6 +7,7 @@
#include <AK/GenericLexer.h>
#include <AK/StdLibExtras.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/Completion.h>
#include <LibWeb/Bindings/BlobPrototype.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/FileAPI/Blob.h>
@ -144,7 +145,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::create(JS::Realm& realm, Optio
ByteBuffer byte_buffer {};
// 2. Let bytes be the result of processing blob parts given blobParts and options.
if (blob_parts.has_value()) {
byte_buffer = TRY_OR_RETURN_OOM(realm, process_blob_parts(blob_parts.value(), options));
byte_buffer = TRY_OR_THROW_OOM(realm.vm(), process_blob_parts(blob_parts.value(), options));
}
auto type = DeprecatedString::empty();
@ -232,7 +233,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::slice(Optional<i64> start, Opt
// a. S refers to span consecutive bytes from this, beginning with the byte at byte-order position relativeStart.
// b. S.size = span.
// c. S.type = relativeContentType.
auto byte_buffer = TRY_OR_RETURN_OOM(realm(), m_byte_buffer.slice(relative_start, span));
auto byte_buffer = TRY_OR_THROW_OOM(realm().vm(), m_byte_buffer.slice(relative_start, span));
return heap().allocate<Blob>(realm(), realm(), move(byte_buffer), move(relative_content_type));
}

View file

@ -5,6 +5,7 @@
*/
#include <AK/Time.h>
#include <LibJS/Runtime/Completion.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/FileAPI/File.h>
@ -24,7 +25,7 @@ File::~File() = default;
WebIDL::ExceptionOr<JS::NonnullGCPtr<File>> File::create(JS::Realm& realm, Vector<BlobPart> const& file_bits, DeprecatedString const& file_name, Optional<FilePropertyBag> const& options)
{
// 1. Let bytes be the result of processing blob parts given fileBits and options.
auto bytes = TRY_OR_RETURN_OOM(realm, process_blob_parts(file_bits, options.has_value() ? static_cast<BlobPropertyBag const&>(*options) : Optional<BlobPropertyBag> {}));
auto bytes = TRY_OR_THROW_OOM(realm.vm(), process_blob_parts(file_bits, options.has_value() ? static_cast<BlobPropertyBag const&>(*options) : Optional<BlobPropertyBag> {}));
// 2. Let n be the fileName argument to the constructor.
// NOTE: Underlying OS filesystems use differing conventions for file name; with constructed files, mandating UTF-16 lessens ambiquity when file names are converted to byte sequences.

View file

@ -8,6 +8,7 @@
#include <AK/DeprecatedString.h>
#include <AK/Utf8View.h>
#include <AK/Vector.h>
#include <LibJS/Runtime/Completion.h>
#include <LibTextCodec/Decoder.h>
#include <LibWeb/Bindings/WorkerGlobalScopePrototype.h>
#include <LibWeb/Forward.h>
@ -137,7 +138,7 @@ WebIDL::ExceptionOr<DeprecatedString> WorkerGlobalScope::btoa(DeprecatedString c
// Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data,
// and then must apply forgiving-base64 encode to that byte sequence and return the result.
return TRY_OR_RETURN_OOM(realm(), encode_base64(byte_string.span())).to_deprecated_string();
return TRY_OR_THROW_OOM(vm(), encode_base64(byte_string.span())).to_deprecated_string();
}
// https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob

View file

@ -5,6 +5,7 @@
*/
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/Value.h>
#include <LibTextCodec/Decoder.h>
#include <LibWeb/Infra/JSON.h>
@ -54,14 +55,12 @@ WebIDL::ExceptionOr<DeprecatedString> serialize_javascript_value_to_json_string(
// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-json-bytes
WebIDL::ExceptionOr<ByteBuffer> serialize_javascript_value_to_json_bytes(JS::VM& vm, JS::Value value)
{
auto& realm = *vm.current_realm();
// 1. Let string be the result of serializing a JavaScript value to a JSON string given value.
auto string = TRY(serialize_javascript_value_to_json_string(vm, value));
// 2. Return the result of running UTF-8 encode on string.
// NOTE: LibJS strings are stored as UTF-8.
return TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(string.bytes()));
return TRY_OR_THROW_OOM(vm, ByteBuffer::copy(string.bytes()));
}
}

View file

@ -14,18 +14,6 @@
namespace Web::WebIDL {
#define TRY_OR_RETURN_OOM(realm, expression) \
({ \
/* Ignore -Wshadow to allow nesting the macro. */ \
AK_IGNORE_DIAGNOSTIC("-Wshadow", \
auto _temporary_result = (expression)); \
if (_temporary_result.is_error()) { \
VERIFY(_temporary_result.error().code() == ENOMEM); \
return WebIDL::UnknownError::create(realm, "Out of memory."sv); \
} \
_temporary_result.release_value(); \
})
// The following have a legacy code value but *don't* produce it as
// DOMException.code value when used as name (and are therefore omitted here):
// - DOMStringSizeError (DOMSTRING_SIZE_ERR = 2)

View file

@ -12,6 +12,7 @@
#include <AK/GenericLexer.h>
#include <AK/QuickSort.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibTextCodec/Decoder.h>
@ -290,6 +291,8 @@ Optional<StringView> XMLHttpRequest::get_final_encoding() const
WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(DeprecatedString const& name_string, DeprecatedString const& value_string)
{
auto& realm = this->realm();
auto& vm = realm.vm();
auto name = name_string.to_byte_buffer();
auto value = value_string.to_byte_buffer();
@ -316,11 +319,11 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(DeprecatedString co
};
// 5. If (name, value) is a forbidden request-header, then return.
if (TRY_OR_RETURN_OOM(realm, Fetch::Infrastructure::is_forbidden_request_header(header)))
if (TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::is_forbidden_request_header(header)))
return {};
// 6. Combine (name, value) in thiss author request headers.
TRY_OR_RETURN_OOM(realm, m_author_request_headers->combine(move(header)));
TRY_OR_THROW_OOM(vm, m_author_request_headers->combine(move(header)));
return {};
}
@ -465,12 +468,12 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest
} else if (body_with_type.has_value()) {
TRY(body_with_type->body.source().visit(
[&](ByteBuffer const& buffer) -> WebIDL::ExceptionOr<void> {
auto byte_buffer = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(buffer));
auto byte_buffer = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(buffer));
request.set_body(move(byte_buffer));
return {};
},
[&](JS::Handle<FileAPI::Blob> const& blob) -> WebIDL::ExceptionOr<void> {
auto byte_buffer = TRY_OR_RETURN_OOM(realm, ByteBuffer::copy(blob->bytes()));
auto byte_buffer = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob->bytes()));
request.set_body(move(byte_buffer));
return {};
},