hash
stringlengths
40
40
date
stringdate
2019-01-22 05:28:56
2025-03-19 19:23:00
author
stringclasses
199 values
commit_message
stringlengths
18
96
is_merge
bool
1 class
masked_commit_message
stringlengths
12
90
type
stringclasses
74 values
git_diff
stringlengths
222
1.21M
28fcf648358b87f362092930c30e738f15908fdf
2024-04-23 22:54:14
Andrew Kaster
documentation: Update Ladybird README with more descriptive information
false
Update Ladybird README with more descriptive information
documentation
diff --git a/Ladybird/README.md b/Ladybird/README.md index 849df92be646..c98dfc6bafac 100644 --- a/Ladybird/README.md +++ b/Ladybird/README.md @@ -1,7 +1,46 @@ # Ladybird -Ladybird is a web browser built on the [LibWeb](https://github.com/SerenityOS/serenity/tree/master/Userland/Libraries/LibWeb) and [LibJS](https://github.com/SerenityOS/serenity/tree/master/Userland/Libraries/LibJS) engines from [SerenityOS](https://github.com/SerenityOS/serenity) with a cross-platform GUI in Qt. +Ladybird is a web browser built on the [LibWeb](https://github.com/SerenityOS/serenity/tree/master/Userland/Libraries/LibWeb) and [LibJS](https://github.com/SerenityOS/serenity/tree/master/Userland/Libraries/LibJS) engines from [SerenityOS](https://github.com/SerenityOS/serenity). +The Browser UI has a cross-platform GUI in Qt6 and a macOS-specific GUI in AppKit. -For more information about Ladybird, see [this blog post](https://awesomekling.github.io/Ladybird-a-new-cross-platform-browser-project/). +Ladybird aims to be a standards-compliant, independent web browser with no third-party dependencies. +Currently, the only dependencies are UI frameworks like Qt6 and AppKit, and low-level platform-specific +libraries like PulseAudio, CoreAudio and OpenGL. -See [build instructions](../Documentation/BuildInstructionsLadybird.md). +> [!IMPORTANT] +> Ladybird is in a pre-alpha state, and only suitable for use by developers + +## Features + +The Ladybird browser application uses a multiprocess architecture with a main UI process, several WebContent renderer processes, +an ImageDecoder process, a RequestServer process, and a SQLServer process for holding cookies. + +Image decoding and network connections are done out of process to be more robust against malicious content. +Each tab has its own renderer process, which is sandboxed from the rest of the system. + +All the core library support components are developed in the serenity monorepo: + +- LibWeb: Web Rendering Engine +- LibJS: JavaScript Engine +- LibWasm: WebAssembly implementation +- LibCrypto/LibTLS: Cryptography primitives and Transport Layer Security (rather than OpenSSL) +- LibHTTP: HTTP/1.1 client +- LibGfx: 2D Graphics Library, Image Decoding and Rendering (rather than skia) +- LibArchive: Archive file format support (rather than libarchive, zlib) +- LibUnicode, LibLocale: Unicode and Locale support (rather than libicu) +- LibAudio, LibVideo: Audio and Video playback (rather than libav, ffmpeg) +- LibCore: Event Loop, OS Abstraction layer +- LibIPC: Inter-Process Communication +- ... and more! + +## Building and Development + +See [build instructions](../Documentation/BuildInstructionsLadybird.md) for information on how to build Ladybird. + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for information on how to contribute to Ladybird. + +## More Information + +For more information about the history of Ladybird, see [this blog post](https://awesomekling.github.io/Ladybird-a-new-cross-platform-browser-project/). + +The official website for Ladybird is [ladybird.dev](https://ladybird.dev).
d2ff92077b2a4ead0a1ef65e7131702e1152cbeb
2024-08-08 03:09:46
Ali Mohammad Pur
libwasm: Use braces to initialize Reference::Foo classes
false
Use braces to initialize Reference::Foo classes
libwasm
diff --git a/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h b/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h index d3112fe37d98..d27f24548952 100644 --- a/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h +++ b/Userland/Libraries/LibWasm/AbstractMachine/AbstractMachine.h @@ -169,13 +169,13 @@ class Value { if constexpr (IsSame<T, Reference>) { switch (m_value.high()) { case 0: - return Reference { Reference::Func(bit_cast<FunctionAddress>(m_value.low())) }; + return Reference { Reference::Func { bit_cast<FunctionAddress>(m_value.low()) } }; case 1: - return Reference { Reference::Extern(bit_cast<ExternAddress>(m_value.low())) }; + return Reference { Reference::Extern { bit_cast<ExternAddress>(m_value.low()) } }; case 2: - return Reference { Reference::Null(ValueType(ValueType::Kind::FunctionReference)) }; + return Reference { Reference::Null { ValueType(ValueType::Kind::FunctionReference) } }; case 3: - return Reference { Reference::Null(ValueType(ValueType::Kind::ExternReference)) }; + return Reference { Reference::Null { ValueType(ValueType::Kind::ExternReference) } }; default: VERIFY_NOT_REACHED(); }
8fbd43cb27aacad32e143f3bb9458bbd1b30f4af
2023-02-18 05:22:47
Kenneth Myhra
libweb: Make factory method of CSS::ResolvedCSSStyleDeclaration fallible
false
Make factory method of CSS::ResolvedCSSStyleDeclaration fallible
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp index 07f3975f1460..f3dcc9ac2de4 100644 --- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp +++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp @@ -20,9 +20,9 @@ namespace Web::CSS { -ResolvedCSSStyleDeclaration* ResolvedCSSStyleDeclaration::create(DOM::Element& element) +WebIDL::ExceptionOr<JS::NonnullGCPtr<ResolvedCSSStyleDeclaration>> ResolvedCSSStyleDeclaration::create(DOM::Element& element) { - return element.realm().heap().allocate<ResolvedCSSStyleDeclaration>(element.realm(), element).release_allocated_value_but_fixme_should_propagate_errors(); + return MUST_OR_THROW_OOM(element.realm().heap().allocate<ResolvedCSSStyleDeclaration>(element.realm(), element)); } ResolvedCSSStyleDeclaration::ResolvedCSSStyleDeclaration(DOM::Element& element) diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h index d6b17cd5315f..b659be5dda3e 100644 --- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h +++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h @@ -14,7 +14,7 @@ class ResolvedCSSStyleDeclaration final : public CSSStyleDeclaration { WEB_PLATFORM_OBJECT(ResolvedCSSStyleDeclaration, CSSStyleDeclaration); public: - static ResolvedCSSStyleDeclaration* create(DOM::Element& element); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<ResolvedCSSStyleDeclaration>> create(DOM::Element& element); virtual ~ResolvedCSSStyleDeclaration() override = default; diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp index c07b8de4191f..e346f804e5df 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.cpp +++ b/Userland/Libraries/LibWeb/DOM/Element.cpp @@ -438,7 +438,7 @@ Element::NeedsRelayout Element::recompute_style() NonnullRefPtr<CSS::StyleProperties> Element::resolved_css_values() { - auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this); + auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this).release_value_but_fixme_should_propagate_errors(); auto properties = CSS::StyleProperties::create(); for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) { diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index df9a7c3893ab..4e8984ddc80f 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -644,7 +644,7 @@ Page const* Window::page() const CSS::CSSStyleDeclaration* Window::get_computed_style_impl(DOM::Element& element) const { - return CSS::ResolvedCSSStyleDeclaration::create(element); + return CSS::ResolvedCSSStyleDeclaration::create(element).release_value_but_fixme_should_propagate_errors().ptr(); } JS::NonnullGCPtr<CSS::MediaQueryList> Window::match_media_impl(DeprecatedString media)
05311782d779e32d478b586d7ec1a9d83349ee37
2020-03-25 14:24:46
Andreas Kling
libweb: Remove debug spam about getting a 2D canvas context
false
Remove debug spam about getting a 2D canvas context
libweb
diff --git a/Libraries/LibWeb/Bindings/HTMLCanvasElementWrapper.cpp b/Libraries/LibWeb/Bindings/HTMLCanvasElementWrapper.cpp index 8b99dc37684f..9c3895b0f09c 100644 --- a/Libraries/LibWeb/Bindings/HTMLCanvasElementWrapper.cpp +++ b/Libraries/LibWeb/Bindings/HTMLCanvasElementWrapper.cpp @@ -41,9 +41,7 @@ HTMLCanvasElementWrapper::HTMLCanvasElementWrapper(HTMLCanvasElement& element) { put_native_function("getContext", [this](JS::Object*, const Vector<JS::Value>& arguments) -> JS::Value { if (arguments.size() >= 1) { - dbg() << "Calling getContext on " << node().tag_name(); auto* context = node().get_context(arguments[0].to_string()); - dbg() << "getContext got 2D context=" << context; return wrap(heap(), *context); } return JS::js_undefined(); diff --git a/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp b/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp index dfced69444e8..efade1291922 100644 --- a/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp +++ b/Libraries/LibWeb/DOM/HTMLCanvasElement.cpp @@ -74,10 +74,8 @@ RefPtr<LayoutNode> HTMLCanvasElement::create_layout_node(const StyleProperties* CanvasRenderingContext2D* HTMLCanvasElement::get_context(String type) { ASSERT(type.to_lowercase() == "2d"); - dbg() << "get_context with m_context=" << m_context.ptr(); if (!m_context) m_context = CanvasRenderingContext2D::create(*this); - dbg() << "get_context returning m_context=" << m_context.ptr(); return m_context; }
3483407ddc11ed064915ab12b7b7b6439d6b0e28
2022-11-19 20:07:31
MacDue
ak: Return non-const types from Ptr class operators
false
Return non-const types from Ptr class operators
ak
diff --git a/AK/NonnullOwnPtr.h b/AK/NonnullOwnPtr.h index b10ac3ddc7c2..60d46401cef5 100644 --- a/AK/NonnullOwnPtr.h +++ b/AK/NonnullOwnPtr.h @@ -93,26 +93,17 @@ class [[nodiscard]] NonnullOwnPtr { return exchange(m_ptr, nullptr); } - ALWAYS_INLINE RETURNS_NONNULL T* ptr() + ALWAYS_INLINE RETURNS_NONNULL T* ptr() const { VERIFY(m_ptr); return m_ptr; } - ALWAYS_INLINE RETURNS_NONNULL const T* ptr() const - { - VERIFY(m_ptr); - return m_ptr; - } - - ALWAYS_INLINE RETURNS_NONNULL T* operator->() { return ptr(); } - ALWAYS_INLINE RETURNS_NONNULL const T* operator->() const { return ptr(); } + ALWAYS_INLINE RETURNS_NONNULL T* operator->() const { return ptr(); } - ALWAYS_INLINE T& operator*() { return *ptr(); } - ALWAYS_INLINE const T& operator*() const { return *ptr(); } + ALWAYS_INLINE T& operator*() const { return *ptr(); } - ALWAYS_INLINE RETURNS_NONNULL operator const T*() const { return ptr(); } - ALWAYS_INLINE RETURNS_NONNULL operator T*() { return ptr(); } + ALWAYS_INLINE RETURNS_NONNULL operator T*() const { return ptr(); } operator bool() const = delete; bool operator!() const = delete; diff --git a/AK/NonnullRefPtr.h b/AK/NonnullRefPtr.h index 22ac6eb701a8..d829ef5c0f5e 100644 --- a/AK/NonnullRefPtr.h +++ b/AK/NonnullRefPtr.h @@ -156,47 +156,27 @@ class [[nodiscard]] NonnullRefPtr { return *ptr; } - ALWAYS_INLINE RETURNS_NONNULL T* ptr() - { - return as_nonnull_ptr(); - } - ALWAYS_INLINE RETURNS_NONNULL T const* ptr() const + ALWAYS_INLINE RETURNS_NONNULL T* ptr() const { return as_nonnull_ptr(); } - ALWAYS_INLINE RETURNS_NONNULL T* operator->() - { - return as_nonnull_ptr(); - } - ALWAYS_INLINE RETURNS_NONNULL T const* operator->() const + ALWAYS_INLINE RETURNS_NONNULL T* operator->() const { return as_nonnull_ptr(); } - ALWAYS_INLINE T& operator*() - { - return *as_nonnull_ptr(); - } - ALWAYS_INLINE T const& operator*() const + ALWAYS_INLINE T& operator*() const { return *as_nonnull_ptr(); } - ALWAYS_INLINE RETURNS_NONNULL operator T*() - { - return as_nonnull_ptr(); - } - ALWAYS_INLINE RETURNS_NONNULL operator T const*() const + ALWAYS_INLINE RETURNS_NONNULL operator T*() const { return as_nonnull_ptr(); } - ALWAYS_INLINE operator T&() - { - return *as_nonnull_ptr(); - } - ALWAYS_INLINE operator T const&() const + ALWAYS_INLINE operator T&() const { return *as_nonnull_ptr(); } @@ -217,7 +197,8 @@ class [[nodiscard]] NonnullRefPtr { bool operator==(NonnullRefPtr const& other) const { return m_ptr == other.m_ptr; } - bool operator==(NonnullRefPtr& other) { return m_ptr == other.m_ptr; } + template<typename RawPtr> + bool operator==(RawPtr other) const requires(IsPointer<RawPtr>) { return m_ptr == other; } // clang-format off private: diff --git a/AK/OwnPtr.h b/AK/OwnPtr.h index 4f6b1fbc64ac..ec486ccc406e 100644 --- a/AK/OwnPtr.h +++ b/AK/OwnPtr.h @@ -131,35 +131,21 @@ class [[nodiscard]] OwnPtr { return NonnullOwnPtr<U>(NonnullOwnPtr<U>::Adopt, static_cast<U&>(*leak_ptr())); } - T* ptr() { return m_ptr; } - const T* ptr() const { return m_ptr; } + T* ptr() const { return m_ptr; } - T* operator->() + T* operator->() const { VERIFY(m_ptr); return m_ptr; } - const T* operator->() const - { - VERIFY(m_ptr); - return m_ptr; - } - - T& operator*() - { - VERIFY(m_ptr); - return *m_ptr; - } - - const T& operator*() const + T& operator*() const { VERIFY(m_ptr); return *m_ptr; } - operator const T*() const { return m_ptr; } - operator T*() { return m_ptr; } + operator T*() const { return m_ptr; } operator bool() { return !!m_ptr; } diff --git a/AK/RefPtr.h b/AK/RefPtr.h index 88b8ec2c6975..8ca2346c4b4d 100644 --- a/AK/RefPtr.h +++ b/AK/RefPtr.h @@ -231,31 +231,19 @@ class [[nodiscard]] RefPtr { return NonnullRefPtr<T>(NonnullRefPtr<T>::Adopt, *ptr); } - ALWAYS_INLINE T* ptr() { return as_ptr(); } - ALWAYS_INLINE T const* ptr() const { return as_ptr(); } + ALWAYS_INLINE T* ptr() const { return as_ptr(); } - ALWAYS_INLINE T* operator->() + ALWAYS_INLINE T* operator->() const { return as_nonnull_ptr(); } - ALWAYS_INLINE T const* operator->() const - { - return as_nonnull_ptr(); - } - - ALWAYS_INLINE T& operator*() - { - return *as_nonnull_ptr(); - } - - ALWAYS_INLINE T const& operator*() const + ALWAYS_INLINE T& operator*() const { return *as_nonnull_ptr(); } - ALWAYS_INLINE operator T const*() const { return as_ptr(); } - ALWAYS_INLINE operator T*() { return as_ptr(); } + ALWAYS_INLINE operator T*() const { return as_ptr(); } ALWAYS_INLINE operator bool() { return !is_null(); } @@ -263,17 +251,11 @@ class [[nodiscard]] RefPtr { bool operator==(RefPtr const& other) const { return as_ptr() == other.as_ptr(); } - bool operator==(RefPtr& other) { return as_ptr() == other.as_ptr(); } - template<typename U> bool operator==(NonnullRefPtr<U> const& other) const { return as_ptr() == other.m_ptr; } - template<typename U> - bool operator==(NonnullRefPtr<U>& other) { return as_ptr() == other.m_ptr; } - - bool operator==(T const* other) const { return as_ptr() == other; } - - bool operator==(T* other) { return as_ptr() == other; } + template<typename RawPtr> + bool operator==(RawPtr other) const requires(IsPointer<RawPtr>) { return as_ptr() == other; } ALWAYS_INLINE bool is_null() const { return !m_ptr; } diff --git a/AK/WeakPtr.h b/AK/WeakPtr.h index 97fc920964da..caf881ce9e24 100644 --- a/AK/WeakPtr.h +++ b/AK/WeakPtr.h @@ -117,10 +117,8 @@ class [[nodiscard]] WeakPtr { } T* ptr() const { return unsafe_ptr(); } - T* operator->() { return unsafe_ptr(); } - const T* operator->() const { return unsafe_ptr(); } - operator const T*() const { return unsafe_ptr(); } - operator T*() { return unsafe_ptr(); } + T* operator->() const { return unsafe_ptr(); } + operator T*() const { return unsafe_ptr(); } [[nodiscard]] T* unsafe_ptr() const {
969d9e1fd34d619dcdd210d3235a3bab4ba39b09
2023-11-05 23:14:48
Simon Wanner
libjs: Remove expensive dead code in get_source_range
false
Remove expensive dead code in get_source_range
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index ad020f2e81f8..24b1b4562c53 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -1174,10 +1174,8 @@ static Optional<UnrealizedSourceRange> get_source_range(ExecutionContext const* // JIT frame for (auto address : native_stack) { auto range = native_executable->get_source_range(*context->executable, address); - if (range.has_value()) { - auto realized = range->realize(); + if (range.has_value()) return range; - } } return {};
077cb7687dbc7f3312689d37a6ffdf340ab13daa
2024-06-16 13:16:43
Tim Ledbetter
libweb: Limit find in page query to documents in the active window
false
Limit find in page query to documents in the active window
libweb
diff --git a/Userland/Libraries/LibWeb/Page/Page.cpp b/Userland/Libraries/LibWeb/Page/Page.cpp index d88fbeb73621..7f2728ac5779 100644 --- a/Userland/Libraries/LibWeb/Page/Page.cpp +++ b/Userland/Libraries/LibWeb/Page/Page.cpp @@ -538,13 +538,23 @@ void Page::set_user_style(String source) } } -void Page::clear_selection() +Vector<JS::Handle<DOM::Document>> Page::documents_in_active_window() const { + if (!top_level_traversable_is_initialized()) + return {}; + auto documents = HTML::main_thread_event_loop().documents_in_this_event_loop(); - for (auto const& document : documents) { - if (&document->page() != this) - continue; + for (ssize_t i = documents.size() - 1; i >= 0; --i) { + if (documents[i]->window() != top_level_traversable()->active_window()) + documents.remove(i); + } + + return documents; +} +void Page::clear_selection() +{ + for (auto const& document : documents_in_active_window()) { auto selection = document->get_selection(); if (!selection) continue; @@ -563,12 +573,8 @@ Page::FindInPageResult Page::find_in_page(String const& query, CaseSensitivity c return {}; } - auto documents = HTML::main_thread_event_loop().documents_in_this_event_loop(); Vector<JS::Handle<DOM::Range>> all_matches; - for (auto const& document : documents) { - if (&document->page() != this) - continue; - + for (auto const& document : documents_in_active_window()) { auto matches = document->find_matching_text(query, case_sensitivity); all_matches.extend(move(matches)); } diff --git a/Userland/Libraries/LibWeb/Page/Page.h b/Userland/Libraries/LibWeb/Page/Page.h index 1ef03b7ccf66..25dbbdf4c922 100644 --- a/Userland/Libraries/LibWeb/Page/Page.h +++ b/Userland/Libraries/LibWeb/Page/Page.h @@ -201,6 +201,8 @@ class Page final : public JS::Cell { JS::GCPtr<HTML::HTMLMediaElement> media_context_menu_element(); + Vector<JS::Handle<DOM::Document>> documents_in_active_window() const; + void update_find_in_page_selection(); JS::NonnullGCPtr<PageClient> m_client;
9720ad3901d6a963f567994f06dc4c8481070424
2021-05-08 04:34:10
Brian Gianforcaro
tests: Move Userland/Utilities/test-js to Tests/LibJS
false
Move Userland/Utilities/test-js to Tests/LibJS
tests
diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index b2c33b68fe23..80e7648dd23b 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -127,7 +127,7 @@ if (BUILD_LAGOM) set_target_properties(ntpquery_lagom PROPERTIES OUTPUT_NAME ntpquery) target_link_libraries(ntpquery_lagom Lagom) - add_executable(test-js_lagom ../../Userland/Utilities/test-js.cpp) + add_executable(test-js_lagom ../../Tests/LibJS/test-js.cpp) set_target_properties(test-js_lagom PROPERTIES OUTPUT_NAME test-js) target_link_libraries(test-js_lagom Lagom) target_link_libraries(test-js_lagom stdc++) diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 729536a728af..3cb4feebc35e 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -3,6 +3,7 @@ add_subdirectory(Kernel) add_subdirectory(LibC) add_subdirectory(LibCompress) add_subdirectory(LibGfx) +add_subdirectory(LibJS) add_subdirectory(LibM) add_subdirectory(LibPthread) add_subdirectory(LibRegex) diff --git a/Tests/LibJS/CMakeLists.txt b/Tests/LibJS/CMakeLists.txt new file mode 100644 index 000000000000..11280a094616 --- /dev/null +++ b/Tests/LibJS/CMakeLists.txt @@ -0,0 +1,3 @@ +add_executable(test-js test-js.cpp) +target_link_libraries(test-js LibJS LibLine LibCore) +install(TARGETS ${CMD_NAME} RUNTIME DESTINATION bin) diff --git a/Userland/Utilities/test-js.cpp b/Tests/LibJS/test-js.cpp similarity index 100% rename from Userland/Utilities/test-js.cpp rename to Tests/LibJS/test-js.cpp diff --git a/Userland/Utilities/CMakeLists.txt b/Userland/Utilities/CMakeLists.txt index 67a705674226..c8caada9737b 100644 --- a/Userland/Utilities/CMakeLists.txt +++ b/Userland/Utilities/CMakeLists.txt @@ -45,7 +45,6 @@ target_link_libraries(tar LibArchive LibCompress) target_link_libraries(telws LibProtocol LibLine) target_link_libraries(test-crypto LibCrypto LibTLS LibLine) target_link_libraries(test-fuzz LibCore LibGemini LibGfx LibHTTP LibIPC LibJS LibMarkdown LibShell) -target_link_libraries(test-js LibJS LibLine LibCore) target_link_libraries(test-pthread LibThread) target_link_libraries(tt LibPthread) target_link_libraries(grep LibRegex)
40983356003f9412694953014ae9a4f2c2bfac7a
2023-04-12 23:32:13
Tim Schumacher
libcompress: Error on truncated uncompressed DEFLATE blocks
false
Error on truncated uncompressed DEFLATE blocks
libcompress
diff --git a/Tests/LibCompress/TestGzip.cpp b/Tests/LibCompress/TestGzip.cpp index 39082ca35723..be90cd88e830 100644 --- a/Tests/LibCompress/TestGzip.cpp +++ b/Tests/LibCompress/TestGzip.cpp @@ -95,3 +95,15 @@ TEST_CASE(gzip_round_trip) EXPECT(!uncompressed.is_error()); EXPECT(uncompressed.value() == original); } + +TEST_CASE(gzip_truncated_uncompressed_block) +{ + Array<u8, 38> const compressed { + 0x1F, 0x8B, 0x08, 0x13, 0x5D, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x1C, + 0x1C, 0xFF, 0xDB, 0xFB, 0xFF, 0xDB + }; + + auto const decompressed_or_error = Compress::GzipDecompressor::decompress_all(compressed); + EXPECT(decompressed_or_error.is_error()); +} diff --git a/Userland/Libraries/LibCompress/Deflate.cpp b/Userland/Libraries/LibCompress/Deflate.cpp index 92fa58841424..bdb7135f3e10 100644 --- a/Userland/Libraries/LibCompress/Deflate.cpp +++ b/Userland/Libraries/LibCompress/Deflate.cpp @@ -238,6 +238,9 @@ ErrorOr<bool> DeflateDecompressor::UncompressedBlock::try_read_more() if (m_bytes_remaining == 0) return false; + if (m_decompressor.m_input_stream->is_eof()) + return Error::from_string_literal("Input data ends in the middle of an uncompressed DEFLATE block"); + Array<u8, 4096> temporary_buffer; auto readable_bytes = temporary_buffer.span().trim(min(m_bytes_remaining, m_decompressor.m_output_buffer.empty_space())); auto read_bytes = TRY(m_decompressor.m_input_stream->read_some(readable_bytes));
457edaa4d28c6d26a8f6091642129c5980ec6824
2021-06-25 04:31:37
Aatos Majava
browser: Add alternate shortcut F6 for focusing the location box
false
Add alternate shortcut F6 for focusing the location box
browser
diff --git a/Userland/Applications/Browser/Tab.cpp b/Userland/Applications/Browser/Tab.cpp index 875d364a237e..5e626ac8aa6c 100644 --- a/Userland/Applications/Browser/Tab.cpp +++ b/Userland/Applications/Browser/Tab.cpp @@ -281,7 +281,7 @@ Tab::Tab(BrowserWindow& window, Type type) } auto focus_location_box_action = GUI::Action::create( - "Focus location box", { Mod_Ctrl, Key_L }, [this](auto&) { + "Focus location box", { Mod_Ctrl, Key_L }, Key_F6, [this](auto&) { m_location_box->select_all(); m_location_box->set_focus(true); },
8a6f69f2c87b3a13ce4705f2f6ca0c6dcc9a89cb
2021-07-21 03:34:54
Karol Kosek
soundplayer: Use full path for playlist items
false
Use full path for playlist items
soundplayer
diff --git a/Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp b/Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp index 294b3dfd177b..c2b8ceb2cfde 100644 --- a/Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp +++ b/Userland/Applications/SoundPlayer/SoundPlayerWidgetAdvancedView.cpp @@ -288,13 +288,12 @@ void SoundPlayerWidgetAdvancedView::try_fill_missing_info(Vector<M3UEntry>& entr LexicalPath playlist_path(playlist_p); Vector<M3UEntry*> to_delete; for (auto& entry : entries) { - LexicalPath entry_path(entry.path); - if (!entry_path.is_absolute()) { - entry.path = String::formatted("{}/{}", playlist_path.dirname(), entry_path.basename()); + if (!LexicalPath(entry.path).is_absolute()) { + entry.path = String::formatted("{}/{}", playlist_path.dirname(), entry.path); } if (!Core::File::exists(entry.path)) { - GUI::MessageBox::show(window(), String::formatted("The file \"{}\" present in the playlist does not exist or was not found. This file will be ignored.", entry_path.basename()), "Error reading playlist", GUI::MessageBox::Type::Warning); + GUI::MessageBox::show(window(), String::formatted("The file \"{}\" present in the playlist does not exist or was not found. This file will be ignored.", entry.path), "Error reading playlist", GUI::MessageBox::Type::Warning); to_delete.append(&entry); continue; }
eb0fb38caca5f77e323d1745b6974cd7d6946634
2021-10-30 01:36:49
Timothy Flynn
libweb: Support parsing some data: URLs in CSS
false
Support parsing some data: URLs in CSS
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 09c3189d4a9c..44f47c1700e3 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -1706,20 +1706,34 @@ Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_ return lists; } -Optional<AK::URL> Parser::parse_url_function(ParsingContext const& context, StyleComponentValueRule const& component_value) +Optional<AK::URL> Parser::parse_url_function(ParsingContext const& context, StyleComponentValueRule const& component_value, AllowedDataUrlType allowed_data_url_type) { // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import // FIXME: Handle data: urls (RFC2397) - auto is_data_url = [](StringView& url_string) -> bool { - return url_string.starts_with("data:", CaseSensitivity::CaseInsensitive); + auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> { + if (url_string.starts_with("data:", CaseSensitivity::CaseInsensitive)) { + auto data_url = AK::URL(url_string); + + switch (allowed_data_url_type) { + case AllowedDataUrlType::Image: + if (data_url.data_mime_type().starts_with("image"sv, CaseSensitivity::CaseInsensitive)) + return data_url; + break; + + default: + break; + } + + return {}; + } + + return context.complete_url(url_string); }; if (component_value.is(Token::Type::Url)) { auto url_string = component_value.token().url(); - if (is_data_url(url_string)) - return {}; - return context.complete_url(url_string); + return convert_string_to_url(url_string); } if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) { auto& function_values = component_value.function().values(); @@ -1730,9 +1744,7 @@ Optional<AK::URL> Parser::parse_url_function(ParsingContext const& context, Styl continue; if (value.is(Token::Type::String)) { auto url_string = value.token().string(); - if (is_data_url(url_string)) - return {}; - return context.complete_url(url_string); + return convert_string_to_url(url_string); } break; } @@ -2370,7 +2382,7 @@ RefPtr<StyleValue> Parser::parse_string_value(ParsingContext const&, StyleCompon RefPtr<StyleValue> Parser::parse_image_value(ParsingContext const& context, StyleComponentValueRule const& component_value) { - auto url = parse_url_function(context, component_value); + auto url = parse_url_function(context, component_value, AllowedDataUrlType::Image); if (url.has_value()) return ImageStyleValue::create(url.value()); // FIXME: Handle gradients. diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h index 3bd48747c69c..2863a3c19d99 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h @@ -195,7 +195,12 @@ class Parser { static Optional<float> try_parse_float(StringView string); static Optional<Color> parse_color(ParsingContext const&, StyleComponentValueRule const&); static Optional<Length> parse_length(ParsingContext const&, StyleComponentValueRule const&); - static Optional<AK::URL> parse_url_function(ParsingContext const&, StyleComponentValueRule const&); + + enum class AllowedDataUrlType { + None, + Image, + }; + static Optional<AK::URL> parse_url_function(ParsingContext const&, StyleComponentValueRule const&, AllowedDataUrlType = AllowedDataUrlType::None); Result<NonnullRefPtr<StyleValue>, ParsingResult> parse_css_value(PropertyID, TokenStream<StyleComponentValueRule>&); static RefPtr<StyleValue> parse_css_value(ParsingContext const&, StyleComponentValueRule const&);
c6813304503e679a2cd0bf442fe6df9e4b0d1537
2022-12-07 22:01:16
Thomas Queiroz
kernel: Don't panic if MemoryManager::find_free_physical_page fails
false
Don't panic if MemoryManager::find_free_physical_page fails
kernel
diff --git a/Kernel/Memory/MemoryManager.cpp b/Kernel/Memory/MemoryManager.cpp index 3fb5d53769aa..7ccff188ca02 100644 --- a/Kernel/Memory/MemoryManager.cpp +++ b/Kernel/Memory/MemoryManager.cpp @@ -923,7 +923,10 @@ RefPtr<PhysicalPage> MemoryManager::find_free_physical_page(bool committed) } } }); - VERIFY(!page.is_null()); + + if (page.is_null()) + dbgln("MM: couldn't find free physical page. Continuing..."); + return page; }
d551e0e55e20c8c3829de237a25e95b121ba47a7
2021-10-04 14:22:15
Linus Groh
libjs: Convert init_typed_array_from_array_like() to ThrowCompletionOr
false
Convert init_typed_array_from_array_like() to ThrowCompletionOr
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/TypedArray.cpp b/Userland/Libraries/LibJS/Runtime/TypedArray.cpp index 6143f9ecf0cf..3379619f1e96 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArray.cpp +++ b/Userland/Libraries/LibJS/Runtime/TypedArray.cpp @@ -239,44 +239,65 @@ static ThrowCompletionOr<void> initialize_typed_array_from_typed_array(GlobalObj // 23.2.5.1.5 InitializeTypedArrayFromArrayLike, https://tc39.es/ecma262/#sec-initializetypedarrayfromarraylike template<typename T> -static void initialize_typed_array_from_array_like(GlobalObject& global_object, TypedArray<T>& typed_array, const Object& array_like) +static ThrowCompletionOr<void> initialize_typed_array_from_array_like(GlobalObject& global_object, TypedArray<T>& typed_array, const Object& array_like) { auto& vm = global_object.vm(); - auto length_or_error = length_of_array_like(global_object, array_like); - if (length_or_error.is_error()) - return; - auto length = length_or_error.release_value(); + + // 1. Let len be ? LengthOfArrayLike(arrayLike). + auto length = TRY(length_of_array_like(global_object, array_like)); + + // 2. Perform ? AllocateTypedArrayBuffer(O, len). + + // 23.2.5.1.6 AllocateTypedArrayBuffer ( O, length ) // Enforce 2GB "Excessive Length" limit - if (length > NumericLimits<i32>::max() / sizeof(T)) { - vm.throw_exception<RangeError>(global_object, ErrorType::InvalidLength, "typed array"); - return; - } + if (length > NumericLimits<i32>::max() / sizeof(T)) + return vm.template throw_completion<RangeError>(global_object, ErrorType::InvalidLength, "typed array"); + + // 1. Assert: O.[[ViewedArrayBuffer]] is undefined. + // 2. Let constructorName be the String value of O.[[TypedArrayName]]. + // 3. Let elementSize be the Element Size value specified in Table 72 for constructorName. auto element_size = typed_array.element_size(); - if (Checked<size_t>::multiplication_would_overflow(element_size, length)) { - vm.throw_exception<RangeError>(global_object, ErrorType::InvalidLength, "typed array"); - return; - } + if (Checked<size_t>::multiplication_would_overflow(element_size, length)) + return vm.template throw_completion<RangeError>(global_object, ErrorType::InvalidLength, "typed array"); + + // 4. Let byteLength be elementSize × length. auto byte_length = element_size * length; - auto array_buffer = ArrayBuffer::create(global_object, byte_length); - if (!array_buffer) - return; - typed_array.set_viewed_array_buffer(array_buffer); + // 5. Let data be ? AllocateArrayBuffer(%ArrayBuffer%, byteLength). + auto* data = ArrayBuffer::create(global_object, byte_length); + if (auto* exception = vm.exception()) + return throw_completion(exception->value()); + + // 6. Set O.[[ViewedArrayBuffer]] to data. + typed_array.set_viewed_array_buffer(data); + + // 7. Set O.[[ByteLength]] to byteLength. typed_array.set_byte_length(byte_length); + + // 8. Set O.[[ByteOffset]] to 0. typed_array.set_byte_offset(0); + + // 9. Set O.[[ArrayLength]] to length. typed_array.set_array_length(length); + // 10. Return O. + // End of 23.2.5.1.6 + + // 4. Repeat, while k < len, for (size_t k = 0; k < length; k++) { - auto value_or_error = array_like.get(k); - if (value_or_error.is_error()) - return; - auto value = value_or_error.release_value(); - auto result_or_error = typed_array.set(k, value, Object::ShouldThrowExceptions::Yes); - if (result_or_error.is_error()) - return; + // a. Let Pk be ! ToString(𝔽(k)). + // b. Let kValue be ? Get(arrayLike, Pk). + auto k_value = TRY(array_like.get(k)); + + // c. Perform ? Set(O, Pk, kValue, true). + TRY(typed_array.set(k, k_value, Object::ShouldThrowExceptions::Yes)); + + // d. Set k to k + 1. } + + return {}; } // 23.2.5.1.4 InitializeTypedArrayFromList, https://tc39.es/ecma262/#sec-initializetypedarrayfromlist @@ -447,7 +468,7 @@ void TypedArrayBase::visit_edges(Visitor& visitor) return {}; \ initialize_typed_array_from_list(global_object(), *typed_array, values); \ } else { \ - initialize_typed_array_from_array_like(global_object(), *typed_array, first_argument.as_object()); \ + TRY_OR_DISCARD(initialize_typed_array_from_array_like(global_object(), *typed_array, first_argument.as_object())); \ } \ if (vm.exception()) \ return {}; \
ab1c84cf537123a939bd040cb2545909031a72ce
2019-04-11 01:58:10
Andreas Kling
libcore: Move HTTP classes from LibGUI to LibCore.
false
Move HTTP classes from LibGUI to LibCore.
libcore
diff --git a/Applications/Downloader/main.cpp b/Applications/Downloader/main.cpp index ef9c62ee82a2..99b536b4614c 100644 --- a/Applications/Downloader/main.cpp +++ b/Applications/Downloader/main.cpp @@ -1,14 +1,14 @@ #include <LibGUI/GApplication.h> -#include <LibGUI/GHttpRequest.h> -#include <LibGUI/GHttpResponse.h> -#include <LibGUI/GNetworkJob.h> +#include <LibCore/CHttpRequest.h> +#include <LibCore/CHttpResponse.h> +#include <LibCore/CNetworkJob.h> #include <stdio.h> int main(int argc, char** argv) { GApplication app(argc, argv); - GHttpRequest request; + CHttpRequest request; request.set_hostname("www.google.com"); request.set_path("/"); @@ -18,7 +18,7 @@ int main(int argc, char** argv) dbgprintf("on_finish: request failed :(\n"); return; } - auto& response = static_cast<const GHttpResponse&>(*job->response()); + auto& response = static_cast<const CHttpResponse&>(*job->response()); printf("%s{%p}: on_receive: code=%d\n", job->class_name(), job, response.code()); //printf("payload:\n"); //printf("%s", response.payload().pointer()); diff --git a/LibGUI/GHttpJob.cpp b/LibCore/CHttpJob.cpp similarity index 79% rename from LibGUI/GHttpJob.cpp rename to LibCore/CHttpJob.cpp index 9a1f84833821..1798005e9baf 100644 --- a/LibGUI/GHttpJob.cpp +++ b/LibCore/CHttpJob.cpp @@ -1,19 +1,19 @@ -#include <LibGUI/GHttpJob.h> -#include <LibGUI/GHttpResponse.h> +#include <LibCore/CHttpJob.h> +#include <LibCore/CHttpResponse.h> #include <LibCore/CTCPSocket.h> #include <stdio.h> #include <unistd.h> -GHttpJob::GHttpJob(const GHttpRequest& request) +CHttpJob::CHttpJob(const CHttpRequest& request) : m_request(request) { } -GHttpJob::~GHttpJob() +CHttpJob::~CHttpJob() { } -void GHttpJob::on_socket_connected() +void CHttpJob::on_socket_connected() { auto raw_request = m_request.to_raw_request(); #if 0 @@ -22,7 +22,7 @@ void GHttpJob::on_socket_connected() bool success = m_socket->send(raw_request); if (!success) - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::TransmissionFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::TransmissionFailed); }); Vector<byte> buffer; while (m_socket->is_connected()) { @@ -33,18 +33,18 @@ void GHttpJob::on_socket_connected() auto line = m_socket->read_line(PAGE_SIZE); if (line.is_null()) { printf("Expected HTTP status\n"); - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::TransmissionFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::TransmissionFailed); }); } auto parts = String::from_byte_buffer(line, Chomp).split(' '); if (parts.size() < 3) { printf("Expected 3-part HTTP status, got '%s'\n", line.pointer()); - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::ProtocolFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::ProtocolFailed); }); } bool ok; m_code = parts[1].to_uint(ok); if (!ok) { printf("Expected numeric HTTP status\n"); - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::ProtocolFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::ProtocolFailed); }); } m_state = State::InHeaders; continue; @@ -55,7 +55,7 @@ void GHttpJob::on_socket_connected() auto line = m_socket->read_line(PAGE_SIZE); if (line.is_null()) { printf("Expected HTTP header\n"); - return did_fail(GNetworkJob::Error::ProtocolFailed); + return did_fail(CNetworkJob::Error::ProtocolFailed); } auto chomped_line = String::from_byte_buffer(line, Chomp); if (chomped_line.is_empty()) { @@ -65,12 +65,12 @@ void GHttpJob::on_socket_connected() auto parts = chomped_line.split(':'); if (parts.is_empty()) { printf("Expected HTTP header with key/value\n"); - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::ProtocolFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::ProtocolFailed); }); } auto name = parts[0]; if (chomped_line.length() < name.length() + 2) { printf("Malformed HTTP header: '%s' (%d)\n", chomped_line.characters(), chomped_line.length()); - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::ProtocolFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::ProtocolFailed); }); } auto value = chomped_line.substring(name.length() + 2, chomped_line.length() - name.length() - 2); m_headers.set(name, value); @@ -84,18 +84,18 @@ void GHttpJob::on_socket_connected() m_state = State::Finished; break; } - return deferred_invoke([this](auto&){ did_fail(GNetworkJob::Error::ProtocolFailed); }); + return deferred_invoke([this](auto&){ did_fail(CNetworkJob::Error::ProtocolFailed); }); } buffer.append(payload.pointer(), payload.size()); } - auto response = GHttpResponse::create(m_code, move(m_headers), ByteBuffer::copy(buffer.data(), buffer.size())); + auto response = CHttpResponse::create(m_code, move(m_headers), ByteBuffer::copy(buffer.data(), buffer.size())); deferred_invoke([this, response] (auto&) { did_finish(move(response)); }); } -void GHttpJob::start() +void CHttpJob::start() { ASSERT(!m_socket); m_socket = new CTCPSocket(this); @@ -105,5 +105,5 @@ void GHttpJob::start() }; bool success = m_socket->connect(m_request.hostname(), m_request.port()); if (!success) - return did_fail(GNetworkJob::Error::ConnectionFailed); + return did_fail(CNetworkJob::Error::ConnectionFailed); } diff --git a/LibGUI/GHttpJob.h b/LibCore/CHttpJob.h similarity index 58% rename from LibGUI/GHttpJob.h rename to LibCore/CHttpJob.h index 8ba52728d254..e30e836b6651 100644 --- a/LibGUI/GHttpJob.h +++ b/LibCore/CHttpJob.h @@ -1,19 +1,19 @@ #pragma once -#include <LibGUI/GNetworkJob.h> -#include <LibGUI/GHttpRequest.h> +#include <LibCore/CNetworkJob.h> +#include <LibCore/CHttpRequest.h> #include <AK/HashMap.h> class CTCPSocket; -class GHttpJob final : public GNetworkJob { +class CHttpJob final : public CNetworkJob { public: - explicit GHttpJob(const GHttpRequest&); - virtual ~GHttpJob() override; + explicit CHttpJob(const CHttpRequest&); + virtual ~CHttpJob() override; virtual void start() override; - virtual const char* class_name() const override { return "GHttpJob"; } + virtual const char* class_name() const override { return "CHttpJob"; } private: void on_socket_connected(); @@ -25,7 +25,7 @@ class GHttpJob final : public GNetworkJob { Finished, }; - GHttpRequest m_request; + CHttpRequest m_request; CTCPSocket* m_socket { nullptr }; State m_state { State::InStatus }; int m_code { -1 }; diff --git a/LibGUI/GHttpRequest.cpp b/LibCore/CHttpRequest.cpp similarity index 63% rename from LibGUI/GHttpRequest.cpp rename to LibCore/CHttpRequest.cpp index 529e340be2c0..3f07fecaa1fd 100644 --- a/LibGUI/GHttpRequest.cpp +++ b/LibCore/CHttpRequest.cpp @@ -1,24 +1,23 @@ -#include <LibGUI/GHttpRequest.h> -#include <LibGUI/GHttpJob.h> -#include <LibGUI/GEventLoop.h> +#include <LibCore/CHttpRequest.h> +#include <LibCore/CHttpJob.h> #include <AK/StringBuilder.h> -GHttpRequest::GHttpRequest() +CHttpRequest::CHttpRequest() { } -GHttpRequest::~GHttpRequest() +CHttpRequest::~CHttpRequest() { } -GNetworkJob* GHttpRequest::schedule() +CNetworkJob* CHttpRequest::schedule() { - auto* job = new GHttpJob(*this); + auto* job = new CHttpJob(*this); job->start(); return job; } -String GHttpRequest::method_name() const +String CHttpRequest::method_name() const { switch (m_method) { case Method::GET: @@ -32,7 +31,7 @@ String GHttpRequest::method_name() const } } -ByteBuffer GHttpRequest::to_raw_request() const +ByteBuffer CHttpRequest::to_raw_request() const { StringBuilder builder; builder.append(method_name()); diff --git a/LibGUI/GHttpRequest.h b/LibCore/CHttpRequest.h similarity index 86% rename from LibGUI/GHttpRequest.h rename to LibCore/CHttpRequest.h index 68f9673d6f95..5432baf4b534 100644 --- a/LibGUI/GHttpRequest.h +++ b/LibCore/CHttpRequest.h @@ -2,14 +2,14 @@ #include <AK/AKString.h> -class GNetworkJob; +class CNetworkJob; -class GHttpRequest { +class CHttpRequest { public: enum Method { Invalid, HEAD, GET, POST }; - GHttpRequest(); - ~GHttpRequest(); + CHttpRequest(); + ~CHttpRequest(); String hostname() const { return m_hostname; } int port() const { return m_port; } @@ -24,7 +24,7 @@ class GHttpRequest { String method_name() const; ByteBuffer to_raw_request() const; - GNetworkJob* schedule(); + CNetworkJob* schedule(); private: String m_hostname; diff --git a/LibCore/CHttpResponse.cpp b/LibCore/CHttpResponse.cpp new file mode 100644 index 000000000000..07fef16ee06e --- /dev/null +++ b/LibCore/CHttpResponse.cpp @@ -0,0 +1,12 @@ +#include <LibCore/CHttpResponse.h> + +CHttpResponse::CHttpResponse(int code, HashMap<String, String>&& headers, ByteBuffer&& payload) + : CNetworkResponse(move(payload)) + , m_code(code) + , m_headers(move(headers)) +{ +} + +CHttpResponse::~CHttpResponse() +{ +} diff --git a/LibGUI/GHttpResponse.h b/LibCore/CHttpResponse.h similarity index 51% rename from LibGUI/GHttpResponse.h rename to LibCore/CHttpResponse.h index 52f90e52acdd..7cf46bc545d9 100644 --- a/LibGUI/GHttpResponse.h +++ b/LibCore/CHttpResponse.h @@ -1,22 +1,22 @@ #pragma once -#include <LibGUI/GNetworkResponse.h> +#include <LibCore/CNetworkResponse.h> #include <AK/AKString.h> #include <AK/HashMap.h> -class GHttpResponse : public GNetworkResponse { +class CHttpResponse : public CNetworkResponse { public: - virtual ~GHttpResponse() override; - static Retained<GHttpResponse> create(int code, HashMap<String, String>&& headers, ByteBuffer&& payload) + virtual ~CHttpResponse() override; + static Retained<CHttpResponse> create(int code, HashMap<String, String>&& headers, ByteBuffer&& payload) { - return adopt(*new GHttpResponse(code, move(headers), move(payload))); + return adopt(*new CHttpResponse(code, move(headers), move(payload))); } int code() const { return m_code; } const HashMap<String, String>& headers() const { return m_headers; } private: - GHttpResponse(int code, HashMap<String, String>&&, ByteBuffer&&); + CHttpResponse(int code, HashMap<String, String>&&, ByteBuffer&&); int m_code { 0 }; HashMap<String, String> m_headers; diff --git a/LibGUI/GNetworkJob.cpp b/LibCore/CNetworkJob.cpp similarity index 59% rename from LibGUI/GNetworkJob.cpp rename to LibCore/CNetworkJob.cpp index fb473a7c0e77..8ff758a3a4f3 100644 --- a/LibGUI/GNetworkJob.cpp +++ b/LibCore/CNetworkJob.cpp @@ -1,16 +1,16 @@ -#include <LibGUI/GNetworkJob.h> -#include <LibGUI/GNetworkResponse.h> +#include <LibCore/CNetworkJob.h> +#include <LibCore/CNetworkResponse.h> #include <stdio.h> -GNetworkJob::GNetworkJob() +CNetworkJob::CNetworkJob() { } -GNetworkJob::~GNetworkJob() +CNetworkJob::~CNetworkJob() { } -void GNetworkJob::did_finish(Retained<GNetworkResponse>&& response) +void CNetworkJob::did_finish(Retained<CNetworkResponse>&& response) { m_response = move(response); printf("%s{%p} job did_finish!\n", class_name(), this); @@ -18,7 +18,7 @@ void GNetworkJob::did_finish(Retained<GNetworkResponse>&& response) on_finish(true); } -void GNetworkJob::did_fail(Error error) +void CNetworkJob::did_fail(Error error) { m_error = error; dbgprintf("%s{%p} job did_fail! error=%u\n", class_name(), this, (unsigned)error); diff --git a/LibGUI/GNetworkJob.h b/LibCore/CNetworkJob.h similarity index 55% rename from LibGUI/GNetworkJob.h rename to LibCore/CNetworkJob.h index fd87244cd2b9..4b6b479c8fbc 100644 --- a/LibGUI/GNetworkJob.h +++ b/LibCore/CNetworkJob.h @@ -3,9 +3,9 @@ #include <LibCore/CObject.h> #include <AK/Function.h> -class GNetworkResponse; +class CNetworkResponse; -class GNetworkJob : public CObject { +class CNetworkJob : public CObject { public: enum class Error { None, @@ -13,25 +13,25 @@ class GNetworkJob : public CObject { TransmissionFailed, ProtocolFailed, }; - virtual ~GNetworkJob() override; + virtual ~CNetworkJob() override; Function<void(bool success)> on_finish; bool has_error() const { return m_error != Error::None; } Error error() const { return m_error; } - GNetworkResponse* response() { return m_response.ptr(); } - const GNetworkResponse* response() const { return m_response.ptr(); } + CNetworkResponse* response() { return m_response.ptr(); } + const CNetworkResponse* response() const { return m_response.ptr(); } virtual void start() = 0; - virtual const char* class_name() const override { return "GNetworkJob"; } + virtual const char* class_name() const override { return "CNetworkJob"; } protected: - GNetworkJob(); - void did_finish(Retained<GNetworkResponse>&&); + CNetworkJob(); + void did_finish(Retained<CNetworkResponse>&&); void did_fail(Error); private: - RetainPtr<GNetworkResponse> m_response; + RetainPtr<CNetworkResponse> m_response; Error m_error { Error::None }; }; diff --git a/LibCore/CNetworkResponse.cpp b/LibCore/CNetworkResponse.cpp new file mode 100644 index 000000000000..1550d8ac690b --- /dev/null +++ b/LibCore/CNetworkResponse.cpp @@ -0,0 +1,10 @@ +#include <LibCore/CNetworkResponse.h> + +CNetworkResponse::CNetworkResponse(ByteBuffer&& payload) + : m_payload(payload) +{ +} + +CNetworkResponse::~CNetworkResponse() +{ +} diff --git a/LibGUI/GNetworkResponse.h b/LibCore/CNetworkResponse.h similarity index 64% rename from LibGUI/GNetworkResponse.h rename to LibCore/CNetworkResponse.h index 6dbeaf5c6437..1968590c7935 100644 --- a/LibGUI/GNetworkResponse.h +++ b/LibCore/CNetworkResponse.h @@ -3,15 +3,15 @@ #include <AK/Retainable.h> #include <AK/ByteBuffer.h> -class GNetworkResponse : public Retainable<GNetworkResponse> { +class CNetworkResponse : public Retainable<CNetworkResponse> { public: - virtual ~GNetworkResponse(); + virtual ~CNetworkResponse(); bool is_error() const { return m_error; } const ByteBuffer& payload() const { return m_payload; } protected: - explicit GNetworkResponse(ByteBuffer&&); + explicit CNetworkResponse(ByteBuffer&&); bool m_error { false }; ByteBuffer m_payload; diff --git a/LibCore/Makefile b/LibCore/Makefile index 4d4409f008c9..f3af95529fd2 100644 --- a/LibCore/Makefile +++ b/LibCore/Makefile @@ -5,6 +5,11 @@ OBJS = \ CTCPSocket.o \ CElapsedTimer.o \ CNotifier.o \ + CHttpRequest.o \ + CHttpResponse.o \ + CHttpJob.o \ + CNetworkJob.o \ + CNetworkResponse.o \ CObject.o \ CEventLoop.o \ CEvent.o diff --git a/LibGUI/GHttpResponse.cpp b/LibGUI/GHttpResponse.cpp deleted file mode 100644 index 95f01c80f51c..000000000000 --- a/LibGUI/GHttpResponse.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include <LibGUI/GHttpResponse.h> - -GHttpResponse::GHttpResponse(int code, HashMap<String, String>&& headers, ByteBuffer&& payload) - : GNetworkResponse(move(payload)) - , m_code(code) - , m_headers(move(headers)) -{ -} - -GHttpResponse::~GHttpResponse() -{ -} diff --git a/LibGUI/GNetworkResponse.cpp b/LibGUI/GNetworkResponse.cpp deleted file mode 100644 index 64bdbd1b680a..000000000000 --- a/LibGUI/GNetworkResponse.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include <LibGUI/GNetworkResponse.h> - -GNetworkResponse::GNetworkResponse(ByteBuffer&& payload) - : m_payload(payload) -{ -} - -GNetworkResponse::~GNetworkResponse() -{ -} diff --git a/LibGUI/Makefile b/LibGUI/Makefile index 6cdf6c8a7aec..3847add902ff 100644 --- a/LibGUI/Makefile +++ b/LibGUI/Makefile @@ -50,11 +50,6 @@ LIBGUI_OBJS = \ GFileSystemModel.o \ GSplitter.o \ GTimer.o \ - GNetworkJob.o \ - GNetworkResponse.o \ - GHttpRequest.o \ - GHttpResponse.o \ - GHttpJob.o \ GSpinBox.o \ GGroupBox.o \ GWindow.o
1aab7b51ea9c27a6ffff8df0c8bcbec87680865c
2024-10-20 12:20:01
Timothy Flynn
libwebview: Generate hyperlinks for attributes that represent links
false
Generate hyperlinks for attributes that represent links
libwebview
diff --git a/Ladybird/AppKit/UI/LadybirdWebView.mm b/Ladybird/AppKit/UI/LadybirdWebView.mm index 5905f4e5a3af..7f21dd19b5ce 100644 --- a/Ladybird/AppKit/UI/LadybirdWebView.mm +++ b/Ladybird/AppKit/UI/LadybirdWebView.mm @@ -1051,12 +1051,12 @@ - (void)setWebViewCallbacks return Ladybird::ns_rect_to_gfx_rect([[self window] frame]); }; - m_web_view_bridge->on_received_source = [weak_self](auto const& url, auto const& source) { + m_web_view_bridge->on_received_source = [weak_self](auto const& url, auto const& base_url, auto const& source) { LadybirdWebView* self = weak_self; if (self == nil) { return; } - auto html = WebView::highlight_source(MUST(url.to_string()), source, Syntax::Language::HTML, WebView::HighlightOutputMode::FullDocument); + auto html = WebView::highlight_source(url, base_url, source, Syntax::Language::HTML, WebView::HighlightOutputMode::FullDocument); [self.observer onCreateNewTab:html url:url diff --git a/Ladybird/Qt/Tab.cpp b/Ladybird/Qt/Tab.cpp index ee76f673e23e..fb72ffb5d989 100644 --- a/Ladybird/Qt/Tab.cpp +++ b/Ladybird/Qt/Tab.cpp @@ -321,8 +321,8 @@ Tab::Tab(BrowserWindow* window, RefPtr<WebView::WebContentClient> parent_client, QObject::connect(focus_location_editor_action, &QAction::triggered, this, &Tab::focus_location_editor); - view().on_received_source = [this](auto const& url, auto const& source) { - auto html = WebView::highlight_source(MUST(url.to_string()), source, Syntax::Language::HTML, WebView::HighlightOutputMode::FullDocument); + view().on_received_source = [this](auto const& url, auto const& base_url, auto const& source) { + auto html = WebView::highlight_source(url, base_url, source, Syntax::Language::HTML, WebView::HighlightOutputMode::FullDocument); m_window->new_tab_from_content(html, Web::HTML::ActivateTab::Yes); }; diff --git a/Userland/Libraries/LibWebView/InspectorClient.cpp b/Userland/Libraries/LibWebView/InspectorClient.cpp index 622833a64882..e9da24e19668 100644 --- a/Userland/Libraries/LibWebView/InspectorClient.cpp +++ b/Userland/Libraries/LibWebView/InspectorClient.cpp @@ -128,8 +128,8 @@ InspectorClient::InspectorClient(ViewImplementation& content_web_view, ViewImple m_inspector_web_view.run_javascript(builder.string_view()); }; - m_content_web_view.on_received_style_sheet_source = [this](Web::CSS::StyleSheetIdentifier const& identifier, String const& source) { - auto html = highlight_source(identifier.url.value_or({}), source, Syntax::Language::CSS, HighlightOutputMode::SourceOnly); + m_content_web_view.on_received_style_sheet_source = [this](Web::CSS::StyleSheetIdentifier const& identifier, auto const& base_url, String const& source) { + auto html = highlight_source(identifier.url.value_or({}), base_url, source, Syntax::Language::CSS, HighlightOutputMode::SourceOnly); auto script = MUST(String::formatted("inspector.setStyleSheetSource({}, \"{}\");", style_sheet_identifier_to_json(identifier), MUST(encode_base64(html.bytes())))); diff --git a/Userland/Libraries/LibWebView/SourceHighlighter.cpp b/Userland/Libraries/LibWebView/SourceHighlighter.cpp index fe1a0588d49c..f4ab5b5f96f6 100644 --- a/Userland/Libraries/LibWebView/SourceHighlighter.cpp +++ b/Userland/Libraries/LibWebView/SourceHighlighter.cpp @@ -11,6 +11,7 @@ #include <LibURL/URL.h> #include <LibWeb/CSS/Parser/Token.h> #include <LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.h> +#include <LibWeb/DOMURL/DOMURL.h> #include <LibWeb/HTML/SyntaxHighlighter/SyntaxHighlighter.h> #include <LibWebView/SourceHighlighter.h> @@ -113,10 +114,10 @@ void SourceHighlighterClient::highlighter_did_set_folding_regions(Vector<Syntax: document().set_folding_regions(move(folding_regions)); } -String highlight_source(String const& url, StringView source, Syntax::Language language, HighlightOutputMode mode) +String highlight_source(URL::URL const& url, URL::URL const& base_url, StringView source, Syntax::Language language, HighlightOutputMode mode) { SourceHighlighterClient highlighter_client { source, language }; - return highlighter_client.to_html_string(url, mode); + return highlighter_client.to_html_string(url, base_url, mode); } StringView SourceHighlighterClient::class_for_token(u64 token_type) const @@ -232,7 +233,7 @@ StringView SourceHighlighterClient::class_for_token(u64 token_type) const } } -String SourceHighlighterClient::to_html_string(String const& url, HighlightOutputMode mode) const +String SourceHighlighterClient::to_html_string(URL::URL const& url, URL::URL const& base_url, HighlightOutputMode mode) const { StringBuilder builder; @@ -266,7 +267,7 @@ String SourceHighlighterClient::to_html_string(String const& url, HighlightOutpu <head> <meta name="color-scheme" content="dark light">)~~~"sv); - builder.appendff("<title>View Source - {}</title>", escape_html_entities(url)); + builder.appendff("<title>View Source - {}</title>", escape_html_entities(url.serialize_for_display())); builder.appendff("<style type=\"text/css\">{}</style>", HTML_HIGHLIGHTER_STYLE); builder.append(R"~~~( </head> @@ -274,6 +275,22 @@ String SourceHighlighterClient::to_html_string(String const& url, HighlightOutpu } builder.append("<pre class=\"html\">"sv); + static constexpr auto href = to_array<u32>({ 'h', 'r', 'e', 'f' }); + static constexpr auto src = to_array<u32>({ 's', 'r', 'c' }); + bool linkify_attribute = false; + + auto resolve_url_for_attribute = [&](Utf32View const& attribute_value) -> Optional<URL::URL> { + if (!linkify_attribute) + return {}; + + auto attribute_url = MUST(String::formatted("{}", attribute_value)); + auto attribute_url_without_quotes = attribute_url.bytes_as_string_view().trim("\""sv); + + if (auto resolved = Web::DOMURL::parse(attribute_url_without_quotes, base_url); resolved.is_valid()) + return resolved; + return {}; + }; + size_t span_index = 0; for (size_t line_index = 0; line_index < document().line_count(); ++line_index) { auto& line = document().line(line_index); @@ -286,11 +303,27 @@ String SourceHighlighterClient::to_html_string(String const& url, HighlightOutpu size_t length = end - start; if (length == 0) return; + auto text = line_view.substring_view(start, length); + if (span.has_value()) { + bool append_anchor_close = false; + + if (span->data == to_underlying(Web::HTML::AugmentedTokenKind::AttributeName)) { + linkify_attribute = text == Utf32View { href } || text == Utf32View { src }; + } else if (span->data == to_underlying(Web::HTML::AugmentedTokenKind::AttributeValue)) { + if (auto href = resolve_url_for_attribute(text); href.has_value()) { + builder.appendff("<a href=\"{}\">", *href); + append_anchor_close = true; + } + } + start_token(span->data); append_escaped(text); end_token(); + + if (append_anchor_close) + builder.append("</a>"sv); } else { append_escaped(text); } diff --git a/Userland/Libraries/LibWebView/SourceHighlighter.h b/Userland/Libraries/LibWebView/SourceHighlighter.h index f5a243e424f3..8b938075e1b7 100644 --- a/Userland/Libraries/LibWebView/SourceHighlighter.h +++ b/Userland/Libraries/LibWebView/SourceHighlighter.h @@ -7,11 +7,13 @@ #pragma once +#include <AK/OwnPtr.h> #include <AK/String.h> #include <AK/StringView.h> #include <LibSyntax/Document.h> #include <LibSyntax/HighlighterClient.h> #include <LibSyntax/Language.h> +#include <LibURL/Forward.h> namespace WebView { @@ -50,7 +52,7 @@ class SourceHighlighterClient final : public Syntax::HighlighterClient { SourceHighlighterClient(StringView source, Syntax::Language); virtual ~SourceHighlighterClient() = default; - String to_html_string(String const&, HighlightOutputMode) const; + String to_html_string(URL::URL const& url, URL::URL const& base_url, HighlightOutputMode) const; private: // ^ Syntax::HighlighterClient @@ -73,7 +75,7 @@ class SourceHighlighterClient final : public Syntax::HighlighterClient { OwnPtr<Syntax::Highlighter> m_highlighter; }; -String highlight_source(String const&, StringView, Syntax::Language, HighlightOutputMode); +String highlight_source(URL::URL const& url, URL::URL const& base_url, StringView, Syntax::Language, HighlightOutputMode); constexpr inline StringView HTML_HIGHLIGHTER_STYLE = R"~~~( @media (prefers-color-scheme: dark) { diff --git a/Userland/Libraries/LibWebView/ViewImplementation.h b/Userland/Libraries/LibWebView/ViewImplementation.h index 4ab7090da2ef..1f6d68411de9 100644 --- a/Userland/Libraries/LibWebView/ViewImplementation.h +++ b/Userland/Libraries/LibWebView/ViewImplementation.h @@ -185,13 +185,13 @@ class ViewImplementation { Function<void(String const& message)> on_request_set_prompt_text; Function<void()> on_request_accept_dialog; Function<void()> on_request_dismiss_dialog; - Function<void(URL::URL const&, ByteString const&)> on_received_source; + Function<void(URL::URL const&, URL::URL const&, String const&)> on_received_source; Function<void(ByteString const&)> on_received_dom_tree; Function<void(Optional<DOMNodeProperties>)> on_received_dom_node_properties; Function<void(ByteString const&)> on_received_accessibility_tree; Function<void(Vector<Web::CSS::StyleSheetIdentifier>)> on_received_style_sheet_list; Function<void(Web::CSS::StyleSheetIdentifier const&)> on_inspector_requested_style_sheet_source; - Function<void(Web::CSS::StyleSheetIdentifier const&, String const&)> on_received_style_sheet_source; + Function<void(Web::CSS::StyleSheetIdentifier const&, URL::URL const&, String const&)> on_received_style_sheet_source; Function<void(i32 node_id)> on_received_hovered_node_id; Function<void(Optional<i32> const& node_id)> on_finshed_editing_dom_node; Function<void(String const&)> on_received_dom_node_html; diff --git a/Userland/Libraries/LibWebView/WebContentClient.cpp b/Userland/Libraries/LibWebView/WebContentClient.cpp index 5e13efc4f736..4b70d5dc0d9f 100644 --- a/Userland/Libraries/LibWebView/WebContentClient.cpp +++ b/Userland/Libraries/LibWebView/WebContentClient.cpp @@ -261,11 +261,11 @@ void WebContentClient::did_request_media_context_menu(u64 page_id, Gfx::IntPoint } } -void WebContentClient::did_get_source(u64 page_id, URL::URL const& url, ByteString const& source) +void WebContentClient::did_get_source(u64 page_id, URL::URL const& url, URL::URL const& base_url, String const& source) { if (auto view = view_for_page_id(page_id); view.has_value()) { if (view->on_received_source) - view->on_received_source(url, source); + view->on_received_source(url, base_url, source); } } @@ -720,11 +720,11 @@ void WebContentClient::inspector_did_request_style_sheet_source(u64 page_id, Web } } -void WebContentClient::did_request_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier const& identifier, String const& source) +void WebContentClient::did_get_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier const& identifier, URL::URL const& base_url, String const& source) { if (auto view = view_for_page_id(page_id); view.has_value()) { if (view->on_received_style_sheet_source) - view->on_received_style_sheet_source(identifier, source); + view->on_received_style_sheet_source(identifier, base_url, source); } } diff --git a/Userland/Libraries/LibWebView/WebContentClient.h b/Userland/Libraries/LibWebView/WebContentClient.h index 4b9d84e2f89a..1ed84612ecf4 100644 --- a/Userland/Libraries/LibWebView/WebContentClient.h +++ b/Userland/Libraries/LibWebView/WebContentClient.h @@ -70,7 +70,7 @@ class WebContentClient final virtual void did_request_link_context_menu(u64 page_id, Gfx::IntPoint, URL::URL const&, ByteString const&, unsigned) override; virtual void did_request_image_context_menu(u64 page_id, Gfx::IntPoint, URL::URL const&, ByteString const&, unsigned, Gfx::ShareableBitmap const&) override; virtual void did_request_media_context_menu(u64 page_id, Gfx::IntPoint, ByteString const&, unsigned, Web::Page::MediaContextMenu const&) override; - virtual void did_get_source(u64 page_id, URL::URL const&, ByteString const&) override; + virtual void did_get_source(u64 page_id, URL::URL const&, URL::URL const&, String const&) override; virtual void did_inspect_dom_tree(u64 page_id, ByteString const&) override; virtual void did_inspect_dom_node(u64 page_id, bool has_style, ByteString const& computed_style, ByteString const& resolved_style, ByteString const& custom_properties, ByteString const& node_box_sizing, ByteString const& aria_properties_state, ByteString const& fonts) override; virtual void did_inspect_accessibility_tree(u64 page_id, ByteString const&) override; @@ -129,7 +129,7 @@ class WebContentClient final virtual Messages::WebContentClient::RequestWorkerAgentResponse request_worker_agent(u64 page_id) override; virtual void inspector_did_list_style_sheets(u64 page_id, Vector<Web::CSS::StyleSheetIdentifier> const& stylesheets) override; virtual void inspector_did_request_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier const& identifier) override; - virtual void did_request_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier const& identifier, String const& source) override; + virtual void did_get_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier const& identifier, URL::URL const&, String const& source) override; Optional<ViewImplementation&> view_for_page_id(u64, SourceLocation = SourceLocation::current()); diff --git a/Userland/Services/WebContent/ConnectionFromClient.cpp b/Userland/Services/WebContent/ConnectionFromClient.cpp index 061e94de0d88..c16725b6a5a9 100644 --- a/Userland/Services/WebContent/ConnectionFromClient.cpp +++ b/Userland/Services/WebContent/ConnectionFromClient.cpp @@ -432,7 +432,7 @@ void ConnectionFromClient::get_source(u64 page_id) { if (auto page = this->page(page_id); page.has_value()) { if (auto* doc = page->page().top_level_browsing_context().active_document()) - async_did_get_source(page_id, doc->url(), doc->source().to_byte_string()); + async_did_get_source(page_id, doc->url(), doc->base_url(), doc->source()); } } @@ -644,9 +644,8 @@ void ConnectionFromClient::request_style_sheet_source(u64 page_id, Web::CSS::Sty return; if (auto* document = page->page().top_level_browsing_context().active_document()) { - auto stylesheet = document->get_style_sheet_source(identifier); - if (stylesheet.has_value()) - async_did_request_style_sheet_source(page_id, identifier, stylesheet.value()); + if (auto stylesheet = document->get_style_sheet_source(identifier); stylesheet.has_value()) + async_did_get_style_sheet_source(page_id, identifier, document->base_url(), stylesheet.value()); } } diff --git a/Userland/Services/WebContent/WebContentClient.ipc b/Userland/Services/WebContent/WebContentClient.ipc index 94b346ccac1a..2fafcb84d165 100644 --- a/Userland/Services/WebContent/WebContentClient.ipc +++ b/Userland/Services/WebContent/WebContentClient.ipc @@ -48,7 +48,7 @@ endpoint WebContentClient did_request_set_prompt_text(u64 page_id, String message) =| did_request_accept_dialog(u64 page_id) =| did_request_dismiss_dialog(u64 page_id) =| - did_get_source(u64 page_id, URL::URL url, ByteString source) =| + did_get_source(u64 page_id, URL::URL url, URL::URL base_url, String source) =| did_inspect_dom_tree(u64 page_id, ByteString dom_tree) =| did_inspect_dom_node(u64 page_id, bool has_style, ByteString computed_style, ByteString resolved_style, ByteString custom_properties, ByteString node_box_sizing, ByteString aria_properties_state, ByteString fonts) =| @@ -59,7 +59,7 @@ endpoint WebContentClient inspector_did_list_style_sheets(u64 page_id, Vector<Web::CSS::StyleSheetIdentifier> style_sheets) =| inspector_did_request_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier identifier) =| - did_request_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier identifier, String source) =| + did_get_style_sheet_source(u64 page_id, Web::CSS::StyleSheetIdentifier identifier, URL::URL base_url, String source) =| did_take_screenshot(u64 page_id, Gfx::ShareableBitmap screenshot) =|
8bc3f4c18611c2190d393fc59f008823f002e579
2022-03-21 23:44:50
Andreas Kling
libweb: Fix logic mistakes in Range stringification
false
Fix logic mistakes in Range stringification
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Range.cpp b/Userland/Libraries/LibWeb/DOM/Range.cpp index e30fee657376..5b2b9bb61666 100644 --- a/Userland/Libraries/LibWeb/DOM/Range.cpp +++ b/Userland/Libraries/LibWeb/DOM/Range.cpp @@ -510,15 +510,15 @@ String Range::to_string() const // 2. If this’s start node is this’s end node and it is a Text node, // then return the substring of that Text node’s data beginning at this’s start offset and ending at this’s end offset. if (start_container() == end_container() && is<Text>(*start_container())) - return static_cast<Text const&>(*start_container()).data().substring(start_offset(), end_offset()); + return static_cast<Text const&>(*start_container()).data().substring(start_offset(), end_offset() - start_offset()); // 3. If this’s start node is a Text node, then append the substring of that node’s data from this’s start offset until the end to s. if (is<Text>(*start_container())) builder.append(static_cast<Text const&>(*start_container()).data().substring_view(start_offset())); // 4. Append the concatenation of the data of all Text nodes that are contained in this, in tree order, to s. - for (Node const* node = start_container()->next_in_pre_order(); node && node != end_container(); node = node->next_in_pre_order()) { - if (is<Text>(*node)) + for (Node const* node = start_container(); node != end_container()->next_sibling(); node = node->next_in_pre_order()) { + if (is<Text>(*node) && contains_node(*node)) builder.append(static_cast<Text const&>(*node).data()); }
68ef7dba70e39dd48f6c88d7f23d03064f161bc5
2023-08-04 14:35:55
Karol Kosek
libweb: Add support for encoding Canvas to JPEG
false
Add support for encoding Canvas to JPEG
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp index d5277ccff81d..0a5502f00208 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp @@ -6,7 +6,9 @@ #include <AK/Base64.h> #include <AK/Checked.h> +#include <AK/MemoryStream.h> #include <LibGfx/Bitmap.h> +#include <LibGfx/ImageFormats/JPEGWriter.h> #include <LibGfx/ImageFormats/PNGWriter.h> #include <LibWeb/Bindings/ExceptionOrUtils.h> #include <LibWeb/CSS/StyleComputer.h> @@ -189,8 +191,23 @@ struct SerializeBitmapResult { }; // https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file -static ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, [[maybe_unused]] StringView type, [[maybe_unused]] Optional<double> quality) +static ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, StringView type, Optional<double> quality) { + // If type is an image format that supports variable quality (such as "image/jpeg"), quality is given, and type is not "image/png", then, + // if Type(quality) is Number, and quality is in the range 0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level. + // Otherwise, the user agent must use its default quality value, as if the quality argument had not been given. + if (quality.has_value() && !(*quality >= 0.0 && *quality <= 1.0)) + quality = OptionalNone {}; + + if (type.equals_ignoring_ascii_case("image/jpeg"sv)) { + AllocatingMemoryStream file; + Gfx::JPEGWriter::Options jpeg_options; + if (quality.has_value()) + jpeg_options.quality = static_cast<int>(quality.value() * 100); + TRY(Gfx::JPEGWriter::encode(file, bitmap, jpeg_options)); + return SerializeBitmapResult { TRY(file.read_until_eof()), "image/jpeg"sv }; + } + // User agents must support PNG ("image/png"). User agents may support other types. // If the user agent does not support the requested type, then it must create the file using the PNG format. [PNG] return SerializeBitmapResult { TRY(Gfx::PNGWriter::encode(bitmap)), "image/png"sv };
d775dea13cf414f7ad8f7c2c22ace68445ae4adb
2020-11-14 14:39:03
Nico Weber
lagom: Add a gemini fuzzer
false
Add a gemini fuzzer
lagom
diff --git a/Meta/Lagom/Fuzzers/CMakeLists.txt b/Meta/Lagom/Fuzzers/CMakeLists.txt index a974296c6f67..4879f5ef9707 100644 --- a/Meta/Lagom/Fuzzers/CMakeLists.txt +++ b/Meta/Lagom/Fuzzers/CMakeLists.txt @@ -16,6 +16,15 @@ target_link_libraries(FuzzELF PRIVATE $<$<C_COMPILER_ID:Clang>:-fsanitize=fuzzer> ) +add_executable(FuzzGemini FuzzGemini.cpp) +target_compile_options(FuzzGemini + PRIVATE $<$<C_COMPILER_ID:Clang>:-g -O1 -fsanitize=fuzzer> + ) +target_link_libraries(FuzzGemini + PUBLIC Lagom + PRIVATE $<$<C_COMPILER_ID:Clang>:-fsanitize=fuzzer> + ) + add_executable(FuzzJs FuzzJs.cpp) target_compile_options(FuzzJs PRIVATE $<$<C_COMPILER_ID:Clang>:-g -O1 -fsanitize=fuzzer> diff --git a/Meta/Lagom/Fuzzers/FuzzGemini.cpp b/Meta/Lagom/Fuzzers/FuzzGemini.cpp new file mode 100644 index 000000000000..0d0a4b29e828 --- /dev/null +++ b/Meta/Lagom/Fuzzers/FuzzGemini.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020, the SerenityOS developers. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <AK/StringView.h> +#include <AK/URL.h> +#include <LibGemini/Document.h> +#include <stddef.h> +#include <stdint.h> + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + auto gemini = AK::StringView(static_cast<const unsigned char*>(data), size); + Gemini::Document::parse(gemini, {}); + return 0; +}
47a4737110743f21e97ef03c2db3828692ef5c22
2021-12-20 08:09:26
Stephan Unverwerth
libgl: Fix texture sampling texel coordinate calculation
false
Fix texture sampling texel coordinate calculation
libgl
diff --git a/Userland/Libraries/LibGL/Tex/Sampler2D.cpp b/Userland/Libraries/LibGL/Tex/Sampler2D.cpp index 8a167d78c6e0..579285f29a50 100644 --- a/Userland/Libraries/LibGL/Tex/Sampler2D.cpp +++ b/Userland/Libraries/LibGL/Tex/Sampler2D.cpp @@ -16,33 +16,34 @@ static constexpr float wrap_repeat(float value) return value - floorf(value); } -static constexpr float wrap_mirrored_repeat(float value) +static constexpr float wrap_clamp_to_edge(float value, int num_texels) { - float integer = floorf(value); - float frac = value - integer; - bool iseven = fmodf(integer, 2.0f) == 0.0f; - return iseven ? frac : 1 - frac; + float const clamp_limit = 1.f / (2 * num_texels); + return clamp(value, clamp_limit, 1.0f - clamp_limit); } -static constexpr float wrap_clamp(float value) +static constexpr float wrap_mirrored_repeat(float value, int num_texels) { - return clamp(value, 0.0f, 1.0f); + float integer = floorf(value); + float frac = value - integer; + bool iseven = fmodf(integer, 2.0f) == 0.0f; + return wrap_clamp_to_edge(iseven ? frac : 1 - frac, num_texels); } -static constexpr float wrap(float value, GLint mode) +static constexpr float wrap(float value, GLint mode, int num_texels) { switch (mode) { case GL_REPEAT: return wrap_repeat(value); - // FIXME: These clamp modes actually have slightly different behavior + // FIXME: These clamp modes actually have slightly different behavior. Currently we use GL_CLAMP_TO_EDGE for all of them. case GL_CLAMP: case GL_CLAMP_TO_BORDER: case GL_CLAMP_TO_EDGE: - return wrap_clamp(value); + return wrap_clamp_to_edge(value, num_texels); case GL_MIRRORED_REPEAT: - return wrap_mirrored_repeat(value); + return wrap_mirrored_repeat(value, num_texels); default: VERIFY_NOT_REACHED(); @@ -59,11 +60,11 @@ FloatVector4 Sampler2D::sample(FloatVector2 const& uv) const if (mip.width() < 1 || mip.height() < 1) return { 1, 1, 1, 1 }; - float x = wrap(uv.x(), m_wrap_t_mode); - float y = wrap(uv.y(), m_wrap_s_mode); + float x = wrap(uv.x(), m_wrap_s_mode, mip.width()); + float y = wrap(uv.y(), m_wrap_t_mode, mip.height()); - x *= mip.width() - 1; - y *= mip.height() - 1; + x *= mip.width(); + y *= mip.height(); // Sampling implemented according to https://www.khronos.org/registry/OpenGL/specs/gl/glspec121.pdf Chapter 3.8 if (m_mag_filter == GL_NEAREST) {
9793d69d4ffbd9b6d430e08fb2fd86338a065a2d
2023-12-16 02:34:46
Andreas Kling
libweb: Make HTML::Window::page() return a Page&
false
Make HTML::Window::page() return a Page&
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp b/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp index 29f6a2b288cc..f5800d765715 100644 --- a/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp +++ b/Userland/Libraries/LibWeb/CSS/MediaQuery.cpp @@ -165,7 +165,7 @@ bool MediaFeature::compare(HTML::Window const& window, MediaFeatureValue left, C left_px = left.length().absolute_length_to_px(); right_px = right.length().absolute_length_to_px(); } else { - auto viewport_rect = window.page()->web_exposed_screen_area(); + auto viewport_rect = window.page().web_exposed_screen_area(); auto const& initial_font = window.associated_document().style_computer().initial_font(); Gfx::FontPixelMetrics const& initial_font_metrics = initial_font.pixel_metrics(); diff --git a/Userland/Libraries/LibWeb/CSS/Screen.cpp b/Userland/Libraries/LibWeb/CSS/Screen.cpp index 0bc24353674c..8f8d3f4814d1 100644 --- a/Userland/Libraries/LibWeb/CSS/Screen.cpp +++ b/Userland/Libraries/LibWeb/CSS/Screen.cpp @@ -40,7 +40,7 @@ void Screen::visit_edges(Cell::Visitor& visitor) Gfx::IntRect Screen::screen_rect() const { - auto screen_rect_in_css_pixels = window().page()->web_exposed_screen_area(); + auto screen_rect_in_css_pixels = window().page().web_exposed_screen_area(); return { screen_rect_in_css_pixels.x().to_int(), screen_rect_in_css_pixels.y().to_int(), diff --git a/Userland/Libraries/LibWeb/Clipboard/Clipboard.cpp b/Userland/Libraries/LibWeb/Clipboard/Clipboard.cpp index de8cc4e819ae..55da3cb9a439 100644 --- a/Userland/Libraries/LibWeb/Clipboard/Clipboard.cpp +++ b/Userland/Libraries/LibWeb/Clipboard/Clipboard.cpp @@ -113,8 +113,7 @@ static void write_blobs_and_option_to_clipboard(JS::Realm& realm, ReadonlySpan<J auto payload = MUST(TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, item->bytes())); // 4. Insert payload and presentationStyle into the system clipboard using formatString as the native clipboard format. - if (auto* page = window.page()) - page->client().page_did_insert_clipboard_entry(move(payload), move(presentation_style), move(format_string)); + window.page().client().page_did_insert_clipboard_entry(move(payload), move(presentation_style), move(format_string)); } // FIXME: 3. Write web custom formats given webCustomFormats. diff --git a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp index 6decedc4a67b..1628f6666bad 100644 --- a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp @@ -1722,19 +1722,13 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> nonstandard_resource_load auto request = fetch_params.request(); - Page* page = nullptr; - auto& global_object = realm.global_object(); - if (is<HTML::Window>(global_object)) - page = static_cast<HTML::Window&>(global_object).page(); - else if (is<HTML::WorkerGlobalScope>(global_object)) - page = static_cast<HTML::WorkerGlobalScope&>(global_object).page(); + auto& page = Bindings::host_defined_page(realm); // NOTE: Using LoadRequest::create_for_url_on_page here will unconditionally add cookies as long as there's a page available. // However, it is up to http_network_or_cache_fetch to determine if cookies should be added to the request. LoadRequest load_request; load_request.set_url(request->current_url()); - if (page) - load_request.set_page(*page); + load_request.set_page(page); load_request.set_method(DeprecatedString::copy(request->method())); for (auto const& header : *request->header_list()) load_request.set_header(DeprecatedString::copy(header.name), DeprecatedString::copy(header.value)); diff --git a/Userland/Libraries/LibWeb/HTML/MimeTypeArray.cpp b/Userland/Libraries/LibWeb/HTML/MimeTypeArray.cpp index d99b9442d6a7..c76a1b8f18f4 100644 --- a/Userland/Libraries/LibWeb/HTML/MimeTypeArray.cpp +++ b/Userland/Libraries/LibWeb/HTML/MimeTypeArray.cpp @@ -32,8 +32,7 @@ Vector<String> MimeTypeArray::supported_property_names() const { // The MimeTypeArray interface supports named properties. If the user agent's PDF viewer supported is true, then they are the PDF viewer mime types. Otherwise, they are the empty list. auto const& window = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)); - VERIFY(window.page()); - if (!window.page()->pdf_viewer_supported()) + if (!window.page().pdf_viewer_supported()) return {}; // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-types diff --git a/Userland/Libraries/LibWeb/HTML/Navigator.cpp b/Userland/Libraries/LibWeb/HTML/Navigator.cpp index 701007f96cb6..d60a919f4431 100644 --- a/Userland/Libraries/LibWeb/HTML/Navigator.cpp +++ b/Userland/Libraries/LibWeb/HTML/Navigator.cpp @@ -42,7 +42,7 @@ bool Navigator::pdf_viewer_enabled() const // The NavigatorPlugins mixin's pdfViewerEnabled getter steps are to return the user agent's PDF viewer supported. // NOTE: The NavigatorPlugins mixin should only be exposed on the Window object. auto const& window = verify_cast<HTML::Window>(HTML::current_global_object()); - return window.page()->pdf_viewer_supported(); + return window.page().pdf_viewer_supported(); } // https://w3c.github.io/webdriver/#dfn-webdriver @@ -52,7 +52,7 @@ bool Navigator::webdriver() const // NOTE: The NavigatorAutomationInformation interface should not be exposed on WorkerNavigator. auto const& window = verify_cast<HTML::Window>(HTML::current_global_object()); - return window.page()->is_webdriver_active(); + return window.page().is_webdriver_active(); } void Navigator::visit_edges(Cell::Visitor& visitor) diff --git a/Userland/Libraries/LibWeb/HTML/Plugin.cpp b/Userland/Libraries/LibWeb/HTML/Plugin.cpp index b2187f1711fb..5d459965e096 100644 --- a/Userland/Libraries/LibWeb/HTML/Plugin.cpp +++ b/Userland/Libraries/LibWeb/HTML/Plugin.cpp @@ -56,8 +56,7 @@ Vector<String> Plugin::supported_property_names() const { // The Plugin interface supports named properties. If the user agent's PDF viewer supported is true, then they are the PDF viewer mime types. Otherwise, they are the empty list. auto const& window = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)); - VERIFY(window.page()); - if (!window.page()->pdf_viewer_supported()) + if (!window.page().pdf_viewer_supported()) return {}; // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-types diff --git a/Userland/Libraries/LibWeb/HTML/PluginArray.cpp b/Userland/Libraries/LibWeb/HTML/PluginArray.cpp index cb5e03636107..fd086a7bc113 100644 --- a/Userland/Libraries/LibWeb/HTML/PluginArray.cpp +++ b/Userland/Libraries/LibWeb/HTML/PluginArray.cpp @@ -38,8 +38,7 @@ Vector<String> PluginArray::supported_property_names() const { // The PluginArray interface supports named properties. If the user agent's PDF viewer supported is true, then they are the PDF viewer plugin names. Otherwise, they are the empty list. auto const& window = verify_cast<HTML::Window>(HTML::relevant_global_object(*this)); - VERIFY(window.page()); - if (!window.page()->pdf_viewer_supported()) + if (!window.page().pdf_viewer_supported()) return {}; // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-names diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index f7523f6bab37..9cc191ad9b1b 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -427,14 +427,14 @@ bool Window::dispatch_event(DOM::Event& event) return DOM::EventDispatcher::dispatch(*this, event, true); } -Page* Window::page() +Page& Window::page() { - return &associated_document().page(); + return associated_document().page(); } -Page const* Window::page() const +Page const& Window::page() const { - return &associated_document().page(); + return associated_document().page(); } Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const @@ -457,15 +457,9 @@ Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID return CSS::MediaFeatureValue(0); // FIXME: device-aspect-ratio case CSS::MediaFeatureID::DeviceHeight: - if (auto* page = this->page()) { - return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().height())); - } - return CSS::MediaFeatureValue(0); + return CSS::MediaFeatureValue(CSS::Length::make_px(page().web_exposed_screen_area().height())); case CSS::MediaFeatureID::DeviceWidth: - if (auto* page = this->page()) { - return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().width())); - } - return CSS::MediaFeatureValue(0); + return CSS::MediaFeatureValue(CSS::Length::make_px(page().web_exposed_screen_area().width())); case CSS::MediaFeatureID::DisplayMode: // FIXME: Detect if window is fullscreen return CSS::MediaFeatureValue(CSS::ValueID::Browser); @@ -498,18 +492,15 @@ Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID case CSS::MediaFeatureID::Pointer: return CSS::MediaFeatureValue(CSS::ValueID::Fine); case CSS::MediaFeatureID::PrefersColorScheme: { - if (auto* page = this->page()) { - switch (page->preferred_color_scheme()) { - case CSS::PreferredColorScheme::Light: - return CSS::MediaFeatureValue(CSS::ValueID::Light); - case CSS::PreferredColorScheme::Dark: - return CSS::MediaFeatureValue(CSS::ValueID::Dark); - case CSS::PreferredColorScheme::Auto: - default: - return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light); - } + switch (page().preferred_color_scheme()) { + case CSS::PreferredColorScheme::Light: + return CSS::MediaFeatureValue(CSS::ValueID::Light); + case CSS::PreferredColorScheme::Dark: + return CSS::MediaFeatureValue(CSS::ValueID::Dark); + case CSS::PreferredColorScheme::Auto: + default: + return CSS::MediaFeatureValue(page().palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light); } - return CSS::MediaFeatureValue(CSS::ValueID::Light); } case CSS::MediaFeatureID::PrefersContrast: // FIXME: Make this a preference @@ -701,8 +692,7 @@ Vector<JS::NonnullGCPtr<Plugin>> Window::pdf_viewer_plugin_objects() // 3. "Microsoft Edge PDF Viewer" // 4. "WebKit built-in PDF" // The values of the above list form the PDF viewer plugin names list. https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-names - VERIFY(page()); - if (!page()->pdf_viewer_supported()) + if (!page().pdf_viewer_supported()) return {}; if (m_pdf_viewer_plugin_objects.is_empty()) { @@ -725,8 +715,7 @@ Vector<JS::NonnullGCPtr<MimeType>> Window::pdf_viewer_mime_type_objects() // 0. "application/pdf" // 1. "text/pdf" // The values of the above list form the PDF viewer mime types list. https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-types - VERIFY(page()); - if (!page()->pdf_viewer_supported()) + if (!page().pdf_viewer_supported()) return {}; if (m_pdf_viewer_mime_type_objects.is_empty()) { @@ -1010,8 +999,7 @@ void Window::alert(String const& message) // for historical reasons. The practical impact of this is that alert(undefined) is // treated as alert("undefined"), but alert() is treated as alert(""). // FIXME: Make this fully spec compliant. - if (auto* page = this->page()) - page->did_request_alert(message); + page().did_request_alert(message); } // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm @@ -1019,18 +1007,14 @@ bool Window::confirm(Optional<String> const& message) { // FIXME: Make this fully spec compliant. // NOTE: `message` has an IDL-provided default value and is never empty. - if (auto* page = this->page()) - return page->did_request_confirm(*message); - return false; + return page().did_request_confirm(*message); } // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_) { // FIXME: Make this fully spec compliant. - if (auto* page = this->page()) - return page->did_request_prompt(*message, *default_); - return {}; + return page().did_request_prompt(*message, *default_); } // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps @@ -1222,9 +1206,7 @@ double Window::scroll_x() const { // The scrollX attribute must return the x-coordinate, relative to the initial containing block origin, // of the left of the viewport, or zero if there is no viewport. - if (auto* page = this->page()) - return page->top_level_traversable()->viewport_scroll_offset().x().to_double(); - return 0; + return page().top_level_traversable()->viewport_scroll_offset().x().to_double(); } // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrolly @@ -1232,9 +1214,7 @@ double Window::scroll_y() const { // The scrollY attribute must return the y-coordinate, relative to the initial containing block origin, // of the top of the viewport, or zero if there is no viewport. - if (auto* page = this->page()) - return page->top_level_traversable()->viewport_scroll_offset().y().to_double(); - return 0; + return page().top_level_traversable()->viewport_scroll_offset().y().to_double(); } // https://w3c.github.io/csswg-drafts/cssom-view/#perform-a-scroll @@ -1256,10 +1236,7 @@ static void perform_a_scroll(Page& page, double x, double y, JS::GCPtr<DOM::Node void Window::scroll(ScrollToOptions const& options) { // 4. If there is no viewport, abort these steps. - auto* page = this->page(); - if (!page) - return; - auto top_level_traversable = page->top_level_traversable(); + auto top_level_traversable = page().top_level_traversable(); // 1. If invoked with one argument, follow these substeps: @@ -1312,7 +1289,7 @@ void Window::scroll(ScrollToOptions const& options) // 12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is // one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options. auto element = JS::GCPtr<DOM::Node const> { document ? &document->root() : nullptr }; - perform_a_scroll(*page, x, y, element, options.behavior); + perform_a_scroll(page(), x, y, element, options.behavior); } // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll @@ -1374,9 +1351,7 @@ i32 Window::screen_x() const { // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed // screen area, of the left of the client window as number of CSS pixels, or zero if there is no such thing. - if (auto* page = this->page()) - return page->window_position().x().value(); - return 0; + return page().window_position().x().value(); } // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screeny @@ -1384,9 +1359,7 @@ i32 Window::screen_y() const { // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the // Web-exposed screen area, of the top of the client window as number of CSS pixels, or zero if there is no such thing. - if (auto* page = this->page()) - return page->window_position().y().value(); - return 0; + return page().window_position().y().value(); } // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerwidth @@ -1394,9 +1367,7 @@ i32 Window::outer_width() const { // The outerWidth attribute must return the width of the client window. If there is no client window this // attribute must return zero. - if (auto* page = this->page()) - return page->window_size().width().value(); - return 0; + return page().window_size().width().value(); } // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerheight @@ -1404,9 +1375,7 @@ i32 Window::outer_height() const { // The outerHeight attribute must return the height of the client window. If there is no client window this // attribute must return zero. - if (auto* page = this->page()) - return page->window_size().height().value(); - return 0; + return page().window_size().height().value(); } // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-devicepixelratio @@ -1416,9 +1385,7 @@ double Window::device_pixel_ratio() const // 2. Let CSS pixel size be the size of a CSS pixel at the current page zoom and using a scale factor of 1.0. // 3. Let device pixel size be the vertical size of a device pixel of the output device. // 4. Return the result of dividing CSS pixel size by device pixel size. - if (auto* page = this->page()) - return page->client().device_pixels_per_css_pixel(); - return 1; + return page().client().device_pixels_per_css_pixel(); } // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-animationframeprovider-requestanimationframe diff --git a/Userland/Libraries/LibWeb/HTML/Window.h b/Userland/Libraries/LibWeb/HTML/Window.h index d568643f0efa..2358c2bf30c9 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.h +++ b/Userland/Libraries/LibWeb/HTML/Window.h @@ -77,8 +77,8 @@ class Window final // ^JS::Object virtual JS::ThrowCompletionOr<bool> internal_set_prototype_of(JS::Object* prototype) override; - Page* page(); - Page const* page() const; + Page& page(); + Page const& page() const; // https://html.spec.whatwg.org/multipage/window-object.html#concept-document-window DOM::Document const& associated_document() const { return *m_associated_document; }
3f13959c68b6e0a632bcea20b2015c9aaaadfa5d
2022-10-17 19:25:55
Andrew Kaster
kernel: Mark Version.h as a dependency of Kernel rather than ALL
false
Mark Version.h as a dependency of Kernel rather than ALL
kernel
diff --git a/Kernel/CMakeLists.txt b/Kernel/CMakeLists.txt index 1b575db4a58c..d16a9a33d0fd 100644 --- a/Kernel/CMakeLists.txt +++ b/Kernel/CMakeLists.txt @@ -422,7 +422,7 @@ add_custom_command( OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/Version.h" VERBATIM ) -add_custom_target(generate_version_header ALL DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/Version.h") +add_custom_target(generate_version_header DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/Version.h") set(GENERATED_SOURCES "${CMAKE_CURRENT_BINARY_DIR}/Version.h") generate_state_machine(../Userland/Libraries/LibVT/StateMachine.txt ../Userland/Libraries/LibVT/EscapeSequenceStateMachine.h) @@ -670,7 +670,7 @@ add_link_options(LINKER:-z,notext) add_library(kernel_heap STATIC ${KERNEL_HEAP_SOURCES}) add_executable(Kernel ${SOURCES}) -add_dependencies(Kernel generate_EscapeSequenceStateMachine.h) +add_dependencies(Kernel generate_EscapeSequenceStateMachine.h generate_version_header) if (NOT "${SERENITY_ARCH}" STREQUAL "aarch64") add_custom_command(
cf2c04eb1356024ed5b63dbc3ff3c2d22bf6cdb1
2021-09-05 21:45:05
Andreas Kling
kernel: Use TRY() in sys$dbgputstr()
false
Use TRY() in sys$dbgputstr()
kernel
diff --git a/Kernel/Syscalls/debug.cpp b/Kernel/Syscalls/debug.cpp index 815648658904..f5d65de3cd3d 100644 --- a/Kernel/Syscalls/debug.cpp +++ b/Kernel/Syscalls/debug.cpp @@ -38,10 +38,7 @@ KResultOr<FlatPtr> Process::sys$dbgputstr(Userspace<const char*> characters, siz return size; } - auto result = try_copy_kstring_from_user(characters, size); - if (result.is_error()) - return result.error(); - auto string = result.release_value(); + auto string = TRY(try_copy_kstring_from_user(characters, size)); dbgputstr(string->view()); return string->length(); }
1fc7d65aadedb8ec421e788d07e6c00ee023c06b
2021-01-10 01:42:31
Tom
ak: Add static Singleton::get function to allow destructible globals
false
Add static Singleton::get function to allow destructible globals
ak
diff --git a/AK/Singleton.h b/AK/Singleton.h index da1305e1c583..615171b85584 100644 --- a/AK/Singleton.h +++ b/AK/Singleton.h @@ -56,36 +56,46 @@ class Singleton { public: Singleton() = default; - T* ptr() const + template<bool allow_create = true> + static T* get(T*& obj_var) { - T* obj = AK::atomic_load(&m_obj, AK::memory_order_consume); + T* obj = AK::atomic_load(&obj_var, AK::memory_order_acquire); if (FlatPtr(obj) <= 0x1) { // If this is the first time, see if we get to initialize it #ifdef KERNEL Kernel::ScopedCritical critical; #endif - if (obj == nullptr && AK::atomic_compare_exchange_strong(&m_obj, obj, (T*)0x1, AK::memory_order_acq_rel)) { - // We're the first one - obj = InitFunction(); - AK::atomic_store(&m_obj, obj, AK::memory_order_release); - } else { - // Someone else was faster, wait until they're done - while (obj == (T*)0x1) { + if constexpr (allow_create) { + if (obj == nullptr && AK::atomic_compare_exchange_strong(&obj_var, obj, (T*)0x1, AK::memory_order_acq_rel)) { + // We're the first one + obj = InitFunction(); + AK::atomic_store(&obj_var, obj, AK::memory_order_release); + return obj; + } + } + // Someone else was faster, wait until they're done + while (obj == (T*)0x1) { #ifdef KERNEL - Kernel::Processor::wait_check(); + Kernel::Processor::wait_check(); #else - // TODO: yield + // TODO: yield #endif - obj = AK::atomic_load(&m_obj, AK::memory_order_consume); - } + obj = AK::atomic_load(&obj_var, AK::memory_order_acquire); + } + if constexpr (allow_create) { + // We should always return an instance if we allow creating one + ASSERT(obj != nullptr); } - // We should always return an instance - ASSERT(obj != nullptr); ASSERT(obj != (T*)0x1); } return obj; } + T* ptr() const + { + return get(m_obj); + } + T* operator->() const { return ptr();
c3018f8beba19fa44967578099e1c3d1732ce830
2023-01-06 16:32:20
Andreas Kling
libvt: Simplify TerminalWidget::widget_size_for_font()
false
Simplify TerminalWidget::widget_size_for_font()
libvt
diff --git a/Userland/Libraries/LibVT/TerminalWidget.cpp b/Userland/Libraries/LibVT/TerminalWidget.cpp index 77cafad7c80c..774f3022761c 100644 --- a/Userland/Libraries/LibVT/TerminalWidget.cpp +++ b/Userland/Libraries/LibVT/TerminalWidget.cpp @@ -1247,9 +1247,10 @@ Gfx::IntSize TerminalWidget::widget_size_for_font(Gfx::Font const& font) const int cell_height = 0; int line_spacing = 0; collect_font_metrics(font, column_width, cell_height, line_height, line_spacing); + auto base_size = compute_base_size(); return { - (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.columns() * column_width) + m_scrollbar->width(), - (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.rows() * line_height) + base_size.width() + (m_terminal.columns() * column_width), + base_size.height() + (m_terminal.rows() * line_height), }; }
dd82a026f89e41403e478ba372d9b16c2392d6cf
2022-11-26 03:14:47
Julian Offenhäuser
libpdf: Pass PDFFont::draw_glyph() a char code instead of a code point
false
Pass PDFFont::draw_glyph() a char code instead of a code point
libpdf
diff --git a/Userland/Libraries/LibPDF/Fonts/PDFFont.h b/Userland/Libraries/LibPDF/Fonts/PDFFont.h index fb732addf237..22ba6595b951 100644 --- a/Userland/Libraries/LibPDF/Fonts/PDFFont.h +++ b/Userland/Libraries/LibPDF/Fonts/PDFFont.h @@ -26,7 +26,7 @@ class PDFFont : public RefCounted<PDFFont> { virtual u32 char_code_to_code_point(u16 char_code) const = 0; virtual float get_char_width(u16 char_code, float font_size) const = 0; - virtual void draw_glyph(Gfx::Painter& painter, Gfx::IntPoint const& point, float width, u32 code_point, Color color) = 0; + virtual void draw_glyph(Gfx::Painter& painter, Gfx::IntPoint const& point, float width, u32 char_code, Color color) = 0; virtual bool is_standard_font() const { return m_is_standard_font; } virtual Type type() const = 0; diff --git a/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp b/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp index cb266f44fe24..b91158e4ccf6 100644 --- a/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp +++ b/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.cpp @@ -67,9 +67,9 @@ PDFErrorOr<void> PS1FontProgram::parse(ReadonlyBytes const& bytes, size_t cleart if (word == "readonly") { break; } else if (word == "dup") { - u32 code_point = TRY(parse_int(reader)); + u32 char_code = TRY(parse_int(reader)); auto name = TRY(parse_word(reader)); - descriptors.set(code_point, { name.starts_with('/') ? name.substring_view(1) : name.view(), code_point }); + descriptors.set(char_code, { name.starts_with('/') ? name.substring_view(1) : name.view(), char_code }); } } m_encoding = TRY(Encoding::create(descriptors)); @@ -87,9 +87,9 @@ PDFErrorOr<void> PS1FontProgram::parse(ReadonlyBytes const& bytes, size_t cleart return parse_encrypted_portion(decrypted); } -RefPtr<Gfx::Bitmap> PS1FontProgram::rasterize_glyph(u32 code_point, float width) +RefPtr<Gfx::Bitmap> PS1FontProgram::rasterize_glyph(u32 char_code, float width) { - auto path = build_char(code_point, width); + auto path = build_char(char_code, width); auto bounding_box = path.bounding_box().size(); u32 w = (u32)ceilf(bounding_box.width()) + 1; @@ -100,9 +100,9 @@ RefPtr<Gfx::Bitmap> PS1FontProgram::rasterize_glyph(u32 code_point, float width) return rasterizer.accumulate(); } -Gfx::Path PS1FontProgram::build_char(u32 code_point, float width) +Gfx::Path PS1FontProgram::build_char(u32 char_code, float width) { - auto maybe_glyph = m_glyph_map.get(code_point); + auto maybe_glyph = m_glyph_map.get(char_code); if (!maybe_glyph.has_value()) return {}; @@ -117,9 +117,9 @@ Gfx::Path PS1FontProgram::build_char(u32 code_point, float width) return glyph.path.copy_transformed(transform); } -Gfx::FloatPoint PS1FontProgram::glyph_translation(u32 code_point, float width) const +Gfx::FloatPoint PS1FontProgram::glyph_translation(u32 char_code, float width) const { - auto maybe_glyph = m_glyph_map.get(code_point); + auto maybe_glyph = m_glyph_map.get(char_code); if (!maybe_glyph.has_value()) return {}; @@ -477,9 +477,9 @@ PDFErrorOr<void> PS1FontProgram::parse_encrypted_portion(ByteBuffer const& buffe auto line = TRY(decrypt(reader.bytes().slice(reader.offset(), encrypted_size), m_encryption_key, m_lenIV)); reader.move_by(encrypted_size); auto name_mapping = m_encoding->name_mapping(); - auto code_point = name_mapping.ensure(word.substring_view(1)); + auto char_code = name_mapping.ensure(word.substring_view(1)); GlyphParserState state; - m_glyph_map.set(code_point, TRY(parse_glyph(line, state))); + m_glyph_map.set(char_code, TRY(parse_glyph(line, state))); } } } diff --git a/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.h b/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.h index 0a8afa733de5..91291473fa9c 100644 --- a/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.h +++ b/Userland/Libraries/LibPDF/Fonts/PS1FontProgram.h @@ -20,11 +20,11 @@ class PS1FontProgram : public RefCounted<PS1FontProgram> { public: PDFErrorOr<void> parse(ReadonlyBytes const&, size_t cleartext_length, size_t encrypted_length); - RefPtr<Gfx::Bitmap> rasterize_glyph(u32 code_point, float width); - Gfx::Path build_char(u32 code_point, float width); + RefPtr<Gfx::Bitmap> rasterize_glyph(u32 char_code, float width); + Gfx::Path build_char(u32 char_code, float width); RefPtr<Encoding> encoding() const { return m_encoding; } - Gfx::FloatPoint glyph_translation(u32 code_point, float width) const; + Gfx::FloatPoint glyph_translation(u32 char_code, float width) const; private: struct Glyph { diff --git a/Userland/Libraries/LibPDF/Fonts/Type1Font.cpp b/Userland/Libraries/LibPDF/Fonts/Type1Font.cpp index e580fe8ada38..a8b5afc0aae8 100644 --- a/Userland/Libraries/LibPDF/Fonts/Type1Font.cpp +++ b/Userland/Libraries/LibPDF/Fonts/Type1Font.cpp @@ -120,22 +120,22 @@ float Type1Font::get_char_width(u16 char_code, float) const return static_cast<float>(width) / 1000.0f; } -void Type1Font::draw_glyph(Gfx::Painter& painter, Gfx::IntPoint const& point, float width, u32 code_point, Color color) +void Type1Font::draw_glyph(Gfx::Painter& painter, Gfx::IntPoint const& point, float width, u32 char_code, Color color) { if (!m_data.font_program) return; RefPtr<Gfx::Bitmap> bitmap; - auto maybe_bitmap = m_glyph_cache.get(code_point); + auto maybe_bitmap = m_glyph_cache.get(char_code); if (maybe_bitmap.has_value()) { bitmap = maybe_bitmap.value(); } else { - bitmap = m_data.font_program->rasterize_glyph(code_point, width); - m_glyph_cache.set(code_point, bitmap); + bitmap = m_data.font_program->rasterize_glyph(char_code, width); + m_glyph_cache.set(char_code, bitmap); } - auto translation = m_data.font_program->glyph_translation(code_point, width); + auto translation = m_data.font_program->glyph_translation(char_code, width); painter.blit_filtered(point.translated(translation.to_rounded<int>()), *bitmap, bitmap->rect(), [color](Color pixel) -> Color { return pixel.multiply(color); }); diff --git a/Userland/Libraries/LibPDF/Fonts/Type1Font.h b/Userland/Libraries/LibPDF/Fonts/Type1Font.h index ce875d27dc90..6be048a69ff0 100644 --- a/Userland/Libraries/LibPDF/Fonts/Type1Font.h +++ b/Userland/Libraries/LibPDF/Fonts/Type1Font.h @@ -34,7 +34,7 @@ class Type1Font : public PDFFont { u32 char_code_to_code_point(u16 char_code) const override; float get_char_width(u16 char_code, float font_size) const override; - void draw_glyph(Gfx::Painter& painter, Gfx::IntPoint const& point, float width, u32 code_point, Color color) override; + void draw_glyph(Gfx::Painter& painter, Gfx::IntPoint const& point, float width, u32 char_code, Color color) override; Type type() const override { return PDFFont::Type::Type1; }
d8b514873f8d0cfd2413b074a4c383278e125408
2023-08-10 08:36:54
Liav A
kernel: Use FixedStringBuffer for fixed-length strings in syscalls
false
Use FixedStringBuffer for fixed-length strings in syscalls
kernel
diff --git a/Base/usr/share/man/man2/pledge.md b/Base/usr/share/man/man2/pledge.md index 979b06c577a6..c399c7b1f2f3 100644 --- a/Base/usr/share/man/man2/pledge.md +++ b/Base/usr/share/man/man2/pledge.md @@ -65,6 +65,7 @@ Promises marked with an asterisk (\*) are SerenityOS specific extensions not sup * `EFAULT`: `promises` and/or `execpromises` are not null and not in readable memory. * `EINVAL`: One or more invalid promises were specified. * `EPERM`: An attempt to increase capabilities was rejected. +* `E2BIG`: `promises` string or `execpromises `string are longer than all known promises strings together. ## History diff --git a/Base/usr/share/man/man2/unveil.md b/Base/usr/share/man/man2/unveil.md index 2c1c7c38a304..2afbd9b3899d 100644 --- a/Base/usr/share/man/man2/unveil.md +++ b/Base/usr/share/man/man2/unveil.md @@ -68,6 +68,7 @@ the error. * `EPERM`: The veil is locked, or an attempt to add more permissions for an already unveiled path was rejected. * `EINVAL`: `path` is not an absolute path, or `permissions` are malformed. +* `E2BIG`: `permissions` string is longer than 5 characters. All of the usual path resolution errors may also occur. diff --git a/Kernel/FileSystem/MountFile.cpp b/Kernel/FileSystem/MountFile.cpp index b2b6d81e6f46..8f1f79d8af51 100644 --- a/Kernel/FileSystem/MountFile.cpp +++ b/Kernel/FileSystem/MountFile.cpp @@ -9,6 +9,7 @@ #include <Kernel/API/Ioctl.h> #include <Kernel/API/POSIX/errno.h> #include <Kernel/API/POSIX/unistd.h> +#include <Kernel/API/Syscall.h> #include <Kernel/FileSystem/Inode.h> #include <Kernel/FileSystem/MountFile.h> #include <Kernel/FileSystem/OpenFileDescription.h> @@ -16,6 +17,7 @@ #include <Kernel/Library/StdLib.h> #include <Kernel/Memory/PrivateInodeVMObject.h> #include <Kernel/Memory/SharedInodeVMObject.h> +#include <Kernel/Tasks/Process.h> namespace Kernel { @@ -51,8 +53,10 @@ ErrorOr<void> MountFile::ioctl(OpenFileDescription&, unsigned request, Userspace auto mount_specific_data = TRY(copy_typed_from_user(user_mount_specific_data)); if ((mount_specific_data.value_type == MountSpecificFlag::ValueType::SignedInteger || mount_specific_data.value_type == MountSpecificFlag::ValueType::UnsignedInteger) && mount_specific_data.value_length != 8) return EDOM; - if (mount_specific_data.key_string_length > MOUNT_SPECIFIC_FLAG_KEY_STRING_MAX_LENGTH) - return ENAMETOOLONG; + + Syscall::StringArgument user_key_string { reinterpret_cast<const char*>(mount_specific_data.key_string_addr), static_cast<size_t>(mount_specific_data.key_string_length) }; + auto key_string = TRY(Process::get_syscall_name_string_fixed_buffer<MOUNT_SPECIFIC_FLAG_KEY_STRING_MAX_LENGTH>(user_key_string)); + if (mount_specific_data.value_type != MountSpecificFlag::ValueType::Boolean && mount_specific_data.value_length == 0) return EINVAL; if (mount_specific_data.value_type != MountSpecificFlag::ValueType::Boolean && mount_specific_data.value_addr == nullptr) @@ -71,7 +75,6 @@ ErrorOr<void> MountFile::ioctl(OpenFileDescription&, unsigned request, Userspace // NOTE: We enforce that the passed argument will be either i64 or u64, so it will always be // exactly 8 bytes. We do that to simplify handling of integers as well as to ensure ABI correctness // in all possible cases. - auto key_string = TRY(try_copy_kstring_from_user(reinterpret_cast<FlatPtr>(mount_specific_data.key_string_addr), static_cast<size_t>(mount_specific_data.key_string_length))); switch (mount_specific_data.value_type) { // NOTE: This is actually considered as simply boolean flag. case MountSpecificFlag::ValueType::Boolean: { @@ -81,27 +84,27 @@ ErrorOr<void> MountFile::ioctl(OpenFileDescription&, unsigned request, Userspace if (value_integer != 0 && value_integer != 1) return EDOM; bool value = (value_integer == 1) ? true : false; - TRY(m_file_system_initializer.handle_mount_boolean_flag(our_mount_specific_data->bytes(), key_string->view(), value)); + TRY(m_file_system_initializer.handle_mount_boolean_flag(our_mount_specific_data->bytes(), key_string.representable_view(), value)); return {}; } case MountSpecificFlag::ValueType::UnsignedInteger: { VERIFY(m_file_system_initializer.handle_mount_unsigned_integer_flag); Userspace<u64*> user_value_addr(reinterpret_cast<FlatPtr>(mount_specific_data.value_addr)); auto value_integer = TRY(copy_typed_from_user(user_value_addr)); - TRY(m_file_system_initializer.handle_mount_unsigned_integer_flag(our_mount_specific_data->bytes(), key_string->view(), value_integer)); + TRY(m_file_system_initializer.handle_mount_unsigned_integer_flag(our_mount_specific_data->bytes(), key_string.representable_view(), value_integer)); return {}; } case MountSpecificFlag::ValueType::SignedInteger: { VERIFY(m_file_system_initializer.handle_mount_signed_integer_flag); Userspace<i64*> user_value_addr(reinterpret_cast<FlatPtr>(mount_specific_data.value_addr)); auto value_integer = TRY(copy_typed_from_user(user_value_addr)); - TRY(m_file_system_initializer.handle_mount_signed_integer_flag(our_mount_specific_data->bytes(), key_string->view(), value_integer)); + TRY(m_file_system_initializer.handle_mount_signed_integer_flag(our_mount_specific_data->bytes(), key_string.representable_view(), value_integer)); return {}; } case MountSpecificFlag::ValueType::ASCIIString: { VERIFY(m_file_system_initializer.handle_mount_ascii_string_flag); auto value_string = TRY(try_copy_kstring_from_user(reinterpret_cast<FlatPtr>(mount_specific_data.value_addr), static_cast<size_t>(mount_specific_data.value_length))); - TRY(m_file_system_initializer.handle_mount_ascii_string_flag(our_mount_specific_data->bytes(), key_string->view(), value_string->view())); + TRY(m_file_system_initializer.handle_mount_ascii_string_flag(our_mount_specific_data->bytes(), key_string.representable_view(), value_string->view())); return {}; } default: diff --git a/Kernel/Net/IPv4Socket.cpp b/Kernel/Net/IPv4Socket.cpp index 9c80ac6ff054..ad1bad00f8e3 100644 --- a/Kernel/Net/IPv4Socket.cpp +++ b/Kernel/Net/IPv4Socket.cpp @@ -622,9 +622,8 @@ ErrorOr<void> IPv4Socket::ioctl(OpenFileDescription&, unsigned request, Userspac TRY(copy_from_user(&route, user_route)); Userspace<const char*> user_rt_dev((FlatPtr)route.rt_dev); - auto ifname = TRY(try_copy_kstring_from_user(user_rt_dev, IFNAMSIZ)); - - auto adapter = NetworkingManagement::the().lookup_by_name(ifname->view()); + auto ifname = TRY(Process::get_syscall_name_string_fixed_buffer<IFNAMSIZ>(user_rt_dev)); + auto adapter = NetworkingManagement::the().lookup_by_name(ifname.representable_view()); if (!adapter) return ENODEV; diff --git a/Kernel/Net/Socket.cpp b/Kernel/Net/Socket.cpp index d8a4e4cd8fa9..078bce028026 100644 --- a/Kernel/Net/Socket.cpp +++ b/Kernel/Net/Socket.cpp @@ -96,8 +96,8 @@ ErrorOr<void> Socket::setsockopt(int level, int option, Userspace<void const*> u if (user_value_size != IFNAMSIZ) return EINVAL; auto user_string = static_ptr_cast<char const*>(user_value); - auto ifname = TRY(try_copy_kstring_from_user(user_string, user_value_size)); - auto device = NetworkingManagement::the().lookup_by_name(ifname->view()); + auto ifname = TRY(Process::get_syscall_name_string_fixed_buffer<IFNAMSIZ>(user_string, user_value_size)); + auto device = NetworkingManagement::the().lookup_by_name(ifname.representable_view()); if (!device) return ENODEV; m_bound_interface.with([&device](auto& bound_device) { diff --git a/Kernel/Syscalls/hostname.cpp b/Kernel/Syscalls/hostname.cpp index 988583ca7afb..c1603d45007d 100644 --- a/Kernel/Syscalls/hostname.cpp +++ b/Kernel/Syscalls/hostname.cpp @@ -15,9 +15,15 @@ ErrorOr<FlatPtr> Process::sys$gethostname(Userspace<char*> buffer, size_t size) if (size > NumericLimits<ssize_t>::max()) return EINVAL; return hostname().with_shared([&](auto const& name) -> ErrorOr<FlatPtr> { - if (size < (name->length() + 1)) + // NOTE: To be able to copy a null-terminated string, we need at most + // 65 characters to store and copy and not 64 here, to store the whole + // hostname string + null terminator. + FixedStringBuffer<UTSNAME_ENTRY_LEN> current_hostname {}; + current_hostname.store_characters(name.representable_view()); + auto name_view = current_hostname.representable_view(); + if (size < (name_view.length() + 1)) return ENAMETOOLONG; - TRY(copy_to_user(buffer, name->characters(), name->length() + 1)); + TRY(copy_to_user(buffer, name_view.characters_without_null_termination(), name_view.length() + 1)); return 0; }); } @@ -30,11 +36,9 @@ ErrorOr<FlatPtr> Process::sys$sethostname(Userspace<char const*> buffer, size_t auto credentials = this->credentials(); if (!credentials->is_superuser()) return EPERM; - if (length > 64) - return ENAMETOOLONG; - auto new_name = TRY(try_copy_kstring_from_user(buffer, length)); + auto new_hostname = TRY(get_syscall_name_string_fixed_buffer<UTSNAME_ENTRY_LEN - 1>(buffer, length)); hostname().with_exclusive([&](auto& name) { - name = move(new_name); + name.store_characters(new_hostname.representable_view()); }); return 0; } diff --git a/Kernel/Syscalls/mount.cpp b/Kernel/Syscalls/mount.cpp index 80fbd3236775..58586c9e0cd8 100644 --- a/Kernel/Syscalls/mount.cpp +++ b/Kernel/Syscalls/mount.cpp @@ -5,6 +5,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/FixedStringBuffer.h> #include <Kernel/FileSystem/Custody.h> #include <Kernel/FileSystem/MountFile.h> #include <Kernel/FileSystem/VirtualFileSystem.h> @@ -20,14 +21,15 @@ ErrorOr<FlatPtr> Process::sys$fsopen(Userspace<Syscall::SC_fsopen_params const*> if (!credentials->is_superuser()) return Error::from_errno(EPERM); auto params = TRY(copy_typed_from_user(user_params)); - auto fs_type_string = TRY(try_copy_kstring_from_user(params.fs_type)); + // NOTE: 16 characters should be enough for any fstype today and in the future. + auto fs_type_string = TRY(get_syscall_name_string_fixed_buffer<16>(params.fs_type)); // NOTE: If some userspace program uses MS_REMOUNT, return EINVAL to indicate that we never want this // flag to appear in the mount table... if (params.flags & MS_REMOUNT || params.flags & MS_BIND) return Error::from_errno(EINVAL); - auto const* fs_type_initializer = TRY(VirtualFileSystem::find_filesystem_type_initializer(fs_type_string->view())); + auto const* fs_type_initializer = TRY(VirtualFileSystem::find_filesystem_type_initializer(fs_type_string.representable_view())); VERIFY(fs_type_initializer); auto mount_file = TRY(MountFile::create(*fs_type_initializer, params.flags)); auto description = TRY(OpenFileDescription::try_create(move(mount_file))); diff --git a/Kernel/Syscalls/pledge.cpp b/Kernel/Syscalls/pledge.cpp index 9610a74715ce..93b7084ba7bc 100644 --- a/Kernel/Syscalls/pledge.cpp +++ b/Kernel/Syscalls/pledge.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/FixedStringBuffer.h> #include <AK/StringView.h> #include <Kernel/Tasks/Process.h> @@ -14,17 +15,19 @@ ErrorOr<FlatPtr> Process::sys$pledge(Userspace<Syscall::SC_pledge_params const*> VERIFY_NO_PROCESS_BIG_LOCK(this); auto params = TRY(copy_typed_from_user(user_params)); - if (params.promises.length > 1024 || params.execpromises.length > 1024) - return E2BIG; + FixedStringBuffer<all_promises_strings_length_with_spaces> promises {}; + bool promises_provided { false }; + FixedStringBuffer<all_promises_strings_length_with_spaces> execpromises {}; + bool execpromises_provided { false }; - OwnPtr<KString> promises; if (params.promises.characters) { - promises = TRY(try_copy_kstring_from_user(params.promises)); + promises_provided = true; + promises = TRY(get_syscall_string_fixed_buffer<all_promises_strings_length_with_spaces>(params.promises)); } - OwnPtr<KString> execpromises; if (params.execpromises.characters) { - execpromises = TRY(try_copy_kstring_from_user(params.execpromises)); + execpromises_provided = true; + execpromises = TRY(get_syscall_string_fixed_buffer<all_promises_strings_length_with_spaces>(params.execpromises)); } auto parse_pledge = [&](auto pledge_spec, u32& mask) { @@ -43,19 +46,19 @@ ErrorOr<FlatPtr> Process::sys$pledge(Userspace<Syscall::SC_pledge_params const*> }; u32 new_promises = 0; - if (promises) { - if (!parse_pledge(promises->view(), new_promises)) + if (promises_provided) { + if (!parse_pledge(promises.representable_view(), new_promises)) return EINVAL; } u32 new_execpromises = 0; - if (execpromises) { - if (!parse_pledge(execpromises->view(), new_execpromises)) + if (execpromises_provided) { + if (!parse_pledge(execpromises.representable_view(), new_execpromises)) return EINVAL; } return with_mutable_protected_data([&](auto& protected_data) -> ErrorOr<FlatPtr> { - if (promises) { + if (promises_provided) { if (protected_data.has_promises && (new_promises & ~protected_data.promises)) { if (!(protected_data.promises & (1u << (u32)Pledge::no_error))) return EPERM; @@ -63,7 +66,7 @@ ErrorOr<FlatPtr> Process::sys$pledge(Userspace<Syscall::SC_pledge_params const*> } } - if (execpromises) { + if (execpromises_provided) { if (protected_data.has_execpromises && (new_execpromises & ~protected_data.execpromises)) { if (!(protected_data.promises & (1u << (u32)Pledge::no_error))) return EPERM; @@ -76,12 +79,12 @@ ErrorOr<FlatPtr> Process::sys$pledge(Userspace<Syscall::SC_pledge_params const*> // erroring out when parsing the exec promises later. Such bugs silently // leave the caller in an unexpected state. - if (promises) { + if (promises_provided) { protected_data.has_promises = true; protected_data.promises = new_promises; } - if (execpromises) { + if (execpromises_provided) { protected_data.has_execpromises = true; protected_data.execpromises = new_execpromises; } diff --git a/Kernel/Syscalls/uname.cpp b/Kernel/Syscalls/uname.cpp index 9da13d0e6b01..7cf1e5087c06 100644 --- a/Kernel/Syscalls/uname.cpp +++ b/Kernel/Syscalls/uname.cpp @@ -38,9 +38,10 @@ ErrorOr<FlatPtr> Process::sys$uname(Userspace<utsname*> user_buf) AK::TypedTransfer<u8>::copy(reinterpret_cast<u8*>(buf.version), SERENITY_VERSION.bytes().data(), min(SERENITY_VERSION.length(), UTSNAME_ENTRY_LEN - 1)); hostname().with_shared([&](auto const& name) { - auto length = min(name->length(), UTSNAME_ENTRY_LEN - 1); - AK::TypedTransfer<char>::copy(reinterpret_cast<char*>(buf.nodename), name->characters(), length); - buf.nodename[length] = '\0'; + auto name_length = name.representable_view().length(); + VERIFY(name_length <= (UTSNAME_ENTRY_LEN - 1)); + AK::TypedTransfer<char>::copy(reinterpret_cast<char*>(buf.nodename), name.representable_view().characters_without_null_termination(), name_length); + buf.nodename[name_length] = '\0'; }); TRY(copy_to_user(user_buf, &buf)); diff --git a/Kernel/Syscalls/unveil.cpp b/Kernel/Syscalls/unveil.cpp index dc9332b84c43..0a36981a798c 100644 --- a/Kernel/Syscalls/unveil.cpp +++ b/Kernel/Syscalls/unveil.cpp @@ -101,19 +101,16 @@ ErrorOr<FlatPtr> Process::sys$unveil(Userspace<Syscall::SC_unveil_params const*> if (!params.path.characters || !params.permissions.characters) return EINVAL; - if (params.permissions.length > 5) - return EINVAL; - auto path = TRY(get_syscall_path_argument(params.path)); if (path->is_empty() || !path->view().starts_with('/')) return EINVAL; - auto permissions = TRY(try_copy_kstring_from_user(params.permissions)); + auto permissions = TRY(get_syscall_string_fixed_buffer<5>(params.permissions)); // Let's work out permissions first... unsigned new_permissions = 0; - for (char const permission : permissions->view()) { + for (char const permission : permissions.representable_view()) { switch (permission) { case 'r': new_permissions |= UnveilAccess::Read; diff --git a/Kernel/Tasks/Process.cpp b/Kernel/Tasks/Process.cpp index 2c7651c59bcb..db41cab4861b 100644 --- a/Kernel/Tasks/Process.cpp +++ b/Kernel/Tasks/Process.cpp @@ -53,9 +53,9 @@ static Atomic<pid_t> next_pid; static Singleton<SpinlockProtected<Process::AllProcessesList, LockRank::None>> s_all_instances; READONLY_AFTER_INIT Memory::Region* g_signal_trampoline_region; -static Singleton<MutexProtected<OwnPtr<KString>>> s_hostname; +static Singleton<MutexProtected<FixedStringBuffer<UTSNAME_ENTRY_LEN - 1>>> s_hostname; -MutexProtected<OwnPtr<KString>>& hostname() +MutexProtected<FixedStringBuffer<UTSNAME_ENTRY_LEN - 1>>& hostname() { return *s_hostname; } @@ -161,7 +161,7 @@ UNMAP_AFTER_INIT void Process::initialize() // Note: This is called before scheduling is initialized, and before APs are booted. // So we can "safely" bypass the lock here. - reinterpret_cast<OwnPtr<KString>&>(hostname()) = KString::must_create("courage"sv); + reinterpret_cast<FixedStringBuffer<UTSNAME_ENTRY_LEN - 1>&>(hostname()).store_characters("courage"sv); create_signal_trampoline(); } diff --git a/Kernel/Tasks/Process.h b/Kernel/Tasks/Process.h index ffb3e42646bf..c127a470ef02 100644 --- a/Kernel/Tasks/Process.h +++ b/Kernel/Tasks/Process.h @@ -41,7 +41,7 @@ namespace Kernel { -MutexProtected<OwnPtr<KString>>& hostname(); +MutexProtected<FixedStringBuffer<UTSNAME_ENTRY_LEN - 1>>& hostname(); UnixDateTime kgettimeofday(); #define ENUMERATE_PLEDGE_PROMISES \ @@ -74,6 +74,15 @@ UnixDateTime kgettimeofday(); __ENUMERATE_PLEDGE_PROMISE(mount) \ __ENUMERATE_PLEDGE_PROMISE(no_error) +#define __ENUMERATE_PLEDGE_PROMISE(x) sizeof(#x) + 1 + +// NOTE: We truncate the last space from the string as it's not needed (with 0 - 1). +constexpr static unsigned all_promises_strings_length_with_spaces = ENUMERATE_PLEDGE_PROMISES 0 - 1; +#undef __ENUMERATE_PLEDGE_PROMISE + +// NOTE: This is a sanity check because length of more than 1024 characters +// is not reasonable. +static_assert(all_promises_strings_length_with_spaces <= 1024); + enum class Pledge : u32 { #define __ENUMERATE_PLEDGE_PROMISE(x) x, ENUMERATE_PLEDGE_PROMISES @@ -605,6 +614,36 @@ class Process final ErrorOr<void> validate_mmap_prot(int prot, bool map_stack, bool map_anonymous, Memory::Region const* region = nullptr) const; ErrorOr<void> validate_inode_mmap_prot(int prot, bool description_readable, bool description_writable, bool map_shared) const; + template<size_t Size> + static ErrorOr<FixedStringBuffer<Size>> get_syscall_string_fixed_buffer(Syscall::StringArgument const& argument) + { + // NOTE: If the string is too much big for the FixedStringBuffer, + // we return E2BIG error here. + FixedStringBuffer<Size> buffer; + TRY(try_copy_string_from_user_into_fixed_string_buffer<Size>(reinterpret_cast<FlatPtr>(argument.characters), buffer, argument.length)); + return buffer; + } + + template<size_t Size> + static ErrorOr<FixedStringBuffer<Size>> get_syscall_name_string_fixed_buffer(Userspace<char const*> user_buffer, size_t user_length = Size) + { + // NOTE: If the string is too much big for the FixedStringBuffer, + // we return E2BIG error here. + FixedStringBuffer<Size> buffer; + TRY(try_copy_string_from_user_into_fixed_string_buffer<Size>(user_buffer, buffer, user_length)); + return buffer; + } + + template<size_t Size> + static ErrorOr<FixedStringBuffer<Size>> get_syscall_name_string_fixed_buffer(Syscall::StringArgument const& argument) + { + // NOTE: If the string is too much big for the FixedStringBuffer, + // we return ENAMETOOLONG error here. + FixedStringBuffer<Size> buffer; + TRY(try_copy_name_from_user_into_fixed_string_buffer<Size>(reinterpret_cast<FlatPtr>(argument.characters), buffer, argument.length)); + return buffer; + } + private: friend class MemoryManager; friend class Scheduler; diff --git a/Tests/Kernel/TestKernelUnveil.cpp b/Tests/Kernel/TestKernelUnveil.cpp index 04d6d9a737b7..5d8d79e661e7 100644 --- a/Tests/Kernel/TestKernelUnveil.cpp +++ b/Tests/Kernel/TestKernelUnveil.cpp @@ -12,6 +12,10 @@ TEST_CASE(test_argument_validation) { auto res = unveil("/etc", "aaaaaaaaaaaa"); EXPECT_EQ(res, -1); + EXPECT_EQ(errno, E2BIG); + + res = unveil("/etc", "aaaaa"); + EXPECT_EQ(res, -1); EXPECT_EQ(errno, EINVAL); res = unveil(nullptr, "r");
37f2818e900b29f8b532fa2e2dcf931ef56bf836
2024-10-27 15:56:12
stelar7
libweb: Fix modulus length being wrong for RSA-OAEP key import
false
Fix modulus length being wrong for RSA-OAEP key import
libweb
diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp index 08c7bd3f8d6b..a8eb9317147d 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp +++ b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp @@ -902,12 +902,12 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> RSAOAEP::import_key(Web::Crypto // 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent. TRY(key->handle().visit( [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> WebIDL::ExceptionOr<void> { - algorithm->set_modulus_length(public_key.length()); + algorithm->set_modulus_length(public_key.modulus().trimmed_byte_length() * 8); TRY(algorithm->set_public_exponent(public_key.public_exponent())); return {}; }, [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> WebIDL::ExceptionOr<void> { - algorithm->set_modulus_length(private_key.length()); + algorithm->set_modulus_length(private_key.modulus().trimmed_byte_length() * 8); TRY(algorithm->set_public_exponent(private_key.public_exponent())); return {}; },
3811be2f7c8169a4ddf973f9bb6cf3c44265d4db
2023-05-04 15:26:55
Andreas Kling
libweb: Make module maps GC-allocated
false
Make module maps GC-allocated
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp index d1aad171fccc..93aeaa0ec57f 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp +++ b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp @@ -33,10 +33,18 @@ EnvironmentSettingsObject::~EnvironmentSettingsObject() responsible_event_loop().unregister_environment_settings_object({}, *this); } +JS::ThrowCompletionOr<void> EnvironmentSettingsObject::initialize(JS::Realm& realm) +{ + MUST_OR_THROW_OOM(Base::initialize(realm)); + m_module_map = realm.heap().allocate_without_realm<ModuleMap>(); + return {}; +} + void EnvironmentSettingsObject::visit_edges(Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(target_browsing_context); + visitor.visit(m_module_map); visitor.ignore(m_outstanding_rejected_promises_weak_set); } @@ -48,7 +56,7 @@ JS::ExecutionContext& EnvironmentSettingsObject::realm_execution_context() ModuleMap& EnvironmentSettingsObject::module_map() { - return m_module_map; + return *m_module_map; } // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object%27s-realm diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h index d2a7bec30565..8652345dfb6a 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h +++ b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h @@ -60,6 +60,7 @@ struct EnvironmentSettingsObject JS_CELL(EnvironmentSettingsObject, JS::Cell); virtual ~EnvironmentSettingsObject() override; + virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; // https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-target-browsing-context JS::ExecutionContext& realm_execution_context(); @@ -124,7 +125,7 @@ struct EnvironmentSettingsObject private: NonnullOwnPtr<JS::ExecutionContext> m_realm_execution_context; - ModuleMap m_module_map; + JS::GCPtr<ModuleMap> m_module_map; EventLoop* m_responsible_event_loop { nullptr }; diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.cpp b/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.cpp index db2642589d24..c38742073836 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.cpp +++ b/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.cpp @@ -8,6 +8,14 @@ namespace Web::HTML { +void ModuleMap::visit_edges(Visitor& visitor) +{ + Base::visit_edges(visitor); + for (auto& it : m_values) { + visitor.visit(it.value.module_script); + } +} + bool ModuleMap::is_fetching(AK::URL const& url, DeprecatedString const& type) const { return is(url, type, EntryType::Fetching); diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.h b/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.h index 12780e8692b3..fef5b2a42914 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.h +++ b/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.h @@ -7,6 +7,7 @@ #pragma once #include <AK/URL.h> +#include <LibJS/Heap/Cell.h> #include <LibWeb/HTML/Scripting/ModuleScript.h> namespace Web::HTML { @@ -33,8 +34,8 @@ class ModuleLocationTuple { }; // https://html.spec.whatwg.org/multipage/webappapis.html#module-map -class ModuleMap { - AK_MAKE_NONCOPYABLE(ModuleMap); +class ModuleMap final : public JS::Cell { + JS_CELL(ModuleMap, Cell); public: ModuleMap() = default; @@ -63,6 +64,8 @@ class ModuleMap { void wait_for_change(AK::URL const& url, DeprecatedString const& type, Function<void(Entry)> callback); private: + virtual void visit_edges(JS::Cell::Visitor&) override; + HashMap<ModuleLocationTuple, Entry> m_values; HashMap<ModuleLocationTuple, Vector<Function<void(Entry)>>> m_callbacks; };
efa9627fc4e4c22bc089f9914209e1ffac8c1243
2021-07-29 18:31:47
Andreas Kling
libweb: Remove unused enum value CSS::StyleValue::Position
false
Remove unused enum value CSS::StyleValue::Position
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h index 3a9ea52ded0a..5501772d5949 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h @@ -223,7 +223,6 @@ class StyleValue : public RefCounted<StyleValue> { Color, Identifier, Image, - Position, CustomProperty, Numeric, ValueList, @@ -240,7 +239,6 @@ class StyleValue : public RefCounted<StyleValue> { bool is_image() const { return type() == Type::Image; } bool is_string() const { return type() == Type::String; } bool is_length() const { return type() == Type::Length; } - bool is_position() const { return type() == Type::Position; } bool is_custom_property() const { return type() == Type::CustomProperty; } bool is_numeric() const { return type() == Type::Numeric; } bool is_value_list() const
a482a3e60915c389bbcb5eb6a54a82b7f607c13f
2021-07-05 23:53:42
Daniel Bertalan
ak: Declare operators `new` and `delete` as global functions
false
Declare operators `new` and `delete` as global functions
ak
diff --git a/AK/kmalloc.cpp b/AK/kmalloc.cpp new file mode 100644 index 000000000000..d6635f9ee22f --- /dev/null +++ b/AK/kmalloc.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Daniel Bertalan <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#if defined(__serenity__) && !defined(KERNEL) + +# include <AK/Assertions.h> +# include <AK/kmalloc.h> + +// However deceptively simple these functions look, they must not be inlined. +// Memory allocated in one translation unit has to be deallocatable in another +// translation unit, so these functions must be the same everywhere. +// By making these functions global, this invariant is enforced. + +void* operator new(size_t size) +{ + void* ptr = malloc(size); + VERIFY(ptr); + return ptr; +} + +void* operator new(size_t size, const std::nothrow_t&) noexcept +{ + return malloc(size); +} + +void operator delete(void* ptr) noexcept +{ + return free(ptr); +} + +void operator delete(void* ptr, size_t) noexcept +{ + return free(ptr); +} + +void* operator new[](size_t size) +{ + void* ptr = malloc(size); + VERIFY(ptr); + return ptr; +} + +void* operator new[](size_t size, const std::nothrow_t&) noexcept +{ + return malloc(size); +} + +void operator delete[](void* ptr) noexcept +{ + return free(ptr); +} + +void operator delete[](void* ptr, size_t) noexcept +{ + return free(ptr); +} + +#endif diff --git a/AK/kmalloc.h b/AK/kmalloc.h index 580782898059..03484a72806b 100644 --- a/AK/kmalloc.h +++ b/AK/kmalloc.h @@ -1,13 +1,27 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Daniel Bertalan <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once -#ifndef __serenity__ +#if defined(KERNEL) +# include <Kernel/Heap/kmalloc.h> +#else # include <new> +# include <stdlib.h> + +# define kcalloc calloc +# define kmalloc malloc +# define kmalloc_good_size malloc_good_size +# define kfree free +# define krealloc realloc +#endif + +#ifndef __serenity__ +# include <AK/Types.h> # ifndef AK_OS_MACOS extern "C" { @@ -28,68 +42,4 @@ inline size_t malloc_good_size(size_t size) { return size; } # define AK_MAKE_ETERNAL #endif -#if defined(KERNEL) -# include <Kernel/Heap/kmalloc.h> -#else -# include <stdlib.h> - -# define kcalloc calloc -# define kmalloc malloc -# define kmalloc_good_size malloc_good_size -# define kfree free -# define krealloc realloc - -# ifdef __serenity__ - -# include <AK/Assertions.h> -# include <new> - -inline void* operator new(size_t size) -{ - void* ptr = kmalloc(size); - VERIFY(ptr); - return ptr; -} - -inline void* operator new(size_t size, const std::nothrow_t&) noexcept -{ - return kmalloc(size); -} - -inline void operator delete(void* ptr) noexcept -{ - return kfree(ptr); -} - -inline void operator delete(void* ptr, size_t) noexcept -{ - return kfree(ptr); -} - -inline void* operator new[](size_t size) -{ - void* ptr = kmalloc(size); - VERIFY(ptr); - return ptr; -} - -inline void* operator new[](size_t size, const std::nothrow_t&) noexcept -{ - return kmalloc(size); -} - -inline void operator delete[](void* ptr) noexcept -{ - return kfree(ptr); -} - -inline void operator delete[](void* ptr, size_t) noexcept -{ - return kfree(ptr); -} - -# endif - -#endif - using std::nothrow;
79e065f0a2aacb4b467cb091ec58e9cec53719f4
2020-03-23 17:44:57
Andreas Kling
libjs: Port garbage collector to Linux
false
Port garbage collector to Linux
libjs
diff --git a/Libraries/LibJS/Heap/Heap.cpp b/Libraries/LibJS/Heap/Heap.cpp index b28911664720..905f52e0e5b1 100644 --- a/Libraries/LibJS/Heap/Heap.cpp +++ b/Libraries/LibJS/Heap/Heap.cpp @@ -31,10 +31,15 @@ #include <LibJS/Heap/HeapBlock.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/Object.h> -#include <serenity.h> #include <setjmp.h> #include <stdio.h> +#ifdef __serenity__ +#include <serenity.h> +#elif __linux__ +#include <pthread.h> +#endif + #define HEAP_DEBUG namespace JS { @@ -105,15 +110,31 @@ void Heap::gather_conservative_roots(HashTable<Cell*>& roots) HashTable<FlatPtr> possible_pointers; - for (size_t i = 0; i < (sizeof(buf->regs) / sizeof(FlatPtr)); ++i) - possible_pointers.set(buf->regs[i]); + const FlatPtr* raw_jmp_buf = reinterpret_cast<const FlatPtr*>(buf); + + for (size_t i = 0; i < sizeof(buf) / sizeof(FlatPtr); i += sizeof(FlatPtr)) + possible_pointers.set(raw_jmp_buf[i]); FlatPtr stack_base; size_t stack_size; + +#ifdef __serenity__ if (get_stack_bounds(&stack_base, &stack_size) < 0) { perror("get_stack_bounds"); ASSERT_NOT_REACHED(); } +#elif __linux__ + pthread_attr_t attr = {}; + if (int rc = pthread_getattr_np(pthread_self(), &attr) != 0) { + fprintf(stderr, "pthread_getattr_np: %s\n", strerror(-rc)); + ASSERT_NOT_REACHED(); + } + if (int rc = pthread_attr_getstack(&attr, (void**)&stack_base, &stack_size) != 0) { + fprintf(stderr, "pthread_attr_getstack: %s\n", strerror(-rc)); + ASSERT_NOT_REACHED(); + } + pthread_attr_destroy(&attr); +#endif FlatPtr stack_reference = reinterpret_cast<FlatPtr>(&dummy); FlatPtr stack_top = stack_base + stack_size; diff --git a/Libraries/LibJS/Heap/HeapBlock.cpp b/Libraries/LibJS/Heap/HeapBlock.cpp index 86a4b41a651f..0e4c9066da86 100644 --- a/Libraries/LibJS/Heap/HeapBlock.cpp +++ b/Libraries/LibJS/Heap/HeapBlock.cpp @@ -37,7 +37,11 @@ NonnullOwnPtr<HeapBlock> HeapBlock::create_with_cell_size(Heap& heap, size_t cel { char name[64]; snprintf(name, sizeof(name), "LibJS: HeapBlock(%zu)", cell_size); +#ifdef __serenity__ auto* block = (HeapBlock*)serenity_mmap(nullptr, block_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, block_size, name); +#else + auto* block = (HeapBlock*)aligned_alloc(block_size, block_size); +#endif ASSERT(block != MAP_FAILED); new (block) HeapBlock(heap, cell_size); return NonnullOwnPtr<HeapBlock>(NonnullOwnPtr<HeapBlock>::Adopt, *block); @@ -45,8 +49,12 @@ NonnullOwnPtr<HeapBlock> HeapBlock::create_with_cell_size(Heap& heap, size_t cel void HeapBlock::operator delete(void* ptr) { +#ifdef __serenity__ int rc = munmap(ptr, block_size); ASSERT(rc == 0); +#else + free(ptr); +#endif } HeapBlock::HeapBlock(Heap& heap, size_t cell_size)
033057683c95ef3ba5be5f1757ad58a6b7e9f63c
2024-07-10 21:43:21
Dennis Camera
everywhere: Don't install code generators and test binaries
false
Don't install code generators and test binaries
everywhere
diff --git a/.github/workflows/lagom-template.yml b/.github/workflows/lagom-template.yml index 65cd559828b7..26b9c8ec74dd 100644 --- a/.github/workflows/lagom-template.yml +++ b/.github/workflows/lagom-template.yml @@ -106,6 +106,7 @@ jobs: cmake -GNinja -S Meta/Lagom -B ${{ github.workspace }}/tools-build \ -DLAGOM_TOOLS_ONLY=ON \ + -DINSTALL_LAGOM_TOOLS=ON \ -DCMAKE_INSTALL_PREFIX=${{ github.workspace }}/tool-install \ -DSERENITY_CACHE_DIR=${{ github.workspace }}/Build/caches \ -DCMAKE_C_COMPILER=gcc-13 \ diff --git a/Meta/Lagom/Tools/CMakeLists.txt b/Meta/Lagom/Tools/CMakeLists.txt index 68a854062b80..9954844eda06 100644 --- a/Meta/Lagom/Tools/CMakeLists.txt +++ b/Meta/Lagom/Tools/CMakeLists.txt @@ -1,14 +1,19 @@ function(lagom_tool tool) - cmake_parse_arguments(LAGOM_TOOL "" "" "SOURCES;LIBS" ${ARGN}) + cmake_parse_arguments(LAGOM_TOOL "" "INSTALL" "SOURCES;LIBS" ${ARGN}) add_executable(${tool} ${SOURCES} ${LAGOM_TOOL_SOURCES}) # alias for parity with exports add_executable(Lagom::${tool} ALIAS ${tool}) target_link_libraries(${tool} AK LibCoreMinimal LibFileSystem GenericClangPlugin ${LAGOM_TOOL_LIBS}) - install( - TARGETS ${tool} - EXPORT LagomTargets - RUNTIME COMPONENT Lagom_Runtime - ) + if (NOT DEFINED LAGOM_TOOL_INSTALL) + set(LAGOM_TOOL_INSTALL ${INSTALL_LAGOM_TOOLS}) + endif() + if (DEFINED LAGOM_TOOL_INSTALL AND LAGOM_TOOL_INSTALL) + install( + TARGETS ${tool} + EXPORT LagomTargets + RUNTIME COMPONENT Lagom_Runtime + ) + endif() endfunction() add_subdirectory(CodeGenerators) diff --git a/Tests/LibAudio/CMakeLists.txt b/Tests/LibAudio/CMakeLists.txt index ae8d4a291099..98574e2abcef 100644 --- a/Tests/LibAudio/CMakeLists.txt +++ b/Tests/LibAudio/CMakeLists.txt @@ -7,7 +7,3 @@ set(TEST_SOURCES foreach(source IN LISTS TEST_SOURCES) serenity_test("${source}" LibAudio LIBS LibAudio LibFileSystem) endforeach() - -install(DIRECTORY ${FLAC_SPEC_TEST_PATH} DESTINATION usr/Tests/LibAudio/FLAC) - -install(DIRECTORY WAV DESTINATION usr/Tests/LibAudio) diff --git a/Tests/LibCompress/CMakeLists.txt b/Tests/LibCompress/CMakeLists.txt index 5ce4dacdc9ff..91e998075973 100644 --- a/Tests/LibCompress/CMakeLists.txt +++ b/Tests/LibCompress/CMakeLists.txt @@ -12,6 +12,3 @@ set(TEST_SOURCES foreach(source IN LISTS TEST_SOURCES) serenity_test("${source}" LibCompress LIBS LibCompress) endforeach() - -install(DIRECTORY brotli-test-files DESTINATION usr/Tests/LibCompress) -install(DIRECTORY deflate-test-files DESTINATION usr/Tests/LibCompress) diff --git a/Tests/LibCore/CMakeLists.txt b/Tests/LibCore/CMakeLists.txt index 1a1f82f1de40..c15e073631e5 100644 --- a/Tests/LibCore/CMakeLists.txt +++ b/Tests/LibCore/CMakeLists.txt @@ -19,5 +19,3 @@ target_link_libraries(TestLibCorePromise PRIVATE LibThreading) # NOTE: Required because of the LocalServer tests target_link_libraries(TestLibCoreStream PRIVATE LibThreading) target_link_libraries(TestLibCoreSharedSingleProducerCircularQueue PRIVATE LibThreading) - -install(FILES long_lines.txt 10kb.txt small.txt DESTINATION usr/Tests/LibCore) diff --git a/Tests/LibGfx/CMakeLists.txt b/Tests/LibGfx/CMakeLists.txt index 225246101f07..05c38ceb4597 100644 --- a/Tests/LibGfx/CMakeLists.txt +++ b/Tests/LibGfx/CMakeLists.txt @@ -18,5 +18,3 @@ set(TEST_SOURCES foreach(source IN LISTS TEST_SOURCES) serenity_test("${source}" LibGfx LIBS LibGfx) endforeach() - -install(DIRECTORY test-inputs DESTINATION usr/Tests/LibGfx) diff --git a/Tests/LibJS/CMakeLists.txt b/Tests/LibJS/CMakeLists.txt index be77c6120478..82e93e6ee247 100644 --- a/Tests/LibJS/CMakeLists.txt +++ b/Tests/LibJS/CMakeLists.txt @@ -1,7 +1,5 @@ serenity_testjs_test(test-js.cpp test-js LIBS LibUnicode) -install(TARGETS test-js RUNTIME DESTINATION bin OPTIONAL) - serenity_test(test-invalid-unicode-js.cpp LibJS LIBS LibJS LibUnicode) serenity_test(test-value-js.cpp LibJS LIBS LibJS LibUnicode) @@ -9,9 +7,7 @@ serenity_test(test-value-js.cpp LibJS LIBS LibJS LibUnicode) add_executable(test262-runner test262-runner.cpp) target_link_libraries(test262-runner PRIVATE LibJS LibCore LibUnicode) serenity_set_implicit_links(test262-runner) -install(TARGETS test262-runner RUNTIME DESTINATION bin OPTIONAL) add_executable(test-test262 test-test262.cpp) target_link_libraries(test-test262 PRIVATE LibMain LibCore LibFileSystem) serenity_set_implicit_links(test-test262) -install(TARGETS test-test262 RUNTIME DESTINATION bin OPTIONAL) diff --git a/Tests/LibWasm/CMakeLists.txt b/Tests/LibWasm/CMakeLists.txt index b6cf81779684..85f61540267e 100644 --- a/Tests/LibWasm/CMakeLists.txt +++ b/Tests/LibWasm/CMakeLists.txt @@ -1,2 +1 @@ serenity_testjs_test(test-wasm.cpp test-wasm LIBS LibWasm LibJS LibCrypto) -install(TARGETS test-wasm RUNTIME DESTINATION bin OPTIONAL) diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt index 65268e0a40be..dad1c094b863 100644 --- a/Tests/LibWeb/CMakeLists.txt +++ b/Tests/LibWeb/CMakeLists.txt @@ -14,5 +14,3 @@ foreach(source IN LISTS TEST_SOURCES) endforeach() target_link_libraries(TestFetchURL PRIVATE LibURL) - -install(FILES tokenizer-test.html DESTINATION usr/Tests/LibWeb)
28acf25035cd3500ff20915ef9770c36575f0059
2023-03-25 22:20:36
Marco Cutecchia
kernel: Use u64 instead of int for the bitfields of CPACR_EL1
false
Use u64 instead of int for the bitfields of CPACR_EL1
kernel
diff --git a/Kernel/Arch/aarch64/Registers.h b/Kernel/Arch/aarch64/Registers.h index 6c68d2892405..b84aa9363bf9 100644 --- a/Kernel/Arch/aarch64/Registers.h +++ b/Kernel/Arch/aarch64/Registers.h @@ -1346,16 +1346,16 @@ static_assert(sizeof(PMCCNTR_EL0) == 8); // D17.2.30 CPACR_EL1, Architectural Feature Access Control Register struct alignas(u64) CPACR_EL1 { - int _reserved0 : 16 = 0; - int ZEN : 2; - int _reserved18 : 2 = 0; - int FPEN : 2; - int _reserved22 : 2 = 0; - int SMEN : 2; - int _reserved26 : 2 = 0; - int TTA : 1; - int _reserved29 : 3 = 0; - int _reserved32 : 32 = 0; + u64 _reserved0 : 16 = 0; + u64 ZEN : 2; + u64 _reserved18 : 2 = 0; + u64 FPEN : 2; + u64 _reserved22 : 2 = 0; + u64 SMEN : 2; + u64 _reserved26 : 2 = 0; + u64 TTA : 1; + u64 _reserved29 : 3 = 0; + u64 _reserved32 : 32 = 0; static inline void write(CPACR_EL1 cpacr_el1) {
d225b5e94cdca39af32f58ba8100fb1bd126a622
2022-02-09 04:38:43
Idan Horowitz
libjs: Add spec comments to %TypedArray%.prototype.set
false
Add spec comments to %TypedArray%.prototype.set
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp index 3b660367fc7a..d3ac4fdcdf06 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2020-2021, Linus Groh <[email protected]> * Copyright (c) 2021, Luke Wilde <[email protected]> - * Copyright (c) 2021, Idan Horowitz <[email protected]> + * Copyright (c) 2021-2022, Idan Horowitz <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -610,124 +610,226 @@ JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::to_string_tag_getter) // 23.2.3.24 %TypedArray%.prototype.set ( source [ , offset ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.set JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::set) { + auto source = vm.argument(0); + + // 1. Let target be the this value. + // 2. Perform ? RequireInternalSlot(target, [[TypedArrayName]]). auto* typed_array = TRY(typed_array_from_this(global_object)); - auto source = vm.argument(0); + // 3. Assert: target has a [[ViewedArrayBuffer]] internal slot. + // 4. Let targetOffset be ? ToIntegerOrInfinity(offset). auto target_offset = TRY(vm.argument(1).to_integer_or_infinity(global_object)); + + // 5. If targetOffset < 0, throw a RangeError exception. if (target_offset < 0) - return vm.throw_completion<JS::RangeError>(global_object, "Invalid target offset"); + return vm.throw_completion<RangeError>(global_object, "Invalid target offset"); + // 6. If source is an Object that has a [[TypedArrayName]] internal slot, then if (source.is_object() && is<TypedArrayBase>(source.as_object())) { - auto& source_typed_array = static_cast<TypedArrayBase&>(source.as_object()); + // a. Perform ? SetTypedArrayFromTypedArray(target, targetOffset, source). + // 23.2.3.23.1 SetTypedArrayFromTypedArray ( target, targetOffset, source ), https://tc39.es/ecma262/#sec-settypedarrayfromtypedarray - auto target_buffer = typed_array->viewed_array_buffer(); + + auto& source_typed_array = static_cast<TypedArrayBase&>(source.as_object()); + + // 1. Let targetBuffer be target.[[ViewedArrayBuffer]]. + auto* target_buffer = typed_array->viewed_array_buffer(); + + // 2. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception. if (target_buffer->is_detached()) - return vm.throw_completion<JS::TypeError>(global_object, ErrorType::DetachedArrayBuffer); + return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer); + + // 3. Let targetLength be target.[[ArrayLength]]. auto target_length = typed_array->array_length(); - auto target_byte_offset = typed_array->byte_offset(); - auto source_buffer = source_typed_array.viewed_array_buffer(); + // 4. Let srcBuffer be source.[[ViewedArrayBuffer]]. + auto* source_buffer = source_typed_array.viewed_array_buffer(); + + // 5. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception. if (source_buffer->is_detached()) - return vm.throw_completion<JS::TypeError>(global_object, ErrorType::DetachedArrayBuffer); + return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer); + + // 6. Let targetName be the String value of target.[[TypedArrayName]]. + // 7. Let targetType be the Element Type value in Table 69 for targetName. + // 8. Let targetElementSize be the Element Size value specified in Table 69 for targetName. + auto target_element_size = typed_array->element_size(); + + // 9. Let targetByteOffset be target.[[ByteOffset]]. + auto target_byte_offset = typed_array->byte_offset(); + + // 10. Let srcName be the String value of source.[[TypedArrayName]]. + // 11. Let srcType be the Element Type value in Table 69 for srcName. + // 12. Let srcElementSize be the Element Size value specified in Table 69 for srcName. + auto source_element_size = source_typed_array.element_size(); + + // 13. Let srcLength be source.[[ArrayLength]]. auto source_length = source_typed_array.array_length(); + + // 14. Let srcByteOffset be source.[[ByteOffset]]. auto source_byte_offset = source_typed_array.byte_offset(); + // 15. If targetOffset is +∞, throw a RangeError exception. if (isinf(target_offset)) - return vm.throw_completion<JS::RangeError>(global_object, "Invalid target offset"); + return vm.throw_completion<RangeError>(global_object, "Invalid target offset"); + // 16. If srcLength + targetOffset > targetLength, throw a RangeError exception. Checked<size_t> checked = source_length; checked += static_cast<u32>(target_offset); if (checked.has_overflow() || checked.value() > target_length) - return vm.throw_completion<JS::RangeError>(global_object, "Overflow or out of bounds in target length"); + return vm.throw_completion<RangeError>(global_object, "Overflow or out of bounds in target length"); + // 17. If target.[[ContentType]] ≠ source.[[ContentType]], throw a TypeError exception. if (typed_array->content_type() != source_typed_array.content_type()) - return vm.throw_completion<JS::TypeError>(global_object, "Copy between arrays of different content types is prohibited"); + return vm.throw_completion<TypeError>(global_object, "Copy between arrays of different content types is prohibited"); + + // FIXME: 18. If both IsSharedArrayBuffer(srcBuffer) and IsSharedArrayBuffer(targetBuffer) are true, then + // FIXME: a. If srcBuffer.[[ArrayBufferData]] and targetBuffer.[[ArrayBufferData]] are the same Shared Data Block values, let same be true; else let same be false. + + // 19. Else, let same be SameValue(srcBuffer, targetBuffer). + auto same = same_value(source_buffer, target_buffer); size_t source_byte_index; - bool same = false; - // FIXME: Step 19: If both IsSharedArrayBuffer(srcBuffer) and IsSharedArrayBuffer(targetBuffer) are true... - same = same_value(source_buffer, target_buffer); + + // 20. If same is true, then if (same) { - // FIXME: Implement this: Step 21 + // a. Let srcByteLength be source.[[ByteLength]]. + // b. Set srcBuffer to ? CloneArrayBuffer(srcBuffer, srcByteOffset, srcByteLength, %ArrayBuffer%). + // c. NOTE: %ArrayBuffer% is used to clone srcBuffer because is it known to not have any observable side-effects. + // d. Let srcByteIndex be 0. TODO(); } else { + // 21. Else, let srcByteIndex be srcByteOffset. source_byte_index = source_byte_offset; } + + // 22. Let targetByteIndex be targetOffset × targetElementSize + targetByteOffset. Checked<size_t> checked_target_byte_index(static_cast<size_t>(target_offset)); - checked_target_byte_index *= typed_array->element_size(); + checked_target_byte_index *= target_element_size; checked_target_byte_index += target_byte_offset; if (checked_target_byte_index.has_overflow()) - return vm.throw_completion<JS::RangeError>(global_object, "Overflow in target byte index"); + return vm.throw_completion<RangeError>(global_object, "Overflow in target byte index"); auto target_byte_index = checked_target_byte_index.value(); + // 23. Let limit be targetByteIndex + targetElementSize × srcLength. Checked<size_t> checked_limit(source_length); - checked_limit *= typed_array->element_size(); + checked_limit *= target_element_size; checked_limit += target_byte_index; if (checked_limit.has_overflow()) - return vm.throw_completion<JS::RangeError>(global_object, "Overflow in target limit"); + return vm.throw_completion<RangeError>(global_object, "Overflow in target limit"); auto limit = checked_limit.value(); + // 24. If srcType is the same as targetType, then if (source_typed_array.element_size() == typed_array->element_size()) { - // FIXME: SharedBuffers use a different mechanism, implement that when SharedBuffers are implemented. + // a. NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data. + // b. Repeat, while targetByteIndex < limit, + // i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, Uint8, true, Unordered). + // ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, Uint8, value, true, Unordered). + // iii. Set srcByteIndex to srcByteIndex + 1. + // iv. Set targetByteIndex to targetByteIndex + 1. target_buffer->buffer().overwrite(target_byte_index, source_buffer->buffer().data(), limit - target_byte_index); } else { + // a. Repeat, while targetByteIndex < limit, while (target_byte_index < limit) { + // i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, srcType, true, Unordered). auto value = source_typed_array.get_value_from_buffer(source_byte_index, ArrayBuffer::Unordered); + // ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, Unordered). typed_array->set_value_in_buffer(target_byte_index, value, ArrayBuffer::Unordered); - source_byte_index += source_typed_array.element_size(); + // iii. Set srcByteIndex to srcByteIndex + srcElementSize. + source_byte_index += source_element_size; + // iv. Set targetByteIndex to targetByteIndex + targetElementSize. target_byte_index += typed_array->element_size(); } } - } else { + } + // 7. Else, + else { + // a. Perform ? SetTypedArrayFromArrayLike(target, targetOffset, source). + // 23.2.3.23.2 SetTypedArrayFromArrayLike ( target, targetOffset, source ), https://tc39.es/ecma262/#sec-settypedarrayfromarraylike - auto target_buffer = typed_array->viewed_array_buffer(); + + // 1. Let targetBuffer be target.[[ViewedArrayBuffer]]. + auto* target_buffer = typed_array->viewed_array_buffer(); + + // 2. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception. if (target_buffer->is_detached()) - return vm.throw_completion<JS::TypeError>(global_object, ErrorType::DetachedArrayBuffer); + return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer); + + // 3. Let targetLength be target.[[ArrayLength]]. auto target_length = typed_array->array_length(); + + // 4. Let targetName be the String value of target.[[TypedArrayName]]. + // 5. Let targetElementSize be the Element Size value specified in Table 69 for targetName. + // 6. Let targetType be the Element Type value in Table 69 for targetName. + auto target_element_size = typed_array->element_size(); + + // 7. Let targetByteOffset be target.[[ByteOffset]]. auto target_byte_offset = typed_array->byte_offset(); - auto src = TRY(source.to_object(global_object)); + // 8. Let src be ? ToObject(source). + auto* src = TRY(source.to_object(global_object)); + + // 9. Let srcLength be ? LengthOfArrayLike(src). auto source_length = TRY(length_of_array_like(global_object, *src)); + // 10. If targetOffset is +∞, throw a RangeError exception. if (isinf(target_offset)) - return vm.throw_completion<JS::RangeError>(global_object, "Invalid target offset"); + return vm.throw_completion<RangeError>(global_object, "Invalid target offset"); + // 11. If srcLength + targetOffset > targetLength, throw a RangeError exception. Checked<size_t> checked = source_length; checked += static_cast<u32>(target_offset); if (checked.has_overflow() || checked.value() > target_length) - return vm.throw_completion<JS::RangeError>(global_object, "Overflow or out of bounds in target length"); + return vm.throw_completion<RangeError>(global_object, "Overflow or out of bounds in target length"); + // 12. Let targetByteIndex be targetOffset × targetElementSize + targetByteOffset. Checked<size_t> checked_target_byte_index(static_cast<size_t>(target_offset)); - checked_target_byte_index *= typed_array->element_size(); + checked_target_byte_index *= target_element_size; checked_target_byte_index += target_byte_offset; if (checked_target_byte_index.has_overflow()) - return vm.throw_completion<JS::RangeError>(global_object, "Overflow in target byte index"); + return vm.throw_completion<RangeError>(global_object, "Overflow in target byte index"); auto target_byte_index = checked_target_byte_index.value(); + // 13. Let k be 0. + auto k = 0; + + // 14. Let limit be targetByteIndex + targetElementSize × srcLength. Checked<size_t> checked_limit(source_length); - checked_limit *= typed_array->element_size(); + checked_limit *= target_element_size; checked_limit += target_byte_index; if (checked_limit.has_overflow()) - return vm.throw_completion<JS::RangeError>(global_object, "Overflow in target limit"); - + return vm.throw_completion<RangeError>(global_object, "Overflow in target limit"); auto limit = checked_limit.value(); - auto k = 0; + + // 15. Repeat, while targetByteIndex < limit, while (target_byte_index < limit) { + // a. Let Pk be ! ToString(𝔽(k)). + // b. Let value be ? Get(src, Pk). auto value = TRY(src->get(k)); + + // c. If target.[[ContentType]] is BigInt, set value to ? ToBigInt(value). if (typed_array->content_type() == TypedArrayBase::ContentType::BigInt) value = TRY(value.to_bigint(global_object)); + // d. Otherwise, set value to ? ToNumber(value). else value = TRY(value.to_number(global_object)); + // e. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception. if (target_buffer->is_detached()) - return vm.throw_completion<JS::TypeError>(global_object, ErrorType::DetachedArrayBuffer); + return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer); + // f. Perform SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, Unordered). typed_array->set_value_in_buffer(target_byte_index, value, ArrayBuffer::Unordered); + + // g. Set k to k + 1. ++k; - target_byte_index += typed_array->element_size(); + + // h. Set targetByteIndex to targetByteIndex + targetElementSize. + target_byte_index += target_element_size; } } + + // 8. Return undefined. return js_undefined(); }
51fe25fdbbb7659e94557b0014b20242f2db408c
2021-04-20 03:02:48
Brian Gianforcaro
meta: Stop limiting stale-bot actions per hour.
false
Stop limiting stale-bot actions per hour.
meta
diff --git a/.github/stale.yml b/.github/stale.yml index faad8387acab..406b409d9849 100644 --- a/.github/stale.yml +++ b/.github/stale.yml @@ -45,7 +45,7 @@ closeComment: > Thank you for your contributions! # Limit the number of actions per hour, from 1-30. Default is 30 -limitPerRun: 2 +limitPerRun: 30 # Limit to only `issues` or `pulls` only: pulls
cf985afdcb2fdeaf46f647aeb60ca83f242242f8
2023-09-16 20:23:32
Aliaksandr Kalenik
libweb: Look for targetStepSHE in parent while creating child navigable
false
Look for targetStepSHE in parent while creating child navigable
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp b/Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp index 4af92389a2a3..f20ff41155b4 100644 --- a/Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp +++ b/Userland/Libraries/LibWeb/HTML/NavigableContainer.cpp @@ -109,7 +109,8 @@ WebIDL::ExceptionOr<void> NavigableContainer::create_new_child_navigable() auto parent_doc_state = parent_navigable->active_session_history_entry()->document_state; // 2. Let targetStepSHE be the first session history entry in traversable's session history entries whose document state equals parentDocState. - auto target_step_she = *(traversable->session_history_entries().find_if([parent_doc_state](auto& entry) { + // NOTE: We need to look for parent document state in parent navigable instead of traversable as specification says. https://github.com/whatwg/html/issues/9686 + auto target_step_she = *(parent_navigable->get_session_history_entries().find_if([parent_doc_state](auto& entry) { return entry->document_state == parent_doc_state; }));
a18b37880e6feb1f89ebabdf6a826abdf6f0caf6
2020-01-01 22:18:41
Andrew Kaster
libelf: Add ELFDynamicObject to dynamically load libaries
false
Add ELFDynamicObject to dynamically load libaries
libelf
diff --git a/Libraries/LibELF/ELFDynamicObject.cpp b/Libraries/LibELF/ELFDynamicObject.cpp new file mode 100644 index 000000000000..1cf238ac8807 --- /dev/null +++ b/Libraries/LibELF/ELFDynamicObject.cpp @@ -0,0 +1,608 @@ +#include <AK/StringBuilder.h> +#include <LibELF/ELFDynamicObject.h> + +#include <assert.h> +#include <mman.h> +#include <stdio.h> +#include <stdlib.h> + +#define DYNAMIC_LOAD_DEBUG +//#define DYNAMIC_LOAD_VERBOSE + +#ifdef DYNAMIC_LOAD_VERBOSE +# define VERBOSE(fmt, ...) dbgprintf(fmt, ##__VA_ARGS__) +#else +# define VERBOSE(fmt, ...) do { } while (0) +#endif + +static bool s_always_bind_now = true; + +static const char* name_for_dtag(Elf32_Sword tag); + +// SYSV ELF hash algorithm +// Note that the GNU HASH algorithm has less collisions +static uint32_t calculate_elf_hash(const char* name) +{ + uint32_t hash = 0; + uint32_t top_nibble_of_hash = 0; + + while (*name != '\0') { + hash = hash << 4; + hash += *name; + name++; + + top_nibble_of_hash = hash & 0xF0000000U; + if (top_nibble_of_hash != 0) + hash ^= top_nibble_of_hash >> 24; + hash &= ~top_nibble_of_hash; + } + + return hash; +} + +NonnullRefPtr<ELFDynamicObject> ELFDynamicObject::construct(const char* filename, int fd, size_t size) +{ + return adopt(*new ELFDynamicObject(filename, fd, size)); +} + +ELFDynamicObject::ELFDynamicObject(const char* filename, int fd, size_t size) + : m_filename(filename) + , m_file_size(size) + , m_image_fd(fd) +{ + String file_mmap_name = String::format("ELF_DYN: %s", m_filename.characters()); + + m_file_mapping = mmap_with_name(nullptr, size, PROT_READ, MAP_PRIVATE, m_image_fd, 0, file_mmap_name.characters()); + if (MAP_FAILED == m_file_mapping) { + m_valid = false; + return; + } + + m_image = AK::make<ELFImage>((u8*)m_file_mapping); + + m_valid = m_image->is_valid() && m_image->parse() && m_image->is_dynamic(); + + if (!m_valid) { + return; + } + + const ELFImage::DynamicSection probably_dynamic_section = m_image->dynamic_section(); + if (StringView(".dynamic") != probably_dynamic_section.name() || probably_dynamic_section.type() != SHT_DYNAMIC) { + m_valid = false; + return; + } +} + +ELFDynamicObject::~ELFDynamicObject() +{ + if (MAP_FAILED != m_file_mapping) + munmap(m_file_mapping, m_file_size); +} + +void ELFDynamicObject::dump() +{ + auto dynamic_section = m_image->dynamic_section(); + + StringBuilder builder; + builder.append("\nd_tag tag_name value\n"); + size_t num_dynamic_sections = 0; + + dynamic_section.for_each_dynamic_entry([&](const ELFImage::DynamicSectionEntry& entry) { + String name_field = String::format("(%s)", name_for_dtag(entry.tag())); + builder.appendf("0x%08X %-17s0x%X\n", entry.tag(), name_field.characters(), entry.val()); + num_dynamic_sections++; + return IterationDecision::Continue; + }); + + dbgprintf("Dynamic section at offset 0x%x contains %zu entries:\n", dynamic_section.offset(), num_dynamic_sections); + dbgprintf(builder.to_string().characters()); +} + +void ELFDynamicObject::parse_dynamic_section() +{ + auto dynamic_section = m_image->dynamic_section(); + dynamic_section.for_each_dynamic_entry([&](const ELFImage::DynamicSectionEntry& entry) { + switch (entry.tag()) { + case DT_INIT: + m_init_offset = entry.ptr(); + break; + case DT_FINI: + m_fini_offset = entry.ptr(); + break; + case DT_INIT_ARRAY: + m_init_array_offset = entry.ptr(); + break; + case DT_INIT_ARRAYSZ: + m_init_array_size = entry.val(); + break; + case DT_HASH: + m_hash_table_offset = entry.ptr(); + break; + case DT_SYMTAB: + m_symbol_table_offset = entry.ptr(); + break; + case DT_STRTAB: + m_string_table_offset = entry.ptr(); + break; + case DT_STRSZ: + m_size_of_string_table = entry.val(); + break; + case DT_SYMENT: + m_size_of_symbol_table_entry = entry.val(); + break; + case DT_PLTGOT: + m_procedure_linkage_table_offset = entry.ptr(); + break; + case DT_PLTRELSZ: + m_size_of_plt_relocation_entry_list = entry.val(); + break; + case DT_PLTREL: + m_procedure_linkage_table_relocation_type = entry.val(); + ASSERT(m_procedure_linkage_table_relocation_type & (DT_REL | DT_RELA)); + break; + case DT_JMPREL: + m_plt_relocation_offset_location = entry.ptr(); + break; + case DT_RELA: + case DT_REL: + m_relocation_table_offset = entry.ptr(); + break; + case DT_RELASZ: + case DT_RELSZ: + m_size_of_relocation_table = entry.val(); + break; + case DT_RELAENT: + case DT_RELENT: + m_size_of_relocation_entry = entry.val(); + break; + case DT_RELACOUNT: + case DT_RELCOUNT: + m_number_of_relocations = entry.val(); + break; + case DT_FLAGS: + m_must_bind_now = entry.val() & DF_BIND_NOW; + m_has_text_relocations = entry.val() & DF_TEXTREL; + m_should_process_origin = entry.val() & DF_ORIGIN; + m_has_static_thread_local_storage = entry.val() & DF_STATIC_TLS; + m_requires_symbolic_symbol_resolution = entry.val() & DF_SYMBOLIC; + break; + case DT_TEXTREL: + m_has_text_relocations = true; // This tag seems to exist for legacy reasons only? + break; + default: + dbgprintf("ELFDynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag())); + printf("ELFDynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag())); + ASSERT_NOT_REACHED(); // FIXME: Maybe just break out here and return false? + break; + } + return IterationDecision::Continue; + }); +} + +typedef void (*InitFunc)(); + +bool ELFDynamicObject::load(unsigned flags) +{ + ASSERT(flags & RTLD_GLOBAL); + ASSERT(flags & RTLD_LAZY); + +#ifdef DYNAMIC_LOAD_DEBUG + dump(); +#endif +#ifdef DYNAMIC_LOAD_VERBOSE + m_image->dump(); +#endif + + parse_dynamic_section(); + + // FIXME: be more flexible? + size_t total_required_allocation_size = 0; + + // FIXME: Can we re-use ELFLoader? This and what follows looks a lot like what's in there... + // With the exception of using desired_load_address().offset(text_segment_begin) + // It seems kinda gross to expect the program headers to be in a specific order.. + m_image->for_each_program_header([&](const ELFImage::ProgramHeader& program_header) { + ProgramHeaderRegion new_region(program_header.raw_header()); + if (new_region.is_load()) + total_required_allocation_size += new_region.required_load_size(); + m_program_header_regions.append(move(new_region)); + auto& region = m_program_header_regions.last(); + if (region.is_tls_template()) + m_tls_region = &region; + else if (region.is_load()) { + if (region.is_executable()) + m_text_region = &region; + else + m_data_region = &region; + } + }); + + ASSERT(m_text_region && m_data_region); + + // Process regions in order: .text, .data, .tls + auto* region = m_text_region; + void* text_segment_begin = mmap_with_name(nullptr, region->required_load_size(), region->mmap_prot(), MAP_PRIVATE, m_image_fd, region->offset(), String::format(".text: %s", m_filename.characters()).characters()); + size_t text_segment_size = region->required_load_size(); + region->set_base_address(VirtualAddress { (u32)text_segment_begin }); + region->set_load_address(VirtualAddress { (u32)text_segment_begin }); + + region = m_data_region; + void* data_segment_begin = mmap_with_name((u8*)text_segment_begin + text_segment_size, region->required_load_size(), region->mmap_prot(), MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, String::format(".data: %s", m_filename.characters()).characters()); + size_t data_segment_size = region->required_load_size(); + VirtualAddress data_segment_actual_addr = region->desired_load_address().offset((u32)text_segment_begin); + region->set_base_address(VirtualAddress { (u32)text_segment_begin }); + region->set_load_address(data_segment_actual_addr); + memcpy(data_segment_actual_addr.as_ptr(), (u8*)m_file_mapping + region->offset(), region->size_in_image()); + + if (m_tls_region) { + region = m_data_region; + VirtualAddress tls_segment_actual_addr = region->desired_load_address().offset((u32)text_segment_begin); + region->set_base_address(VirtualAddress { (u32)text_segment_begin }); + region->set_load_address(tls_segment_actual_addr); + memcpy(tls_segment_actual_addr.as_ptr(), (u8*)m_file_mapping + region->offset(), region->size_in_image()); + } + + // sanity check + u8* end_of_in_memory_image = (u8*)data_segment_begin + data_segment_size; + ASSERT((ptrdiff_t)total_required_allocation_size == (ptrdiff_t)(end_of_in_memory_image - (u8*)text_segment_begin)); + + if (m_has_text_relocations) { + if (0 > mprotect(m_text_region->load_address().as_ptr(), m_text_region->required_load_size(), PROT_READ | PROT_WRITE)) { + perror("mprotect"); // FIXME: dlerror? + return false; + } + } + + do_relocations(); + +#ifdef DYNAMIC_LOAD_DEBUG + dbgprintf("Done relocating!\n"); +#endif + + // FIXME: PLT patching doesn't seem to work as expected. + // Need to dig into the spec to see what we're doing wrong + // Hopefully it won't need an assembly entry point... :/ + /// For now we can just BIND_NOW every time + + // This should be the address of section ".got.plt" + const ELFImage::Section& got_section = m_image->lookup_section(".got.plt"); + VirtualAddress got_address = m_text_region->load_address().offset(got_section.address()); + + u32* got_u32_ptr = reinterpret_cast<u32*>(got_address.as_ptr()); + got_u32_ptr[1] = (u32)this; + got_u32_ptr[2] = (u32)&ELFDynamicObject::patch_plt_entry; + +#ifdef DYNAMIC_LOAD_DEBUG + dbgprintf("Set GOT PLT entries at %p: [0] = %p [1] = %p, [2] = %p\n", got_u32_ptr, got_u32_ptr[0], got_u32_ptr[1], got_u32_ptr[2]); +#endif + + // Clean up our setting of .text to PROT_READ | PROT_WRITE + if (m_has_text_relocations) { + if (0 > mprotect(m_text_region->load_address().as_ptr(), m_text_region->required_load_size(), PROT_READ | PROT_EXEC)) { + perror("mprotect"); // FIXME: dlerror? + return false; + } + } + + u8* load_addr = m_text_region->load_address().as_ptr(); + InitFunc init_function = (InitFunc)(load_addr + m_init_offset); + +#ifdef DYNAMIC_LOAD_DEBUG + dbgprintf("Calling DT_INIT at %p\n", init_function); +#endif + // FIXME: + // Disassembly of section .init: + // + // 00007e98 <_init>: + // 7e98: 55 push ebp + // + // Where da ret at? related to -nostartfiles for sure... + //(init_function)(); + + InitFunc* init_begin = (InitFunc*)(load_addr + m_init_array_offset); + u32 init_end = (u32)((u8*)init_begin + m_init_array_size); + while ((u32)init_begin < init_end) { + // Andriod sources claim that these can be -1, to be ignored. + // 0 definitely shows up. Apparently 0/-1 are valid? Confusing. + if (!*init_begin || ((i32)*init_begin == -1)) + continue; +#ifdef DYNAMIC_LOAD_DEBUG + dbgprintf("Calling DT_INITARRAY entry at %p\n", *init_begin); +#endif + (*init_begin)(); + ++init_begin; + } + +#ifdef DYNAMIC_LOAD_DEBUG + dbgprintf("Loaded %s\n", m_filename.characters()); +#endif + // FIXME: return false sometimes? missing symbol etc + return true; +} + +void* ELFDynamicObject::symbol_for_name(const char* name) +{ + // FIXME: If we enable gnu hash in the compiler, we should use that here instead + // The algo is way better with less collisions + uint32_t hash_value = calculate_elf_hash(name); + + u8* load_addr = m_text_region->load_address().as_ptr(); + + // NOTE: We need to use the loaded hash/string/symbol tables here to get the right + // addresses. The ones that are in the ELFImage won't cut it, they aren't relocated + u32* hash_table_begin = (u32*)(load_addr + m_hash_table_offset); + Elf32_Sym* symtab = (Elf32_Sym*)(load_addr + m_symbol_table_offset); + const char* strtab = (const char*)load_addr + m_string_table_offset; + + size_t num_buckets = hash_table_begin[0]; + + // This is here for completeness, but, since we're using the fact that every chain + // will end at chain 0 (which means 'not found'), we don't need to check num_chains. + // Interestingly, num_chains is required to be num_symbols + //size_t num_chains = hash_table_begin[1]; + + u32* buckets = &hash_table_begin[2]; + u32* chains = &buckets[num_buckets]; + + for (u32 i = buckets[hash_value % num_buckets]; i; i = chains[i]) { + if (strcmp(name, strtab + symtab[i].st_name) == 0) { + void* retval = load_addr + symtab[i].st_value; +#ifdef DYNAMIC_LOAD_DEBUG + dbgprintf("Returning dynamic symbol with index %d for %s: %p\n", i, strtab + symtab[i].st_name, retval); +#endif + return retval; + } + } + + return nullptr; +} + +// offset is from PLT entry +// Tag is inserted into GOT #2 for 'this' DSO (literally the this pointer) +void ELFDynamicObject::patch_plt_entry(u32 got_offset, void* dso_got_tag) +{ + // FIXME: This is never called :( + CRASH(); + dbgprintf("------ PATCHING PLT ENTRY -------"); + // NOTE: We put 'this' into the GOT when we loaded it into memory + auto* dynamic_object_object = reinterpret_cast<ELFDynamicObject*>(dso_got_tag); + + // FIXME: might actually be a RelA, check m_plt_relocation_type + // u32 base_addr_offset = dynamic_object_object->m_relocation_table_offset + got_offset; + // Elf32_Rel relocation = *reinterpret_cast<Elf32_Rel*>(&((u8*)dynamic_object_object->m_file_mapping)[base_addr_offset]); + u32 relocation_index = got_offset / dynamic_object_object->m_size_of_relocation_entry; + auto relocation = dynamic_object_object->m_image->dynamic_relocation_section().relocation(relocation_index); + + ASSERT(relocation.type() == R_386_JMP_SLOT); + + auto sym = relocation.symbol(); + + auto* text_load_address = dynamic_object_object->m_text_region->load_address().as_ptr(); + u8* relocation_address = text_load_address + relocation.offset(); + + if (0 > mprotect(text_load_address, dynamic_object_object->m_text_region->required_load_size(), PROT_READ | PROT_WRITE)) { + ASSERT_NOT_REACHED(); // uh oh, no can do boss + } + + dbgprintf("Found relocation address: %p for %s", relocation_address, sym.name()); + + *(u32*)relocation_address = (u32)(text_load_address + sym.value()); + + if (0 > mprotect(text_load_address, dynamic_object_object->m_text_region->required_load_size(), PROT_READ | PROT_EXEC)) { + ASSERT_NOT_REACHED(); // uh oh, no can do boss + } + + CRASH(); + // FIXME: Call the relocated method here? +} + +void ELFDynamicObject::do_relocations() +{ + auto dyn_relocation_section = m_image->dynamic_relocation_section(); + if (StringView(".rel.dyn") != dyn_relocation_section.name() || SHT_REL != dyn_relocation_section.type()) { + ASSERT_NOT_REACHED(); + } + + u8* load_base_address = m_text_region->base_address().as_ptr(); + + int i = -1; + + // FIXME: We should really bail on undefined symbols here. (but, there's some TLS vars that are currently undef soooo.... :) ) + + dyn_relocation_section.for_each_relocation([&](const ELFImage::DynamicRelocation& relocation) { + ++i; + VERBOSE("====== RELOCATION %d: offset 0x%08X, type %d, symidx %08X\n", i, relocation.offset(), relocation.type(), relocation.symbol_index()); + u32* patch_ptr = (u32*)(load_base_address + relocation.offset()); + switch (relocation.type()) { + case R_386_NONE: + // Apparently most loaders will just skip these? + // Seems if the 'link editor' generates one something is funky with your code + VERBOSE("None relocation. No symbol, no nothin.\n"); + break; + case R_386_32: { + auto symbol = relocation.symbol(); + + VERBOSE("Absolute relocation: name: '%s', value: %p\n", symbol.name(), symbol.value()); + if (symbol.bind() == STB_LOCAL) { + u32 symbol_address = symbol.section().address() + symbol.value(); + *patch_ptr += symbol_address; + } else if (symbol.bind() == STB_GLOBAL) { + u32 symbol_address = symbol.value() + (u32)load_base_address; + *patch_ptr += symbol_address; + } else if (symbol.bind() == STB_WEAK) { + // FIXME: Handle weak symbols... + dbgprintf("ELFDynamicObject: Ignoring weak symbol %s\n", symbol.name()); + } else { + VERBOSE("Found new fun symbol bind value %d\n", symbol.bind()); + ASSERT_NOT_REACHED(); + } + VERBOSE(" Symbol address: %p\n", *patch_ptr); + break; + } + case R_386_PC32: { + auto symbol = relocation.symbol(); + VERBOSE("PC-relative relocation: '%s', value: %p\n", symbol.name(), symbol.value()); + u32 relative_offset = (symbol.value() - relocation.offset()); + *patch_ptr += relative_offset; + VERBOSE(" Symbol address: %p\n", *patch_ptr); + break; + } + case R_386_GLOB_DAT: { + auto symbol = relocation.symbol(); + VERBOSE("Global data relocation: '%s', value: %p\n", symbol.name(), symbol.value()); + u32 symbol_location = (u32)(m_data_region->base_address().as_ptr() + symbol.value()); + *patch_ptr = symbol_location; + VERBOSE(" Symbol address: %p\n", *patch_ptr); + break; + } + case R_386_RELATIVE: { + // FIXME: According to the spec, R_386_relative ones must be done first. + // We could explicitly do them first using m_number_of_relocatoins from DT_RELCOUNT + // However, our compiler is nice enough to put them at the front of the relocations for us :) + VERBOSE("Load address relocation at offset %X\n", relocation.offset()); + VERBOSE(" patch ptr == %p, adding load base address (%p) to it and storing %p\n", *patch_ptr, load_base_address, *patch_ptr + (u32)load_base_address); + *patch_ptr += (u32)load_base_address; // + addend for RelA (addend for Rel is stored at addr) + break; + } + case R_386_TLS_TPOFF: { + VERBOSE("Relocation type: R_386_TLS_TPOFF at offset %X\n", relocation.offset()); + // FIXME: this can't be right? I have no idea what "negative offset into TLS storage" means... + // FIXME: Check m_has_static_tls and do something different for dynamic TLS + VirtualAddress tls_region_loctation = m_tls_region->desired_load_address(); + *patch_ptr = relocation.offset() - (u32)tls_region_loctation.as_ptr() - *patch_ptr; + break; + } + default: + // Raise the alarm! Someone needs to implement this relocation type + dbgprintf("Found a new exciting relocation type %d\n", relocation.type()); + printf("ELFDynamicObject: Found unknown relocation type %d\n", relocation.type()); + ASSERT_NOT_REACHED(); + break; + } + return IterationDecision::Continue; + }); + + // FIXME: Or BIND_NOW flag passed in? + if (m_must_bind_now || s_always_bind_now) { + // FIXME: Why do we keep jumping to the entry in the GOT without going to our callback first? + // that would make this s_always_bind_now redundant + + for (size_t idx = 0; idx < m_size_of_plt_relocation_entry_list; idx += m_size_of_relocation_entry) { + VirtualAddress relocation_vaddr = m_text_region->load_address().offset(m_plt_relocation_offset_location).offset(idx); + Elf32_Rel* jump_slot_relocation = (Elf32_Rel*)relocation_vaddr.as_ptr(); + + ASSERT(ELF32_R_TYPE(jump_slot_relocation->r_info) == R_386_JMP_SLOT); + + auto sym = m_image->dynamic_symbol(ELF32_R_SYM(jump_slot_relocation->r_info)); + + auto* image_base_address = m_text_region->base_address().as_ptr(); + u8* relocation_address = image_base_address + jump_slot_relocation->r_offset; + u32 symbol_location = (u32)(image_base_address + sym.value()); + + VERBOSE("ELFDynamicObject: Jump slot relocation: putting %s (%p) into PLT at %p\n", sym.name(), symbol_location, relocation_address); + + *(u32*)relocation_address = symbol_location; + } + } +} + +u32 ELFDynamicObject::ProgramHeaderRegion::mmap_prot() const +{ + int prot = 0; + prot |= is_executable() ? PROT_EXEC : 0; + prot |= is_readable() ? PROT_READ : 0; + prot |= is_writable() ? PROT_WRITE : 0; + return prot; +} + +static const char* name_for_dtag(Elf32_Sword d_tag) +{ + switch (d_tag) { + case DT_NULL: + return "NULL"; /* marks end of _DYNAMIC array */ + case DT_NEEDED: + return "NEEDED"; /* string table offset of needed lib */ + case DT_PLTRELSZ: + return "PLTRELSZ"; /* size of relocation entries in PLT */ + case DT_PLTGOT: + return "PLTGOT"; /* address PLT/GOT */ + case DT_HASH: + return "HASH"; /* address of symbol hash table */ + case DT_STRTAB: + return "STRTAB"; /* address of string table */ + case DT_SYMTAB: + return "SYMTAB"; /* address of symbol table */ + case DT_RELA: + return "RELA"; /* address of relocation table */ + case DT_RELASZ: + return "RELASZ"; /* size of relocation table */ + case DT_RELAENT: + return "RELAENT"; /* size of relocation entry */ + case DT_STRSZ: + return "STRSZ"; /* size of string table */ + case DT_SYMENT: + return "SYMENT"; /* size of symbol table entry */ + case DT_INIT: + return "INIT"; /* address of initialization func. */ + case DT_FINI: + return "FINI"; /* address of termination function */ + case DT_SONAME: + return "SONAME"; /* string table offset of shared obj */ + case DT_RPATH: + return "RPATH"; /* string table offset of library search path */ + case DT_SYMBOLIC: + return "SYMBOLIC"; /* start sym search in shared obj. */ + case DT_REL: + return "REL"; /* address of rel. tbl. w addends */ + case DT_RELSZ: + return "RELSZ"; /* size of DT_REL relocation table */ + case DT_RELENT: + return "RELENT"; /* size of DT_REL relocation entry */ + case DT_PLTREL: + return "PLTREL"; /* PLT referenced relocation entry */ + case DT_DEBUG: + return "DEBUG"; /* bugger */ + case DT_TEXTREL: + return "TEXTREL"; /* Allow rel. mod. to unwritable seg */ + case DT_JMPREL: + return "JMPREL"; /* add. of PLT's relocation entries */ + case DT_BIND_NOW: + return "BIND_NOW"; /* Bind now regardless of env setting */ + case DT_INIT_ARRAY: + return "INIT_ARRAY"; /* address of array of init func */ + case DT_FINI_ARRAY: + return "FINI_ARRAY"; /* address of array of term func */ + case DT_INIT_ARRAYSZ: + return "INIT_ARRAYSZ"; /* size of array of init func */ + case DT_FINI_ARRAYSZ: + return "FINI_ARRAYSZ"; /* size of array of term func */ + case DT_RUNPATH: + return "RUNPATH"; /* strtab offset of lib search path */ + case DT_FLAGS: + return "FLAGS"; /* Set of DF_* flags */ + case DT_ENCODING: + return "ENCODING"; /* further DT_* follow encoding rules */ + case DT_PREINIT_ARRAY: + return "PREINIT_ARRAY"; /* address of array of preinit func */ + case DT_PREINIT_ARRAYSZ: + return "PREINIT_ARRAYSZ"; /* size of array of preinit func */ + case DT_LOOS: + return "LOOS"; /* reserved range for OS */ + case DT_HIOS: + return "HIOS"; /* specific dynamic array tags */ + case DT_LOPROC: + return "LOPROC"; /* reserved range for processor */ + case DT_HIPROC: + return "HIPROC"; /* specific dynamic array tags */ + case DT_GNU_HASH: + return "GNU_HASH"; /* address of GNU hash table */ + case DT_RELACOUNT: + return "RELACOUNT"; /* if present, number of RELATIVE */ + case DT_RELCOUNT: + return "RELCOUNT"; /* relocs, which must come first */ + case DT_FLAGS_1: + return "FLAGS_1"; + default: + return "??"; + } +} diff --git a/Libraries/LibELF/ELFDynamicObject.h b/Libraries/LibELF/ELFDynamicObject.h new file mode 100644 index 000000000000..98f09e9b1a41 --- /dev/null +++ b/Libraries/LibELF/ELFDynamicObject.h @@ -0,0 +1,122 @@ +#pragma once + +#include <LibELF/ELFImage.h> +#include <LibELF/exec_elf.h> +#include <dlfcn.h> +#include <mman.h> + +#include <AK/OwnPtr.h> +#include <AK/RefCounted.h> +#include <AK/String.h> + +#define ALIGN_ROUND_UP(x, align) ((((size_t)(x)) + align - 1) & (~(align - 1))) + +class ELFDynamicObject : public RefCounted<ELFDynamicObject> { +public: + static NonnullRefPtr<ELFDynamicObject> construct(const char* filename, int fd, size_t file_size); + + ~ELFDynamicObject(); + + bool is_valid() const { return m_valid; } + + // FIXME: How can we resolve all of the symbols without having the original elf image for our process? + // RTLD_LAZY only at first probably... though variables ('objects') need resolved at load time every time + bool load(unsigned flags); + + // Intended for use by dlsym or other internal methods + void* symbol_for_name(const char*); + + void dump(); + +private: + class ProgramHeaderRegion { + public: + ProgramHeaderRegion(const Elf32_Phdr& header) + : m_program_header(header) + { + } + + VirtualAddress load_address() const { return m_load_address; } + VirtualAddress base_address() const { return m_image_base_address; } + + void set_load_address(VirtualAddress addr) { m_load_address = addr; } + void set_base_address(VirtualAddress addr) { m_image_base_address = addr; } + + // Information from ELF Program header + u32 type() const { return m_program_header.p_type; } + u32 flags() const { return m_program_header.p_flags; } + u32 offset() const { return m_program_header.p_offset; } + VirtualAddress desired_load_address() const { return VirtualAddress(m_program_header.p_vaddr); } + u32 size_in_memory() const { return m_program_header.p_memsz; } + u32 size_in_image() const { return m_program_header.p_filesz; } + u32 alignment() const { return m_program_header.p_align; } + u32 mmap_prot() const; + bool is_readable() const { return flags() & PF_R; } + bool is_writable() const { return flags() & PF_W; } + bool is_executable() const { return flags() & PF_X; } + bool is_tls_template() const { return type() == PT_TLS; } + bool is_load() const { return type() == PT_LOAD; } + bool is_dynamic() const { return type() == PT_DYNAMIC; } + + u32 required_load_size() { return ALIGN_ROUND_UP(m_program_header.p_memsz, m_program_header.p_align); } + + private: + Elf32_Phdr m_program_header; // Explictly a copy of the PHDR in the image + VirtualAddress m_load_address { 0 }; + VirtualAddress m_image_base_address { 0 }; + }; + + explicit ELFDynamicObject(const char* filename, int fd, size_t file_size); + + String m_filename; + size_t m_file_size { 0 }; + int m_image_fd { -1 }; + void* m_file_mapping { nullptr }; + bool m_valid { false }; + + OwnPtr<ELFImage> m_image; + + void parse_dynamic_section(); + void do_relocations(); + + static void patch_plt_entry(u32 got_offset, void* dso_got_tag); + + Vector<ProgramHeaderRegion> m_program_header_regions; + ProgramHeaderRegion* m_text_region { nullptr }; + ProgramHeaderRegion* m_data_region { nullptr }; + ProgramHeaderRegion* m_tls_region { nullptr }; + + // Begin Section information collected from DT_* entries + uintptr_t m_init_offset { 0 }; + uintptr_t m_fini_offset { 0 }; + + uintptr_t m_init_array_offset { 0 }; + size_t m_init_array_size { 0 }; + + uintptr_t m_hash_table_offset { 0 }; + + uintptr_t m_string_table_offset { 0 }; + uintptr_t m_symbol_table_offset { 0 }; + size_t m_size_of_string_table { 0 }; + size_t m_size_of_symbol_table_entry { 0 }; + + Elf32_Sword m_procedure_linkage_table_relocation_type { -1 }; + uintptr_t m_plt_relocation_offset_location { 0 }; // offset of PLT relocations, at end of relocations + size_t m_size_of_plt_relocation_entry_list { 0 }; + uintptr_t m_procedure_linkage_table_offset { 0 }; + + // NOTE: We'll only ever either RELA or REL entries, not both (thank god) + size_t m_number_of_relocations { 0 }; + size_t m_size_of_relocation_entry { 0 }; + size_t m_size_of_relocation_table { 0 }; + uintptr_t m_relocation_table_offset { 0 }; + + // DT_FLAGS + bool m_should_process_origin = false; + bool m_requires_symbolic_symbol_resolution = false; + // Text relocations meaning: we need to edit the .text section which is normally mapped PROT_READ + bool m_has_text_relocations = false; + bool m_must_bind_now = false; // FIXME: control with an environment var as well? + bool m_has_static_thread_local_storage = false; + // End Section information from DT_* entries +}; diff --git a/Libraries/LibELF/ELFImage.cpp b/Libraries/LibELF/ELFImage.cpp index dfd9cb73b861..832711afbce4 100644 --- a/Libraries/LibELF/ELFImage.cpp +++ b/Libraries/LibELF/ELFImage.cpp @@ -43,6 +43,11 @@ unsigned ELFImage::symbol_count() const return section(m_symbol_table_section_index).entry_count(); } +unsigned ELFImage::dynamic_symbol_count() const +{ + return section(m_dynamic_symbol_table_section_index).entry_count(); +} + void ELFImage::dump() const { dbgprintf("ELFImage{%p} {\n", this); @@ -110,8 +115,25 @@ bool ELFImage::parse() m_symbol_table_section_index = i; } if (sh.sh_type == SHT_STRTAB && i != header().e_shstrndx) { - ASSERT(!m_string_table_section_index || m_string_table_section_index == i); - m_string_table_section_index = i; + if (StringView(".strtab") == section_header_table_string(sh.sh_name)) + m_string_table_section_index = i; + else if (StringView(".dynstr") == section_header_table_string(sh.sh_name)) + m_dynamic_string_table_section_index = i; + else + ASSERT_NOT_REACHED(); + } + if (sh.sh_type == SHT_DYNAMIC) { + ASSERT(!m_dynamic_section_index || m_dynamic_section_index == i); + m_dynamic_section_index = i; + } + if (sh.sh_type == SHT_DYNSYM) { + ASSERT(!m_dynamic_symbol_table_section_index || m_dynamic_symbol_table_section_index == i); + m_dynamic_symbol_table_section_index = i; + } + if (sh.sh_type == SHT_REL) { + if (StringView(".rel.dyn") == section_header_table_string(sh.sh_name)) { + m_dynamic_relocation_section_index = i; + } } } @@ -140,6 +162,14 @@ const char* ELFImage::table_string(unsigned offset) const return raw_data(sh.sh_offset + offset); } +const char* ELFImage::dynamic_table_string(unsigned offset) const +{ + auto& sh = section_header(m_dynamic_string_table_section_index); + if (sh.sh_type != SHT_STRTAB) + return nullptr; + return raw_data(sh.sh_offset + offset); +} + const char* ELFImage::raw_data(unsigned offset) const { return reinterpret_cast<const char*>(m_buffer) + offset; @@ -159,7 +189,7 @@ const Elf32_Phdr& ELFImage::program_header_internal(unsigned index) const const Elf32_Shdr& ELFImage::section_header(unsigned index) const { ASSERT(index < header().e_shnum); - return *reinterpret_cast<const Elf32_Shdr*>(raw_data(header().e_shoff + (index * sizeof(Elf32_Shdr)))); + return *reinterpret_cast<const Elf32_Shdr*>(raw_data(header().e_shoff + (index * header().e_shentsize))); } const ELFImage::Symbol ELFImage::symbol(unsigned index) const @@ -169,6 +199,13 @@ const ELFImage::Symbol ELFImage::symbol(unsigned index) const return Symbol(*this, index, raw_syms[index]); } +const ELFImage::DynamicSymbol ELFImage::dynamic_symbol(unsigned index) const +{ + ASSERT(index < symbol_count()); + auto* raw_syms = reinterpret_cast<const Elf32_Sym*>(raw_data(section(m_dynamic_symbol_table_section_index).offset())); + return DynamicSymbol(*this, index, raw_syms[index]); +} + const ELFImage::Section ELFImage::section(unsigned index) const { ASSERT(index < section_count()); @@ -188,6 +225,13 @@ const ELFImage::Relocation ELFImage::RelocationSection::relocation(unsigned inde return Relocation(m_image, rels[index]); } +const ELFImage::DynamicRelocation ELFImage::DynamicRelocationSection::relocation(unsigned index) const +{ + ASSERT(index < relocation_count()); + auto* rels = reinterpret_cast<const Elf32_Rel*>(m_image.raw_data(offset())); + return DynamicRelocation(m_image, rels[index]); +} + const ELFImage::RelocationSection ELFImage::Section::relocations() const { // FIXME: This is ugly. @@ -213,3 +257,15 @@ const ELFImage::Section ELFImage::lookup_section(const char* name) const return section((*it).value); return section(0); } + +const ELFImage::DynamicSection ELFImage::dynamic_section() const +{ + ASSERT(is_dynamic()); + return section(m_dynamic_section_index); +} + +const ELFImage::DynamicRelocationSection ELFImage::dynamic_relocation_section() const +{ + ASSERT(is_dynamic()); + return section(m_dynamic_relocation_section_index); +} diff --git a/Libraries/LibELF/ELFImage.h b/Libraries/LibELF/ELFImage.h index 5ca519e2c54d..e30e2a71e09f 100644 --- a/Libraries/LibELF/ELFImage.h +++ b/Libraries/LibELF/ELFImage.h @@ -16,8 +16,13 @@ class ELFImage { class Section; class RelocationSection; + class DynamicRelocationSection; class Symbol; + class DynamicSymbol; class Relocation; + class DynamicRelocation; + class DynamicSection; + class DynamicSectionEntry; class Symbol { public: @@ -45,6 +50,32 @@ class ELFImage { const unsigned m_index; }; + class DynamicSymbol { + public: + DynamicSymbol(const ELFImage& image, unsigned index, const Elf32_Sym& sym) + : m_image(image) + , m_sym(sym) + , m_index(index) + { + } + + ~DynamicSymbol() {} + + const char* name() const { return m_image.dynamic_table_string(m_sym.st_name); } + unsigned section_index() const { return m_sym.st_shndx; } + unsigned value() const { return m_sym.st_value; } + unsigned size() const { return m_sym.st_size; } + unsigned index() const { return m_index; } + unsigned type() const { return ELF32_ST_TYPE(m_sym.st_info); } + unsigned bind() const { return ELF32_ST_BIND(m_sym.st_info); } + const Section section() const { return m_image.section(section_index()); } + + private: + const ELFImage& m_image; + const Elf32_Sym& m_sym; + const unsigned m_index; + }; + class ProgramHeader { public: ProgramHeader(const ELFImage& image, unsigned program_header_index) @@ -67,6 +98,7 @@ class ELFImage { bool is_writable() const { return flags() & PF_W; } bool is_executable() const { return flags() & PF_X; } const char* raw_data() const { return m_image.raw_data(m_program_header.p_offset); } + Elf32_Phdr raw_header() const { return m_program_header; } private: const ELFImage& m_image; @@ -100,6 +132,8 @@ class ELFImage { protected: friend class RelocationSection; + friend class DynamicSection; + friend class DynamicRelocationSection; const ELFImage& m_image; const Elf32_Shdr& m_section_header; unsigned m_section_index; @@ -117,6 +151,38 @@ class ELFImage { void for_each_relocation(F) const; }; + class DynamicRelocationSection : public Section { + public: + DynamicRelocationSection(const Section& section) + : Section(section.m_image, section.m_section_index) + { + } + unsigned relocation_count() const { return entry_count(); } + const DynamicRelocation relocation(unsigned index) const; + template<typename F> + void for_each_relocation(F) const; + }; + + class DynamicRelocation { + public: + DynamicRelocation(const ELFImage& image, const Elf32_Rel& rel) + : m_image(image) + , m_rel(rel) + { + } + + ~DynamicRelocation() {} + + unsigned offset() const { return m_rel.r_offset; } + unsigned type() const { return ELF32_R_TYPE(m_rel.r_info); } + unsigned symbol_index() const { return ELF32_R_SYM(m_rel.r_info); } + const DynamicSymbol symbol() const { return m_image.dynamic_symbol(symbol_index()); } + + private: + const ELFImage& m_image; + const Elf32_Rel& m_rel; + }; + class Relocation { public: Relocation(const ELFImage& image, const Elf32_Rel& rel) @@ -137,13 +203,48 @@ class ELFImage { const Elf32_Rel& m_rel; }; + class DynamicSection : public Section { + public: + DynamicSection(const Section& section) + : Section(section.m_image, section.m_section_index) + { + ASSERT(type() == SHT_DYNAMIC); + } + + template<typename F> + void for_each_dynamic_entry(F) const; + }; + + class DynamicSectionEntry { + public: + DynamicSectionEntry(const ELFImage& image, const Elf32_Dyn& dyn) + : m_image(image) + , m_dyn(dyn) + { + } + + ~DynamicSectionEntry() {} + + Elf32_Sword tag() const { return m_dyn.d_tag; } + Elf32_Addr ptr() const { return m_dyn.d_un.d_ptr; } + Elf32_Word val() const { return m_dyn.d_un.d_val; } + + private: + const ELFImage& m_image; + const Elf32_Dyn& m_dyn; + }; + unsigned symbol_count() const; + unsigned dynamic_symbol_count() const; unsigned section_count() const; unsigned program_header_count() const; const Symbol symbol(unsigned) const; + const DynamicSymbol dynamic_symbol(unsigned) const; const Section section(unsigned) const; const ProgramHeader program_header(unsigned const) const; + const DynamicSection dynamic_section() const; + const DynamicRelocationSection dynamic_relocation_section() const; template<typename F> void for_each_section(F) const; @@ -152,6 +253,8 @@ class ELFImage { template<typename F> void for_each_symbol(F) const; template<typename F> + void for_each_dynamic_symbol(F) const; + template<typename F> void for_each_program_header(F) const; // NOTE: Returns section(0) if section with name is not found. @@ -160,6 +263,7 @@ class ELFImage { bool is_executable() const { return header().e_type == ET_EXEC; } bool is_relocatable() const { return header().e_type == ET_REL; } + bool is_dynamic() const { return header().e_type == ET_DYN; } VirtualAddress entry() const { return VirtualAddress(header().e_entry); } @@ -172,12 +276,17 @@ class ELFImage { const char* table_string(unsigned offset) const; const char* section_header_table_string(unsigned offset) const; const char* section_index_to_string(unsigned index) const; + const char* dynamic_table_string(unsigned offset) const; const u8* m_buffer { nullptr }; HashMap<String, unsigned> m_sections; bool m_valid { false }; unsigned m_symbol_table_section_index { 0 }; unsigned m_string_table_section_index { 0 }; + unsigned m_dynamic_symbol_table_section_index { 0 }; // .dynsym + unsigned m_dynamic_string_table_section_index { 0 }; // .dynstr + unsigned m_dynamic_section_index { 0 }; // .dynamic + unsigned m_dynamic_relocation_section_index { 0 }; // .rel.dyn }; template<typename F> @@ -208,6 +317,15 @@ inline void ELFImage::RelocationSection::for_each_relocation(F func) const } } +template<typename F> +inline void ELFImage::DynamicRelocationSection::for_each_relocation(F func) const +{ + for (unsigned i = 0; i < relocation_count(); ++i) { + if (func(relocation(i)) == IterationDecision::Break) + break; + } +} + template<typename F> inline void ELFImage::for_each_symbol(F func) const { @@ -217,9 +335,31 @@ inline void ELFImage::for_each_symbol(F func) const } } +template<typename F> +inline void ELFImage::for_each_dynamic_symbol(F func) const +{ + for (unsigned i = 0; i < dynamic_symbol_count(); ++i) { + if (func(symbol(i)) == IterationDecision::Break) + break; + } +} + template<typename F> inline void ELFImage::for_each_program_header(F func) const { for (unsigned i = 0; i < program_header_count(); ++i) func(program_header(i)); } + +template<typename F> +inline void ELFImage::DynamicSection::for_each_dynamic_entry(F func) const +{ + auto* dyns = reinterpret_cast<const Elf32_Dyn*>(m_image.raw_data(offset())); + for (unsigned i = 0;; ++i) { + auto&& dyn = DynamicSectionEntry(m_image, dyns[i]); + if (dyn.tag() == DT_NULL) + break; + if (func(dyn) == IterationDecision::Break) + break; + } +} diff --git a/Libraries/LibELF/exec_elf.h b/Libraries/LibELF/exec_elf.h index 2be5076801fe..9d39ef400523 100644 --- a/Libraries/LibELF/exec_elf.h +++ b/Libraries/LibELF/exec_elf.h @@ -775,7 +775,17 @@ struct elf_args { #define ELF_TARG_VER 1 /* The ver for which this code is intended */ -#define R_386_32 1 -#define R_386_PC32 2 +/* Relocation types */ +#define R_386_NONE 0 +#define R_386_32 1 /* Symbol + Addend */ +#define R_386_PC32 2 /* Symbol + Addend - Section offset */ +#define R_386_GOT32 3 /* Used by build-time linker to create GOT entry */ +#define R_386_PLT32 4 /* Used by build-time linker to create PLT entry */ +#define R_386_COPY 5 /* https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter4-10454.html#chapter4-84604 */ +#define R_386_GLOB_DAT 6 /* Relation b/w GOT entry and symbol */ +#define R_386_JMP_SLOT 7 /* Fixed up by dynamic loader */ +#define R_386_RELATIVE 8 /* Base address + Addned */ +#define R_386_TLS_TPOFF 14 /* Negative offset into the static TLS storage */ + #endif /* _SYS_EXEC_ELF_H_ */
c130fd6993e3fe1186478ce3e44f9a376f587a09
2023-03-08 05:03:34
Linus Groh
libweb: Start generating code for the Window object from IDL :^)
false
Start generating code for the Window object from IDL :^)
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index 6d3b44fd3b5b..0df34e76ebb7 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -1122,6 +1122,8 @@ WebIDL::ExceptionOr<void> Window::initialize_web_interfaces(Badge<WindowEnvironm m_location = MUST_OR_THROW_OOM(heap().allocate<Location>(realm, realm)); m_navigator = MUST_OR_THROW_OOM(heap().allocate<Navigator>(realm, realm)); + MUST_OR_THROW_OOM(Bindings::WindowGlobalMixin::initialize(realm, *this)); + // FIXME: These should be native accessors, not properties define_native_accessor(realm, "top", top_getter, nullptr, JS::Attribute::Enumerable); define_native_accessor(realm, "window", window_getter, {}, JS::Attribute::Enumerable); diff --git a/Userland/Libraries/LibWeb/HTML/Window.h b/Userland/Libraries/LibWeb/HTML/Window.h index f849bad84d96..102d5a446af4 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.h +++ b/Userland/Libraries/LibWeb/HTML/Window.h @@ -23,6 +23,7 @@ #include <LibWeb/HTML/Plugin.h> #include <LibWeb/HTML/Scripting/ImportMap.h> #include <LibWeb/HTML/WindowEventHandlers.h> +#include <LibWeb/Bindings/WindowGlobalMixin.h> namespace Web::HTML { @@ -34,7 +35,8 @@ using TimerHandler = Variant<JS::Handle<WebIDL::CallbackType>, DeprecatedString> class Window final : public DOM::EventTarget , public HTML::GlobalEventHandlers - , public HTML::WindowEventHandlers { + , public HTML::WindowEventHandlers + , public Bindings::WindowGlobalMixin { WEB_PLATFORM_OBJECT(Window, DOM::EventTarget); public: diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake index f54b19580d72..cae18ad00666 100644 --- a/Userland/Libraries/LibWeb/idl_files.cmake +++ b/Userland/Libraries/LibWeb/idl_files.cmake @@ -163,7 +163,7 @@ libweb_js_bindings(HTML/PromiseRejectionEvent) libweb_js_bindings(HTML/Storage) libweb_js_bindings(HTML/SubmitEvent) libweb_js_bindings(HTML/TextMetrics) -libweb_js_bindings(HTML/Window) +libweb_js_bindings(HTML/Window GLOBAL) libweb_js_bindings(HTML/Worker) libweb_js_bindings(HTML/WorkerGlobalScope) libweb_js_bindings(HTML/WorkerLocation)
b060643941c6c7d2dd684eaa8550f1a5ee768f25
2024-01-02 18:46:53
Sönke Holz
kernel: Remove outdated comment from `console_out`
false
Remove outdated comment from `console_out`
kernel
diff --git a/Kernel/kprintf.cpp b/Kernel/kprintf.cpp index c9b0bb28ba6d..ab21e2414ae6 100644 --- a/Kernel/kprintf.cpp +++ b/Kernel/kprintf.cpp @@ -72,8 +72,6 @@ static void console_out(char ch) if (s_serial_debug_enabled) serial_putch(ch); - // It would be bad to reach the assert in ConsoleDevice()::the() and do a stack overflow - if (DeviceManagement::the().is_console_device_attached()) { DeviceManagement::the().console_device().put_char(ch); } else {
7110c0ecb05f0a386f3d66e83a2a2158e1735a43
2022-01-08 16:04:08
Luke Wilde
ports: Update OpenSSL port to version 1.1.1m
false
Update OpenSSL port to version 1.1.1m
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index 1fd78fa025ff..0824f713a6f8 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -130,7 +130,7 @@ Please make sure to keep this list up to date when adding and updating ports. :^ | [`ntbtls`](ntbtls/) | The Not Too Bad TLS Library | 0.2.0 | https://gnupg.org/software/ntbtls/index.html | | [`nyancat`](nyancat/) | Nyancat | | https://github.com/klange/nyancat | | [`openssh`](openssh/) | OpenSSH | 8.3-9ca7e9c | https://github.com/openssh/openssh-portable | -| [`openssl`](openssl/) | OpenSSL | 1.1.1k | https://www.openssl.org/ | +| [`openssl`](openssl/) | OpenSSL | 1.1.1m | https://www.openssl.org/ | | [`openttd`](openttd/) | OpenTTD | 1.11.0 | https://www.openttd.org/ | | [`openttd-opengfx`](openttd-opengfx/) | OpenGFX graphics for OpenTTD | 0.6.1 | https://www.openttd.org/ | | [`openttd-opensfx`](openttd-opensfx/) | OpenSFX audio files for OpenTTD | 1.0.1 | https://www.openttd.org/ | diff --git a/Ports/openssl/package.sh b/Ports/openssl/package.sh index b91b1c9cd637..45b3d6e2a2da 100755 --- a/Ports/openssl/package.sh +++ b/Ports/openssl/package.sh @@ -1,10 +1,10 @@ #!/usr/bin/env -S bash ../.port_include.sh port=openssl branch='1.1.1' -version="${branch}k" +version="${branch}m" useconfigure=true configscript=Configure -files="https://ftp.nluug.nl/security/openssl/openssl-${version}.tar.gz openssl-${version}.tar.gz 892a0875b9872acd04a9fde79b1f943075d5ea162415de3047c327df33fbaee5" +files="https://ftp.nluug.nl/security/openssl/openssl-${version}.tar.gz openssl-${version}.tar.gz f89199be8b23ca45fc7cb9f1d8d3ee67312318286ad030f5316aca6462db6c96" auth_type=sha256 depends=("zlib") diff --git a/Ports/openssl/patches/serenity-configuration.patch b/Ports/openssl/patches/serenity-configuration.patch index a6a9b15ac439..e16e06cfe789 100644 --- a/Ports/openssl/patches/serenity-configuration.patch +++ b/Ports/openssl/patches/serenity-configuration.patch @@ -1,5 +1,5 @@ ---- openssl-1.1.1k/Configurations/10-main.conf 2021-03-25 21:28:38.000000000 +0800 -+++ openssl-1.1.1k/Configurations/10-main.conf 2021-09-26 00:05:04.340004623 +0800 +--- openssl-1.1.1m/Configurations/10-main.conf 2021-03-25 21:28:38.000000000 +0800 ++++ openssl-1.1.1m/Configurations/10-main.conf 2021-09-26 00:05:04.340004623 +0800 @@ -627,6 +627,30 @@ shared_extension => ".so", }, diff --git a/Ports/openssl/patches/shared-info.patch b/Ports/openssl/patches/shared-info.patch index 7921d871daec..b6fa7e8f2264 100644 --- a/Ports/openssl/patches/shared-info.patch +++ b/Ports/openssl/patches/shared-info.patch @@ -1,5 +1,5 @@ ---- openssl-1.1.1k/Configurations/shared-info.pl 2021-03-25 21:28:38.000000000 +0800 -+++ openssl-1.1.1k/Configurations/shared-info.pl 2021-09-26 00:05:04.340004623 +0800 +--- openssl-1.1.1m/Configurations/shared-info.pl 2021-03-25 21:28:38.000000000 +0800 ++++ openssl-1.1.1m/Configurations/shared-info.pl 2021-09-26 00:05:04.340004623 +0800 @@ -34,6 +34,13 @@ shared_defflag => '-Wl,--version-script=', };
5238e38886ba2985d5fa7e71c497c3edb4d059d4
2022-03-01 00:00:35
Idan Horowitz
base: Remove TelnetServer and WebServer from the generated manpage list
false
Remove TelnetServer and WebServer from the generated manpage list
base
diff --git a/Base/root/generate_manpages.sh b/Base/root/generate_manpages.sh index 38e336b9185f..9c07033ffa1a 100755 --- a/Base/root/generate_manpages.sh +++ b/Base/root/generate_manpages.sh @@ -9,8 +9,6 @@ rm -rf generated_manpages || exit 1 for i in ( \ (UserspaceEmulator 1) \ - (TelnetServer 1) \ - (WebServer 1) \ (config 1) \ (fortune 1) \ (grep 1) \
d987ddc0ee080e6c047ac8af4199625f417ba346
2022-12-12 22:31:16
Ali Mohammad Pur
ak: Actually don't include <unistd.h> for windows in Platform.h
false
Actually don't include <unistd.h> for windows in Platform.h
ak
diff --git a/AK/Platform.h b/AK/Platform.h index 534a0ab46b14..f9dd0281bc1b 100644 --- a/AK/Platform.h +++ b/AK/Platform.h @@ -173,14 +173,16 @@ # define PAGE_SIZE 4096 // On macOS (at least Mojave), Apple's version of this header is not wrapped // in extern "C". -# elif defined(AK_OS_MACOS) +# else +# if defined(AK_OS_MACOS) extern "C" { -# endif -# include <unistd.h> -# undef PAGE_SIZE -# define PAGE_SIZE sysconf(_SC_PAGESIZE) -# ifdef AK_OS_MACOS +# endif +# include <unistd.h> +# undef PAGE_SIZE +# define PAGE_SIZE sysconf(_SC_PAGESIZE) +# ifdef AK_OS_MACOS } +# endif # endif #endif
9040194d54de2453f54b3076ee321a5924fe7429
2022-11-26 03:58:39
Zaggy1024
libvideo: Make Matroska Block and Cluster timestamps absolute
false
Make Matroska Block and Cluster timestamps absolute
libvideo
diff --git a/Userland/Libraries/LibVideo/Containers/Matroska/Document.h b/Userland/Libraries/LibVideo/Containers/Matroska/Document.h index eb7d8e24d521..96b2962c744c 100644 --- a/Userland/Libraries/LibVideo/Containers/Matroska/Document.h +++ b/Userland/Libraries/LibVideo/Containers/Matroska/Document.h @@ -12,6 +12,7 @@ #include <AK/NonnullOwnPtrVector.h> #include <AK/OwnPtr.h> #include <AK/String.h> +#include <AK/Time.h> #include <AK/Utf8View.h> #include <LibVideo/Color/CodingIndependentCodePoints.h> @@ -152,8 +153,8 @@ class Block { u64 track_number() const { return m_track_number; } void set_track_number(u64 track_number) { m_track_number = track_number; } - i16 timestamp() const { return m_timestamp; } - void set_timestamp(i16 timestamp) { m_timestamp = timestamp; } + Time timestamp() const { return m_timestamp; } + void set_timestamp(Time timestamp) { m_timestamp = timestamp; } bool only_keyframes() const { return m_only_keyframes; } void set_only_keyframes(bool only_keyframes) { m_only_keyframes = only_keyframes; } bool invisible() const { return m_invisible; } @@ -170,7 +171,7 @@ class Block { private: u64 m_track_number { 0 }; - i16 m_timestamp { 0 }; + Time m_timestamp { Time::zero() }; bool m_only_keyframes { false }; bool m_invisible { false }; Lacing m_lacing { None }; @@ -180,11 +181,11 @@ class Block { class Cluster { public: - u64 timestamp() const { return m_timestamp; } - void set_timestamp(u64 timestamp) { m_timestamp = timestamp; } + Time timestamp() const { return m_timestamp; } + void set_timestamp(Time timestamp) { m_timestamp = timestamp; } private: - u64 m_timestamp; + Time m_timestamp { Time::zero() }; }; } diff --git a/Userland/Libraries/LibVideo/Containers/Matroska/MatroskaDemuxer.cpp b/Userland/Libraries/LibVideo/Containers/Matroska/MatroskaDemuxer.cpp index 04920926f5f2..10984bd6de16 100644 --- a/Userland/Libraries/LibVideo/Containers/Matroska/MatroskaDemuxer.cpp +++ b/Userland/Libraries/LibVideo/Containers/Matroska/MatroskaDemuxer.cpp @@ -72,10 +72,8 @@ DecoderErrorOr<NonnullOwnPtr<Sample>> MatroskaDemuxer::get_next_sample_for_track status.block = TRY(status.iterator.next_block()); status.frame_index = 0; } - auto const& cluster = status.iterator.current_cluster(); - Time timestamp = Time::from_nanoseconds((cluster.timestamp() + status.block->timestamp()) * TRY(m_reader.segment_information()).timestamp_scale()); auto cicp = TRY(m_reader.track_for_track_number(track.identifier())).video_track()->color_format.to_cicp(); - return make<VideoSample>(status.block->frame(status.frame_index++), cicp, timestamp); + return make<VideoSample>(status.block->frame(status.frame_index++), cicp, status.block->timestamp()); } DecoderErrorOr<Time> MatroskaDemuxer::duration() diff --git a/Userland/Libraries/LibVideo/Containers/Matroska/Reader.cpp b/Userland/Libraries/LibVideo/Containers/Matroska/Reader.cpp index 449262f32740..de3c3cc54a95 100644 --- a/Userland/Libraries/LibVideo/Containers/Matroska/Reader.cpp +++ b/Userland/Libraries/LibVideo/Containers/Matroska/Reader.cpp @@ -487,7 +487,7 @@ constexpr size_t get_element_id_size(u32 element_id) return sizeof(element_id) - (count_leading_zeroes(element_id) / 8); } -static DecoderErrorOr<Cluster> parse_cluster(Streamer& streamer) +static DecoderErrorOr<Cluster> parse_cluster(Streamer& streamer, u64 timestamp_scale) { Optional<u64> timestamp; size_t first_element_position = 0; @@ -516,11 +516,11 @@ static DecoderErrorOr<Cluster> parse_cluster(Streamer& streamer) TRY_READ(streamer.seek_to_position(first_element_position)); Cluster cluster; - cluster.set_timestamp(timestamp.release_value()); + cluster.set_timestamp(Time::from_nanoseconds(timestamp.release_value() * timestamp_scale)); return cluster; } -static DecoderErrorOr<Block> parse_simple_block(Streamer& streamer) +static DecoderErrorOr<Block> parse_simple_block(Streamer& streamer, Time cluster_timestamp, u64 timestamp_scale) { Block block; @@ -529,7 +529,7 @@ static DecoderErrorOr<Block> parse_simple_block(Streamer& streamer) auto position_before_track_number = streamer.position(); block.set_track_number(TRY_READ(streamer.read_variable_size_integer())); - block.set_timestamp(TRY_READ(streamer.read_i16())); + block.set_timestamp(cluster_timestamp + Time::from_nanoseconds(TRY_READ(streamer.read_i16()) * timestamp_scale)); auto flags = TRY_READ(streamer.read_octet()); block.set_only_keyframes((flags & (1u << 7u)) != 0); @@ -627,10 +627,10 @@ DecoderErrorOr<Block> SampleIterator::next_block() if (element_id == CLUSTER_ELEMENT_ID) { dbgln_if(MATROSKA_DEBUG, " Iterator is parsing new cluster."); - m_current_cluster = TRY(parse_cluster(streamer)); + m_current_cluster = TRY(parse_cluster(streamer, m_timestamp_scale)); } else if (element_id == SIMPLE_BLOCK_ID) { dbgln_if(MATROSKA_TRACE_DEBUG, " Iterator is parsing new block."); - auto candidate_block = TRY(parse_simple_block(streamer)); + auto candidate_block = TRY(parse_simple_block(streamer, m_current_cluster->timestamp(), m_timestamp_scale)); if (candidate_block.track_number() == m_track_id) block = move(candidate_block); } else { diff --git a/Userland/Utilities/matroska.cpp b/Userland/Utilities/matroska.cpp index 92a40ee8d739..5f287eaac63b 100644 --- a/Userland/Utilities/matroska.cpp +++ b/Userland/Utilities/matroska.cpp @@ -56,7 +56,7 @@ ErrorOr<int> serenity_main(Main::Arguments) return block_result.release_error(); } auto block = block_result.release_value(); - outln("\t\tBlock at timestamp {}:", iterator.current_cluster().timestamp() + block.timestamp()); + outln("\t\tBlock at timestamp {}ms:", block.timestamp().to_milliseconds()); outln("\t\t\tContains {} frames", block.frame_count()); outln("\t\t\tLacing is {}", static_cast<u8>(block.lacing())); }
94236c2532dbac552bad89a691f3adbad4fb273f
2023-09-20 21:59:17
Andreas Kling
libweb: Remove unused "frame nesting" tracking from BrowsingContext
false
Remove unused "frame nesting" tracking from BrowsingContext
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp index 2607de5492d6..0491ba0ea43d 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp @@ -489,16 +489,6 @@ void BrowsingContext::select_all() (void)selection->select_all_children(*document->body()); } -void BrowsingContext::register_frame_nesting(AK::URL const& url) -{ - m_frame_nesting_levels.ensure(url)++; -} - -bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const -{ - return m_frame_nesting_levels.get(url).value_or(0) < 3; -} - bool BrowsingContext::increment_cursor_position_offset() { if (!m_cursor_position.increment_offset()) diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h index df497a804347..b042edadd654 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h @@ -171,12 +171,6 @@ class BrowsingContext final void did_edit(Badge<EditEventHandler>); - void register_frame_nesting(AK::URL const&); - bool is_frame_nesting_allowed(AK::URL const&) const; - - void set_frame_nesting_levels(HashMap<AK::URL, size_t> frame_nesting_levels) { m_frame_nesting_levels = move(frame_nesting_levels); } - HashMap<AK::URL, size_t> const& frame_nesting_levels() const { return m_frame_nesting_levels; } - bool has_a_rendering_opportunity() const; JS::GCPtr<DOM::Node> currently_focused_area(); @@ -255,7 +249,6 @@ class BrowsingContext final RefPtr<Core::Timer> m_cursor_blink_timer; bool m_cursor_blink_state { false }; - HashMap<AK::URL, size_t> m_frame_nesting_levels; DeprecatedString m_name; // https://html.spec.whatwg.org/multipage/browsers.html#tlbc-group
ebc29842c8df22e407f53376e7e90999b3b7ca6d
2022-09-18 00:57:17
Sam Atkins
libweb: Start implementing the IDL Overload Resolution Algorithm :^)
false
Start implementing the IDL Overload Resolution Algorithm :^)
libweb
diff --git a/Userland/Libraries/LibWeb/Bindings/IDLOverloadResolution.cpp b/Userland/Libraries/LibWeb/Bindings/IDLOverloadResolution.cpp new file mode 100644 index 000000000000..e2195a878cc7 --- /dev/null +++ b/Userland/Libraries/LibWeb/Bindings/IDLOverloadResolution.cpp @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2022, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibJS/Runtime/ArrayBuffer.h> +#include <LibJS/Runtime/DataView.h> +#include <LibJS/Runtime/FunctionObject.h> +#include <LibJS/Runtime/TypedArray.h> +#include <LibJS/Runtime/Value.h> +#include <LibWeb/Bindings/IDLOverloadResolution.h> +#include <LibWeb/Bindings/PlatformObject.h> + +namespace Web::Bindings { + +// https://webidl.spec.whatwg.org/#dfn-convert-ecmascript-to-idl-value +static JS::Value convert_ecmascript_type_to_idl_value(JS::Value value, IDL::Type const&) +{ + // FIXME: We have this code already in the code generator, in `generate_to_cpp()`, but how do we use it here? + return value; +} + +template<typename Match> +static bool has_overload_with_argument_type_or_subtype_matching(IDL::EffectiveOverloadSet& overloads, size_t argument_index, Match match) +{ + // NOTE: This is to save some repetition. + // Almost every sub-step of step 12 of the overload resolution algorithm matches overloads with an argument that is: + // - One of several specific types. + // - "an annotated type whose inner type is one of the above types" + // - "a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types" + // So, this function lets you pass in the first check, and handles the others automatically. + + return overloads.has_overload_with_matching_argument_at_index(argument_index, + [match](IDL::Type const& type, auto) { + if (match(type)) + return true; + + // FIXME: - an annotated type whose inner type is one of the above types + + if (type.is_union()) { + auto flattened_members = type.as_union().flattened_member_types(); + for (auto const& member : flattened_members) { + if (match(member)) + return true; + + // FIXME: - an annotated type whose inner type is one of the above types + } + return false; + } + + return false; + }); +} + +// https://webidl.spec.whatwg.org/#es-overloads +JS::ThrowCompletionOr<ResolvedOverload> resolve_overload(JS::VM& vm, IDL::EffectiveOverloadSet& overloads) +{ + // 1. Let maxarg be the length of the longest type list of the entries in S. + // 2. Let n be the size of args. + // 3. Initialize argcount to be min(maxarg, n). + // 4. Remove from S all entries whose type list is not of length argcount. + // NOTE: Our caller already performs these steps, so our effective overload set only contains overloads with the correct number of arguments. + int argument_count = vm.argument_count(); + + // 5. If S is empty, then throw a TypeError. + if (overloads.is_empty()) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::OverloadResolutionFailed); + + // 6. Initialize d to −1. + auto distinguishing_argument_index = -1; + + // 7. Initialize method to undefined. + Optional<JS::FunctionObject&> method; + + // 8. If there is more than one entry in S, then set d to be the distinguishing argument index for the entries of S. + if (overloads.size() > 1) + distinguishing_argument_index = overloads.distinguishing_argument_index(); + + // 9. Initialize values to be an empty list, where each entry will be either an IDL value or the special value “missing”. + Vector<ResolvedOverload::Argument> values; + + // 10. Initialize i to 0. + auto i = 0; + + // 11. While i < d: + while (i < distinguishing_argument_index) { + // 1. Let V be args[i]. + auto const& value = vm.argument(i); + + auto const& item = overloads.items().first(); + + // 2. Let type be the type at index i in the type list of any entry in S. + auto const& type = item.types[i]; + + // 3. Let optionality be the value at index i in the list of optionality values of any entry in S. + auto const& optionality = item.optionality_values[i]; + + // 4. If optionality is “optional” and V is undefined, then: + if (optionality == IDL::Optionality::Optional && value.is_undefined()) { + // FIXME: 1. If the argument at index i is declared with a default value, then append to values that default value. + + // 2. Otherwise, append to values the special value “missing”. + values.empend(ResolvedOverload::Missing {}); + } + + // 5. Otherwise, append to values the result of converting V to IDL type type. + values.empend(convert_ecmascript_type_to_idl_value(value, type)); + + // 6. Set i to i + 1. + ++i; + } + + // 12. If i = d, then: + if (i == distinguishing_argument_index) { + // 1. Let V be args[i]. + auto const& value = vm.argument(i); + + // 2. If V is undefined, and there is an entry in S whose list of optionality values has “optional” at index i, then remove from S all other entries. + if (value.is_undefined() + && overloads.has_overload_with_matching_argument_at_index(i, [](auto&, IDL::Optionality const& optionality) { return optionality == IDL::Optionality::Optional; })) { + overloads.remove_all_other_entries(); + } + + // 3. Otherwise: if V is null or undefined, and there is an entry in S that has one of the following types at position i of its type list, + // - a nullable type + // - a dictionary type + // - an annotated type whose inner type is one of the above types + // - a union type or annotated union type that includes a nullable type or that has a dictionary type in its flattened members + // then remove from S all other entries. + // NOTE: This is the one case we can't use `has_overload_with_argument_type_or_subtype_matching()` because we also need to look + // for dictionary types in the flattened members. + else if ((value.is_undefined() || value.is_null()) + && overloads.has_overload_with_matching_argument_at_index(i, [](IDL::Type const& type, auto) { + if (type.is_nullable()) + return true; + // FIXME: - a dictionary type + // FIXME: - an annotated type whose inner type is one of the above types + if (type.is_union()) { + auto flattened_members = type.as_union().flattened_member_types(); + for (auto const& member : flattened_members) { + if (member.is_nullable()) + return true; + // FIXME: - a dictionary type + // FIXME: - an annotated type whose inner type is one of the above types + } + return false; + } + return false; + })) { + overloads.remove_all_other_entries(); + } + + // 4. Otherwise: if V is a platform object, and there is an entry in S that has one of the following types at position i of its type list, + // - an interface type that V implements + // - object + // - a nullable version of any of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_object() && is<Bindings::PlatformObject>(value.as_object()) + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { + // FIXME: - an interface type that V implements + if (type.is_object()) + return true; + return false; + })) { + overloads.remove_all_other_entries(); + } + + // 5. Otherwise: if Type(V) is Object, V has an [[ArrayBufferData]] internal slot, and there is an entry in S that has one of the following types at position i of its type list, + // - ArrayBuffer + // - object + // - a nullable version of either of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_object() && is<JS::ArrayBuffer>(value.as_object()) + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { + if (type.is_plain() && type.name() == "ArrayBuffer") + return true; + if (type.is_object()) + return true; + return false; + })) { + overloads.remove_all_other_entries(); + } + + // 6. Otherwise: if Type(V) is Object, V has a [[DataView]] internal slot, and there is an entry in S that has one of the following types at position i of its type list, + // - DataView + // - object + // - a nullable version of either of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_object() && is<JS::DataView>(value.as_object()) + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { + if (type.is_plain() && type.name() == "DataView") + return true; + if (type.is_object()) + return true; + return false; + })) { + overloads.remove_all_other_entries(); + } + + // 7. Otherwise: if Type(V) is Object, V has a [[TypedArrayName]] internal slot, and there is an entry in S that has one of the following types at position i of its type list, + // - a typed array type whose name is equal to the value of V’s [[TypedArrayName]] internal slot + // - object + // - a nullable version of either of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_object() && value.as_object().is_typed_array() + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [&](IDL::Type const& type) { + if (type.is_plain() && type.name() == static_cast<JS::TypedArrayBase const&>(value.as_object()).element_name()) + return true; + if (type.is_object()) + return true; + return false; + })) { + overloads.remove_all_other_entries(); + } + + // 8. Otherwise: if IsCallable(V) is true, and there is an entry in S that has one of the following types at position i of its type list, + // - a callback function type + // - object + // - a nullable version of any of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_function() + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { + // FIXME: - a callback function type + if (type.is_object()) + return true; + return false; + })) { + overloads.remove_all_other_entries(); + } + + // FIXME: 9. Otherwise: if Type(V) is Object and there is an entry in S that has one of the following types at position i of its type list, + // - a sequence type + // - a frozen array type + // - a nullable version of any of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // and after performing the following steps, + // { + // 1. Let method be ? GetMethod(V, @@iterator). + // } + // method is not undefined, then remove from S all other entries. + + // 10. Otherwise: if Type(V) is Object and there is an entry in S that has one of the following types at position i of its type list, + // - a callback interface type + // - a dictionary type + // - a record type + // - object + // - a nullable version of any of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_object() + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { + // FIXME: - a callback interface type + // FIXME: - a dictionary type + // FIXME: - a record type + if (type.is_object()) + return true; + return false; + })) { + overloads.remove_all_other_entries(); + } + + // 11. Otherwise: if Type(V) is Boolean and there is an entry in S that has one of the following types at position i of its type list, + // - boolean + // - a nullable boolean + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_boolean() + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_boolean(); })) { + overloads.remove_all_other_entries(); + } + + // 12. Otherwise: if Type(V) is Number and there is an entry in S that has one of the following types at position i of its type list, + // - a numeric type + // - a nullable numeric type + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_number() + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_numeric(); })) { + overloads.remove_all_other_entries(); + } + + // 13. Otherwise: if Type(V) is BigInt and there is an entry in S that has one of the following types at position i of its type list, + // - bigint + // - a nullable bigint + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (value.is_bigint() + && has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_bigint(); })) { + overloads.remove_all_other_entries(); + } + + // 14. Otherwise: if there is an entry in S that has one of the following types at position i of its type list, + // - a string type + // - a nullable version of any of the above types + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_string(); })) { + overloads.remove_all_other_entries(); + } + + // 15. Otherwise: if there is an entry in S that has one of the following types at position i of its type list, + // - a numeric type + // - a nullable numeric type + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_numeric(); })) { + overloads.remove_all_other_entries(); + } + + // 16. Otherwise: if there is an entry in S that has one of the following types at position i of its type list, + // - boolean + // - a nullable boolean + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_boolean(); })) { + overloads.remove_all_other_entries(); + } + + // 17. Otherwise: if there is an entry in S that has one of the following types at position i of its type list, + // - bigint + // - a nullable bigint + // - an annotated type whose inner type is one of the above types + // - a union type, nullable union type, or annotated union type that has one of the above types in its flattened member types + // then remove from S all other entries. + else if (has_overload_with_argument_type_or_subtype_matching(overloads, i, [](IDL::Type const& type) { return type.is_bigint(); })) { + overloads.remove_all_other_entries(); + } + + // 18. Otherwise: if there is an entry in S that has any at position i of its type list, then remove from S all other entries. + else if (overloads.has_overload_with_matching_argument_at_index(i, [](auto const& type, auto) { return type.is_any(); })) { + overloads.remove_all_other_entries(); + } + + // 19. Otherwise: throw a TypeError. + else { + // FIXME: Remove this message once all the above sub-steps are implemented. + dbgln("Failed to determine IDL overload. (Probably because of unimplemented steps.)"); + return vm.throw_completion<JS::TypeError>(JS::ErrorType::OverloadResolutionFailed); + } + } + + // 13. Let callable be the operation or extended attribute of the single entry in S. + auto const& callable = overloads.only_item(); + + // 14. If i = d and method is not undefined, then + if (i == distinguishing_argument_index && method.has_value()) { + // 1. Let V be args[i]. + auto const& value = vm.argument(i); + + // 2. Let T be the type at index i in the type list of the remaining entry in S. + auto const& type = overloads.only_item().types[i]; + + (void)value; + (void)type; + // FIXME: 3. If T is a sequence type, then append to values the result of creating a sequence of type T from V and method. + + // FIXME: 4. Otherwise, T is a frozen array type. Append to values the result of creating a frozen array of type T from V and method. + + // 5. Set i to i + 1. + ++i; + } + + // 15. While i < argcount: + while (i < argument_count) { + // 1. Let V be args[i]. + auto const& value = vm.argument(i); + + // 2. Let type be the type at index i in the type list of the remaining entry in S. + auto const& entry = overloads.only_item(); + auto const& type = entry.types[i]; + + // 3. Let optionality be the value at index i in the list of optionality values of the remaining entry in S. + auto const& optionality = entry.optionality_values[i]; + + // 4. If optionality is “optional” and V is undefined, then: + if (optionality == IDL::Optionality::Optional && value.is_undefined()) { + // FIXME: 1. If the argument at index i is declared with a default value, then append to values that default value. + + // 2. Otherwise, append to values the special value “missing”. + values.empend(ResolvedOverload::Missing {}); + } + + // 5. Otherwise, append to values the result of converting V to IDL type type. + else { + values.append(convert_ecmascript_type_to_idl_value(value, type)); + } + + // 6. Set i to i + 1. + ++i; + } + + // 16. While i is less than the number of arguments callable is declared to take: + while (i < static_cast<int>(callable.types.size())) { + // FIXME: 1. If callable’s argument at index i is declared with a default value, then append to values that default value. + if (false) { + } + + // 2. Otherwise, if callable’s argument at index i is not variadic, then append to values the special value “missing”. + else if (callable.optionality_values[i] != IDL::Optionality::Variadic) { + values.empend(ResolvedOverload::Missing {}); + } + + // 3. Set i to i + 1. + ++i; + } + + // 17. Return the pair <callable, values>. + return ResolvedOverload { callable.callable_id, move(values) }; +} + +} diff --git a/Userland/Libraries/LibWeb/Bindings/IDLOverloadResolution.h b/Userland/Libraries/LibWeb/Bindings/IDLOverloadResolution.h new file mode 100644 index 000000000000..41a2efada0fd --- /dev/null +++ b/Userland/Libraries/LibWeb/Bindings/IDLOverloadResolution.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Optional.h> +#include <AK/Vector.h> +#include <LibIDL/Types.h> +#include <LibJS/Runtime/VM.h> + +namespace Web::Bindings { + +struct ResolvedOverload { + // Corresponds to "the special value “missing”" in the overload resolution algorithm. + struct Missing { }; + using Argument = Variant<JS::Value, Missing>; + + int callable_id; + Vector<Argument> arguments; +}; + +// https://webidl.spec.whatwg.org/#es-overloads +JS::ThrowCompletionOr<ResolvedOverload> resolve_overload(JS::VM&, IDL::EffectiveOverloadSet&); + +} diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 26ea86867b72..223afed183b2 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -6,6 +6,7 @@ set(SOURCES Bindings/CallbackType.cpp Bindings/CrossOriginAbstractOperations.cpp Bindings/IDLAbstractOperations.cpp + Bindings/IDLOverloadResolution.cpp Bindings/ImageConstructor.cpp Bindings/LegacyPlatformObject.cpp Bindings/LocationConstructor.cpp @@ -427,7 +428,7 @@ set(GENERATED_SOURCES serenity_lib(LibWeb web) # NOTE: We link with LibSoftGPU here instead of lazy loading it via dlopen() so that we do not have to unveil the library and pledge prot_exec. -target_link_libraries(LibWeb LibCore LibJS LibMarkdown LibGemini LibGL LibGUI LibGfx LibSoftGPU LibTextCodec LibWasm LibXML) +target_link_libraries(LibWeb LibCore LibJS LibMarkdown LibGemini LibGL LibGUI LibGfx LibSoftGPU LibTextCodec LibWasm LibXML LibIDL) link_with_locale_data(LibWeb) generate_js_wrappers(LibWeb)
a0acb6f058c52cc9baf6bc0f2cc813141ac9fc8a
2021-07-05 06:19:55
Andreas Kling
libjs: Fix accidental west-const in ArgumentsObject
false
Fix accidental west-const in ArgumentsObject
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp b/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp index c49d9719b884..aa8190098abe 100644 --- a/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp @@ -33,7 +33,7 @@ void ArgumentsObject::visit_edges(Cell::Visitor& visitor) } // 10.4.4.3 [[Get]] ( P, Receiver ), https://tc39.es/ecma262/#sec-arguments-exotic-objects-get-p-receiver -Value ArgumentsObject::internal_get(const PropertyName& property_name, Value receiver) const +Value ArgumentsObject::internal_get(PropertyName const& property_name, Value receiver) const { // 1. Let map be args.[[ParameterMap]]. auto& map = *m_parameter_map;
dd5550dde39f177d44cd776ebca033ea99ce5749
2024-08-09 21:49:56
simonkrauter
libwebview: Remove early exit in `InspectorClient::inspect()`
false
Remove early exit in `InspectorClient::inspect()`
libwebview
diff --git a/Userland/Libraries/LibWebView/InspectorClient.cpp b/Userland/Libraries/LibWebView/InspectorClient.cpp index 6b97f3b8c8b9..9f51a34ae7b3 100644 --- a/Userland/Libraries/LibWebView/InspectorClient.cpp +++ b/Userland/Libraries/LibWebView/InspectorClient.cpp @@ -194,8 +194,6 @@ void InspectorClient::inspect() { if (!m_inspector_loaded) return; - if (m_dom_tree_loaded) - return; m_content_web_view.inspect_dom_tree(); m_content_web_view.inspect_accessibility_tree();
705cd2491cc0e5bb6b9196901d4ad67c7a4aed5f
2019-07-19 16:49:47
Andreas Kling
kernel: Some small refinements to the thread blockers.
false
Some small refinements to the thread blockers.
kernel
diff --git a/Kernel/FileSystem/FileDescription.cpp b/Kernel/FileSystem/FileDescription.cpp index a8a35faf355f..9a02da8f8fbf 100644 --- a/Kernel/FileSystem/FileDescription.cpp +++ b/Kernel/FileSystem/FileDescription.cpp @@ -143,14 +143,16 @@ ssize_t FileDescription::write(const u8* data, ssize_t size) return nwritten; } -bool FileDescription::can_write() +bool FileDescription::can_write() const { - return m_file->can_write(*this); + // FIXME: Remove this const_cast. + return m_file->can_write(const_cast<FileDescription&>(*this)); } -bool FileDescription::can_read() +bool FileDescription::can_read() const { - return m_file->can_read(*this); + // FIXME: Remove this const_cast. + return m_file->can_read(const_cast<FileDescription&>(*this)); } ByteBuffer FileDescription::read_entire_file() diff --git a/Kernel/FileSystem/FileDescription.h b/Kernel/FileSystem/FileDescription.h index 6ef4309dec4e..ebf9e44e8ffa 100644 --- a/Kernel/FileSystem/FileDescription.h +++ b/Kernel/FileSystem/FileDescription.h @@ -36,8 +36,8 @@ class FileDescription : public RefCounted<FileDescription> { KResult fchmod(mode_t); - bool can_read(); - bool can_write(); + bool can_read() const; + bool can_write() const; ssize_t get_dir_entries(u8* buffer, ssize_t); diff --git a/Kernel/Scheduler.cpp b/Kernel/Scheduler.cpp index 9bf6cded2057..7bef7efc5512 100644 --- a/Kernel/Scheduler.cpp +++ b/Kernel/Scheduler.cpp @@ -51,67 +51,63 @@ void Scheduler::beep() s_beep_timeout = g_uptime + 100; } -Thread::FileDescriptionBlocker::FileDescriptionBlocker(const RefPtr<FileDescription>& description) +Thread::FileDescriptionBlocker::FileDescriptionBlocker(const FileDescription& description) : m_blocked_description(description) {} -RefPtr<FileDescription> Thread::FileDescriptionBlocker::blocked_description() const +const FileDescription& Thread::FileDescriptionBlocker::blocked_description() const { return m_blocked_description; } -Thread::AcceptBlocker::AcceptBlocker(const RefPtr<FileDescription>& description) +Thread::AcceptBlocker::AcceptBlocker(const FileDescription& description) : FileDescriptionBlocker(description) { } bool Thread::AcceptBlocker::should_unblock(Thread&, time_t, long) { - auto& description = *blocked_description(); - auto& socket = *description.socket(); - + auto& socket = *blocked_description().socket(); return socket.can_accept(); } -Thread::ReceiveBlocker::ReceiveBlocker(const RefPtr<FileDescription>& description) +Thread::ReceiveBlocker::ReceiveBlocker(const FileDescription& description) : FileDescriptionBlocker(description) { } bool Thread::ReceiveBlocker::should_unblock(Thread&, time_t now_sec, long now_usec) { - auto& description = *blocked_description(); - auto& socket = *description.socket(); + auto& socket = *blocked_description().socket(); // FIXME: Block until the amount of data wanted is available. bool timed_out = now_sec > socket.receive_deadline().tv_sec || (now_sec == socket.receive_deadline().tv_sec && now_usec >= socket.receive_deadline().tv_usec); - if (timed_out || description.can_read()) + if (timed_out || blocked_description().can_read()) return true; return false; } -Thread::ConnectBlocker::ConnectBlocker(const RefPtr<FileDescription>& description) +Thread::ConnectBlocker::ConnectBlocker(const FileDescription& description) : FileDescriptionBlocker(description) { } bool Thread::ConnectBlocker::should_unblock(Thread&, time_t, long) { - auto& description = *blocked_description(); - auto& socket = *description.socket(); + auto& socket = *blocked_description().socket(); return socket.is_connected(); } -Thread::WriteBlocker::WriteBlocker(const RefPtr<FileDescription>& description) +Thread::WriteBlocker::WriteBlocker(const FileDescription& description) : FileDescriptionBlocker(description) { } bool Thread::WriteBlocker::should_unblock(Thread&, time_t, long) { - return blocked_description()->can_write(); + return blocked_description().can_write(); } -Thread::ReadBlocker::ReadBlocker(const RefPtr<FileDescription>& description) +Thread::ReadBlocker::ReadBlocker(const FileDescription& description) : FileDescriptionBlocker(description) { } @@ -119,10 +115,10 @@ Thread::ReadBlocker::ReadBlocker(const RefPtr<FileDescription>& description) bool Thread::ReadBlocker::should_unblock(Thread&, time_t, long) { // FIXME: Block until the amount of data wanted is available. - return blocked_description()->can_read(); + return blocked_description().can_read(); } -Thread::ConditionBlocker::ConditionBlocker(const char* state_string, Function<bool()> &condition) +Thread::ConditionBlocker::ConditionBlocker(const char* state_string, Function<bool()>&& condition) : m_block_until_condition(move(condition)) , m_state_string(state_string) { diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index b8fca99784c0..fafdac35363a 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -110,7 +110,7 @@ void Thread::unblock() void Thread::block_until(const char* state_string, Function<bool()>&& condition) { - block<ConditionBlocker>(state_string, condition); + block<ConditionBlocker>(state_string, move(condition)); } void Thread::block_helper() diff --git a/Kernel/Thread.h b/Kernel/Thread.h index bd7bbc1081df..d668f5bd7621 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -75,62 +75,62 @@ class Thread : public InlineLinkedListNode<Thread> { class FileDescriptionBlocker : public Blocker { public: - FileDescriptionBlocker(const RefPtr<FileDescription>& description); - RefPtr<FileDescription> blocked_description() const; + explicit FileDescriptionBlocker(const FileDescription&); + const FileDescription& blocked_description() const; private: - RefPtr<FileDescription> m_blocked_description; + NonnullRefPtr<FileDescription> m_blocked_description; }; - class AcceptBlocker : public FileDescriptionBlocker { + class AcceptBlocker final : public FileDescriptionBlocker { public: - AcceptBlocker(const RefPtr<FileDescription>& description); + explicit AcceptBlocker(const FileDescription&); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return "Accepting"; } }; - class ReceiveBlocker : public FileDescriptionBlocker { + class ReceiveBlocker final : public FileDescriptionBlocker { public: - ReceiveBlocker(const RefPtr<FileDescription>& description); + explicit ReceiveBlocker(const FileDescription&); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return "Receiving"; } }; - class ConnectBlocker : public FileDescriptionBlocker { + class ConnectBlocker final : public FileDescriptionBlocker { public: - ConnectBlocker(const RefPtr<FileDescription>& description); + explicit ConnectBlocker(const FileDescription&); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return "Connecting"; } }; - class WriteBlocker : public FileDescriptionBlocker { + class WriteBlocker final : public FileDescriptionBlocker { public: - WriteBlocker(const RefPtr<FileDescription>& description); + explicit WriteBlocker(const FileDescription&); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return "Writing"; } }; - class ReadBlocker : public FileDescriptionBlocker { + class ReadBlocker final : public FileDescriptionBlocker { public: - ReadBlocker(const RefPtr<FileDescription>& description); + explicit ReadBlocker(const FileDescription&); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return "Reading"; } }; - class ConditionBlocker : public Blocker { + class ConditionBlocker final : public Blocker { public: - ConditionBlocker(const char* state_string, Function<bool()> &condition); + ConditionBlocker(const char* state_string, Function<bool()>&& condition); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return m_state_string; } private: Function<bool()> m_block_until_condition; - const char* m_state_string; + const char* m_state_string { nullptr }; }; - class SleepBlocker : public Blocker { + class SleepBlocker final : public Blocker { public: - SleepBlocker(u64 wakeup_time); + explicit SleepBlocker(u64 wakeup_time); virtual bool should_unblock(Thread&, time_t, long) override; virtual const char* state_string() const override { return "Sleeping"; } @@ -138,7 +138,7 @@ class Thread : public InlineLinkedListNode<Thread> { u64 m_wakeup_time { 0 }; }; - class SelectBlocker : public Blocker { + class SelectBlocker final : public Blocker { public: typedef Vector<int, FD_SETSIZE> FDVector; SelectBlocker(const timeval& tv, bool select_has_timeout, const FDVector& read_fds, const FDVector& write_fds, const FDVector& except_fds); @@ -153,7 +153,7 @@ class Thread : public InlineLinkedListNode<Thread> { const FDVector& m_select_exceptional_fds; }; - class WaitBlocker : public Blocker { + class WaitBlocker final : public Blocker { public: WaitBlocker(int wait_options, pid_t& waitee_pid); virtual bool should_unblock(Thread&, time_t, long) override; @@ -164,7 +164,7 @@ class Thread : public InlineLinkedListNode<Thread> { pid_t& m_waitee_pid; }; - class SemiPermanentBlocker : public Blocker { + class SemiPermanentBlocker final : public Blocker { public: enum class Reason { Lurking, @@ -176,10 +176,10 @@ class Thread : public InlineLinkedListNode<Thread> { virtual const char* state_string() const override { switch (m_reason) { - case Reason::Lurking: - return "Lurking"; - case Reason::Signal: - return "Signal"; + case Reason::Lurking: + return "Lurking"; + case Reason::Signal: + return "Signal"; } ASSERT_NOT_REACHED(); } @@ -192,10 +192,7 @@ class Thread : public InlineLinkedListNode<Thread> { u32 times_scheduled() const { return m_times_scheduled; } bool is_stopped() const { return m_state == Stopped; } - bool is_blocked() const - { - return m_state == Blocked; - } + bool is_blocked() const { return m_state == Blocked; } bool in_kernel() const { return (m_tss.cs & 0x03) == 0; } u32 frame_ptr() const { return m_tss.ebp; }
f860763c77334ae3677e52ed9d55051f05acfc69
2024-05-30 20:59:20
Matthew Olsson
tests: Add tests for ClangPlugin's macro validation
false
Add tests for ClangPlugin's macro validation
tests
diff --git a/Tests/ClangPlugins/LibJSGCTests/Macros/classes_are_missing_expected_macros.cpp b/Tests/ClangPlugins/LibJSGCTests/Macros/classes_are_missing_expected_macros.cpp new file mode 100644 index 000000000000..c79066d26c9b --- /dev/null +++ b/Tests/ClangPlugins/LibJSGCTests/Macros/classes_are_missing_expected_macros.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024, Matthew Olsson <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +// RUN: %clang++ -cc1 -verify %plugin_opts% %s 2>&1 + +#include <LibJS/Runtime/PrototypeObject.h> +#include <LibWeb/Bindings/PlatformObject.h> + +// expected-error@+1 {{Expected record to have a JS_CELL macro invocation}} +class TestCellClass : JS::Cell { +}; + +// expected-error@+1 {{Expected record to have a JS_OBJECT macro invocation}} +class TestObjectClass : JS::Object { +}; + +// expected-error@+1 {{Expected record to have a JS_ENVIRONMENT macro invocation}} +class TestEnvironmentClass : JS::Environment { +}; + +// expected-error@+1 {{Expected record to have a JS_PROTOTYPE_OBJECT macro invocation}} +class TestPrototypeClass : JS::PrototypeObject<TestCellClass, TestCellClass> { +}; + +// expected-error@+1 {{Expected record to have a WEB_PLATFORM_OBJECT macro invocation}} +class TestPlatformClass : Web::Bindings::PlatformObject { +}; diff --git a/Tests/ClangPlugins/LibJSGCTests/Macros/classes_have_expected_macros.cpp b/Tests/ClangPlugins/LibJSGCTests/Macros/classes_have_expected_macros.cpp new file mode 100644 index 000000000000..e02fe9259e88 --- /dev/null +++ b/Tests/ClangPlugins/LibJSGCTests/Macros/classes_have_expected_macros.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024, Matthew Olsson <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +// RUN: %clang++ -cc1 -verify %plugin_opts% %s 2>&1 +// expected-no-diagnostics + +#include <LibJS/Runtime/PrototypeObject.h> +#include <LibWeb/Bindings/PlatformObject.h> + +class TestCellClass : JS::Cell { + JS_CELL(TestCellClass, JS::Cell); +}; + +class TestObjectClass : JS::Object { + JS_OBJECT(TestObjectClass, JS::Object); +}; + +class TestEnvironmentClass : JS::Environment { + JS_ENVIRONMENT(TestEnvironmentClass, JS::Environment); +}; + +class TestPlatformClass : Web::Bindings::PlatformObject { + WEB_PLATFORM_OBJECT(TestPlatformClass, Web::Bindings::PlatformObject); +}; + +namespace JS { + +class TestPrototypeClass : JS::PrototypeObject<TestCellClass, TestCellClass> { + JS_PROTOTYPE_OBJECT(TestPrototypeClass, TestCellClass, TestCellClass); +}; + +} + +// Nested classes +class Parent1 { }; +class Parent2 : JS::Cell { + JS_CELL(Parent2, JS::Cell); +}; +class Parent3 { }; +class Parent4 : public Parent2 { + JS_CELL(Parent4, Parent2); +}; + +class NestedCellClass + : Parent1 + , Parent3 + , Parent4 { + JS_CELL(NestedCellClass, Parent4); // Not Parent2 +}; diff --git a/Tests/ClangPlugins/LibJSGCTests/Macros/classes_have_incorrect_macro_types.cpp b/Tests/ClangPlugins/LibJSGCTests/Macros/classes_have_incorrect_macro_types.cpp new file mode 100644 index 000000000000..eb777ac1c160 --- /dev/null +++ b/Tests/ClangPlugins/LibJSGCTests/Macros/classes_have_incorrect_macro_types.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024, Matthew Olsson <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +// RUN: %clang++ -cc1 -verify %plugin_opts% %s 2>&1 + +#include <LibJS/Runtime/Object.h> +#include <LibJS/Runtime/PrototypeObject.h> + +// Note: Using WEB_PLATFORM_OBJECT() on a class that doesn't inherit from Web::Bindings::PlatformObject +// is a compilation error, so that is not tested here. +// Note: It's pretty hard to have the incorrect type in a JS::PrototypeObject, since the base name would +// have a comma in it, and wouldn't be passable as the basename without a typedef. + +class CellWithObjectMacro : JS::Cell { + // expected-error@+1 {{Invalid JS-CELL-like macro invocation; expected JS_CELL}} + JS_OBJECT(CellWithObjectMacro, JS::Cell); +}; + +class CellWithEnvironmentMacro : JS::Cell { + // expected-error@+1 {{Invalid JS-CELL-like macro invocation; expected JS_CELL}} + JS_ENVIRONMENT(CellWithEnvironmentMacro, JS::Cell); +}; + +class ObjectWithCellMacro : JS::Object { + // expected-error@+1 {{Invalid JS-CELL-like macro invocation; expected JS_OBJECT}} + JS_CELL(ObjectWithCellMacro, JS::Object); +}; + +class ObjectWithEnvironmentMacro : JS::Object { + // expected-error@+1 {{Invalid JS-CELL-like macro invocation; expected JS_OBJECT}} + JS_ENVIRONMENT(ObjectWithEnvironmentMacro, JS::Object); +}; + +// JS_PROTOTYPE_OBJECT can only be used in the JS namespace +namespace JS { + +class CellWithPrototypeMacro : Cell { + // expected-error@+1 {{Invalid JS-CELL-like macro invocation; expected JS_CELL}} + JS_PROTOTYPE_OBJECT(CellWithPrototypeMacro, Cell, Cell); +}; + +class ObjectWithPrototypeMacro : Object { + // expected-error@+1 {{Invalid JS-CELL-like macro invocation; expected JS_OBJECT}} + JS_PROTOTYPE_OBJECT(ObjectWithPrototypeMacro, Object, Object); +}; + +} diff --git a/Tests/ClangPlugins/LibJSGCTests/Macros/nested_macros.cpp b/Tests/ClangPlugins/LibJSGCTests/Macros/nested_macros.cpp new file mode 100644 index 000000000000..b8778d26fe5a --- /dev/null +++ b/Tests/ClangPlugins/LibJSGCTests/Macros/nested_macros.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024, Matthew Olsson <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +// RUN: %clang++ -cc1 -verify %plugin_opts% %s 2>&1 + +#include <LibJS/Runtime/Object.h> + +class TestClass : JS::Object { + JS_OBJECT(TestClass, JS::Object); + + struct NestedClassOk : JS::Cell { + JS_CELL(NestedClassOk, JS::Cell); + }; + + // expected-error@+1 {{Expected record to have a JS_OBJECT macro invocation}} + struct NestedClassBad : JS::Object { + }; + + struct NestedClassNonCell { + }; +}; + +// Same test, but the parent object is not a cell +class TestClass2 { + struct NestedClassOk : JS::Cell { + JS_CELL(NestedClassOk, JS::Cell); + }; + + // expected-error@+1 {{Expected record to have a JS_OBJECT macro invocation}} + struct NestedClassBad : JS::Object { + }; + + struct NestedClassNonCell { + }; +}; diff --git a/Tests/ClangPlugins/LibJSGCTests/Macros/wrong_basename_arg.cpp b/Tests/ClangPlugins/LibJSGCTests/Macros/wrong_basename_arg.cpp new file mode 100644 index 000000000000..0204748760ae --- /dev/null +++ b/Tests/ClangPlugins/LibJSGCTests/Macros/wrong_basename_arg.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024, Matthew Olsson <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +// RUN: %clang++ -cc1 -verify %plugin_opts% %s 2>&1 + +#include <LibJS/Runtime/Object.h> + +// The only way to have an incorrect basename is if the class is deeply nested, and the base name +// refers to a parent class + +class ParentObject : JS::Object { + JS_OBJECT(ParentObject, JS::Object); +}; + +class TestClass : ParentObject { + // expected-error@+1 {{Expected second argument of JS_OBJECT macro invocation to be ParentObject}} + JS_OBJECT(TestClass, JS::Object); +}; + +// Basename must exactly match the argument +namespace JS { + +class TestClass : ::ParentObject { + // expected-error@+1 {{Expected second argument of JS_OBJECT macro invocation to be ::ParentObject}} + JS_OBJECT(TestClass, ParentObject); +}; + +} + +// Nested classes +class Parent1 { }; +class Parent2 : JS::Cell { + JS_CELL(Parent2, JS::Cell); +}; +class Parent3 { }; +class Parent4 : public Parent2 { + JS_CELL(Parent4, Parent2); +}; + +class NestedCellClass + : Parent1 + , Parent3 + , Parent4 { + // expected-error@+1 {{Expected second argument of JS_CELL macro invocation to be Parent4}} + JS_CELL(NestedCellClass, Parent2); +}; diff --git a/Tests/ClangPlugins/LibJSGCTests/Macros/wrong_classname_arg.cpp b/Tests/ClangPlugins/LibJSGCTests/Macros/wrong_classname_arg.cpp new file mode 100644 index 000000000000..a51a5a69a83d --- /dev/null +++ b/Tests/ClangPlugins/LibJSGCTests/Macros/wrong_classname_arg.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024, Matthew Olsson <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +// RUN: %clang++ -cc1 -verify %plugin_opts% %s 2>&1 + +#include <LibJS/Runtime/PrototypeObject.h> +#include <LibWeb/Bindings/PlatformObject.h> + +// An incorrect first argument for JS_PROTOTYPE_OBJECT is a compile error, so that is not tested + +class TestCellClass : JS::Cell { + // expected-error@+1 {{Expected first argument of JS_CELL macro invocation to be TestCellClass}} + JS_CELL(bad, JS::Cell); +}; + +class TestObjectClass : JS::Object { + // expected-error@+1 {{Expected first argument of JS_OBJECT macro invocation to be TestObjectClass}} + JS_OBJECT(bad, JS::Object); +}; + +class TestEnvironmentClass : JS::Environment { + // expected-error@+1 {{Expected first argument of JS_ENVIRONMENT macro invocation to be TestEnvironmentClass}} + JS_ENVIRONMENT(bad, JS::Environment); +}; + +class TestPlatformClass : Web::Bindings::PlatformObject { + // expected-error@+1 {{Expected first argument of WEB_PLATFORM_OBJECT macro invocation to be TestPlatformClass}} + WEB_PLATFORM_OBJECT(bad, Web::Bindings::PlatformObject); +}; + +struct Outer { + struct Inner; +}; + +struct Outer::Inner : JS::Cell { + // expected-error@+1 {{Expected first argument of JS_CELL macro invocation to be Outer::Inner}} + JS_CELL(Inner, JS::Cell); +};
ff63b2603ddc58735286e03cca3d6ffa546561d8
2023-12-25 03:19:19
Andreas Kling
libweb: Use cached Element `id` attribute in HTMLCollection
false
Use cached Element `id` attribute in HTMLCollection
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/HTMLCollection.cpp b/Userland/Libraries/LibWeb/DOM/HTMLCollection.cpp index ed18a597e293..13a8db280091 100644 --- a/Userland/Libraries/LibWeb/DOM/HTMLCollection.cpp +++ b/Userland/Libraries/LibWeb/DOM/HTMLCollection.cpp @@ -89,7 +89,7 @@ Element* HTMLCollection::named_item(FlyString const& name_) const auto elements = collect_matching_elements(); // 2. Return the first element in the collection for which at least one of the following is true: // - it has an ID which is key; - if (auto it = elements.find_if([&](auto& entry) { return entry->deprecated_attribute(HTML::AttributeNames::id) == name; }); it != elements.end()) + if (auto it = elements.find_if([&](auto& entry) { return entry->id().has_value() && entry->id().value() == name_; }); it != elements.end()) return *it; // - it is in the HTML namespace and has a name attribute whose value is key; if (auto it = elements.find_if([&](auto& entry) { return entry->namespace_uri() == Namespace::HTML && entry->name() == name; }); it != elements.end()) @@ -109,9 +109,9 @@ Vector<FlyString> HTMLCollection::supported_property_names() const for (auto& element : elements) { // 1. If element has an ID which is not in result, append element’s ID to result. - if (auto maybe_id = element->attribute(HTML::AttributeNames::id); maybe_id.has_value()) { - if (!result.contains_slow(maybe_id.value())) - result.append(maybe_id.release_value()); + if (auto const& id = element->id(); id.has_value()) { + if (!result.contains_slow(id.value())) + result.append(id.value()); } // 2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string nor is in result, append element’s name attribute value to result.
60cddb4179e401a7c5e6cc044ead6d4b742dbf11
2023-05-20 07:41:53
Hediadyoin1
kernel: Check only for the first equal sign in the kernel command line
false
Check only for the first equal sign in the kernel command line
kernel
diff --git a/Kernel/CommandLine.cpp b/Kernel/CommandLine.cpp index d52f4ce0e0d9..dd08f41f6486 100644 --- a/Kernel/CommandLine.cpp +++ b/Kernel/CommandLine.cpp @@ -58,15 +58,13 @@ UNMAP_AFTER_INIT void CommandLine::add_arguments(Vector<StringView> const& args) if (str == ""sv) { continue; } - - auto pair = str.split_view('='); - VERIFY(pair.size() == 2 || pair.size() == 1); - - if (pair.size() == 1) { - m_params.set(pair[0], ""sv); - } else { - m_params.set(pair[0], pair[1]); - } + // Some boot loaders may include complex key-value pairs where the value is a composite entry, + // we handle this by only checking for the first equals sign in each command line parameter. + auto key = str.find_first_split_view('='); + if (key.length() == str.length()) + m_params.set(key, ""sv); + else + m_params.set(key, str.substring_view(key.length() + 1)); } }
da57563c1cc27790417eac55b99e0d52da8528c9
2021-05-16 19:23:58
Stephan Unverwerth
libgl: Implement glShadeModel()
false
Implement glShadeModel()
libgl
diff --git a/Userland/Libraries/LibGL/CMakeLists.txt b/Userland/Libraries/LibGL/CMakeLists.txt index 8214a8a6e5a0..3455679f7280 100644 --- a/Userland/Libraries/LibGL/CMakeLists.txt +++ b/Userland/Libraries/LibGL/CMakeLists.txt @@ -3,6 +3,7 @@ set(SOURCES GLBlend.cpp GLColor.cpp GLContext.cpp + GLLights.cpp GLLists.cpp GLMat.cpp GLUtils.cpp diff --git a/Userland/Libraries/LibGL/GL/gl.h b/Userland/Libraries/LibGL/GL/gl.h index 7d40f453f9ff..325e0899c81a 100644 --- a/Userland/Libraries/LibGL/GL/gl.h +++ b/Userland/Libraries/LibGL/GL/gl.h @@ -79,6 +79,10 @@ extern "C" { #define GL_COMPILE 0x1300 #define GL_COMPILE_AND_EXECUTE 0x1301 +// Lighting related defines +#define GL_FLAT 0x1D00 +#define GL_SMOOTH 0x1D01 + // More blend factors #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 @@ -147,6 +151,7 @@ GLAPI void glNewList(GLuint list, GLenum mode); GLAPI void glFlush(); GLAPI void glFinish(); GLAPI void glBlendFunc(GLenum sfactor, GLenum dfactor); +GLAPI void glShadeModel(GLenum mode); #ifdef __cplusplus } diff --git a/Userland/Libraries/LibGL/GLContext.h b/Userland/Libraries/LibGL/GLContext.h index 6074454c4121..084c4db5da0f 100644 --- a/Userland/Libraries/LibGL/GLContext.h +++ b/Userland/Libraries/LibGL/GLContext.h @@ -50,6 +50,7 @@ class GLContext { virtual void gl_flush() = 0; virtual void gl_finish() = 0; virtual void gl_blend_func(GLenum src_factor, GLenum dst_factor) = 0; + virtual void gl_shade_model(GLenum mode) = 0; virtual void present() = 0; }; diff --git a/Userland/Libraries/LibGL/GLLights.cpp b/Userland/Libraries/LibGL/GLLights.cpp new file mode 100644 index 000000000000..afd1c746d170 --- /dev/null +++ b/Userland/Libraries/LibGL/GLLights.cpp @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2021, Stephan Unverwerth <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "GL/gl.h" +#include "GLContext.h" + +extern GL::GLContext* g_gl_context; + +void glShadeModel(GLenum mode) +{ + g_gl_context->gl_shade_model(mode); +} diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.cpp b/Userland/Libraries/LibGL/SoftwareGLContext.cpp index a286f3bef4ef..0df1c513ba56 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.cpp +++ b/Userland/Libraries/LibGL/SoftwareGLContext.cpp @@ -925,6 +925,23 @@ void SoftwareGLContext::gl_blend_func(GLenum src_factor, GLenum dst_factor) m_rasterizer.set_options(options); } +void SoftwareGLContext::gl_shade_model(GLenum mode) +{ + if (m_in_draw_state) { + m_error = GL_INVALID_OPERATION; + return; + } + + if (mode != GL_FLAT && mode != GL_SMOOTH) { + m_error = GL_INVALID_ENUM; + return; + } + + auto options = m_rasterizer.options(); + options.shade_smooth = (mode == GL_SMOOTH); + m_rasterizer.set_options(options); +} + void SoftwareGLContext::present() { m_rasterizer.blit_to(*m_frontbuffer); diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.h b/Userland/Libraries/LibGL/SoftwareGLContext.h index 93fa2091eb7a..a13944d390f4 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.h +++ b/Userland/Libraries/LibGL/SoftwareGLContext.h @@ -56,6 +56,7 @@ class SoftwareGLContext : public GLContext { virtual void gl_flush() override; virtual void gl_finish() override; virtual void gl_blend_func(GLenum src_factor, GLenum dst_factor) override; + virtual void gl_shade_model(GLenum mode) override; virtual void present() override; diff --git a/Userland/Libraries/LibGL/SoftwareRasterizer.cpp b/Userland/Libraries/LibGL/SoftwareRasterizer.cpp index aea228365b54..5f5c7ffa2f8b 100644 --- a/Userland/Libraries/LibGL/SoftwareRasterizer.cpp +++ b/Userland/Libraries/LibGL/SoftwareRasterizer.cpp @@ -295,11 +295,16 @@ static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& re barycentric = barycentric * FloatVector3(triangle.vertices[0].w, triangle.vertices[1].w, triangle.vertices[2].w) * interpolated_w; // FIXME: make this more generic. We want to interpolate more than just color and uv - auto rgba = interpolate( - FloatVector4(triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a), - FloatVector4(triangle.vertices[1].r, triangle.vertices[1].g, triangle.vertices[1].b, triangle.vertices[1].a), - FloatVector4(triangle.vertices[2].r, triangle.vertices[2].g, triangle.vertices[2].b, triangle.vertices[2].a), - barycentric); + FloatVector4 vertex_color; + if (options.shade_smooth) { + vertex_color = interpolate( + FloatVector4(triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a), + FloatVector4(triangle.vertices[1].r, triangle.vertices[1].g, triangle.vertices[1].b, triangle.vertices[1].a), + FloatVector4(triangle.vertices[2].r, triangle.vertices[2].g, triangle.vertices[2].b, triangle.vertices[2].a), + barycentric); + } else { + vertex_color = { triangle.vertices[0].r, triangle.vertices[0].g, triangle.vertices[0].b, triangle.vertices[0].a }; + } auto uv = interpolate( FloatVector2(triangle.vertices[0].u, triangle.vertices[0].v), @@ -307,7 +312,7 @@ static void rasterize_triangle(const RasterizerOptions& options, Gfx::Bitmap& re FloatVector2(triangle.vertices[2].u, triangle.vertices[2].v), barycentric); - *pixel = pixel_shader(uv, rgba); + *pixel = pixel_shader(uv, vertex_color); } }
9632d8ee492610ab272f940d3b0ece7b86475a16
2023-11-18 01:17:53
Nico Weber
libpdf: Make SimpleFont font matrix configurable
false
Make SimpleFont font matrix configurable
libpdf
diff --git a/Userland/Libraries/LibPDF/Fonts/SimpleFont.cpp b/Userland/Libraries/LibPDF/Fonts/SimpleFont.cpp index 4e05ec78adbe..69c94f8c8a45 100644 --- a/Userland/Libraries/LibPDF/Fonts/SimpleFont.cpp +++ b/Userland/Libraries/LibPDF/Fonts/SimpleFont.cpp @@ -52,11 +52,11 @@ PDFErrorOr<Gfx::FloatPoint> SimpleFont::draw_string(Gfx::Painter& painter, Gfx:: // and use the default width for the given font otherwise. float glyph_width; if (auto width = m_widths.get(char_code); width.has_value()) - glyph_width = font_size * width.value() / 1000.0f; + glyph_width = font_size * width.value() * m_font_matrix.x_scale(); else if (auto width = get_glyph_width(char_code); width.has_value()) glyph_width = width.value(); else - glyph_width = m_missing_width; + glyph_width = m_missing_width; // FIXME: times m_font_matrix.x_scale() probably? TRY(draw_glyph(painter, glyph_position, glyph_width, char_code, paint_color)); diff --git a/Userland/Libraries/LibPDF/Fonts/SimpleFont.h b/Userland/Libraries/LibPDF/Fonts/SimpleFont.h index 783fb1e1a2a1..47673d767118 100644 --- a/Userland/Libraries/LibPDF/Fonts/SimpleFont.h +++ b/Userland/Libraries/LibPDF/Fonts/SimpleFont.h @@ -22,11 +22,18 @@ class SimpleFont : public PDFFont { RefPtr<Encoding>& encoding() { return m_encoding; } RefPtr<Encoding> const& encoding() const { return m_encoding; } + Gfx::AffineTransform& font_matrix() { return m_font_matrix; } + private: RefPtr<Encoding> m_encoding; RefPtr<StreamObject> m_to_unicode; HashMap<u8, u16> m_widths; u16 m_missing_width { 0 }; + + // "For all font types except Type 3, the units of glyph space are one-thousandth of a unit of text space; + // for a Type 3 font, the transformation from glyph space to text space is defined by a font matrix specified + // in an explicit FontMatrix entry in the font." + Gfx::AffineTransform m_font_matrix { 1.0f / 1000.0f, 0, 0, 1.0f / 1000.0f, 0, 0 }; }; }
6fd3b39bef7fadffde712e2b8ee3b11713e4b10f
2023-06-10 00:07:51
Sam Atkins
libweb: Parse `aspect-ratio` property
false
Parse `aspect-ratio` property
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h index b750570fa3e1..6aca2839cd3c 100644 --- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h +++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h @@ -15,6 +15,7 @@ #include <LibWeb/CSS/GridTrackSize.h> #include <LibWeb/CSS/LengthBox.h> #include <LibWeb/CSS/PercentageOr.h> +#include <LibWeb/CSS/Ratio.h> #include <LibWeb/CSS/Size.h> #include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h> #include <LibWeb/CSS/StyleValues/ShadowStyleValue.h> @@ -22,8 +23,14 @@ namespace Web::CSS { +struct AspectRatio { + bool use_natural_aspect_ratio_if_available; + Optional<Ratio> preferred_ratio; +}; + class InitialValues { public: + static AspectRatio aspect_ratio() { return AspectRatio { true, {} }; } static float font_size() { return 16; } static int font_weight() { return 400; } static CSS::FontVariant font_variant() { return CSS::FontVariant::Normal; } @@ -211,6 +218,7 @@ inline Gfx::Painter::ScalingMode to_gfx_scaling_mode(CSS::ImageRendering css_val class ComputedValues { public: + AspectRatio aspect_ratio() const { return m_noninherited.aspect_ratio; } CSS::Float float_() const { return m_noninherited.float_; } CSS::Clear clear() const { return m_noninherited.clear; } CSS::Clip clip() const { return m_noninherited.clip; } @@ -344,6 +352,7 @@ class ComputedValues { } m_inherited; struct { + AspectRatio aspect_ratio { InitialValues::aspect_ratio() }; CSS::Float float_ { InitialValues::float_() }; CSS::Clear clear { InitialValues::clear() }; CSS::Clip clip { InitialValues::clip() }; @@ -418,6 +427,7 @@ class ImmutableComputedValues final : public ComputedValues { class MutableComputedValues final : public ComputedValues { public: + void set_aspect_ratio(AspectRatio aspect_ratio) { m_noninherited.aspect_ratio = aspect_ratio; } void set_font_size(float font_size) { m_inherited.font_size = font_size; } void set_font_weight(int font_weight) { m_inherited.font_weight = font_weight; } void set_font_variant(CSS::FontVariant font_variant) { m_inherited.font_variant = font_variant; } diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index d8b4c2c82123..e169f1339665 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -4457,6 +4457,51 @@ static void remove_property(Vector<PropertyID>& properties, PropertyID property_ properties.remove_first_matching([&](auto it) { return it == property_to_remove; }); } +// https://www.w3.org/TR/css-sizing-4/#aspect-ratio +ErrorOr<RefPtr<StyleValue>> Parser::parse_aspect_ratio_value(Vector<ComponentValue> const& component_values) +{ + // `auto || <ratio>` + RefPtr<StyleValue> auto_value; + RefPtr<StyleValue> ratio_value; + + auto tokens = TokenStream { component_values }; + while (tokens.has_next_token()) { + auto maybe_value = TRY(parse_css_value_for_property(PropertyID::AspectRatio, tokens)); + if (!maybe_value) + return nullptr; + + if (maybe_value->is_ratio()) { + if (ratio_value) + return nullptr; + ratio_value = maybe_value.release_nonnull(); + continue; + } + + if (maybe_value->is_identifier() && maybe_value->as_identifier().id() == ValueID::Auto) { + if (auto_value) + return nullptr; + auto_value = maybe_value.release_nonnull(); + continue; + } + + return nullptr; + } + + if (auto_value && ratio_value) { + return TRY(StyleValueList::create( + StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() }, + StyleValueList::Separator::Space)); + } + + if (ratio_value) + return ratio_value.release_nonnull(); + + if (auto_value) + return auto_value.release_nonnull(); + + return nullptr; +} + ErrorOr<RefPtr<StyleValue>> Parser::parse_background_value(Vector<ComponentValue> const& component_values) { StyleValueVector background_images; @@ -7307,6 +7352,10 @@ Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(Property // Special-case property handling switch (property_id) { + case PropertyID::AspectRatio: + if (auto parsed_value = FIXME_TRY(parse_aspect_ratio_value(component_values))) + return parsed_value.release_nonnull(); + return ParseError::SyntaxError; case PropertyID::BackdropFilter: if (auto parsed_value = FIXME_TRY(parse_filter_value_list_value(component_values))) return parsed_value.release_nonnull(); diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h index d099ba44939c..c696de0be1a2 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h @@ -307,6 +307,7 @@ class Parser { ErrorOr<RefPtr<StyleValue>> parse_simple_comma_separated_value_list(PropertyID, Vector<ComponentValue> const&); ErrorOr<RefPtr<StyleValue>> parse_filter_value_list_value(Vector<ComponentValue> const&); + ErrorOr<RefPtr<StyleValue>> parse_aspect_ratio_value(Vector<ComponentValue> const&); ErrorOr<RefPtr<StyleValue>> parse_background_value(Vector<ComponentValue> const&); ErrorOr<RefPtr<StyleValue>> parse_single_background_position_value(TokenStream<ComponentValue>&); ErrorOr<RefPtr<StyleValue>> parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>&, PropertyID); diff --git a/Userland/Libraries/LibWeb/CSS/Properties.json b/Userland/Libraries/LibWeb/CSS/Properties.json index b481abb9f858..1326993dc3a8 100644 --- a/Userland/Libraries/LibWeb/CSS/Properties.json +++ b/Userland/Libraries/LibWeb/CSS/Properties.json @@ -138,6 +138,17 @@ "appearance" ] }, + "aspect-ratio": { + "affects-layout": true, + "inherited": false, + "initial": "auto", + "valid-types": [ + "ratio" + ], + "valid-identifiers":[ + "auto" + ] + }, "backdrop-filter": { "affects-layout": false, "affects-stacking-context": true, diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp index ab666f061256..12ad2f26bb8c 100644 --- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp +++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp @@ -33,6 +33,7 @@ #include <LibWeb/CSS/StyleValues/NumberStyleValue.h> #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h> #include <LibWeb/CSS/StyleValues/PositionStyleValue.h> +#include <LibWeb/CSS/StyleValues/RatioStyleValue.h> #include <LibWeb/CSS/StyleValues/RectStyleValue.h> #include <LibWeb/CSS/StyleValues/ShadowStyleValue.h> #include <LibWeb/CSS/StyleValues/StyleValueList.h> @@ -263,6 +264,19 @@ ErrorOr<RefPtr<StyleValue const>> ResolvedCSSStyleDeclaration::style_value_for_p return TRY(IdentifierStyleValue::create(to_value_id(layout_node.computed_values().align_self()))); case PropertyID::Appearance: return TRY(IdentifierStyleValue::create(to_value_id(layout_node.computed_values().appearance()))); + case PropertyID::AspectRatio: { + auto aspect_ratio = layout_node.computed_values().aspect_ratio(); + if (aspect_ratio.use_natural_aspect_ratio_if_available && aspect_ratio.preferred_ratio.has_value()) { + return TRY(StyleValueList::create( + StyleValueVector { + TRY(IdentifierStyleValue::create(ValueID::Auto)), + TRY(RatioStyleValue::create(aspect_ratio.preferred_ratio.value())) }, + StyleValueList::Separator::Space)); + } + if (aspect_ratio.preferred_ratio.has_value()) + return TRY(RatioStyleValue::create(aspect_ratio.preferred_ratio.value())); + return TRY(IdentifierStyleValue::create(ValueID::Auto)); + } case PropertyID::Background: { auto maybe_background_color = property(PropertyID::BackgroundColor); auto maybe_background_image = property(PropertyID::BackgroundImage); diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp index ccc74bb40a14..20d1955cbdee 100644 --- a/Userland/Libraries/LibWeb/Layout/Node.cpp +++ b/Userland/Libraries/LibWeb/Layout/Node.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2018-2023, Andreas Kling <[email protected]> + * Copyright (c) 2021-2023, Sam Atkins <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -10,9 +11,11 @@ #include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h> #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h> #include <LibWeb/CSS/StyleValues/EdgeStyleValue.h> +#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h> #include <LibWeb/CSS/StyleValues/LengthStyleValue.h> #include <LibWeb/CSS/StyleValues/NumberStyleValue.h> #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h> +#include <LibWeb/CSS/StyleValues/RatioStyleValue.h> #include <LibWeb/CSS/StyleValues/StyleValueList.h> #include <LibWeb/CSS/StyleValues/TimeStyleValue.h> #include <LibWeb/CSS/StyleValues/URLStyleValue.h> @@ -707,6 +710,20 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& computed_style) if (auto border_collapse = computed_style.border_collapse(); border_collapse.has_value()) computed_values.set_border_collapse(border_collapse.value()); + + auto aspect_ratio = computed_style.property(CSS::PropertyID::AspectRatio); + if (aspect_ratio->is_value_list()) { + auto& values_list = aspect_ratio->as_value_list().values(); + if (values_list.size() == 2 + && values_list[0]->is_identifier() && values_list[0]->as_identifier().id() == CSS::ValueID::Auto + && values_list[1]->is_ratio()) { + computed_values.set_aspect_ratio({ true, values_list[1]->as_ratio().ratio() }); + } + } else if (aspect_ratio->is_identifier() && aspect_ratio->as_identifier().id() == CSS::ValueID::Auto) { + computed_values.set_aspect_ratio({ true, {} }); + } else if (aspect_ratio->is_ratio()) { + computed_values.set_aspect_ratio({ false, aspect_ratio->as_ratio().ratio() }); + } } bool Node::is_root_element() const
20c066b8e0d9c2097cd9a46fc7e56b92fc300255
2021-06-20 18:27:26
Ali Mohammad Pur
libcore: Call optional did_construct() method when constucting objects
false
Call optional did_construct() method when constucting objects
libcore
diff --git a/Userland/Libraries/LibCore/Object.h b/Userland/Libraries/LibCore/Object.h index d9d0a2df2a5d..1cfa64683b2f 100644 --- a/Userland/Libraries/LibCore/Object.h +++ b/Userland/Libraries/LibCore/Object.h @@ -59,10 +59,13 @@ enum class TimerShouldFireWhenNotVisible { #define C_OBJECT(klass) \ public: \ virtual const char* class_name() const override { return #klass; } \ - template<class... Args> \ + template<typename Klass = klass, class... Args> \ static inline NonnullRefPtr<klass> construct(Args&&... args) \ { \ - return adopt_ref(*new klass(forward<Args>(args)...)); \ + auto obj = adopt_ref(*new Klass(forward<Args>(args)...)); \ + if constexpr (requires { declval<Klass>().did_construct(); }) \ + obj->did_construct(); \ + return obj; \ } #define C_OBJECT_ABSTRACT(klass) \
4cb765e52059edd2e466f01c66ea087e1ba3ce8c
2020-04-25 20:19:09
Peter Nelson
libgfx: Remove unnecessary casts
false
Remove unnecessary casts
libgfx
diff --git a/Libraries/LibGfx/GIFLoader.cpp b/Libraries/LibGfx/GIFLoader.cpp index 81e73c9e89ea..91497430ee08 100644 --- a/Libraries/LibGfx/GIFLoader.cpp +++ b/Libraries/LibGfx/GIFLoader.cpp @@ -139,7 +139,7 @@ class LZWDecoder { const u16 control_code = m_code_table.size(); m_code_table.append({ {}, control_code }); m_original_code_table.append({ {}, control_code }); - if ((int)m_code_table.size() >= pow(2, m_code_size) && m_code_size < 12) { + if (m_code_table.size() >= pow(2, m_code_size) && m_code_size < 12) { ++m_code_size; ++m_original_code_size; } @@ -220,7 +220,7 @@ class LZWDecoder { { if (entry.size() > 1 && m_code_table.size() < 4096) { m_code_table.append({ entry, (u16)m_code_table.size() }); - if ((int)m_code_table.size() >= pow(2, m_code_size) && m_code_size < 12) { + if (m_code_table.size() >= pow(2, m_code_size) && m_code_size < 12) { ++m_code_size; } }
6c8f0fbb35fa97e6314235a5088e1faa39f73c35
2021-07-15 04:20:03
Linus Groh
libjs: Use more specific return types for some Temporal AOs
false
Use more specific return types for some Temporal AOs
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp index 3c2e3a8eb4a4..043af0cafd80 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp @@ -45,7 +45,7 @@ JS_DEFINE_NATIVE_FUNCTION(Now::instant) } // 2.2.1 SystemTimeZone ( ), https://tc39.es/proposal-temporal/#sec-temporal-systemtimezone -Object* system_time_zone(GlobalObject& global_object) +TimeZone* system_time_zone(GlobalObject& global_object) { // 1. Let identifier be ! DefaultTimeZone(). auto identifier = default_time_zone(); @@ -78,7 +78,7 @@ BigInt* system_utc_epoch_nanoseconds(GlobalObject& global_object) } // 2.2.3 SystemInstant ( ) -Object* system_instant(GlobalObject& global_object) +Instant* system_instant(GlobalObject& global_object) { // 1. Let ns be ! SystemUTCEpochNanoseconds(). auto* ns = system_utc_epoch_nanoseconds(global_object); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.h b/Userland/Libraries/LibJS/Runtime/Temporal/Now.h index 05ed506595d5..b18652ee28c8 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.h @@ -23,8 +23,8 @@ class Now final : public Object { JS_DECLARE_NATIVE_FUNCTION(instant); }; -Object* system_time_zone(GlobalObject&); +TimeZone* system_time_zone(GlobalObject&); BigInt* system_utc_epoch_nanoseconds(GlobalObject&); -Object* system_instant(GlobalObject&); +Instant* system_instant(GlobalObject&); } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp index ecbf860d042f..6e19933543d7 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp @@ -60,7 +60,7 @@ String default_time_zone() } // 11.6.2 CreateTemporalTimeZone ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaltimezone -Object* create_temporal_time_zone(GlobalObject& global_object, String const& identifier, FunctionObject* new_target) +TimeZone* create_temporal_time_zone(GlobalObject& global_object, String const& identifier, FunctionObject* new_target) { auto& vm = global_object.vm(); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h index d9c84ba51615..d98ff0005800 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h @@ -38,7 +38,7 @@ class TimeZone final : public Object { bool is_valid_time_zone_name(String const& time_zone); String canonicalize_time_zone_name(String const& time_zone); String default_time_zone(); -Object* create_temporal_time_zone(GlobalObject&, String const& identifier, FunctionObject* new_target = nullptr); +TimeZone* create_temporal_time_zone(GlobalObject&, String const& identifier, FunctionObject* new_target = nullptr); double parse_time_zone_offset_string(GlobalObject&, String const&); String format_time_zone_offset_string(double offset_nanoseconds);
a58f39c9e24796e72750d2d20e1ba86ed5d486ca
2024-10-09 22:38:47
Jelle Raaijmakers
libweb: Implement selectionchange event according to spec
false
Implement selectionchange event according to spec
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.h b/Userland/Libraries/LibWeb/DOM/Document.h index dc4466681eeb..80d7693d52c0 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.h +++ b/Userland/Libraries/LibWeb/DOM/Document.h @@ -568,6 +568,10 @@ class Document bool query_command_supported(String const& command); String query_command_value(String const& command); + // https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event + bool has_scheduled_selectionchange_event() const { return m_has_scheduled_selectionchange_event; } + void set_scheduled_selectionchange_event(bool value) { m_has_scheduled_selectionchange_event = value; } + bool is_allowed_to_use_feature(PolicyControlledFeature) const; void did_stop_being_active_document_in_navigable(); @@ -1000,6 +1004,9 @@ class Document // https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots bool m_allow_declarative_shadow_roots { false }; + // https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event + bool m_has_scheduled_selectionchange_event { false }; + JS::GCPtr<JS::ConsoleClient> m_console_client; JS::GCPtr<DOM::Position> m_cursor_position; diff --git a/Userland/Libraries/LibWeb/DOM/Range.cpp b/Userland/Libraries/LibWeb/DOM/Range.cpp index 399efe7e429d..1ea0736555cb 100644 --- a/Userland/Libraries/LibWeb/DOM/Range.cpp +++ b/Userland/Libraries/LibWeb/DOM/Range.cpp @@ -2,6 +2,7 @@ * Copyright (c) 2020, the SerenityOS developers. * Copyright (c) 2022, Luke Wilde <[email protected]> * Copyright (c) 2022-2023, Andreas Kling <[email protected]> + * Copyright (c) 2024, Jelle Raaijmakers <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -21,6 +22,8 @@ #include <LibWeb/Geometry/DOMRect.h> #include <LibWeb/Geometry/DOMRectList.h> #include <LibWeb/HTML/HTMLHtmlElement.h> +#include <LibWeb/HTML/HTMLInputElement.h> +#include <LibWeb/HTML/HTMLTextAreaElement.h> #include <LibWeb/HTML/Window.h> #include <LibWeb/Layout/Viewport.h> #include <LibWeb/Namespace.h> @@ -96,30 +99,70 @@ void Range::set_associated_selection(Badge<Selection::Selection>, JS::GCPtr<Sele void Range::update_associated_selection() { - if (auto* viewport = m_start_container->document().paintable()) { + auto& document = m_start_container->document(); + if (auto* viewport = document.paintable()) { viewport->recompute_selection_states(*this); viewport->update_selection(); viewport->set_needs_display(); } - if (!m_associated_selection) + // https://w3c.github.io/selection-api/#selectionchange-event + // When the selection is dissociated with its range, associated with a new range, or the + // associated range's boundary point is mutated either by the user or the content script, the + // user agent must schedule a selectionchange event on document. + schedule_a_selectionchange_event(document); + + // When an input or textarea element provide a text selection and its selection changes (in + // either extent or direction), the user agent must schedule a selectionchange event on the + // element. + if (m_start_container == m_end_container) { + if (is<HTML::HTMLInputElement>(*m_start_container)) + schedule_a_selectionchange_event(verify_cast<HTML::HTMLInputElement>(*m_start_container)); + if (is<HTML::HTMLTextAreaElement>(*m_start_container)) + schedule_a_selectionchange_event(verify_cast<HTML::HTMLTextAreaElement>(*m_start_container)); + } +} + +// https://w3c.github.io/selection-api/#scheduling-selectionhange-event +template<SelectionChangeTarget T> +void Range::schedule_a_selectionchange_event(T& target) +{ + // 1. If target's has scheduled selectionchange event is true, abort these steps. + if (target.has_scheduled_selectionchange_event()) return; - // https://w3c.github.io/selection-api/#selectionchange-event - // When the selection is dissociated with its range, associated with a new range or the associated range's boundary - // point is mutated either by the user or the content script, the user agent must queue a task on the user interaction - // task source to fire an event named selectionchange, which does not bubble and is not cancelable, at the document - // associated with the selection. - auto document = m_associated_selection->document(); - queue_global_task(HTML::Task::Source::UserInteraction, relevant_global_object(*document), JS::create_heap_function(document->heap(), [document] { - EventInit event_init; - event_init.bubbles = false; - event_init.cancelable = false; - auto event = DOM::Event::create(document->realm(), HTML::EventNames::selectionchange, event_init); - document->dispatch_event(event); + // AD-HOC (https://github.com/w3c/selection-api/issues/338): + // Set target's has scheduled selectionchange event to true + target.set_scheduled_selectionchange_event(true); + + // 2. Queue a task on the user interaction task source to fire a selectionchange event on + // target. + JS::NonnullGCPtr<Document> document = m_start_container->document(); + queue_global_task(HTML::Task::Source::UserInteraction, relevant_global_object(*document), JS::create_heap_function(document->heap(), [&] { + fire_a_selectionchange_event(target); })); } +// https://w3c.github.io/selection-api/#firing-selectionhange-event +template<SelectionChangeTarget T> +void Range::fire_a_selectionchange_event(T& target) +{ + // 1. Set target's has scheduled selectionchange event to false. + target.set_scheduled_selectionchange_event(false); + + // 2. If target is an element, fire an event named selectionchange, which bubbles and not + // cancelable, at target. + // 3. Otherwise, if target is a document, fire an event named selectionchange, which does not + // bubble and not cancelable, at target. + EventInit event_init; + event_init.bubbles = SameAs<T, Element>; + event_init.cancelable = false; + + auto& realm = m_start_container->document().realm(); + auto event = DOM::Event::create(realm, HTML::EventNames::selectionchange, event_init); + target.dispatch_event(event); +} + // https://dom.spec.whatwg.org/#concept-range-root Node& Range::root() { diff --git a/Userland/Libraries/LibWeb/DOM/Range.h b/Userland/Libraries/LibWeb/DOM/Range.h index 33c6c657ab59..bbcc78e86ee7 100644 --- a/Userland/Libraries/LibWeb/DOM/Range.h +++ b/Userland/Libraries/LibWeb/DOM/Range.h @@ -23,6 +23,13 @@ enum class RelativeBoundaryPointPosition { // https://dom.spec.whatwg.org/#concept-range-bp-position RelativeBoundaryPointPosition position_of_boundary_point_relative_to_other_boundary_point(Node const& node_a, u32 offset_a, Node const& node_b, u32 offset_b); +// https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event +template<typename T> +concept SelectionChangeTarget = DerivedFrom<T, EventTarget> && requires(T t) { + { t.has_scheduled_selectionchange_event() } -> SameAs<bool>; + { t.set_scheduled_selectionchange_event(bool()) } -> SameAs<void>; +}; + class Range final : public AbstractRange { WEB_PLATFORM_OBJECT(Range, AbstractRange); JS_DECLARE_ALLOCATOR(Range); @@ -108,6 +115,10 @@ class Range final : public AbstractRange { Node const& root() const; void update_associated_selection(); + template<SelectionChangeTarget T> + void schedule_a_selectionchange_event(T&); + template<SelectionChangeTarget T> + void fire_a_selectionchange_event(T&); enum class StartOrEnd { Start, diff --git a/Userland/Libraries/LibWeb/HTML/FormAssociatedElement.h b/Userland/Libraries/LibWeb/HTML/FormAssociatedElement.h index 7f6714a30adc..5ca9da57e5f4 100644 --- a/Userland/Libraries/LibWeb/HTML/FormAssociatedElement.h +++ b/Userland/Libraries/LibWeb/HTML/FormAssociatedElement.h @@ -162,6 +162,10 @@ class FormAssociatedTextControlElement : public FormAssociatedElement { // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange WebIDL::ExceptionOr<void> set_selection_range(Optional<WebIDL::UnsignedLong> start, Optional<WebIDL::UnsignedLong> end, Optional<String> direction); + // https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event + bool has_scheduled_selectionchange_event() const { return m_has_scheduled_selectionchange_event; } + void set_scheduled_selectionchange_event(bool value) { m_has_scheduled_selectionchange_event = value; } + protected: // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-textarea/input-relevant-value void relevant_value_was_changed(JS::GCPtr<DOM::Text>); @@ -173,6 +177,9 @@ class FormAssociatedTextControlElement : public FormAssociatedElement { WebIDL::UnsignedLong m_selection_start { 0 }; WebIDL::UnsignedLong m_selection_end { 0 }; SelectionDirection m_selection_direction { SelectionDirection::None }; + + // https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event + bool m_has_scheduled_selectionchange_event { false }; }; }
52c449293a814ee3ede64cdfe38214f3016a9b7c
2024-10-26 01:34:21
Andrew Kaster
libweb: Update PromiseRejectionEvent's promise field to be object
false
Update PromiseRejectionEvent's promise field to be object
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.cpp b/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.cpp index 9329dbf0b315..17dd435ed98a 100644 --- a/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.cpp +++ b/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.cpp @@ -24,7 +24,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PromiseRejectionEvent>> PromiseRejectionEve PromiseRejectionEvent::PromiseRejectionEvent(JS::Realm& realm, FlyString const& event_name, PromiseRejectionEventInit const& event_init) : DOM::Event(realm, event_name, event_init) - , m_promise(const_cast<JS::Promise*>(event_init.promise.cell())) + , m_promise(*event_init.promise) , m_reason(event_init.reason) { } diff --git a/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.h b/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.h index a4ca47aa1a14..b0c1ab856db1 100644 --- a/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.h +++ b/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.h @@ -16,7 +16,7 @@ namespace Web::HTML { struct PromiseRejectionEventInit : public DOM::EventInit { - JS::Handle<JS::Promise> promise; + JS::Handle<JS::Object> promise; JS::Value reason; }; @@ -31,7 +31,7 @@ class PromiseRejectionEvent final : public DOM::Event { virtual ~PromiseRejectionEvent() override; // Needs to return a pointer for the generated JS bindings to work. - JS::Promise const* promise() const { return m_promise; } + JS::Object const* promise() const { return m_promise; } JS::Value reason() const { return m_reason; } private: @@ -40,7 +40,7 @@ class PromiseRejectionEvent final : public DOM::Event { virtual void initialize(JS::Realm&) override; virtual void visit_edges(Cell::Visitor&) override; - JS::GCPtr<JS::Promise> m_promise; + JS::NonnullGCPtr<JS::Object> m_promise; JS::Value m_reason; }; diff --git a/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.idl b/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.idl index 01c2dce80879..a76a5074cbbb 100644 --- a/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.idl +++ b/Userland/Libraries/LibWeb/HTML/PromiseRejectionEvent.idl @@ -1,15 +1,15 @@ #import <DOM/Event.idl> -// https://html.spec.whatwg.org/#promiserejectionevent -[Exposed=(Window,Worker)] +// https://html.spec.whatwg.org/multipage/webappapis.html#promiserejectionevent +[Exposed=*] interface PromiseRejectionEvent : Event { constructor(DOMString type, PromiseRejectionEventInit eventInitDict); - readonly attribute Promise<any> promise; + readonly attribute object promise; readonly attribute any reason; }; dictionary PromiseRejectionEventInit : EventInit { - required Promise<any> promise; + required object promise; any reason; };
db324664997287489b9f137b9a6403035172de68
2022-02-05 21:18:14
Idan Horowitz
libweb: Mark SelectorEngine matches-related functions as inline
false
Mark SelectorEngine matches-related functions as inline
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp b/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp index fef535a51f75..98a5b76ead5a 100644 --- a/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp +++ b/Userland/Libraries/LibWeb/CSS/SelectorEngine.cpp @@ -15,7 +15,7 @@ namespace Web::SelectorEngine { -static bool matches_hover_pseudo_class(DOM::Element const& element) +static inline bool matches_hover_pseudo_class(DOM::Element const& element) { auto* hovered_node = element.document().hovered_node(); if (!hovered_node) @@ -25,7 +25,7 @@ static bool matches_hover_pseudo_class(DOM::Element const& element) return element.is_ancestor_of(*hovered_node); } -static bool matches_attribute(CSS::Selector::SimpleSelector::Attribute const& attribute, DOM::Element const& element) +static inline bool matches_attribute(CSS::Selector::SimpleSelector::Attribute const& attribute, DOM::Element const& element) { switch (attribute.match_type) { case CSS::Selector::SimpleSelector::Attribute::MatchType::HasAttribute: @@ -52,7 +52,7 @@ static bool matches_attribute(CSS::Selector::SimpleSelector::Attribute const& at return false; } -static bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClass const& pseudo_class, DOM::Element const& element) +static inline bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClass const& pseudo_class, DOM::Element const& element) { switch (pseudo_class.type) { case CSS::Selector::SimpleSelector::PseudoClass::Type::None: @@ -165,7 +165,7 @@ static bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClass cons return false; } -static bool matches(CSS::Selector::SimpleSelector const& component, DOM::Element const& element) +static inline bool matches(CSS::Selector::SimpleSelector const& component, DOM::Element const& element) { switch (component.type) { case CSS::Selector::SimpleSelector::Type::Universal: @@ -188,7 +188,7 @@ static bool matches(CSS::Selector::SimpleSelector const& component, DOM::Element } } -static bool matches(CSS::Selector const& selector, int component_list_index, DOM::Element const& element) +static inline bool matches(CSS::Selector const& selector, int component_list_index, DOM::Element const& element) { auto& relative_selector = selector.compound_selectors()[component_list_index]; for (auto& simple_selector : relative_selector.simple_selectors) {
b3d87f8e3747aa40d2f72c5d91a25d38e505501b
2022-06-19 20:15:14
kleines Filmröllchen
ports: Update mold to 1.0.3
false
Update mold to 1.0.3
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index fb4881cf11a1..7b97585713e8 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -142,7 +142,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n | [`mc`](mc/) | Midnight Commander | 4.8.28 | https://midnight-commander.org/ | | [`mgba`](mgba/) | Game Boy, Game Boy Color and Game Boy Advance emulator | 0.9.3 | https://mgba.io/ | | [`milkytracker`](milkytracker/) | milkytracker | 1.03.00 | https://github.com/milkytracker/MilkyTracker | -| [`mold`](mold/) | A Modern Linker | 1.0.2 | https://github.com/rui314/mold | +| [`mold`](mold/) | A Modern Linker | 1.0.3 | https://github.com/rui314/mold | | [`mpc`](mpc/) | GNU Multiple Precision Complex Library (MPC) | 1.2.1 | http://www.multiprecision.org/mpc/ | | [`mpfr`](mpfr/) | GNU Multiple Precision Floating-Point Reliable Library (MPFR) | 4.1.0 | https://www.mpfr.org/ | | [`mrsh`](mrsh/) | mrsh | cd3c3a4 | https://mrsh.sh/ | diff --git a/Ports/mold/package.sh b/Ports/mold/package.sh index 2a2f54f98373..c2226b8a72ea 100755 --- a/Ports/mold/package.sh +++ b/Ports/mold/package.sh @@ -1,7 +1,7 @@ #!/usr/bin/env -S bash ../.port_include.sh port=mold -version=1.0.2 -files="https://github.com/rui314/mold/archive/refs/tags/v${version}.tar.gz mold-${version}.tgz 1a5c4779d10c6c81d21092ea776504f51e6a4994121f536550c60a8e7bb6a028" +version=1.0.3 +files="https://github.com/rui314/mold/archive/refs/tags/v${version}.tar.gz mold-${version}.tgz 488c12058b4c7c77bff94c6f919e40b2f12c304214e2e0d7d4833c21167837c0" auth_type=sha256 depends=("zlib" "openssl") makeopts=("OS=SerenityOS" "LDFLAGS=-L${DESTDIR}/usr/local/lib" "-j$(nproc)") diff --git a/Ports/mold/patches/0001-Disable-mold-wrapper.so-for-Serenity.patch b/Ports/mold/patches/0001-Disable-mold-wrapper.so-for-Serenity.patch index b80c39c1ce92..a12f760256e1 100644 --- a/Ports/mold/patches/0001-Disable-mold-wrapper.so-for-Serenity.patch +++ b/Ports/mold/patches/0001-Disable-mold-wrapper.so-for-Serenity.patch @@ -10,7 +10,7 @@ implemented in the Serenity DynamicLoader. 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile -index e2d7cd9..18262a1 100644 +index 844d149..946c952 100644 --- a/Makefile +++ b/Makefile @@ -119,7 +119,7 @@ ifeq ($(OS), Linux) diff --git a/Ports/mold/patches/0002-Disable-mimalloc-for-serenity.patch b/Ports/mold/patches/0002-Disable-mimalloc-for-serenity.patch index 6ccc77a98b2f..bf89af15f08b 100644 --- a/Ports/mold/patches/0002-Disable-mimalloc-for-serenity.patch +++ b/Ports/mold/patches/0002-Disable-mimalloc-for-serenity.patch @@ -10,7 +10,7 @@ That's one yak too far for right now. 1 file changed, 2 insertions(+) diff --git a/Makefile b/Makefile -index 18262a1..98c26cc 100644 +index 946c952..dc8563d 100644 --- a/Makefile +++ b/Makefile @@ -60,6 +60,8 @@ endif
0c4befd811dbf426ce98f7781ef1fe68cc06cd59
2022-11-27 06:21:36
davidot
libjs: Use the source offset to sort imports in module
false
Use the source offset to sort imports in module
libjs
diff --git a/Userland/Libraries/LibJS/AST.h b/Userland/Libraries/LibJS/AST.h index f01f6c1917d3..d08b78dbae27 100644 --- a/Userland/Libraries/LibJS/AST.h +++ b/Userland/Libraries/LibJS/AST.h @@ -54,6 +54,7 @@ class ASTNode : public RefCounted<ASTNode> { virtual void dump(int indent) const; [[nodiscard]] SourceRange source_range() const; + u32 start_offset() const { return m_start_offset; } void set_end_offset(Badge<Parser>, u32 end_offset) { m_end_offset = end_offset; } diff --git a/Userland/Libraries/LibJS/SourceTextModule.cpp b/Userland/Libraries/LibJS/SourceTextModule.cpp index 5004c4b12652..386e1f53f0c1 100644 --- a/Userland/Libraries/LibJS/SourceTextModule.cpp +++ b/Userland/Libraries/LibJS/SourceTextModule.cpp @@ -47,27 +47,26 @@ static Vector<ModuleRequest> module_requests(Program& program, Vector<String> co // A List of all the ModuleSpecifier strings used by the module represented by this record to request the importation of a module. // Note: The List is source text occurrence ordered! struct RequestedModuleAndSourceIndex { - u64 source_index { 0 }; + u32 source_offset { 0 }; ModuleRequest* module_request { nullptr }; }; Vector<RequestedModuleAndSourceIndex> requested_modules_with_indices; - for (auto& import_statement : program.imports()) { - requested_modules_with_indices.empend(import_statement.source_range().start.offset, &import_statement.module_request()); - } + for (auto& import_statement : program.imports()) + requested_modules_with_indices.empend(import_statement.start_offset(), &import_statement.module_request()); for (auto& export_statement : program.exports()) { for (auto& export_entry : export_statement.entries()) { if (!export_entry.is_module_request()) continue; - requested_modules_with_indices.empend(export_statement.source_range().start.offset, &export_statement.module_request()); + requested_modules_with_indices.empend(export_statement.start_offset(), &export_statement.module_request()); } } // Note: The List is source code occurrence ordered. https://tc39.es/proposal-import-assertions/#table-cyclic-module-fields quick_sort(requested_modules_with_indices, [&](RequestedModuleAndSourceIndex const& lhs, RequestedModuleAndSourceIndex const& rhs) { - return lhs.source_index < rhs.source_index; + return lhs.source_offset < rhs.source_offset; }); Vector<ModuleRequest> requested_modules_in_source_order;
efb55b1a4f70dad9bd5919cff31e7238728fdfb9
2020-08-22 15:24:30
thankyouverycool
base: Add new Calendar icons
false
Add new Calendar icons
base
diff --git a/Base/res/icons/16x16/add-event.png b/Base/res/icons/16x16/add-event.png new file mode 100644 index 000000000000..e6c44424cc3d Binary files /dev/null and b/Base/res/icons/16x16/add-event.png differ diff --git a/Base/res/icons/16x16/calendar-date.png b/Base/res/icons/16x16/calendar-date.png new file mode 100644 index 000000000000..eba765a429d9 Binary files /dev/null and b/Base/res/icons/16x16/calendar-date.png differ diff --git a/Base/res/icons/32x32/app-calendar.png b/Base/res/icons/32x32/app-calendar.png new file mode 100644 index 000000000000..3855a0c264e3 Binary files /dev/null and b/Base/res/icons/32x32/app-calendar.png differ
e9b16970fe5353823d3ce5aa1fcb12a0047af3c2
2024-03-20 21:48:57
Andrew Kaster
ak: Add base64url encoding and decoding methods
false
Add base64url encoding and decoding methods
ak
diff --git a/AK/Base64.cpp b/AK/Base64.cpp index 2918ddb89879..776f1d68517a 100644 --- a/AK/Base64.cpp +++ b/AK/Base64.cpp @@ -24,10 +24,9 @@ size_t calculate_base64_encoded_length(ReadonlyBytes input) return ((4 * input.size() / 3) + 3) & ~3; } -ErrorOr<ByteBuffer> decode_base64(StringView input) +template<auto alphabet_lookup_table> +ErrorOr<ByteBuffer> decode_base64_impl(StringView input) { - auto alphabet_lookup_table = base64_lookup_table(); - auto get = [&](size_t& offset, bool* is_padding, bool& parsed_something) -> ErrorOr<u8> { while (offset < input.length() && is_ascii_space(input[offset])) ++offset; @@ -80,7 +79,8 @@ ErrorOr<ByteBuffer> decode_base64(StringView input) return ByteBuffer::copy(output); } -ErrorOr<String> encode_base64(ReadonlyBytes input) +template<auto alphabet> +ErrorOr<String> encode_base64_impl(ReadonlyBytes input) { StringBuilder output(calculate_base64_encoded_length(input)); @@ -106,10 +106,10 @@ ErrorOr<String> encode_base64(ReadonlyBytes input) const u8 index2 = ((in1 << 2) | (in2 >> 6)) & 0x3f; const u8 index3 = in2 & 0x3f; - char const out0 = base64_alphabet[index0]; - char const out1 = base64_alphabet[index1]; - char const out2 = is_16bit ? '=' : base64_alphabet[index2]; - char const out3 = is_8bit ? '=' : base64_alphabet[index3]; + char const out0 = alphabet[index0]; + char const out1 = alphabet[index1]; + char const out2 = is_16bit ? '=' : alphabet[index2]; + char const out3 = is_8bit ? '=' : alphabet[index3]; TRY(output.try_append(out0)); TRY(output.try_append(out1)); @@ -120,4 +120,23 @@ ErrorOr<String> encode_base64(ReadonlyBytes input) return output.to_string(); } +ErrorOr<ByteBuffer> decode_base64(StringView input) +{ + return decode_base64_impl<base64_lookup_table()>(input); +} + +ErrorOr<ByteBuffer> decode_base64url(StringView input) +{ + return decode_base64_impl<base64url_lookup_table()>(input); +} + +ErrorOr<String> encode_base64(ReadonlyBytes input) +{ + return encode_base64_impl<base64_alphabet>(input); +} +ErrorOr<String> encode_base64url(ReadonlyBytes input) +{ + return encode_base64_impl<base64url_alphabet>(input); +} + } diff --git a/AK/Base64.h b/AK/Base64.h index fcda96011975..f9f29bab6c93 100644 --- a/AK/Base64.h +++ b/AK/Base64.h @@ -14,6 +14,7 @@ namespace AK { +// https://datatracker.ietf.org/doc/html/rfc4648#section-4 constexpr Array base64_alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', @@ -25,6 +26,18 @@ constexpr Array base64_alphabet = { '4', '5', '6', '7', '8', '9', '+', '/' }; +// https://datatracker.ietf.org/doc/html/rfc4648#section-5 +constexpr Array base64url_alphabet = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '-', '_' +}; + consteval auto base64_lookup_table() { Array<i16, 256> table; @@ -35,16 +48,30 @@ consteval auto base64_lookup_table() return table; } +consteval auto base64url_lookup_table() +{ + Array<i16, 256> table; + table.fill(-1); + for (size_t i = 0; i < base64url_alphabet.size(); ++i) { + table[base64url_alphabet[i]] = static_cast<i16>(i); + } + return table; +} + [[nodiscard]] size_t calculate_base64_decoded_length(StringView); [[nodiscard]] size_t calculate_base64_encoded_length(ReadonlyBytes); [[nodiscard]] ErrorOr<ByteBuffer> decode_base64(StringView); +[[nodiscard]] ErrorOr<ByteBuffer> decode_base64url(StringView); [[nodiscard]] ErrorOr<String> encode_base64(ReadonlyBytes); +[[nodiscard]] ErrorOr<String> encode_base64url(ReadonlyBytes); } #if USING_AK_GLOBALLY using AK::decode_base64; +using AK::decode_base64url; using AK::encode_base64; +using AK::encode_base64url; #endif diff --git a/Tests/AK/TestBase64.cpp b/Tests/AK/TestBase64.cpp index 02539a606121..9ca486dba91e 100644 --- a/Tests/AK/TestBase64.cpp +++ b/Tests/AK/TestBase64.cpp @@ -27,6 +27,8 @@ TEST_CASE(test_decode) decode_equal("Zm9vYmFy"sv, "foobar"sv); decode_equal("Z m\r9\n v\v Ym\tFy"sv, "foobar"sv); EXPECT_EQ(decode_base64(" ZD Qg\r\nPS An Zm91cic\r\n 7"sv).value(), decode_base64("ZDQgPSAnZm91cic7"sv).value()); + + decode_equal("aGVsbG8/d29ybGQ="sv, "hello?world"sv); } TEST_CASE(test_decode_invalid) @@ -35,6 +37,23 @@ TEST_CASE(test_decode_invalid) EXPECT(decode_base64(("asdf\x80qwe"sv)).is_error()); EXPECT(decode_base64(("asdf:qwe"sv)).is_error()); EXPECT(decode_base64(("asdf=qwe"sv)).is_error()); + + EXPECT(decode_base64("aGVsbG8_d29ybGQ="sv).is_error()); + EXPECT(decode_base64url("aGVsbG8/d29ybGQ="sv).is_error()); +} + +TEST_CASE(test_decode_only_padding) +{ + // Only padding is not allowed + EXPECT(decode_base64("="sv).is_error()); + EXPECT(decode_base64("=="sv).is_error()); + EXPECT(decode_base64("==="sv).is_error()); + EXPECT(decode_base64("===="sv).is_error()); + + EXPECT(decode_base64url("="sv).is_error()); + EXPECT(decode_base64url("=="sv).is_error()); + EXPECT(decode_base64url("==="sv).is_error()); + EXPECT(decode_base64url("===="sv).is_error()); } TEST_CASE(test_encode) @@ -53,3 +72,46 @@ TEST_CASE(test_encode) encode_equal("fooba"sv, "Zm9vYmE="sv); encode_equal("foobar"sv, "Zm9vYmFy"sv); } + +TEST_CASE(test_urldecode) +{ + auto decode_equal = [&](StringView input, StringView expected) { + auto decoded = TRY_OR_FAIL(decode_base64url(input)); + EXPECT(ByteString::copy(decoded) == expected); + EXPECT(expected.length() <= calculate_base64_decoded_length(input.bytes())); + }; + + decode_equal(""sv, ""sv); + decode_equal("Zg=="sv, "f"sv); + decode_equal("Zm8="sv, "fo"sv); + decode_equal("Zm9v"sv, "foo"sv); + decode_equal("Zm9vYg=="sv, "foob"sv); + decode_equal("Zm9vYmE="sv, "fooba"sv); + decode_equal("Zm9vYmFy"sv, "foobar"sv); + decode_equal("Z m\r9\n v\v Ym\tFy"sv, "foobar"sv); + + decode_equal("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEu"sv, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."sv); + decode_equal("aGVsbG8_d29ybGQ="sv, "hello?world"sv); +} + +TEST_CASE(test_urlencode) +{ + auto encode_equal = [&](StringView input, StringView expected) { + auto encoded = MUST(encode_base64url(input.bytes())); + EXPECT(encoded == expected); + EXPECT_EQ(expected.length(), calculate_base64_encoded_length(input.bytes())); + }; + + encode_equal(""sv, ""sv); + encode_equal("f"sv, "Zg=="sv); + encode_equal("fo"sv, "Zm8="sv); + encode_equal("foo"sv, "Zm9v"sv); + encode_equal("foob"sv, "Zm9vYg=="sv); + encode_equal("fooba"sv, "Zm9vYmE="sv); + encode_equal("foobar"sv, "Zm9vYmFy"sv); + + encode_equal("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."sv, "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEu"sv); + encode_equal("hello?world"sv, "aGVsbG8_d29ybGQ="sv); + + encode_equal("hello!!world"sv, "aGVsbG8hIXdvcmxk"sv); +}
045a42cf35ae9f58d0a4bcfb9af94118d580d83f
2021-11-30 22:35:32
davidot
libjs: Parse dynamic import calls 'import()' and 'import.meta'
false
Parse dynamic import calls 'import()' and 'import.meta'
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index f45de4533b15..0b62e408481d 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -2880,17 +2880,39 @@ void MetaProperty::dump(int indent) const outln("{} {}", class_name(), name); } -Value MetaProperty::execute(Interpreter& interpreter, GlobalObject&) const +Value MetaProperty::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; if (m_type == MetaProperty::Type::NewTarget) return interpreter.vm().get_new_target().value_or(js_undefined()); - if (m_type == MetaProperty::Type::ImportMeta) - TODO(); + if (m_type == MetaProperty::Type::ImportMeta) { + interpreter.vm().throw_exception<InternalError>(global_object, ErrorType::NotImplemented, "'import.meta' in modules"); + return {}; + } + VERIFY_NOT_REACHED(); } +void ImportCall::dump(int indent) const +{ + ASTNode::dump(indent); + print_indent(indent); + outln("(Specifier)"); + m_specifier->dump(indent + 1); + if (m_options) { + outln("(Options)"); + m_options->dump(indent + 1); + } +} + +Value ImportCall::execute(Interpreter& interpreter, GlobalObject& global_object) const +{ + InterpreterNodeScope node_scope { interpreter, *this }; + interpreter.vm().throw_exception<InternalError>(global_object, ErrorType::NotImplemented, "'import(...)' in modules"); + return {}; +} + Value StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; diff --git a/Userland/Libraries/LibJS/AST.h b/Userland/Libraries/LibJS/AST.h index f0e630fd1d33..db28e68fbc7e 100644 --- a/Userland/Libraries/LibJS/AST.h +++ b/Userland/Libraries/LibJS/AST.h @@ -1671,6 +1671,23 @@ class MetaProperty final : public Expression { Type m_type; }; +class ImportCall final : public Expression { +public: + ImportCall(SourceRange source_range, NonnullRefPtr<Expression> specifier, RefPtr<Expression> options) + : Expression(source_range) + , m_specifier(move(specifier)) + , m_options(move(options)) + { + } + + virtual void dump(int indent) const override; + virtual Value execute(Interpreter&, GlobalObject&) const override; + +private: + NonnullRefPtr<Expression> m_specifier; + RefPtr<Expression> m_options; +}; + class ConditionalExpression final : public Expression { public: ConditionalExpression(SourceRange source_range, NonnullRefPtr<Expression> test, NonnullRefPtr<Expression> consequent, NonnullRefPtr<Expression> alternate) diff --git a/Userland/Libraries/LibJS/Parser.cpp b/Userland/Libraries/LibJS/Parser.cpp index 0f1127d6c395..2fd41c36fd31 100644 --- a/Userland/Libraries/LibJS/Parser.cpp +++ b/Userland/Libraries/LibJS/Parser.cpp @@ -874,6 +874,63 @@ RefPtr<MetaProperty> Parser::try_parse_new_target_expression() return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::NewTarget); } +RefPtr<MetaProperty> Parser::try_parse_import_meta_expression() +{ + // Optimization which skips the save/load state. + if (next_token().type() != TokenType::Period) + return {}; + + save_state(); + auto rule_start = push_start(); + ArmedScopeGuard state_rollback_guard = [&] { + load_state(); + }; + + consume(TokenType::Import); + consume(TokenType::Period); + if (!match(TokenType::Identifier)) + return {}; + // The string 'meta' cannot have escapes so we check original value. + if (consume().original_value() != "meta"sv) + return {}; + + state_rollback_guard.disarm(); + discard_saved_state(); + return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::ImportMeta); +} + +NonnullRefPtr<ImportCall> Parser::parse_import_call() +{ + auto rule_start = push_start(); + + // We use the extended definition: + // ImportCall[Yield, Await]: + // import(AssignmentExpression[+In, ?Yield, ?Await] ,opt) + // import(AssignmentExpression[+In, ?Yield, ?Await] ,AssignmentExpression[+In, ?Yield, ?Await] ,opt) + // From https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call + + consume(TokenType::Import); + consume(TokenType::ParenOpen); + auto argument = parse_expression(2); + + RefPtr<Expression> options; + if (match(TokenType::Comma)) { + consume(TokenType::Comma); + + if (!match(TokenType::ParenClose)) { + options = parse_expression(2); + + // Second optional comma + if (match(TokenType::Comma)) + consume(TokenType::Comma); + } + } + + consume(TokenType::ParenClose); + + return create_ast_node<ImportCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), move(options)); +} + NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration() { auto rule_start = push_start(); @@ -1305,6 +1362,19 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() } return { parse_new_expression() }; } + case TokenType::Import: { + auto lookahead_token = next_token(); + VERIFY(lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen); + if (lookahead_token.type() == TokenType::ParenOpen) + return { parse_import_call() }; + + if (auto import_meta = try_parse_import_meta_expression()) { + if (m_program_type != Program::Type::Module) + syntax_error("import.meta is only allowed in modules"); + return { import_meta.release_nonnull() }; + } + break; + } case TokenType::Yield: if (!m_state.in_generator_function_context) goto read_as_identifier; @@ -1321,10 +1391,11 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() default: if (match_identifier_name()) goto read_as_identifier; - expected("primary expression"); - consume(); - return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) }; + break; } + expected("primary expression"); + consume(); + return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) }; } NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal() @@ -2115,6 +2186,8 @@ NonnullRefPtr<NewExpression> Parser::parse_new_expression() consume(TokenType::New); auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen, TokenType::QuestionMarkPeriod }); + if (is<ImportCall>(*callee)) + syntax_error("Cannot call new on dynamic import", callee->source_range().start); Vector<CallExpression::Argument> arguments; @@ -3343,6 +3416,11 @@ bool Parser::match(TokenType type) const bool Parser::match_expression() const { auto type = m_state.current_token.type(); + if (type == TokenType::Import) { + auto lookahead_token = next_token(); + return lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen; + } + return type == TokenType::BoolLiteral || type == TokenType::NumericLiteral || type == TokenType::BigIntLiteral diff --git a/Userland/Libraries/LibJS/Parser.h b/Userland/Libraries/LibJS/Parser.h index 7255058b7a7b..47a3d27af449 100644 --- a/Userland/Libraries/LibJS/Parser.h +++ b/Userland/Libraries/LibJS/Parser.h @@ -122,6 +122,8 @@ class Parser { RefPtr<FunctionExpression> try_parse_arrow_function_expression(bool expect_parens, bool is_async = false); RefPtr<Statement> try_parse_labelled_statement(AllowLabelledFunction allow_function); RefPtr<MetaProperty> try_parse_new_target_expression(); + RefPtr<MetaProperty> try_parse_import_meta_expression(); + NonnullRefPtr<ImportCall> parse_import_call(); Vector<CallExpression::Argument> parse_arguments();
597cf88c08540984d825195d5e46d62434b352d1
2021-06-19 01:05:23
Linus Groh
libjs: Implement the 'Hashbang Grammar for JS' proposal
false
Implement the 'Hashbang Grammar for JS' proposal
libjs
diff --git a/Userland/Libraries/LibJS/Lexer.cpp b/Userland/Libraries/LibJS/Lexer.cpp index cf4c05207280..1245817d5be4 100644 --- a/Userland/Libraries/LibJS/Lexer.cpp +++ b/Userland/Libraries/LibJS/Lexer.cpp @@ -308,7 +308,9 @@ bool Lexer::is_line_comment_start(bool line_has_token_yet) const // "-->" is considered a line comment start if the current line is only whitespace and/or // other block comment(s); or in other words: the current line does not have a token or // ongoing line comment yet - || (match('-', '-', '>') && !line_has_token_yet); + || (match('-', '-', '>') && !line_has_token_yet) + // https://tc39.es/proposal-hashbang/out.html#sec-updated-syntax + || (match('#', '!') && m_position == 1); } bool Lexer::is_block_comment_start() const diff --git a/Userland/Libraries/LibJS/Tests/comments-basic.js b/Userland/Libraries/LibJS/Tests/comments-basic.js index 101e520a2934..7ad452bf2975 100644 --- a/Userland/Libraries/LibJS/Tests/comments-basic.js +++ b/Userland/Libraries/LibJS/Tests/comments-basic.js @@ -33,3 +33,12 @@ test("unterminated multi-line comment", () => { expect("/* foo").not.toEval(); expect("foo /*").not.toEval(); }); + +test("hashbang comments", () => { + expect("#!").toEvalTo(undefined); + expect("#!/bin/js").toEvalTo(undefined); + expect("#!\n1").toEvalTo(1); + expect(" #!").not.toEval(); + expect("\n#!").not.toEval(); + expect("#!\n#!").not.toEval(); +}); diff --git a/Userland/Utilities/js.cpp b/Userland/Utilities/js.cpp index 6e2e617a008d..69e45a178d56 100644 --- a/Userland/Utilities/js.cpp +++ b/Userland/Utilities/js.cpp @@ -508,23 +508,6 @@ static void print(JS::Value value) outln(); } -static bool file_has_shebang(ByteBuffer const& file_contents) -{ - if (file_contents.size() >= 2 && file_contents[0] == '#' && file_contents[1] == '!') - return true; - return false; -} - -static StringView strip_shebang(ByteBuffer const& file_contents) -{ - size_t i = 0; - for (i = 2; i < file_contents.size(); ++i) { - if (file_contents[i] == '\n') - break; - } - return StringView((const char*)file_contents.data() + i, file_contents.size() - i); -} - static bool write_to_file(const String& path) { int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666); @@ -650,9 +633,7 @@ static JS::Value load_file_impl(JS::VM& vm, JS::GlobalObject& global_object) return {}; } auto file_contents = file->read_all(); - auto source = file_has_shebang(file_contents) - ? strip_shebang(file_contents) - : StringView { file_contents }; + auto source = StringView { file_contents }; auto parser = JS::Parser(JS::Lexer(source)); auto program = parser.parse_program(); if (parser.has_errors()) { @@ -1099,13 +1080,7 @@ int main(int argc, char** argv) return 1; } auto file_contents = file->read_all(); - - StringView source; - if (file_has_shebang(file_contents)) { - source = strip_shebang(file_contents); - } else { - source = file_contents; - } + auto source = StringView { file_contents }; builder.append(source); }
5e64156fce5913665e598db4fe929b9c83bf744f
2021-07-29 02:27:30
Linus Groh
libjs: Implement Temporal.Now.plainTimeISO()
false
Implement Temporal.Now.plainTimeISO()
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h index 1ee234dafe8c..904813d9629e 100644 --- a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h +++ b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h @@ -291,6 +291,7 @@ namespace JS { P(plainDateISO) \ P(plainDateTime) \ P(plainDateTimeISO) \ + P(plainTimeISO) \ P(pop) \ P(pow) \ P(preventExtensions) \ diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp index 749b48722851..9a3d6e855eae 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp @@ -11,6 +11,7 @@ #include <LibJS/Runtime/Temporal/Now.h> #include <LibJS/Runtime/Temporal/PlainDate.h> #include <LibJS/Runtime/Temporal/PlainDateTime.h> +#include <LibJS/Runtime/Temporal/PlainTime.h> #include <LibJS/Runtime/Temporal/TimeZone.h> #include <time.h> @@ -38,6 +39,7 @@ void Now::initialize(GlobalObject& global_object) define_native_function(vm.names.plainDateTimeISO, plain_date_time_iso, 0, attr); define_native_function(vm.names.plainDate, plain_date, 1, attr); define_native_function(vm.names.plainDateISO, plain_date_iso, 0, attr); + define_native_function(vm.names.plainTimeISO, plain_time_iso, 0, attr); } // 2.2.1 Temporal.Now.timeZone ( ), https://tc39.es/proposal-temporal/#sec-temporal.now.timezone @@ -112,6 +114,24 @@ JS_DEFINE_NATIVE_FUNCTION(Now::plain_date_iso) return create_temporal_date(global_object, date_time->iso_year(), date_time->iso_month(), date_time->iso_day(), date_time->calendar()); } +// 2.2.9 Temporal.Now.plainTimeISO ( [ temporalTimeZoneLike ] ), https://tc39.es/proposal-temporal/#sec-temporal.now.plaintimeiso +JS_DEFINE_NATIVE_FUNCTION(Now::plain_time_iso) +{ + auto temporal_time_zone_like = vm.argument(0); + + // 1. Let calendar be ? GetISO8601Calendar(). + // NOTE: No exception check needed for GetISO8601Calendar, see https://github.com/tc39/proposal-temporal/pull/1643 + auto* calendar = get_iso8601_calendar(global_object); + + // 2. Let dateTime be ? SystemDateTime(temporalTimeZoneLike, calendar). + auto date_time = system_date_time(global_object, temporal_time_zone_like, calendar); + if (vm.exception()) + return {}; + + // 3. Return ? CreateTemporalTime(dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]]). + return create_temporal_time(global_object, date_time->iso_hour(), date_time->iso_minute(), date_time->iso_second(), date_time->iso_millisecond(), date_time->iso_microsecond(), date_time->iso_nanosecond()); +} + // 2.3.1 SystemTimeZone ( ), https://tc39.es/proposal-temporal/#sec-temporal-systemtimezone TimeZone* system_time_zone(GlobalObject& global_object) { diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.h b/Userland/Libraries/LibJS/Runtime/Temporal/Now.h index f3d561fe8b7a..5f230feaeede 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.h @@ -25,6 +25,7 @@ class Now final : public Object { JS_DECLARE_NATIVE_FUNCTION(plain_date_time_iso); JS_DECLARE_NATIVE_FUNCTION(plain_date); JS_DECLARE_NATIVE_FUNCTION(plain_date_iso); + JS_DECLARE_NATIVE_FUNCTION(plain_time_iso); }; TimeZone* system_time_zone(GlobalObject&); diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/Now/Now.plainTimeISO.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Now/Now.plainTimeISO.js new file mode 100644 index 000000000000..bfdab226c5fb --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Now/Now.plainTimeISO.js @@ -0,0 +1,22 @@ +describe("correct behavior", () => { + test("length is 0", () => { + expect(Temporal.Now.plainTimeISO).toHaveLength(0); + }); + + test("basic functionality", () => { + const plainTime = Temporal.Now.plainTimeISO(); + expect(plainTime).toBeInstanceOf(Temporal.PlainTime); + expect(plainTime.calendar.id).toBe("iso8601"); + }); + + test("custom time zone", () => { + const timeZone = { + getOffsetNanosecondsFor() { + return 86400000000000; + }, + }; + const plainTime = Temporal.Now.plainTimeISO(); + const plainTimeWithOffset = Temporal.Now.plainTimeISO(timeZone); + // FIXME: Compare these in a sensible way + }); +});
5d379fcfb4c4cfd933e30f21703361ef2fab53f1
2021-04-05 02:13:43
Andreas Kling
systemmonitor: Actually reuse existing process properties windows
false
Actually reuse existing process properties windows
systemmonitor
diff --git a/Userland/Applications/SystemMonitor/main.cpp b/Userland/Applications/SystemMonitor/main.cpp index d8c13fa4691c..cbaa8b2514bc 100644 --- a/Userland/Applications/SystemMonitor/main.cpp +++ b/Userland/Applications/SystemMonitor/main.cpp @@ -301,13 +301,16 @@ int main(int argc, char** argv) auto pid = selected_id(ProcessModel::Column::PID); RefPtr<GUI::Window> process_window; - if (!process_windows.contains(pid)) { + auto it = process_windows.find(pid); + if (it == process_windows.end()) { process_window = build_process_window(pid); process_window->on_close_request = [pid, &process_windows] { process_windows.remove(pid); return GUI::Window::CloseRequestDecision::Close; }; process_windows.set(pid, *process_window); + } else { + process_window = it->value; } process_window->show(); process_window->move_to_front();
246e0e47ec731fdb7c5b930f1c2c55af3dfa84bc
2020-06-15 01:39:35
Andreas Kling
libweb: Make the specificity sort comparator a bit more readable
false
Make the specificity sort comparator a bit more readable
libweb
diff --git a/Libraries/LibWeb/CSS/StyleResolver.cpp b/Libraries/LibWeb/CSS/StyleResolver.cpp index 62a8e44ff570..142a1003428f 100644 --- a/Libraries/LibWeb/CSS/StyleResolver.cpp +++ b/Libraries/LibWeb/CSS/StyleResolver.cpp @@ -497,15 +497,12 @@ NonnullRefPtr<StyleProperties> StyleResolver::resolve_style(const Element& eleme quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) { auto& a_selector = a.rule->selectors()[a.selector_index]; auto& b_selector = b.rule->selectors()[b.selector_index]; - if (a_selector.specificity() < b_selector.specificity()) - return true; - if (!(a_selector.specificity() == b_selector.specificity())) - return false; - if (a.style_sheet_index < b.style_sheet_index) - return true; - if (a.style_sheet_index > b.style_sheet_index) - return false; - return a.rule_index < b.rule_index; + if (a_selector.specificity() == b_selector.specificity()) { + if (a.style_sheet_index == b.style_sheet_index) + return a.rule_index < b.rule_index; + return a.style_sheet_index < b.style_sheet_index; + } + return a_selector.specificity() < b_selector.specificity(); }); for (auto& match : matching_rules) {
79ab9cce18de191444ec6ff599ee25308f3d3229
2021-06-27 19:16:42
Gunnar Beutner
kernel: Clear segment registers on x86_64
false
Clear segment registers on x86_64
kernel
diff --git a/Kernel/Arch/x86/x86_64/Boot/boot.S b/Kernel/Arch/x86/x86_64/Boot/boot.S index ba65ee00d5c2..85554d806d59 100644 --- a/Kernel/Arch/x86/x86_64/Boot/boot.S +++ b/Kernel/Arch/x86/x86_64/Boot/boot.S @@ -265,6 +265,13 @@ start: .code64 1: + mov $0, %ax + mov %ax, %ss + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + call init add $4, %rsp
87e063db6581ba027d958028cd66a9fd9ef3b691
2023-09-25 16:49:25
Hendiadyoin1
libjs: Make GC deferral friendship based
false
Make GC deferral friendship based
libjs
diff --git a/Userland/Libraries/LibJS/Heap/DeferGC.h b/Userland/Libraries/LibJS/Heap/DeferGC.h index c2a5ab8f2686..c57b99d41af2 100644 --- a/Userland/Libraries/LibJS/Heap/DeferGC.h +++ b/Userland/Libraries/LibJS/Heap/DeferGC.h @@ -15,12 +15,12 @@ class DeferGC { explicit DeferGC(Heap& heap) : m_heap(heap) { - m_heap.defer_gc({}); + m_heap.defer_gc(); } ~DeferGC() { - m_heap.undefer_gc({}); + m_heap.undefer_gc(); } private: diff --git a/Userland/Libraries/LibJS/Heap/Heap.cpp b/Userland/Libraries/LibJS/Heap/Heap.cpp index 14234b6d72ed..bfb797edb052 100644 --- a/Userland/Libraries/LibJS/Heap/Heap.cpp +++ b/Userland/Libraries/LibJS/Heap/Heap.cpp @@ -575,12 +575,12 @@ void Heap::did_destroy_weak_container(Badge<WeakContainer>, WeakContainer& set) m_weak_containers.remove(set); } -void Heap::defer_gc(Badge<DeferGC>) +void Heap::defer_gc() { ++m_gc_deferrals; } -void Heap::undefer_gc(Badge<DeferGC>) +void Heap::undefer_gc() { VERIFY(m_gc_deferrals > 0); --m_gc_deferrals; diff --git a/Userland/Libraries/LibJS/Heap/Heap.h b/Userland/Libraries/LibJS/Heap/Heap.h index c92e68a4c9f1..1a97a1e7d47e 100644 --- a/Userland/Libraries/LibJS/Heap/Heap.h +++ b/Userland/Libraries/LibJS/Heap/Heap.h @@ -73,9 +73,6 @@ class Heap : public HeapBase { void did_create_weak_container(Badge<WeakContainer>, WeakContainer&); void did_destroy_weak_container(Badge<WeakContainer>, WeakContainer&); - void defer_gc(Badge<DeferGC>); - void undefer_gc(Badge<DeferGC>); - BlockAllocator& block_allocator() { return m_block_allocator; } void uproot_cell(Cell* cell); @@ -83,6 +80,10 @@ class Heap : public HeapBase { private: friend class MarkingVisitor; friend class GraphConstructorVisitor; + friend class DeferGC; + + void defer_gc(); + void undefer_gc(); static bool cell_must_survive_garbage_collection(Cell const&);
458706c4cf56c29bd2a39ee0dd76652eeab39310
2019-02-07 13:54:41
Andreas Kling
kernel: Let's try disabling the CPU's page-level caching for framebuffers.
false
Let's try disabling the CPU's page-level caching for framebuffers.
kernel
diff --git a/Kernel/MemoryManager.cpp b/Kernel/MemoryManager.cpp index 85d47792936f..7f7020395974 100644 --- a/Kernel/MemoryManager.cpp +++ b/Kernel/MemoryManager.cpp @@ -483,6 +483,8 @@ void MemoryManager::remap_region_page(Region& region, unsigned page_index_in_reg pte.set_writable(false); else pte.set_writable(region.is_writable()); + pte.set_cache_disabled(!region.vmo().m_allow_cpu_caching); + pte.set_write_through(!region.vmo().m_allow_cpu_caching); pte.set_user_allowed(user_allowed); region.page_directory()->flush(page_laddr); #ifdef MM_DEBUG @@ -517,6 +519,8 @@ void MemoryManager::map_region_at_address(PageDirectory& page_directory, Region& pte.set_writable(false); else pte.set_writable(region.is_writable()); + pte.set_cache_disabled(!region.vmo().m_allow_cpu_caching); + pte.set_write_through(!region.vmo().m_allow_cpu_caching); } else { pte.set_physical_page_base(0); pte.set_present(false); @@ -676,7 +680,9 @@ RetainPtr<VMObject> VMObject::create_anonymous(size_t size) RetainPtr<VMObject> VMObject::create_framebuffer_wrapper(PhysicalAddress paddr, size_t size) { size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE; - return adopt(*new VMObject(paddr, size)); + auto vmo = adopt(*new VMObject(paddr, size)); + vmo->m_allow_cpu_caching = false; + return vmo; } RetainPtr<VMObject> VMObject::clone() diff --git a/Kernel/MemoryManager.h b/Kernel/MemoryManager.h index 78ed36fc1172..b5974c3d6708 100644 --- a/Kernel/MemoryManager.h +++ b/Kernel/MemoryManager.h @@ -114,6 +114,7 @@ class VMObject : public Retainable<VMObject> { bool m_anonymous { false }; off_t m_inode_offset { 0 }; size_t m_size { 0 }; + bool m_allow_cpu_caching { true }; RetainPtr<Inode> m_inode; Vector<RetainPtr<PhysicalPage>> m_physical_pages; Lock m_paging_lock; @@ -292,6 +293,8 @@ class MemoryManager { Present = 1 << 0, ReadWrite = 1 << 1, UserSupervisor = 1 << 2, + WriteThrough = 1 << 3, + CacheDisabled = 1 << 4, }; bool is_present() const { return raw() & Present; } @@ -303,6 +306,12 @@ class MemoryManager { bool is_writable() const { return raw() & ReadWrite; } void set_writable(bool b) { set_bit(ReadWrite, b); } + bool is_write_through() const { return raw() & WriteThrough; } + void set_write_through(bool b) { set_bit(WriteThrough, b); } + + bool is_cache_disabled() const { return raw() & CacheDisabled; } + void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); } + void set_bit(byte bit, bool value) { if (value) @@ -331,6 +340,8 @@ class MemoryManager { Present = 1 << 0, ReadWrite = 1 << 1, UserSupervisor = 1 << 2, + WriteThrough = 1 << 3, + CacheDisabled = 1 << 4, }; bool is_present() const { return raw() & Present; } @@ -342,6 +353,12 @@ class MemoryManager { bool is_writable() const { return raw() & ReadWrite; } void set_writable(bool b) { set_bit(ReadWrite, b); } + bool is_write_through() const { return raw() & WriteThrough; } + void set_write_through(bool b) { set_bit(WriteThrough, b); } + + bool is_cache_disabled() const { return raw() & CacheDisabled; } + void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); } + void set_bit(byte bit, bool value) { if (value)
41980675f2c8e4060f358042fad101da7dda8695
2023-02-25 19:30:23
Nico Weber
lagom: Build `file` in lagom builds
false
Build `file` in lagom builds
lagom
diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index b4aba13ebbd9..7dae1bfde5f9 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -485,6 +485,12 @@ if (BUILD_LAGOM) target_link_libraries(disasm LibCore LibELF LibX86 LibMain) endif() + if (NOT EMSCRIPTEN) + # LibELF is part of LibC in SerenityOS builds, but not in Lagom. + add_executable(file ../../Userland/Utilities/file.cpp) + target_link_libraries(file LibCompress LibCore LibELF LibGfx LibIPC LibMain) + endif() + add_executable(gml-format ../../Userland/Utilities/gml-format.cpp) target_link_libraries(gml-format LibCore LibGUI LibMain)
ac274eee72be852afc0e357a3525f133699a3dc9
2022-09-06 03:57:09
Andreas Kling
libweb: Remove the NO_INSTANCE option now that all wrappers are gone
false
Remove the NO_INSTANCE option now that all wrappers are gone
libweb
diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake index 9979a1492dbc..8716944bd32b 100644 --- a/Meta/CMake/libweb_generators.cmake +++ b/Meta/CMake/libweb_generators.cmake @@ -106,7 +106,6 @@ function (generate_js_wrappers target) function(libweb_js_wrapper class) cmake_parse_arguments(PARSE_ARGV 1 LIBWEB_WRAPPER "ITERABLE" "" "") - cmake_parse_arguments(PARSE_ARGV 1 LIBWEB_WRAPPER "NO_INSTANCE" "" "") get_filename_component(basename "${class}" NAME) set(BINDINGS_SOURCES "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}Constructor.h" @@ -120,32 +119,9 @@ function (generate_js_wrappers target) prototype-header prototype-implementation ) - if(NOT LIBWEB_WRAPPER_NO_INSTANCE) - set(BINDINGS_SOURCES - ${BINDINGS_SOURCES} - "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}Wrapper.h" - "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}Wrapper.cpp" - ) - - set(BINDINGS_TYPES - ${BINDINGS_TYPES} - header - implementation - ) - endif() # FIXME: Instead of requiring a manual declaration of iterable wrappers, we should ask WrapperGenerator if it's iterable if(LIBWEB_WRAPPER_ITERABLE) - if(NOT LIBWEB_WRAPPER_NO_INSTANCE) - list(APPEND BINDINGS_SOURCES - "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}IteratorWrapper.h" - "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}IteratorWrapper.cpp" - ) - list(APPEND BINDINGS_TYPES - iterator-header - iterator-implementation - ) - endif() list(APPEND BINDINGS_SOURCES "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}IteratorPrototype.h" "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}IteratorPrototype.cpp" diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake index 7708d8d2c2d1..9e91f119fd5f 100644 --- a/Userland/Libraries/LibWeb/idl_files.cmake +++ b/Userland/Libraries/LibWeb/idl_files.cmake @@ -1,190 +1,190 @@ # This file is included from "Meta/CMake/libweb_data.cmake" # It is defined here so that there is no need to go to the Meta directory when adding new idl files -libweb_js_wrapper(Crypto/Crypto NO_INSTANCE) -libweb_js_wrapper(Crypto/SubtleCrypto NO_INSTANCE) -libweb_js_wrapper(CSS/CSSConditionRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSFontFaceRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSGroupingRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSImportRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSMediaRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSRuleList NO_INSTANCE) -libweb_js_wrapper(CSS/CSSStyleDeclaration NO_INSTANCE) -libweb_js_wrapper(CSS/CSSStyleRule NO_INSTANCE) -libweb_js_wrapper(CSS/CSSStyleSheet NO_INSTANCE) -libweb_js_wrapper(CSS/CSSSupportsRule NO_INSTANCE) -libweb_js_wrapper(CSS/MediaList NO_INSTANCE) -libweb_js_wrapper(CSS/MediaQueryList NO_INSTANCE) -libweb_js_wrapper(CSS/MediaQueryListEvent NO_INSTANCE) -libweb_js_wrapper(CSS/Screen NO_INSTANCE) -libweb_js_wrapper(CSS/StyleSheet NO_INSTANCE) -libweb_js_wrapper(CSS/StyleSheetList NO_INSTANCE) -libweb_js_wrapper(DOM/AbstractRange NO_INSTANCE) -libweb_js_wrapper(DOM/Attribute NO_INSTANCE) -libweb_js_wrapper(DOM/AbortController NO_INSTANCE) -libweb_js_wrapper(DOM/AbortSignal NO_INSTANCE) -libweb_js_wrapper(DOM/CDATASection NO_INSTANCE) -libweb_js_wrapper(DOM/CharacterData NO_INSTANCE) -libweb_js_wrapper(DOM/Comment NO_INSTANCE) -libweb_js_wrapper(DOM/CustomEvent NO_INSTANCE) -libweb_js_wrapper(DOM/Document NO_INSTANCE) -libweb_js_wrapper(DOM/DocumentFragment NO_INSTANCE) -libweb_js_wrapper(DOM/DocumentType NO_INSTANCE) -libweb_js_wrapper(DOM/DOMException NO_INSTANCE) -libweb_js_wrapper(DOM/DOMImplementation NO_INSTANCE) -libweb_js_wrapper(DOM/DOMTokenList NO_INSTANCE) -libweb_js_wrapper(DOM/Element NO_INSTANCE) -libweb_js_wrapper(DOM/Event NO_INSTANCE) -libweb_js_wrapper(DOM/EventTarget NO_INSTANCE) -libweb_js_wrapper(DOM/HTMLCollection NO_INSTANCE) -libweb_js_wrapper(DOM/MutationRecord NO_INSTANCE) -libweb_js_wrapper(DOM/MutationObserver NO_INSTANCE) -libweb_js_wrapper(DOM/NamedNodeMap NO_INSTANCE) -libweb_js_wrapper(DOM/Node NO_INSTANCE) -libweb_js_wrapper(DOM/NodeIterator NO_INSTANCE) -libweb_js_wrapper(DOM/NodeList NO_INSTANCE) -libweb_js_wrapper(DOM/ProcessingInstruction NO_INSTANCE) -libweb_js_wrapper(DOM/Range NO_INSTANCE) -libweb_js_wrapper(DOM/ShadowRoot NO_INSTANCE) -libweb_js_wrapper(DOM/StaticRange NO_INSTANCE) -libweb_js_wrapper(DOM/Text NO_INSTANCE) -libweb_js_wrapper(DOM/TreeWalker NO_INSTANCE) -libweb_js_wrapper(DOMParsing/XMLSerializer NO_INSTANCE) -libweb_js_wrapper(Encoding/TextDecoder NO_INSTANCE) -libweb_js_wrapper(Encoding/TextEncoder NO_INSTANCE) -libweb_js_wrapper(Fetch/Headers ITERABLE NO_INSTANCE) -libweb_js_wrapper(FileAPI/Blob NO_INSTANCE) -libweb_js_wrapper(FileAPI/File NO_INSTANCE) -libweb_js_wrapper(Geometry/DOMPoint NO_INSTANCE) -libweb_js_wrapper(Geometry/DOMPointReadOnly NO_INSTANCE) -libweb_js_wrapper(Geometry/DOMRect NO_INSTANCE) -libweb_js_wrapper(Geometry/DOMRectList NO_INSTANCE) -libweb_js_wrapper(Geometry/DOMRectReadOnly NO_INSTANCE) -libweb_js_wrapper(HTML/CanvasGradient NO_INSTANCE) -libweb_js_wrapper(HTML/CanvasRenderingContext2D NO_INSTANCE) -libweb_js_wrapper(HTML/CloseEvent NO_INSTANCE) -libweb_js_wrapper(HTML/DOMParser NO_INSTANCE) -libweb_js_wrapper(HTML/DOMStringMap NO_INSTANCE) -libweb_js_wrapper(HTML/ErrorEvent NO_INSTANCE) -libweb_js_wrapper(HTML/History NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLAnchorElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLAreaElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLAudioElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLBaseElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLBodyElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLBRElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLButtonElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLCanvasElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDataElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDataListElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDetailsElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDialogElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDirectoryElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDivElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLDListElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLEmbedElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLFieldSetElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLFontElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLFormElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLFrameElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLFrameSetElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLHeadElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLHeadingElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLHRElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLHtmlElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLIFrameElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLImageElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLInputElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLLabelElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLLegendElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLLIElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLLinkElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLMapElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLMarqueeElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLMediaElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLMenuElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLMetaElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLMeterElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLModElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLObjectElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLOListElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLOptGroupElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLOptionElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLOptionsCollection NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLOutputElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLParagraphElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLParamElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLPictureElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLPreElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLProgressElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLQuoteElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLScriptElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLSelectElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLSlotElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLSourceElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLSpanElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLStyleElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTableCaptionElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTableCellElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTableColElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTableElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTableRowElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTableSectionElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTemplateElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTextAreaElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTimeElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTitleElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLTrackElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLUListElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLUnknownElement NO_INSTANCE) -libweb_js_wrapper(HTML/HTMLVideoElement NO_INSTANCE) -libweb_js_wrapper(HTML/ImageData NO_INSTANCE) -libweb_js_wrapper(HTML/MessageChannel NO_INSTANCE) -libweb_js_wrapper(HTML/MessageEvent NO_INSTANCE) -libweb_js_wrapper(HTML/MessagePort NO_INSTANCE) -libweb_js_wrapper(HTML/PageTransitionEvent NO_INSTANCE) -libweb_js_wrapper(HTML/Path2D NO_INSTANCE) -libweb_js_wrapper(HTML/PromiseRejectionEvent NO_INSTANCE) -libweb_js_wrapper(HTML/Storage NO_INSTANCE) -libweb_js_wrapper(HTML/SubmitEvent NO_INSTANCE) -libweb_js_wrapper(HTML/TextMetrics NO_INSTANCE) -libweb_js_wrapper(HTML/Worker NO_INSTANCE) -libweb_js_wrapper(HTML/WorkerGlobalScope NO_INSTANCE) -libweb_js_wrapper(HTML/WorkerLocation NO_INSTANCE) -libweb_js_wrapper(HTML/WorkerNavigator NO_INSTANCE) -libweb_js_wrapper(HighResolutionTime/Performance NO_INSTANCE) -libweb_js_wrapper(IntersectionObserver/IntersectionObserver NO_INSTANCE) -libweb_js_wrapper(NavigationTiming/PerformanceTiming NO_INSTANCE) -libweb_js_wrapper(RequestIdleCallback/IdleDeadline NO_INSTANCE) -libweb_js_wrapper(ResizeObserver/ResizeObserver NO_INSTANCE) -libweb_js_wrapper(SVG/SVGAnimatedLength NO_INSTANCE) -libweb_js_wrapper(SVG/SVGClipPathElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGDefsElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGGeometryElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGGraphicsElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGCircleElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGEllipseElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGLength NO_INSTANCE) -libweb_js_wrapper(SVG/SVGLineElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGPathElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGPolygonElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGPolylineElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGRectElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGSVGElement NO_INSTANCE) -libweb_js_wrapper(SVG/SVGTextContentElement NO_INSTANCE) -libweb_js_wrapper(Selection/Selection NO_INSTANCE) -libweb_js_wrapper(UIEvents/FocusEvent NO_INSTANCE) -libweb_js_wrapper(UIEvents/KeyboardEvent NO_INSTANCE) -libweb_js_wrapper(UIEvents/MouseEvent NO_INSTANCE) -libweb_js_wrapper(UIEvents/UIEvent NO_INSTANCE) -libweb_js_wrapper(URL/URL NO_INSTANCE) -libweb_js_wrapper(URL/URLSearchParams ITERABLE NO_INSTANCE) -libweb_js_wrapper(WebGL/WebGLContextEvent NO_INSTANCE) -libweb_js_wrapper(WebGL/WebGLRenderingContext NO_INSTANCE) -libweb_js_wrapper(WebSockets/WebSocket NO_INSTANCE) -libweb_js_wrapper(XHR/ProgressEvent NO_INSTANCE) -libweb_js_wrapper(XHR/XMLHttpRequest NO_INSTANCE) -libweb_js_wrapper(XHR/XMLHttpRequestEventTarget NO_INSTANCE) +libweb_js_wrapper(Crypto/Crypto) +libweb_js_wrapper(Crypto/SubtleCrypto) +libweb_js_wrapper(CSS/CSSConditionRule) +libweb_js_wrapper(CSS/CSSFontFaceRule) +libweb_js_wrapper(CSS/CSSGroupingRule) +libweb_js_wrapper(CSS/CSSImportRule) +libweb_js_wrapper(CSS/CSSMediaRule) +libweb_js_wrapper(CSS/CSSRule) +libweb_js_wrapper(CSS/CSSRuleList) +libweb_js_wrapper(CSS/CSSStyleDeclaration) +libweb_js_wrapper(CSS/CSSStyleRule) +libweb_js_wrapper(CSS/CSSStyleSheet) +libweb_js_wrapper(CSS/CSSSupportsRule) +libweb_js_wrapper(CSS/MediaList) +libweb_js_wrapper(CSS/MediaQueryList) +libweb_js_wrapper(CSS/MediaQueryListEvent) +libweb_js_wrapper(CSS/Screen) +libweb_js_wrapper(CSS/StyleSheet) +libweb_js_wrapper(CSS/StyleSheetList) +libweb_js_wrapper(DOM/AbstractRange) +libweb_js_wrapper(DOM/Attribute) +libweb_js_wrapper(DOM/AbortController) +libweb_js_wrapper(DOM/AbortSignal) +libweb_js_wrapper(DOM/CDATASection) +libweb_js_wrapper(DOM/CharacterData) +libweb_js_wrapper(DOM/Comment) +libweb_js_wrapper(DOM/CustomEvent) +libweb_js_wrapper(DOM/Document) +libweb_js_wrapper(DOM/DocumentFragment) +libweb_js_wrapper(DOM/DocumentType) +libweb_js_wrapper(DOM/DOMException) +libweb_js_wrapper(DOM/DOMImplementation) +libweb_js_wrapper(DOM/DOMTokenList) +libweb_js_wrapper(DOM/Element) +libweb_js_wrapper(DOM/Event) +libweb_js_wrapper(DOM/EventTarget) +libweb_js_wrapper(DOM/HTMLCollection) +libweb_js_wrapper(DOM/MutationRecord) +libweb_js_wrapper(DOM/MutationObserver) +libweb_js_wrapper(DOM/NamedNodeMap) +libweb_js_wrapper(DOM/Node) +libweb_js_wrapper(DOM/NodeIterator) +libweb_js_wrapper(DOM/NodeList) +libweb_js_wrapper(DOM/ProcessingInstruction) +libweb_js_wrapper(DOM/Range) +libweb_js_wrapper(DOM/ShadowRoot) +libweb_js_wrapper(DOM/StaticRange) +libweb_js_wrapper(DOM/Text) +libweb_js_wrapper(DOM/TreeWalker) +libweb_js_wrapper(DOMParsing/XMLSerializer) +libweb_js_wrapper(Encoding/TextDecoder) +libweb_js_wrapper(Encoding/TextEncoder) +libweb_js_wrapper(Fetch/Headers ITERABLE) +libweb_js_wrapper(FileAPI/Blob) +libweb_js_wrapper(FileAPI/File) +libweb_js_wrapper(Geometry/DOMPoint) +libweb_js_wrapper(Geometry/DOMPointReadOnly) +libweb_js_wrapper(Geometry/DOMRect) +libweb_js_wrapper(Geometry/DOMRectList) +libweb_js_wrapper(Geometry/DOMRectReadOnly) +libweb_js_wrapper(HTML/CanvasGradient) +libweb_js_wrapper(HTML/CanvasRenderingContext2D) +libweb_js_wrapper(HTML/CloseEvent) +libweb_js_wrapper(HTML/DOMParser) +libweb_js_wrapper(HTML/DOMStringMap) +libweb_js_wrapper(HTML/ErrorEvent) +libweb_js_wrapper(HTML/History) +libweb_js_wrapper(HTML/HTMLAnchorElement) +libweb_js_wrapper(HTML/HTMLAreaElement) +libweb_js_wrapper(HTML/HTMLAudioElement) +libweb_js_wrapper(HTML/HTMLBaseElement) +libweb_js_wrapper(HTML/HTMLBodyElement) +libweb_js_wrapper(HTML/HTMLBRElement) +libweb_js_wrapper(HTML/HTMLButtonElement) +libweb_js_wrapper(HTML/HTMLCanvasElement) +libweb_js_wrapper(HTML/HTMLDataElement) +libweb_js_wrapper(HTML/HTMLDataListElement) +libweb_js_wrapper(HTML/HTMLDetailsElement) +libweb_js_wrapper(HTML/HTMLDialogElement) +libweb_js_wrapper(HTML/HTMLDirectoryElement) +libweb_js_wrapper(HTML/HTMLDivElement) +libweb_js_wrapper(HTML/HTMLDListElement) +libweb_js_wrapper(HTML/HTMLElement) +libweb_js_wrapper(HTML/HTMLEmbedElement) +libweb_js_wrapper(HTML/HTMLFieldSetElement) +libweb_js_wrapper(HTML/HTMLFontElement) +libweb_js_wrapper(HTML/HTMLFormElement) +libweb_js_wrapper(HTML/HTMLFrameElement) +libweb_js_wrapper(HTML/HTMLFrameSetElement) +libweb_js_wrapper(HTML/HTMLHeadElement) +libweb_js_wrapper(HTML/HTMLHeadingElement) +libweb_js_wrapper(HTML/HTMLHRElement) +libweb_js_wrapper(HTML/HTMLHtmlElement) +libweb_js_wrapper(HTML/HTMLIFrameElement) +libweb_js_wrapper(HTML/HTMLImageElement) +libweb_js_wrapper(HTML/HTMLInputElement) +libweb_js_wrapper(HTML/HTMLLabelElement) +libweb_js_wrapper(HTML/HTMLLegendElement) +libweb_js_wrapper(HTML/HTMLLIElement) +libweb_js_wrapper(HTML/HTMLLinkElement) +libweb_js_wrapper(HTML/HTMLMapElement) +libweb_js_wrapper(HTML/HTMLMarqueeElement) +libweb_js_wrapper(HTML/HTMLMediaElement) +libweb_js_wrapper(HTML/HTMLMenuElement) +libweb_js_wrapper(HTML/HTMLMetaElement) +libweb_js_wrapper(HTML/HTMLMeterElement) +libweb_js_wrapper(HTML/HTMLModElement) +libweb_js_wrapper(HTML/HTMLObjectElement) +libweb_js_wrapper(HTML/HTMLOListElement) +libweb_js_wrapper(HTML/HTMLOptGroupElement) +libweb_js_wrapper(HTML/HTMLOptionElement) +libweb_js_wrapper(HTML/HTMLOptionsCollection) +libweb_js_wrapper(HTML/HTMLOutputElement) +libweb_js_wrapper(HTML/HTMLParagraphElement) +libweb_js_wrapper(HTML/HTMLParamElement) +libweb_js_wrapper(HTML/HTMLPictureElement) +libweb_js_wrapper(HTML/HTMLPreElement) +libweb_js_wrapper(HTML/HTMLProgressElement) +libweb_js_wrapper(HTML/HTMLQuoteElement) +libweb_js_wrapper(HTML/HTMLScriptElement) +libweb_js_wrapper(HTML/HTMLSelectElement) +libweb_js_wrapper(HTML/HTMLSlotElement) +libweb_js_wrapper(HTML/HTMLSourceElement) +libweb_js_wrapper(HTML/HTMLSpanElement) +libweb_js_wrapper(HTML/HTMLStyleElement) +libweb_js_wrapper(HTML/HTMLTableCaptionElement) +libweb_js_wrapper(HTML/HTMLTableCellElement) +libweb_js_wrapper(HTML/HTMLTableColElement) +libweb_js_wrapper(HTML/HTMLTableElement) +libweb_js_wrapper(HTML/HTMLTableRowElement) +libweb_js_wrapper(HTML/HTMLTableSectionElement) +libweb_js_wrapper(HTML/HTMLTemplateElement) +libweb_js_wrapper(HTML/HTMLTextAreaElement) +libweb_js_wrapper(HTML/HTMLTimeElement) +libweb_js_wrapper(HTML/HTMLTitleElement) +libweb_js_wrapper(HTML/HTMLTrackElement) +libweb_js_wrapper(HTML/HTMLUListElement) +libweb_js_wrapper(HTML/HTMLUnknownElement) +libweb_js_wrapper(HTML/HTMLVideoElement) +libweb_js_wrapper(HTML/ImageData) +libweb_js_wrapper(HTML/MessageChannel) +libweb_js_wrapper(HTML/MessageEvent) +libweb_js_wrapper(HTML/MessagePort) +libweb_js_wrapper(HTML/PageTransitionEvent) +libweb_js_wrapper(HTML/Path2D) +libweb_js_wrapper(HTML/PromiseRejectionEvent) +libweb_js_wrapper(HTML/Storage) +libweb_js_wrapper(HTML/SubmitEvent) +libweb_js_wrapper(HTML/TextMetrics) +libweb_js_wrapper(HTML/Worker) +libweb_js_wrapper(HTML/WorkerGlobalScope) +libweb_js_wrapper(HTML/WorkerLocation) +libweb_js_wrapper(HTML/WorkerNavigator) +libweb_js_wrapper(HighResolutionTime/Performance) +libweb_js_wrapper(IntersectionObserver/IntersectionObserver) +libweb_js_wrapper(NavigationTiming/PerformanceTiming) +libweb_js_wrapper(RequestIdleCallback/IdleDeadline) +libweb_js_wrapper(ResizeObserver/ResizeObserver) +libweb_js_wrapper(SVG/SVGAnimatedLength) +libweb_js_wrapper(SVG/SVGClipPathElement) +libweb_js_wrapper(SVG/SVGDefsElement) +libweb_js_wrapper(SVG/SVGElement) +libweb_js_wrapper(SVG/SVGGeometryElement) +libweb_js_wrapper(SVG/SVGGraphicsElement) +libweb_js_wrapper(SVG/SVGCircleElement) +libweb_js_wrapper(SVG/SVGEllipseElement) +libweb_js_wrapper(SVG/SVGLength) +libweb_js_wrapper(SVG/SVGLineElement) +libweb_js_wrapper(SVG/SVGPathElement) +libweb_js_wrapper(SVG/SVGPolygonElement) +libweb_js_wrapper(SVG/SVGPolylineElement) +libweb_js_wrapper(SVG/SVGRectElement) +libweb_js_wrapper(SVG/SVGSVGElement) +libweb_js_wrapper(SVG/SVGTextContentElement) +libweb_js_wrapper(Selection/Selection) +libweb_js_wrapper(UIEvents/FocusEvent) +libweb_js_wrapper(UIEvents/KeyboardEvent) +libweb_js_wrapper(UIEvents/MouseEvent) +libweb_js_wrapper(UIEvents/UIEvent) +libweb_js_wrapper(URL/URL) +libweb_js_wrapper(URL/URLSearchParams ITERABLE) +libweb_js_wrapper(WebGL/WebGLContextEvent) +libweb_js_wrapper(WebGL/WebGLRenderingContext) +libweb_js_wrapper(WebSockets/WebSocket) +libweb_js_wrapper(XHR/ProgressEvent) +libweb_js_wrapper(XHR/XMLHttpRequest) +libweb_js_wrapper(XHR/XMLHttpRequestEventTarget)
2a5cff232bb5d313545ba46f6640aefda279258d
2021-12-27 01:52:59
Andreas Kling
kernel: Use slab allocation automagically for small kmalloc() requests
false
Use slab allocation automagically for small kmalloc() requests
kernel
diff --git a/Kernel/Heap/kmalloc.cpp b/Kernel/Heap/kmalloc.cpp index 02558061b3ac..5650b45ab8dc 100644 --- a/Kernel/Heap/kmalloc.cpp +++ b/Kernel/Heap/kmalloc.cpp @@ -47,6 +47,95 @@ struct KmallocSubheap { Heap<CHUNK_SIZE, KMALLOC_SCRUB_BYTE, KFREE_SCRUB_BYTE> allocator; }; +class KmallocSlabBlock { +public: + static constexpr size_t block_size = 64 * KiB; + static constexpr FlatPtr block_mask = ~(block_size - 1); + + KmallocSlabBlock(size_t slab_size) + { + size_t slab_count = (block_size - sizeof(KmallocSlabBlock)) / slab_size; + for (size_t i = 0; i < slab_count; ++i) { + auto* freelist_entry = (FreelistEntry*)(void*)(&m_data[i * slab_size]); + freelist_entry->next = m_freelist; + m_freelist = freelist_entry; + } + } + + void* allocate() + { + VERIFY(m_freelist); + return exchange(m_freelist, m_freelist->next); + } + + void deallocate(void* ptr) + { + VERIFY(ptr >= &m_data && ptr < ((u8*)this + block_size)); + auto* freelist_entry = (FreelistEntry*)ptr; + freelist_entry->next = m_freelist; + m_freelist = freelist_entry; + } + + bool is_full() const + { + return m_freelist == nullptr; + } + + IntrusiveListNode<KmallocSlabBlock> list_node; + +private: + struct FreelistEntry { + FreelistEntry* next; + }; + + FreelistEntry* m_freelist { nullptr }; + + [[gnu::aligned(16)]] u8 m_data[]; +}; + +class KmallocSlabheap { +public: + KmallocSlabheap(size_t slab_size) + : m_slab_size(slab_size) + { + } + + size_t slab_size() const { return m_slab_size; } + + void* allocate() + { + if (m_usable_blocks.is_empty()) { + auto* slot = kmalloc_aligned(KmallocSlabBlock::block_size, KmallocSlabBlock::block_size); + if (!slot) { + // FIXME: Dare to return nullptr! + PANIC("OOM while growing slabheap ({})", m_slab_size); + } + auto* block = new (slot) KmallocSlabBlock(m_slab_size); + m_usable_blocks.append(*block); + } + auto* block = m_usable_blocks.first(); + auto* ptr = block->allocate(); + if (block->is_full()) + m_full_blocks.append(*block); + return ptr; + } + + void deallocate(void* ptr) + { + auto* block = (KmallocSlabBlock*)((FlatPtr)ptr & KmallocSlabBlock::block_mask); + bool block_was_full = block->is_full(); + block->deallocate(ptr); + if (block_was_full) + m_usable_blocks.append(*block); + } + +private: + size_t m_slab_size { 0 }; + + IntrusiveList<&KmallocSlabBlock::list_node> m_usable_blocks; + IntrusiveList<&KmallocSlabBlock::list_node> m_full_blocks; +}; + struct KmallocGlobalData { static constexpr size_t minimum_subheap_size = 1 * MiB; @@ -67,6 +156,11 @@ struct KmallocGlobalData { { VERIFY(!expansion_in_progress); + for (auto& slabheap : slabheaps) { + if (size <= slabheap.slab_size()) + return slabheap.allocate(); + } + for (auto& subheap : subheaps) { if (auto* ptr = subheap.allocator.allocate(size)) return ptr; @@ -83,6 +177,11 @@ struct KmallocGlobalData { { VERIFY(!expansion_in_progress); + for (auto& slabheap : slabheaps) { + if (size <= slabheap.slab_size()) + return slabheap.deallocate(ptr); + } + for (auto& subheap : subheaps) { if (subheap.allocator.contains(ptr)) { subheap.allocator.deallocate(ptr); @@ -191,6 +290,8 @@ struct KmallocGlobalData { IntrusiveList<&KmallocSubheap::list_node> subheaps; + KmallocSlabheap slabheaps[6] = { 16, 32, 64, 128, 256, 512 }; + bool expansion_in_progress { false }; };
b1fd06eb4cf27d0439e240551a632f31a6dfe6f9
2020-11-25 02:06:28
Sergey Bugaev
userland: Add a test for pthread_once()
false
Add a test for pthread_once()
userland
diff --git a/Userland/CMakeLists.txt b/Userland/CMakeLists.txt index 286d4075cc5e..85b379f70046 100644 --- a/Userland/CMakeLists.txt +++ b/Userland/CMakeLists.txt @@ -40,6 +40,7 @@ target_link_libraries(test-crypto LibCrypto LibTLS LibLine) target_link_libraries(test-compress LibCompress) target_link_libraries(test-gfx-font LibGUI LibCore) target_link_libraries(test-js LibJS LibLine LibCore) +target_link_libraries(test-pthread LibThread) target_link_libraries(test-web LibWeb) target_link_libraries(tt LibPthread) target_link_libraries(gunzip LibCompress) diff --git a/Userland/test-pthread.cpp b/Userland/test-pthread.cpp new file mode 100644 index 000000000000..991bd539c0b6 --- /dev/null +++ b/Userland/test-pthread.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2020, Sergey Bugaev <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <AK/Assertions.h> +#include <AK/NonnullRefPtrVector.h> +#include <LibThread/Thread.h> +#include <pthread.h> + +static void test_once() +{ + constexpr size_t threads_count = 10; + + static Vector<int> v; + v.clear(); + pthread_once_t once = PTHREAD_ONCE_INIT; + NonnullRefPtrVector<LibThread::Thread, threads_count> threads; + + for (size_t i = 0; i < threads_count; i++) { + threads.append(LibThread::Thread::construct([&] { + return pthread_once(&once, [] { + v.append(35); + sleep(1); + }); + })); + threads.last().start(); + } + for (auto& thread : threads) + thread.join(); + + ASSERT(v.size() == 1); +} + +int main() +{ + test_once(); + return 0; +}
04bb17ca94f5537a29e5d7996970cabf6410a51d
2022-03-15 22:00:58
Timothy Flynn
libjs: Reorganize spec steps for Intl.RelativeTimeFormat
false
Reorganize spec steps for Intl.RelativeTimeFormat
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp index 2da5156f8ad7..ed8c52450f34 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp @@ -51,80 +51,7 @@ StringView RelativeTimeFormat::numeric_string() const } } -// 17.1.1 InitializeRelativeTimeFormat ( relativeTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat -ThrowCompletionOr<RelativeTimeFormat*> initialize_relative_time_format(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, Value locales_value, Value options_value) -{ - auto& vm = global_object.vm(); - - // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales). - auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value)); - - // 2. Set options to ? CoerceOptionsToObject(options). - auto* options = TRY(coerce_options_to_object(global_object, options_value)); - - // 3. Let opt be a new Record. - LocaleOptions opt {}; - - // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit"). - auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv)); - - // 5. Set opt.[[LocaleMatcher]] to matcher. - opt.locale_matcher = matcher; - - // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined). - auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {})); - - // 7. If numberingSystem is not undefined, then - if (!numbering_system.is_undefined()) { - // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception. - if (!Unicode::is_type_identifier(numbering_system.as_string().string())) - return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv); - - // 8. Set opt.[[nu]] to numberingSystem. - opt.nu = numbering_system.as_string().string(); - } - - // 9. Let localeData be %RelativeTimeFormat%.[[LocaleData]]. - // 10. Let r be ResolveLocale(%RelativeTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %RelativeTimeFormat%.[[RelevantExtensionKeys]], localeData). - auto result = resolve_locale(requested_locales, opt, RelativeTimeFormat::relevant_extension_keys()); - - // 11. Let locale be r.[[locale]]. - auto locale = move(result.locale); - - // 12. Set relativeTimeFormat.[[Locale]] to locale. - relative_time_format.set_locale(locale); - - // 13. Set relativeTimeFormat.[[DataLocale]] to r.[[dataLocale]]. - relative_time_format.set_data_locale(move(result.data_locale)); - - // 14. Set relativeTimeFormat.[[NumberingSystem]] to r.[[nu]]. - if (result.nu.has_value()) - relative_time_format.set_numbering_system(result.nu.release_value()); - - // 15. Let style be ? GetOption(options, "style", "string", « "long", "short", "narrow" », "long"). - auto style = TRY(get_option(global_object, *options, vm.names.style, Value::Type::String, { "long"sv, "short"sv, "narrow"sv }, "long"sv)); - - // 16. Set relativeTimeFormat.[[Style]] to style. - relative_time_format.set_style(style.as_string().string()); - - // 17. Let numeric be ? GetOption(options, "numeric", "string", « "always", "auto" », "always"). - auto numeric = TRY(get_option(global_object, *options, vm.names.numeric, Value::Type::String, { "always"sv, "auto"sv }, "always"sv)); - - // 18. Set relativeTimeFormat.[[Numeric]] to numeric. - relative_time_format.set_numeric(numeric.as_string().string()); - - // 19. Let relativeTimeFormat.[[NumberFormat]] be ! Construct(%NumberFormat%, « locale »). - auto* number_format = MUST(construct(global_object, *global_object.intl_number_format_constructor(), js_string(vm, locale))); - relative_time_format.set_number_format(static_cast<NumberFormat*>(number_format)); - - // 20. Let relativeTimeFormat.[[PluralRules]] be ! Construct(%PluralRules%, « locale »). - // FIXME: We do not yet support Intl.PluralRules. - - // 21. Return relativeTimeFormat. - return &relative_time_format; -} - -// 17.1.2 SingularRelativeTimeUnit ( unit ), https://tc39.es/ecma402/#sec-singularrelativetimeunit +// 17.5.1 SingularRelativeTimeUnit ( unit ), https://tc39.es/ecma402/#sec-singularrelativetimeunit ThrowCompletionOr<Unicode::TimeUnit> singular_relative_time_unit(GlobalObject& global_object, StringView unit) { auto& vm = global_object.vm(); @@ -163,7 +90,7 @@ ThrowCompletionOr<Unicode::TimeUnit> singular_relative_time_unit(GlobalObject& g return vm.throw_completion<RangeError>(global_object, ErrorType::IntlInvalidUnit, unit); } -// 17.1.3 PartitionRelativeTimePattern ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-PartitionRelativeTimePattern +// 17.5.2 PartitionRelativeTimePattern ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-PartitionRelativeTimePattern ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_pattern(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit) { auto& vm = global_object.vm(); @@ -262,7 +189,7 @@ ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_patt return make_parts_list(pattern->pattern, Unicode::time_unit_to_string(time_unit), move(value_partitions)); } -// 17.1.4 MakePartsList ( pattern, unit, parts ), https://tc39.es/ecma402/#sec-makepartslist +// 17.5.3 MakePartsList ( pattern, unit, parts ), https://tc39.es/ecma402/#sec-makepartslist Vector<PatternPartitionWithUnit> make_parts_list(StringView pattern, StringView unit, Vector<PatternPartition> parts) { // 1. Let patternParts be PartitionPattern(pattern). @@ -295,7 +222,7 @@ Vector<PatternPartitionWithUnit> make_parts_list(StringView pattern, StringView return result; } -// 17.1.5 FormatRelativeTime ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTime +// 17.5.4 FormatRelativeTime ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTime ThrowCompletionOr<String> format_relative_time(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit) { // 1. Let parts be ? PartitionRelativeTimePattern(relativeTimeFormat, value, unit). @@ -314,7 +241,7 @@ ThrowCompletionOr<String> format_relative_time(GlobalObject& global_object, Rela return result.build(); } -// 17.1.6 FormatRelativeTimeToParts ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts +// 17.5.5 FormatRelativeTimeToParts ( relativeTimeFormat, value, unit ), https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts ThrowCompletionOr<Array*> format_relative_time_to_parts(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit) { auto& vm = global_object.vm(); diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h index 675db2f62fd2..61ee1904facb 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h @@ -28,7 +28,7 @@ class RelativeTimeFormat final : public Object { static constexpr auto relevant_extension_keys() { - // 17.3.3 Internal slots, https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat-internal-slots + // 17.2.3 Internal slots, https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat-internal-slots // The value of the [[RelevantExtensionKeys]] internal slot is « "nu" ». return AK::Array { "nu"sv }; } @@ -77,7 +77,6 @@ struct PatternPartitionWithUnit : public PatternPartition { StringView unit; }; -ThrowCompletionOr<RelativeTimeFormat*> initialize_relative_time_format(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, Value locales_value, Value options_value); ThrowCompletionOr<Unicode::TimeUnit> singular_relative_time_unit(GlobalObject& global_object, StringView unit); ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_pattern(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, double value, StringView unit); Vector<PatternPartitionWithUnit> make_parts_list(StringView pattern, StringView unit, Vector<PatternPartition> parts); diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp index a87ed428bef0..48b64215500a 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp @@ -8,12 +8,15 @@ #include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Intl/AbstractOperations.h> +#include <LibJS/Runtime/Intl/NumberFormat.h> +#include <LibJS/Runtime/Intl/NumberFormatConstructor.h> #include <LibJS/Runtime/Intl/RelativeTimeFormat.h> #include <LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h> +#include <LibUnicode/Locale.h> namespace JS::Intl { -// 17.2 The Intl.RelativeTimeFormat Constructor, https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor +// 17.1 The Intl.RelativeTimeFormat Constructor, https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor RelativeTimeFormatConstructor::RelativeTimeFormatConstructor(GlobalObject& global_object) : NativeFunction(vm().names.RelativeTimeFormat.as_string(), *global_object.function_prototype()) { @@ -25,7 +28,7 @@ void RelativeTimeFormatConstructor::initialize(GlobalObject& global_object) auto& vm = this->vm(); - // 17.3.1 Intl.RelativeTimeFormat.prototype, https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype + // 17.2.1 Intl.RelativeTimeFormat.prototype, https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype define_direct_property(vm.names.prototype, global_object.intl_relative_time_format_prototype(), 0); define_direct_property(vm.names.length, Value(0), Attribute::Configurable); @@ -33,14 +36,14 @@ void RelativeTimeFormatConstructor::initialize(GlobalObject& global_object) define_native_function(vm.names.supportedLocalesOf, supported_locales_of, 1, attr); } -// 17.2.1 Intl.RelativeTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat +// 17.1.1 Intl.RelativeTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat ThrowCompletionOr<Value> RelativeTimeFormatConstructor::call() { // 1. If NewTarget is undefined, throw a TypeError exception. return vm().throw_completion<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, "Intl.RelativeTimeFormat"); } -// 17.2.1 Intl.RelativeTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat +// 17.1.1 Intl.RelativeTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat ThrowCompletionOr<Object*> RelativeTimeFormatConstructor::construct(FunctionObject& new_target) { auto& vm = this->vm(); @@ -56,7 +59,7 @@ ThrowCompletionOr<Object*> RelativeTimeFormatConstructor::construct(FunctionObje return TRY(initialize_relative_time_format(global_object, *relative_time_format, locales, options)); } -// 17.3.2 Intl.RelativeTimeFormat.supportedLocalesOf ( locales [ , options ] ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf +// 17.2.2 Intl.RelativeTimeFormat.supportedLocalesOf ( locales [ , options ] ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatConstructor::supported_locales_of) { auto locales = vm.argument(0); @@ -71,4 +74,77 @@ JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatConstructor::supported_locales_of) return TRY(supported_locales(global_object, requested_locales, options)); } +// 17.1.2 InitializeRelativeTimeFormat ( relativeTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat +ThrowCompletionOr<RelativeTimeFormat*> initialize_relative_time_format(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, Value locales_value, Value options_value) +{ + auto& vm = global_object.vm(); + + // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales). + auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value)); + + // 2. Set options to ? CoerceOptionsToObject(options). + auto* options = TRY(coerce_options_to_object(global_object, options_value)); + + // 3. Let opt be a new Record. + LocaleOptions opt {}; + + // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit"). + auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv)); + + // 5. Set opt.[[LocaleMatcher]] to matcher. + opt.locale_matcher = matcher; + + // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined). + auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {})); + + // 7. If numberingSystem is not undefined, then + if (!numbering_system.is_undefined()) { + // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception. + if (!Unicode::is_type_identifier(numbering_system.as_string().string())) + return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv); + + // 8. Set opt.[[nu]] to numberingSystem. + opt.nu = numbering_system.as_string().string(); + } + + // 9. Let localeData be %RelativeTimeFormat%.[[LocaleData]]. + // 10. Let r be ResolveLocale(%RelativeTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %RelativeTimeFormat%.[[RelevantExtensionKeys]], localeData). + auto result = resolve_locale(requested_locales, opt, RelativeTimeFormat::relevant_extension_keys()); + + // 11. Let locale be r.[[locale]]. + auto locale = move(result.locale); + + // 12. Set relativeTimeFormat.[[Locale]] to locale. + relative_time_format.set_locale(locale); + + // 13. Set relativeTimeFormat.[[DataLocale]] to r.[[dataLocale]]. + relative_time_format.set_data_locale(move(result.data_locale)); + + // 14. Set relativeTimeFormat.[[NumberingSystem]] to r.[[nu]]. + if (result.nu.has_value()) + relative_time_format.set_numbering_system(result.nu.release_value()); + + // 15. Let style be ? GetOption(options, "style", "string", « "long", "short", "narrow" », "long"). + auto style = TRY(get_option(global_object, *options, vm.names.style, Value::Type::String, { "long"sv, "short"sv, "narrow"sv }, "long"sv)); + + // 16. Set relativeTimeFormat.[[Style]] to style. + relative_time_format.set_style(style.as_string().string()); + + // 17. Let numeric be ? GetOption(options, "numeric", "string", « "always", "auto" », "always"). + auto numeric = TRY(get_option(global_object, *options, vm.names.numeric, Value::Type::String, { "always"sv, "auto"sv }, "always"sv)); + + // 18. Set relativeTimeFormat.[[Numeric]] to numeric. + relative_time_format.set_numeric(numeric.as_string().string()); + + // 19. Let relativeTimeFormat.[[NumberFormat]] be ! Construct(%NumberFormat%, « locale »). + auto* number_format = MUST(construct(global_object, *global_object.intl_number_format_constructor(), js_string(vm, locale))); + relative_time_format.set_number_format(static_cast<NumberFormat*>(number_format)); + + // 20. Let relativeTimeFormat.[[PluralRules]] be ! Construct(%PluralRules%, « locale »). + // FIXME: We do not yet support Intl.PluralRules. + + // 21. Return relativeTimeFormat. + return &relative_time_format; +} + } diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h index fce4363cf83f..aceae05a70e6 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h @@ -27,4 +27,6 @@ class RelativeTimeFormatConstructor final : public NativeFunction { JS_DECLARE_NATIVE_FUNCTION(supported_locales_of); }; +ThrowCompletionOr<RelativeTimeFormat*> initialize_relative_time_format(GlobalObject& global_object, RelativeTimeFormat& relative_time_format, Value locales_value, Value options_value); + } diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatPrototype.cpp index be1fefa2b74c..063d4ea96422 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatPrototype.cpp @@ -10,7 +10,7 @@ namespace JS::Intl { -// 17.4 Properties of the Intl.RelativeTimeFormat Prototype Object, https://tc39.es/ecma402/#sec-properties-of-intl-relativetimeformat-prototype-object +// 17.3 Properties of the Intl.RelativeTimeFormat Prototype Object, https://tc39.es/ecma402/#sec-properties-of-intl-relativetimeformat-prototype-object RelativeTimeFormatPrototype::RelativeTimeFormatPrototype(GlobalObject& global_object) : PrototypeObject(*global_object.object_prototype()) { @@ -22,7 +22,7 @@ void RelativeTimeFormatPrototype::initialize(GlobalObject& global_object) auto& vm = this->vm(); - // 17.4.2 Intl.RelativeTimeFormat.prototype[ @@toStringTag ], https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype-toStringTag + // 17.3.2 Intl.RelativeTimeFormat.prototype[ @@toStringTag ], https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype-toStringTag define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm, "Intl.RelativeTimeFormat"sv), Attribute::Configurable); u8 attr = Attribute::Writable | Attribute::Configurable; @@ -31,7 +31,7 @@ void RelativeTimeFormatPrototype::initialize(GlobalObject& global_object) define_native_function(vm.names.resolvedOptions, resolved_options, 0, attr); } -// 17.4.3 Intl.RelativeTimeFormat.prototype.format ( value, unit ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.format +// 17.3.3 Intl.RelativeTimeFormat.prototype.format ( value, unit ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.format JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::format) { // 1. Let relativeTimeFormat be the this value. @@ -49,7 +49,7 @@ JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::format) return js_string(vm, move(formatted)); } -// 17.4.4 Intl.RelativeTimeFormat.prototype.formatToParts ( value, unit ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.formatToParts +// 17.3.4 Intl.RelativeTimeFormat.prototype.formatToParts ( value, unit ), https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.formatToParts JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::format_to_parts) { // 1. Let relativeTimeFormat be the this value. @@ -66,7 +66,7 @@ JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::format_to_parts) return TRY(format_relative_time_to_parts(global_object, *relative_time_format, value.as_double(), unit)); } -// 17.4.5 Intl.RelativeTimeFormat.prototype.resolvedOptions ( ), https://tc39.es/ecma402/#sec-intl.relativetimeformat.prototype.resolvedoptions +// 17.3.5 Intl.RelativeTimeFormat.prototype.resolvedOptions ( ), https://tc39.es/ecma402/#sec-intl.relativetimeformat.prototype.resolvedoptions JS_DEFINE_NATIVE_FUNCTION(RelativeTimeFormatPrototype::resolved_options) { // 1. Let relativeTimeFormat be the this value.
b22341fc772b538f725f2657c2e3af39cb1af143
2024-11-23 09:27:54
Psychpsyo
libgfx: Support AVIF images with missing pixi property
false
Support AVIF images with missing pixi property
libgfx
diff --git a/Libraries/LibGfx/ImageFormats/AVIFLoader.cpp b/Libraries/LibGfx/ImageFormats/AVIFLoader.cpp index f10030bbcccb..1f68fc3c91b5 100644 --- a/Libraries/LibGfx/ImageFormats/AVIFLoader.cpp +++ b/Libraries/LibGfx/ImageFormats/AVIFLoader.cpp @@ -68,6 +68,11 @@ static ErrorOr<void> decode_avif_header(AVIFLoadingContext& context) if (context.decoder == nullptr) { return Error::from_string_literal("failed to allocate AVIF decoder"); } + + // This makes the decoder not error if an item in the file is missing the mandatory pixi property. + // Reason for this is that older versions of ImageMagick do not set this property, which leads to + // broken web content if the error is not ignored. + context.decoder->strictFlags &= ~AVIF_STRICT_PIXI_REQUIRED; } avifResult result = avifDecoderSetIOMemory(context.decoder, context.data.data(), context.data.size()); diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cpp index f9287720d77d..201553c870d4 100644 --- a/Tests/LibGfx/TestImageDecoder.cpp +++ b/Tests/LibGfx/TestImageDecoder.cpp @@ -1067,3 +1067,9 @@ TEST_CASE(test_avif_frame_out_of_bounds) auto frame1 = TRY_OR_FAIL(plugin_decoder->frame(0)); EXPECT(plugin_decoder->frame(1).is_error()); } + +TEST_CASE(test_avif_missing_pixi_property) +{ + auto file = TRY_OR_FAIL(Core::MappedFile::map(TEST_INPUT("avif/missing-pixi-property.avif"sv))); + EXPECT(Gfx::AVIFImageDecoderPlugin::sniff(file->bytes())); +} diff --git a/Tests/LibGfx/test-inputs/avif/missing-pixi-property.avif b/Tests/LibGfx/test-inputs/avif/missing-pixi-property.avif new file mode 100644 index 000000000000..0c538b1655fd Binary files /dev/null and b/Tests/LibGfx/test-inputs/avif/missing-pixi-property.avif differ
efabfd4c66b932e65fde7c07e7f50d7734b4b68a
2023-03-05 23:51:43
Nico Weber
libgfx: Fill in remaining values in built-in sRGB profile
false
Fill in remaining values in built-in sRGB profile
libgfx
diff --git a/Userland/Libraries/LibGfx/ICC/WellKnownProfiles.cpp b/Userland/Libraries/LibGfx/ICC/WellKnownProfiles.cpp index 389c40c7b79c..7b420b530a64 100644 --- a/Userland/Libraries/LibGfx/ICC/WellKnownProfiles.cpp +++ b/Userland/Libraries/LibGfx/ICC/WellKnownProfiles.cpp @@ -43,7 +43,7 @@ ErrorOr<NonnullRefPtr<Profile>> sRGB() // Returns an sRGB profile. // https://en.wikipedia.org/wiki/SRGB - // FIXME: There's a surprising amount of variety in sRGB ICC profiles in the wild. + // FIXME: There are many different sRGB ICC profiles in the wild. // Explain why, and why this picks the numbers it does. auto header = rgb_header(); @@ -61,16 +61,23 @@ ErrorOr<NonnullRefPtr<Profile>> sRGB() TRY(tag_table.try_set(greenTRCTag, curve)); TRY(tag_table.try_set(blueTRCTag, curve)); - // Chromatic adaptation matrix, chromacities and whitepoint. - // FIXME: Actual values for chromatic adaptation matrix and chromacities. - TRY(tag_table.try_set(mediaWhitePointTag, TRY(XYZ_data(XYZ { 0, 0, 0 })))); - TRY(tag_table.try_set(redMatrixColumnTag, TRY(XYZ_data(XYZ { 0, 0, 0 })))); - TRY(tag_table.try_set(greenMatrixColumnTag, TRY(XYZ_data(XYZ { 0, 0, 0 })))); - TRY(tag_table.try_set(blueMatrixColumnTag, TRY(XYZ_data(XYZ { 0, 0, 0 })))); + // White point. + // ICC v4, 9.2.36 mediaWhitePointTag: " For displays, the values specified shall be those of the PCS illuminant as defined in 7.2.16." + TRY(tag_table.try_set(mediaWhitePointTag, TRY(XYZ_data(header.pcs_illuminant)))); - Vector<S15Fixed16, 9> chromatic_adaptation_matrix = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + // The chromatic_adaptation_matrix values are from https://www.color.org/chadtag.xalter + // That leads to exactly the S15Fixed16 values in the sRGB profiles in GIMP, Android, RawTherapee (but not in Compact-ICC-Profiles's v4 sRGB profile). + Vector<S15Fixed16, 9> chromatic_adaptation_matrix = { 1.047882, 0.022918, -0.050217, 0.029586, 0.990478, -0.017075, -0.009247, 0.015075, 0.751678 }; TRY(tag_table.try_set(chromaticAdaptationTag, TRY(try_make_ref_counted<S15Fixed16ArrayTagData>(0, 0, move(chromatic_adaptation_matrix))))); + // The chromaticity values are from https://www.color.org/srgb.pdf + // The chromatic adaptation matrix in that document is slightly different from the one on https://www.color.org/chadtag.xalter, + // so the values in our sRGB profile are currently not fully self-consistent. + // FIXME: Make values self-consistent (probably by using slightly different chromaticities). + TRY(tag_table.try_set(redMatrixColumnTag, TRY(XYZ_data(XYZ { 0.436030342570117, 0.222438466210245, 0.013897440074263 })))); + TRY(tag_table.try_set(greenMatrixColumnTag, TRY(XYZ_data(XYZ { 0.385101860087134, 0.716942745571917, 0.097076381494207 })))); + TRY(tag_table.try_set(blueMatrixColumnTag, TRY(XYZ_data(XYZ { 0.143067806654203, 0.060618777416563, 0.713926257896652 })))); + return Profile::create(header, move(tag_table)); }
e33bbdb6ba860f4d570d06516090df0e6cf3e91a
2019-11-06 18:28:08
Andreas Kling
ak: Remove unused AK::not_implemented()
false
Remove unused AK::not_implemented()
ak
diff --git a/AK/Assertions.h b/AK/Assertions.h index bced43f6585d..7e5793f4df9e 100644 --- a/AK/Assertions.h +++ b/AK/Assertions.h @@ -15,10 +15,3 @@ #endif -namespace AK { - -inline void not_implemented() { ASSERT(false); } - -} - -using AK::not_implemented; diff --git a/Kernel/TTY/VirtualConsole.cpp b/Kernel/TTY/VirtualConsole.cpp index 36566cf418d3..78d72f142172 100644 --- a/Kernel/TTY/VirtualConsole.cpp +++ b/Kernel/TTY/VirtualConsole.cpp @@ -310,11 +310,11 @@ void VirtualConsole::escape$J(const Vector<unsigned>& params) switch (mode) { case 0: // FIXME: Clear from cursor to end of screen. - not_implemented(); + ASSERT_NOT_REACHED(); break; case 1: // FIXME: Clear from cursor to beginning of screen. - not_implemented(); + ASSERT_NOT_REACHED(); break; case 2: clear();
a5d4ef462cf53bcc074cf7562d9a9fca0ebf15ac
2021-04-16 22:27:58
Linus Groh
libjs: Remove #if !defined(KERNEL)
false
Remove #if !defined(KERNEL)
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/JSONObject.cpp b/Userland/Libraries/LibJS/Runtime/JSONObject.cpp index c1bcfe0c0e29..fa7d04a53cb9 100644 --- a/Userland/Libraries/LibJS/Runtime/JSONObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/JSONObject.cpp @@ -423,10 +423,8 @@ Value JSONObject::parse_json_value(GlobalObject& global_object, const JsonValue& return Value(parse_json_array(global_object, value.as_array())); if (value.is_null()) return js_null(); -#if !defined(KERNEL) if (value.is_double()) return Value(value.as_double()); -#endif if (value.is_number()) return Value(value.to_i32(0)); if (value.is_string())
5da1a40ccff3d8f63d638bce4fee85a66df163f0
2020-04-14 17:10:04
Linus Groh
libjs: Support multiple arguments in Array.prototype.push()
false
Support multiple arguments in Array.prototype.push()
libjs
diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index b8b1f32a726d..a5e52642dbfc 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -37,9 +37,9 @@ namespace JS { ArrayPrototype::ArrayPrototype() { - put_native_function("shift", shift); - put_native_function("pop", pop); + put_native_function("pop", pop, 0); put_native_function("push", push, 1); + put_native_function("shift", shift, 0); put_native_function("toString", to_string, 0); put("length", Value(0)); } @@ -65,9 +65,8 @@ Value ArrayPrototype::push(Interpreter& interpreter) auto* array = array_from(interpreter); if (!array) return {}; - if (!interpreter.argument_count()) - return js_undefined(); - array->elements().append(interpreter.argument(0)); + for (size_t i = 0; i < interpreter.argument_count(); ++i) + array->elements().append(interpreter.argument(i)); return Value(array->length()); } diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.h b/Libraries/LibJS/Runtime/ArrayPrototype.h index bed19807a565..d4df4858ff61 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.h +++ b/Libraries/LibJS/Runtime/ArrayPrototype.h @@ -38,9 +38,9 @@ class ArrayPrototype final : public Object { private: virtual const char* class_name() const override { return "ArrayPrototype"; } + static Value pop(Interpreter&); static Value push(Interpreter&); static Value shift(Interpreter&); - static Value pop(Interpreter&); static Value to_string(Interpreter&); }; diff --git a/Libraries/LibJS/Tests/Array.prototype.push.js b/Libraries/LibJS/Tests/Array.prototype.push.js new file mode 100644 index 000000000000..f739aec463bd --- /dev/null +++ b/Libraries/LibJS/Tests/Array.prototype.push.js @@ -0,0 +1,30 @@ +load("test-common.js"); + +try { + assert(Array.prototype.push.length === 1); + + var a = ["hello"]; + var length = a.push(); + assert(length === 1); + assert(a.length === 1); + assert(a[0] === "hello"); + + length = a.push("friends"); + assert(length === 2); + assert(a.length === 2); + assert(a[0] === "hello"); + assert(a[1] === "friends"); + + length = a.push(1, 2, 3); + assert(length === 5); + assert(a.length === 5); + assert(a[0] === "hello"); + assert(a[1] === "friends"); + assert(a[2] === 1); + assert(a[3] === 2); + assert(a[4] === 3); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}
e54d96d53ea1a6f3d9f713528432ab203ce59637
2021-05-24 23:33:25
Stephan Unverwerth
libgl: Implement glReadPixels()
false
Implement glReadPixels()
libgl
diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.cpp b/Userland/Libraries/LibGL/SoftwareGLContext.cpp index d985ddd2d084..950c948f8963 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.cpp +++ b/Userland/Libraries/LibGL/SoftwareGLContext.cpp @@ -1113,10 +1113,239 @@ void SoftwareGLContext::gl_read_pixels(GLint x, GLint y, GLsizei width, GLsizei } } + // Some helper functions for converting float values to integer types + auto float_to_i8 = [](float f) -> GLchar { + return static_cast<GLchar>((0x7f * min(max(f, 0.0f), 1.0f) - 1) / 2); + }; + + auto float_to_i16 = [](float f) -> GLshort { + return static_cast<GLshort>((0x7fff * min(max(f, 0.0f), 1.0f) - 1) / 2); + }; + + auto float_to_i32 = [](float f) -> GLint { + return static_cast<GLint>((0x7fffffff * min(max(f, 0.0f), 1.0f) - 1) / 2); + }; + + auto float_to_u8 = [](float f) -> GLubyte { + return static_cast<GLubyte>(0xff * min(max(f, 0.0f), 1.0f)); + }; + + auto float_to_u16 = [](float f) -> GLushort { + return static_cast<GLushort>(0xffff * min(max(f, 0.0f), 1.0f)); + }; + + auto float_to_u32 = [](float f) -> GLuint { + return static_cast<GLuint>(0xffffffff * min(max(f, 0.0f), 1.0f)); + }; + if (format == GL_DEPTH_COMPONENT) { // Read from depth buffer + for (size_t i = 0; i < height; ++i) { + for (size_t j = 0; j < width; ++j) { + float depth = m_rasterizer.get_depthbuffer_value(x + j, y + i); + + switch (type) { + case GL_BYTE: + reinterpret_cast<GLchar*>(pixels)[i * width + j] = float_to_i8(depth); + break; + case GL_SHORT: + reinterpret_cast<GLshort*>(pixels)[i * width + j] = float_to_i16(depth); + break; + case GL_INT: + reinterpret_cast<GLint*>(pixels)[i * width + j] = float_to_i32(depth); + break; + case GL_UNSIGNED_BYTE: + reinterpret_cast<GLubyte*>(pixels)[i * width + j] = float_to_u8(depth); + break; + case GL_UNSIGNED_SHORT: + reinterpret_cast<GLushort*>(pixels)[i * width + j] = float_to_u16(depth); + break; + case GL_UNSIGNED_INT: + reinterpret_cast<GLuint*>(pixels)[i * width + j] = float_to_u32(depth); + break; + case GL_FLOAT: + reinterpret_cast<GLfloat*>(pixels)[i * width + j] = min(max(depth, 0.0f), 1.0f); + break; + } + } + } return; } + + bool write_red = false; + bool write_green = false; + bool write_blue = false; + bool write_alpha = false; + size_t component_count = 0; + size_t component_size = 0; + size_t red_offset = 0; + size_t green_offset = 0; + size_t blue_offset = 0; + size_t alpha_offset = 0; + char* red_ptr = nullptr; + char* green_ptr = nullptr; + char* blue_ptr = nullptr; + char* alpha_ptr = nullptr; + + switch (format) { + case GL_RGB: + write_red = true; + write_green = true; + write_blue = true; + component_count = 3; + red_offset = 2; + green_offset = 1; + blue_offset = 0; + break; + case GL_RGBA: + write_red = true; + write_green = true; + write_blue = true; + write_alpha = true; + component_count = 4; + red_offset = 3; + green_offset = 2; + blue_offset = 1; + alpha_offset = 0; + break; + case GL_RED: + write_red = true; + component_count = 1; + red_offset = 0; + break; + case GL_GREEN: + write_green = true; + component_count = 1; + green_offset = 0; + break; + case GL_BLUE: + write_blue = true; + component_count = 1; + blue_offset = 0; + break; + case GL_ALPHA: + write_alpha = true; + component_count = 1; + alpha_offset = 0; + break; + } + + switch (type) { + case GL_BYTE: + case GL_UNSIGNED_BYTE: + component_size = 1; + break; + case GL_SHORT: + case GL_UNSIGNED_SHORT: + component_size = 2; + break; + case GL_INT: + case GL_UNSIGNED_INT: + case GL_FLOAT: + component_size = 4; + break; + } + + char* out_ptr = reinterpret_cast<char*>(pixels); + for (int i = 0; i < (int)height; ++i) { + for (int j = 0; j < (int)width; ++j) { + Gfx::RGBA32 color {}; + if (m_current_read_buffer == GL_FRONT || m_current_read_buffer == GL_LEFT || m_current_read_buffer == GL_FRONT_LEFT) { + if (y + i >= m_frontbuffer->width() || x + j >= m_frontbuffer->height()) + color = 0; + else + color = m_frontbuffer->scanline(y + i)[x + j]; + } else { + color = m_rasterizer.get_backbuffer_pixel(x + j, y + i); + } + + float red = ((color >> 24) & 0xff) / 255.0f; + float green = ((color >> 16) & 0xff) / 255.0f; + float blue = ((color >> 8) & 0xff) / 255.0f; + float alpha = (color & 0xff) / 255.0f; + + // FIXME: Set up write pointers based on selected endianness (glPixelStore) + red_ptr = out_ptr + (component_size * red_offset); + green_ptr = out_ptr + (component_size * green_offset); + blue_ptr = out_ptr + (component_size * blue_offset); + alpha_ptr = out_ptr + (component_size * alpha_offset); + + switch (type) { + case GL_BYTE: + if (write_red) + *reinterpret_cast<GLchar*>(red_ptr) = float_to_i8(red); + if (write_green) + *reinterpret_cast<GLchar*>(green_ptr) = float_to_i8(green); + if (write_blue) + *reinterpret_cast<GLchar*>(blue_ptr) = float_to_i8(blue); + if (write_alpha) + *reinterpret_cast<GLchar*>(alpha_ptr) = float_to_i8(alpha); + break; + case GL_UNSIGNED_BYTE: + if (write_red) + *reinterpret_cast<GLubyte*>(red_ptr) = float_to_u8(red); + if (write_green) + *reinterpret_cast<GLubyte*>(green_ptr) = float_to_u8(green); + if (write_blue) + *reinterpret_cast<GLubyte*>(blue_ptr) = float_to_u8(blue); + if (write_alpha) + *reinterpret_cast<GLubyte*>(alpha_ptr) = float_to_u8(alpha); + break; + case GL_SHORT: + if (write_red) + *reinterpret_cast<GLshort*>(red_ptr) = float_to_i16(red); + if (write_green) + *reinterpret_cast<GLshort*>(green_ptr) = float_to_i16(green); + if (write_blue) + *reinterpret_cast<GLshort*>(blue_ptr) = float_to_i16(blue); + if (write_alpha) + *reinterpret_cast<GLshort*>(alpha_ptr) = float_to_i16(alpha); + break; + case GL_UNSIGNED_SHORT: + if (write_red) + *reinterpret_cast<GLushort*>(red_ptr) = float_to_u16(red); + if (write_green) + *reinterpret_cast<GLushort*>(green_ptr) = float_to_u16(green); + if (write_blue) + *reinterpret_cast<GLushort*>(blue_ptr) = float_to_u16(blue); + if (write_alpha) + *reinterpret_cast<GLushort*>(alpha_ptr) = float_to_u16(alpha); + break; + case GL_INT: + if (write_red) + *reinterpret_cast<GLint*>(red_ptr) = float_to_i32(red); + if (write_green) + *reinterpret_cast<GLint*>(green_ptr) = float_to_i32(green); + if (write_blue) + *reinterpret_cast<GLint*>(blue_ptr) = float_to_i32(blue); + if (write_alpha) + *reinterpret_cast<GLint*>(alpha_ptr) = float_to_i32(alpha); + break; + case GL_UNSIGNED_INT: + if (write_red) + *reinterpret_cast<GLuint*>(red_ptr) = float_to_u32(red); + if (write_green) + *reinterpret_cast<GLuint*>(green_ptr) = float_to_u32(green); + if (write_blue) + *reinterpret_cast<GLuint*>(blue_ptr) = float_to_u32(blue); + if (write_alpha) + *reinterpret_cast<GLuint*>(alpha_ptr) = float_to_u32(alpha); + break; + case GL_FLOAT: + if (write_red) + *reinterpret_cast<GLfloat*>(red_ptr) = min(max(red, 0.0f), 1.0f); + if (write_green) + *reinterpret_cast<GLfloat*>(green_ptr) = min(max(green, 0.0f), 1.0f); + if (write_blue) + *reinterpret_cast<GLfloat*>(blue_ptr) = min(max(blue, 0.0f), 1.0f); + if (write_alpha) + *reinterpret_cast<GLfloat*>(alpha_ptr) = min(max(alpha, 0.0f), 1.0f); + break; + } + + out_ptr += component_size * component_count; + } + } } void SoftwareGLContext::present() diff --git a/Userland/Libraries/LibGL/SoftwareRasterizer.cpp b/Userland/Libraries/LibGL/SoftwareRasterizer.cpp index 4a35cf981d7e..9acca22a1397 100644 --- a/Userland/Libraries/LibGL/SoftwareRasterizer.cpp +++ b/Userland/Libraries/LibGL/SoftwareRasterizer.cpp @@ -470,4 +470,22 @@ void SoftwareRasterizer::set_options(const RasterizerOptions& options) // FIXME: Recreate or reinitialize render threads here when multithreading is being implemented } +Gfx::RGBA32 SoftwareRasterizer::get_backbuffer_pixel(int x, int y) +{ + // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks + if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height()) + return 0; + + return m_render_target->scanline(y)[x]; +} + +float SoftwareRasterizer::get_depthbuffer_value(int x, int y) +{ + // FIXME: Reading individual pixels is very slow, rewrite this to transfer whole blocks + if (x < 0 || y < 0 || x >= m_render_target->width() || y >= m_render_target->height()) + return 1.0f; + + return m_depth_buffer->scanline(y)[x]; +} + } diff --git a/Userland/Libraries/LibGL/SoftwareRasterizer.h b/Userland/Libraries/LibGL/SoftwareRasterizer.h index 62c7e66a73ae..841bbc5f559a 100644 --- a/Userland/Libraries/LibGL/SoftwareRasterizer.h +++ b/Userland/Libraries/LibGL/SoftwareRasterizer.h @@ -38,6 +38,8 @@ class SoftwareRasterizer final { void wait_for_all_threads() const; void set_options(const RasterizerOptions&); RasterizerOptions options() const { return m_options; } + Gfx::RGBA32 get_backbuffer_pixel(int x, int y); + float get_depthbuffer_value(int x, int y); private: RefPtr<Gfx::Bitmap> m_render_target;
2a460aa369453cc1d23ca30df292f156db3578ab
2020-04-13 04:19:24
AnotherTest
shell: Do not manually write to the editor buffer when completing paths
false
Do not manually write to the editor buffer when completing paths
shell
diff --git a/Shell/main.cpp b/Shell/main.cpp index fa8f1a25a600..5662ef2e81b9 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -1080,7 +1080,6 @@ int main(int argc, char** argv) String path; Vector<String> suggestions; - editor.suggest(token.length(), 0); ssize_t last_slash = token.length() - 1; while (last_slash >= 0 && token[last_slash] != '/') --last_slash; @@ -1099,57 +1098,36 @@ int main(int argc, char** argv) path = g.cwd; } - // This is a bit naughty, but necessary without reordering the loop - // below. The loop terminates early, meaning that - // the suggestions list is incomplete. - // We only do this if the token is empty though. - if (token.is_empty()) { - Core::DirIterator suggested_files(path, Core::DirIterator::SkipDots); - while (suggested_files.has_next()) { - suggestions.append(suggested_files.next_path()); - } - } - - String completion; + // the invariant part of the token is actually just the last segment + // e.g. in `cd /foo/bar', 'bar' is the invariant + // since we are not suggesting anything starting with + // `/foo/', but rather just `bar...' + editor.suggest(token.length(), 0); - bool seen_others = false; Core::DirIterator files(path, Core::DirIterator::SkipDots); while (files.has_next()) { auto file = files.next_path(); if (file.starts_with(token)) { - if (!token.is_empty()) - suggestions.append(file); - if (completion.is_empty()) { - completion = file; // Will only be set once. - } else { - editor.cut_mismatching_chars(completion, file, token.length()); - if (completion.is_empty()) // We cut everything off! - return suggestions; - seen_others = true; - } + suggestions.append(file); } } - if (completion.is_empty()) - return suggestions; - // If we have characters to add, add them. - if (completion.length() > token.length()) - editor.insert(completion.substring(token.length(), completion.length() - token.length())); // If we have a single match and it's a directory, we add a slash. If it's // a regular file, we add a space, unless we already have one. - if (!seen_others) { + if (suggestions.size() == 1) { + auto& completion = suggestions[0]; String file_path = String::format("%s/%s", path.characters(), completion.characters()); struct stat program_status; int stat_error = stat(file_path.characters(), &program_status); if (!stat_error) { if (S_ISDIR(program_status.st_mode)) - editor.insert('/'); + completion = String::format("%s/", suggestions[0].characters()); else if (editor.cursor() == editor.buffer().size() || editor.buffer_at(editor.cursor()) != ' ') - editor.insert(' '); + completion = String::format("%s ", suggestions[0].characters()); } } - return {}; // Return an empty vector + return suggestions; }; signal(SIGINT, [](int) {
f19b17e089f1d95aa44154fbbc6890fb6e745428
2024-02-12 18:08:10
MacDue
libweb: Use paths for text in CRC2D (if possible)
false
Use paths for text in CRC2D (if possible)
libweb
diff --git a/Tests/LibWeb/Ref/canvas-text.html b/Tests/LibWeb/Ref/canvas-text.html new file mode 100644 index 000000000000..d29efeffac04 --- /dev/null +++ b/Tests/LibWeb/Ref/canvas-text.html @@ -0,0 +1,46 @@ +<link rel="match" href="reference/canvas-text-ref.html" /> +<html> + <head> + <style> + canvas { + border: 1px solid black; + image-rendering: pixelated; + } + </style> + </head> + <body> + <script> + const canvas = document.createElement("canvas"); + canvas.width = 600; + canvas.height = 280; + document.body.appendChild(canvas); + + const ctx = canvas.getContext("2d"); + ctx.font = "48px serif"; + + ctx.save(); + ctx.translate(20, 250); + ctx.rotate(-Math.PI*0.2); + ctx.fillText("Rotated Text!", 10, 40); + ctx.restore(); + + ctx.strokeText("Stroke Text!", 10, 50); + + const gradient = ctx.createLinearGradient(280, 20, 580, 120); + gradient.addColorStop(0,"red"); + gradient.addColorStop(0.15,"yellow"); + gradient.addColorStop(0.3,"green"); + gradient.addColorStop(0.45,"aqua"); + gradient.addColorStop(0.6,"blue"); + gradient.addColorStop(0.7,"fuchsia"); + gradient.addColorStop(1,"red"); + + ctx.fillStyle = gradient; + ctx.fillText("Gradient Text!", 260, 150); + + ctx.fillStyle = "red"; + ctx.fillText("Squished Text", 50, 120, 100); + + </script> + </body> +</html> diff --git a/Tests/LibWeb/Ref/reference/canvas-text-ref.html b/Tests/LibWeb/Ref/reference/canvas-text-ref.html new file mode 100644 index 000000000000..968b1098507c --- /dev/null +++ b/Tests/LibWeb/Ref/reference/canvas-text-ref.html @@ -0,0 +1,9 @@ +<style> + * { + margin: 0; + } + body { + background-color: white; + } + </style> + <img src="./images/canvas-text-ref.png"> diff --git a/Tests/LibWeb/Ref/reference/images/canvas-text-ref.png b/Tests/LibWeb/Ref/reference/images/canvas-text-ref.png new file mode 100644 index 000000000000..0684ebcba58c Binary files /dev/null and b/Tests/LibWeb/Ref/reference/images/canvas-text-ref.png differ diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp index 7d769c20d028..229497a2196d 100644 --- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp +++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.cpp @@ -198,7 +198,7 @@ Optional<Gfx::AntiAliasingPainter> CanvasRenderingContext2D::antialiased_painter return {}; } -void CanvasRenderingContext2D::fill_text(StringView text, float x, float y, Optional<double> max_width) +void CanvasRenderingContext2D::bitmap_font_fill_text(StringView text, float x, float y, Optional<double> max_width) { if (max_width.has_value() && max_width.value() <= 0) return; @@ -207,9 +207,8 @@ void CanvasRenderingContext2D::fill_text(StringView text, float x, float y, Opti auto& drawing_state = this->drawing_state(); auto& base_painter = painter.underlying_painter(); - auto font = current_font(); - // Create text rect from font + auto font = current_font(); auto text_rect = Gfx::FloatRect(x, y, max_width.has_value() ? static_cast<float>(max_width.value()) : font->width(text), font->pixel_size()); // Apply text align to text_rect @@ -242,10 +241,72 @@ void CanvasRenderingContext2D::fill_text(StringView text, float x, float y, Opti }); } +Gfx::Path CanvasRenderingContext2D::text_path(StringView text, float x, float y, Optional<double> max_width) +{ + if (max_width.has_value() && max_width.value() <= 0) + return {}; + + auto& drawing_state = this->drawing_state(); + auto font = current_font(); + + Gfx::Path path; + path.move_to({ x, y }); + path.text(Utf8View { text }, *font); + + auto text_width = path.bounding_box().width(); + Gfx::AffineTransform transform = {}; + + // https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm: + // 6. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box + // is greater than maxWidth CSS pixels, then change font to have a more condensed font (if one is + // available or if a reasonably readable one can be synthesized by applying a horizontal scale + // factor to the font) or a smaller font, and return to the previous step. + if (max_width.has_value() && text_width > float(*max_width)) { + auto horizontal_scale = float(*max_width) / text_width; + transform = Gfx::AffineTransform {}.scale({ horizontal_scale, 1 }); + text_width *= horizontal_scale; + } + + // Apply text align + // FIXME: CanvasTextAlign::Start and CanvasTextAlign::End currently do not nothing for right-to-left languages: + // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textalign-start + // Default alignment of draw_text is left so do nothing by CanvasTextAlign::Start and CanvasTextAlign::Left + if (drawing_state.text_align == Bindings::CanvasTextAlign::Center) { + transform = Gfx::AffineTransform {}.set_translation({ -text_width / 2, 0 }).multiply(transform); + } + if (drawing_state.text_align == Bindings::CanvasTextAlign::End || drawing_state.text_align == Bindings::CanvasTextAlign::Right) { + transform = Gfx::AffineTransform {}.set_translation({ -text_width, 0 }).multiply(transform); + } + + // Apply text baseline + // FIXME: Implement CanvasTextBasline::Hanging, Bindings::CanvasTextAlign::Alphabetic and Bindings::CanvasTextAlign::Ideographic for real + // right now they are just handled as textBaseline = top or bottom. + // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-textbaseline-hanging + // Default baseline of draw_text is top so do nothing by CanvasTextBaseline::Top and CanvasTextBasline::Hanging + if (drawing_state.text_baseline == Bindings::CanvasTextBaseline::Middle) { + transform = Gfx::AffineTransform {}.set_translation({ 0, font->pixel_size() / 2 }).multiply(transform); + } + if (drawing_state.text_baseline == Bindings::CanvasTextBaseline::Top || drawing_state.text_baseline == Bindings::CanvasTextBaseline::Hanging) { + transform = Gfx::AffineTransform {}.set_translation({ 0, font->pixel_size() }).multiply(transform); + } + + transform = Gfx::AffineTransform { drawing_state.transform }.multiply(transform); + path = path.copy_transformed(transform); + return path; +} + +void CanvasRenderingContext2D::fill_text(StringView text, float x, float y, Optional<double> max_width) +{ + if (is<Gfx::BitmapFont>(*current_font())) + return bitmap_font_fill_text(text, x, y, max_width); + fill_internal(text_path(text, x, y, max_width), Gfx::Painter::WindingRule::Nonzero); +} + void CanvasRenderingContext2D::stroke_text(StringView text, float x, float y, Optional<double> max_width) { - // FIXME: Stroke the text instead of filling it. - fill_text(text, x, y, max_width); + if (is<Gfx::BitmapFont>(*current_font())) + return bitmap_font_fill_text(text, x, y, max_width); + stroke_internal(text_path(text, x, y, max_width)); } void CanvasRenderingContext2D::begin_path() diff --git a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h index cce9f5a3f437..7bfc536a7b5b 100644 --- a/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h +++ b/Userland/Libraries/LibWeb/HTML/CanvasRenderingContext2D.h @@ -145,6 +145,9 @@ class CanvasRenderingContext2D Gfx::Path rect_path(float x, float y, float width, float height); + Gfx::Path text_path(StringView text, float x, float y, Optional<double> max_width); + void bitmap_font_fill_text(StringView text, float x, float y, Optional<double> max_width); + void stroke_internal(Gfx::Path const&); void fill_internal(Gfx::Path const&, Gfx::Painter::WindingRule); void clip_internal(Gfx::Path&, Gfx::Painter::WindingRule);
d74f8039eb26f7956e02b4ae091a24338d127f1f
2022-08-23 18:28:30
Linus Groh
libjs: Replace GlobalObject with VM in Promise AOs [Part 8/19]
false
Replace GlobalObject with VM in Promise AOs [Part 8/19]
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index d90529b7583d..5e9f83c87371 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -3359,11 +3359,11 @@ Completion ImportCall::execute(Interpreter& interpreter) const // Note: options_value is undefined by default. // 6. Let promiseCapability be ! NewPromiseCapability(%Promise%). - auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto promise_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 7. Let specifierString be Completion(ToString(specifier)). // 8. IfAbruptRejectPromise(specifierString, promiseCapability). - auto specifier_string = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, specifier->to_string(vm)); + auto specifier_string = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, specifier->to_string(vm)); // 9. Let assertions be a new empty List. Vector<ModuleRequest::Assertion> assertions; @@ -3382,7 +3382,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const // b. Let assertionsObj be Get(options, "assert"). // c. IfAbruptRejectPromise(assertionsObj, promiseCapability). - auto assertion_object = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, options_value.get(vm, vm.names.assert)); + auto assertion_object = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, options_value.get(vm, vm.names.assert)); // d. If assertionsObj is not undefined, if (!assertion_object.is_undefined()) { @@ -3398,10 +3398,10 @@ Completion ImportCall::execute(Interpreter& interpreter) const // ii. Let keys be EnumerableOwnPropertyNames(assertionsObj, key). // iii. IfAbruptRejectPromise(keys, promiseCapability). - auto keys = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, assertion_object.as_object().enumerable_own_property_names(Object::PropertyKind::Key)); + auto keys = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, assertion_object.as_object().enumerable_own_property_names(Object::PropertyKind::Key)); // iv. Let supportedAssertions be ! HostGetSupportedImportAssertions(). - auto supported_assertions = interpreter.vm().host_get_supported_import_assertions(); + auto supported_assertions = vm.host_get_supported_import_assertions(); // v. For each String key of keys, for (auto const& key : keys) { @@ -3409,7 +3409,7 @@ Completion ImportCall::execute(Interpreter& interpreter) const // 1. Let value be Get(assertionsObj, key). // 2. IfAbruptRejectPromise(value, promiseCapability). - auto value = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, assertion_object.get(vm, property_key)); + auto value = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, assertion_object.get(vm, property_key)); // 3. If Type(value) is not String, then if (!value.is_string()) { diff --git a/Userland/Libraries/LibJS/CyclicModule.cpp b/Userland/Libraries/LibJS/CyclicModule.cpp index 63c6f534f4bb..021213c0dc43 100644 --- a/Userland/Libraries/LibJS/CyclicModule.cpp +++ b/Userland/Libraries/LibJS/CyclicModule.cpp @@ -201,7 +201,7 @@ ThrowCompletionOr<Promise*> CyclicModule::evaluate(VM& vm) // 6. Let capability be ! NewPromiseCapability(%Promise%). // 7. Set module.[[TopLevelCapability]] to capability. - m_top_level_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + m_top_level_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 8. Let result be Completion(InnerModuleEvaluation(module, stack, 0)). auto result = inner_module_evaluation(vm, stack, 0); @@ -443,7 +443,7 @@ void CyclicModule::execute_async_module(VM& vm) VERIFY(m_has_top_level_await); // 3. Let capability be ! NewPromiseCapability(%Promise%). - auto capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 4. Let fulfilledClosure be a new Abstract Closure with no parameters that captures module and performs the following steps when called: auto fulfilled_closure = [&](VM& vm, GlobalObject&) -> ThrowCompletionOr<Value> { diff --git a/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp b/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp index 8ac474089c46..8125b2f506a9 100644 --- a/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/AsyncFromSyncIteratorPrototype.cpp @@ -39,15 +39,15 @@ static Object* async_from_sync_iterator_continuation(VM& vm, Object& result, Pro // 1. NOTE: Because promiseCapability is derived from the intrinsic %Promise%, the calls to promiseCapability.[[Reject]] entailed by the use IfAbruptRejectPromise below are guaranteed not to throw. // 2. Let done be Completion(IteratorComplete(result)). // 3. IfAbruptRejectPromise(done, promiseCapability). - auto done = TRY_OR_MUST_REJECT(global_object, promise_capability, iterator_complete(vm, result)); + auto done = TRY_OR_MUST_REJECT(vm, promise_capability, iterator_complete(vm, result)); // 4. Let value be Completion(IteratorValue(result)). // 5. IfAbruptRejectPromise(value, promiseCapability). - auto value = TRY_OR_MUST_REJECT(global_object, promise_capability, iterator_value(vm, result)); + auto value = TRY_OR_MUST_REJECT(vm, promise_capability, iterator_value(vm, result)); // 6. Let valueWrapper be PromiseResolve(%Promise%, value). // 7. IfAbruptRejectPromise(valueWrapper, promiseCapability). - auto value_wrapper = TRY_OR_MUST_REJECT(global_object, promise_capability, promise_resolve(global_object, *global_object.promise_constructor(), value)); + auto value_wrapper = TRY_OR_MUST_REJECT(vm, promise_capability, promise_resolve(vm, *global_object.promise_constructor(), value)); // 8. Let unwrap be a new Abstract Closure with parameters (value) that captures done and performs the following steps when called: auto unwrap = [done](VM& vm, GlobalObject&) -> ThrowCompletionOr<Value> { @@ -74,7 +74,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::next) auto* this_object = MUST(typed_this_object(vm)); // 3. Let promiseCapability be ! NewPromiseCapability(%Promise%). - auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto promise_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]]. auto& sync_iterator_record = this_object->sync_iterator_record(); @@ -84,7 +84,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::next) // 6. Else, // a. Let result be Completion(IteratorNext(syncIteratorRecord)). // 7. IfAbruptRejectPromise(result, promiseCapability). - auto* result = TRY_OR_REJECT(global_object, promise_capability, + auto* result = TRY_OR_REJECT(vm, promise_capability, (vm.argument_count() > 0 ? iterator_next(vm, sync_iterator_record, vm.argument(0)) : iterator_next(vm, sync_iterator_record))); @@ -102,14 +102,14 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::return_) auto* this_object = MUST(typed_this_object(vm)); // 3. Let promiseCapability be ! NewPromiseCapability(%Promise%). - auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto promise_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]]. auto* sync_iterator = this_object->sync_iterator_record().iterator; // 5. Let return be Completion(GetMethod(syncIterator, "return")). // 6. IfAbruptRejectPromise(return, promiseCapability). - auto* return_method = TRY_OR_REJECT(global_object, promise_capability, Value(sync_iterator).get_method(vm, vm.names.return_)); + auto* return_method = TRY_OR_REJECT(vm, promise_capability, Value(sync_iterator).get_method(vm, vm.names.return_)); // 7. If return is undefined, then if (return_method == nullptr) { @@ -128,7 +128,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::return_) // 9. Else, // a. Let result be Completion(Call(return, syncIterator)). // 10. IfAbruptRejectPromise(result, promiseCapability). - auto result = TRY_OR_REJECT(global_object, promise_capability, + auto result = TRY_OR_REJECT(vm, promise_capability, (vm.argument_count() > 0 ? call(global_object, return_method, sync_iterator, vm.argument(0)) : call(global_object, return_method, sync_iterator))); @@ -155,14 +155,14 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::throw_) auto* this_object = MUST(typed_this_object(vm)); // 3. Let promiseCapability be ! NewPromiseCapability(%Promise%). - auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto promise_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]]. auto* sync_iterator = this_object->sync_iterator_record().iterator; // 5. Let throw be Completion(GetMethod(syncIterator, "throw")). // 6. IfAbruptRejectPromise(throw, promiseCapability). - auto* throw_method = TRY_OR_REJECT(global_object, promise_capability, Value(sync_iterator).get_method(vm, vm.names.throw_)); + auto* throw_method = TRY_OR_REJECT(vm, promise_capability, Value(sync_iterator).get_method(vm, vm.names.throw_)); // 7. If throw is undefined, then if (throw_method == nullptr) { @@ -176,7 +176,7 @@ JS_DEFINE_NATIVE_FUNCTION(AsyncFromSyncIteratorPrototype::throw_) // 9. Else, // a. Let result be Completion(Call(throw, syncIterator)). // 10. IfAbruptRejectPromise(result, promiseCapability). - auto result = TRY_OR_REJECT(global_object, promise_capability, + auto result = TRY_OR_REJECT(vm, promise_capability, (vm.argument_count() > 0 ? call(global_object, throw_method, sync_iterator, vm.argument(0)) : call(global_object, throw_method, sync_iterator))); diff --git a/Userland/Libraries/LibJS/Runtime/Completion.cpp b/Userland/Libraries/LibJS/Runtime/Completion.cpp index 303d33adbe5c..dd6b19f84809 100644 --- a/Userland/Libraries/LibJS/Runtime/Completion.cpp +++ b/Userland/Libraries/LibJS/Runtime/Completion.cpp @@ -38,7 +38,7 @@ ThrowCompletionOr<Value> await(GlobalObject& global_object, Value value) // NOTE: This is not needed, as we don't suspend anything. // 2. Let promise be ? PromiseResolve(%Promise%, value). - auto* promise_object = TRY(promise_resolve(global_object, *global_object.promise_constructor(), value)); + auto* promise_object = TRY(promise_resolve(vm, *global_object.promise_constructor(), value)); Optional<bool> success; Value result; diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp index d06f8c14c0e6..444a1d4a2317 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp @@ -867,7 +867,7 @@ Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body() // AsyncFunctionBody : FunctionBody else if (m_kind == FunctionKind::Async) { // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%). - auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto promise_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 2. Let declResult be Completion(FunctionDeclarationInstantiation(functionObject, argumentsList)). auto declaration_result = function_declaration_instantiation(ast_interpreter); diff --git a/Userland/Libraries/LibJS/Runtime/FinalizationRegistry.cpp b/Userland/Libraries/LibJS/Runtime/FinalizationRegistry.cpp index 2a33a676ee7b..f6e2cc18f195 100644 --- a/Userland/Libraries/LibJS/Runtime/FinalizationRegistry.cpp +++ b/Userland/Libraries/LibJS/Runtime/FinalizationRegistry.cpp @@ -53,7 +53,6 @@ void FinalizationRegistry::remove_dead_cells(Badge<Heap>) ThrowCompletionOr<void> FinalizationRegistry::cleanup(Optional<JobCallback> callback) { auto& vm = this->vm(); - auto& global_object = this->global_object(); // 1. Assert: finalizationRegistry has [[Cells]] and [[CleanupCallback]] internal slots. // Note: Ensured by type. @@ -73,7 +72,7 @@ ThrowCompletionOr<void> FinalizationRegistry::cleanup(Optional<JobCallback> call it.remove(m_records); // c. Perform ? HostCallJobCallback(callback, undefined, « cell.[[HeldValue]] »). - TRY(vm.host_call_job_callback(global_object, cleanup_callback, js_undefined(), move(arguments))); + TRY(vm.host_call_job_callback(cleanup_callback, js_undefined(), move(arguments))); } // 4. Return unused. diff --git a/Userland/Libraries/LibJS/Runtime/JobCallback.h b/Userland/Libraries/LibJS/Runtime/JobCallback.h index 8679ac26aa6a..f383a67ae9e9 100644 --- a/Userland/Libraries/LibJS/Runtime/JobCallback.h +++ b/Userland/Libraries/LibJS/Runtime/JobCallback.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Linus Groh <[email protected]> + * Copyright (c) 2021-2022, Linus Groh <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -30,8 +30,11 @@ inline JobCallback make_job_callback(FunctionObject& callback) } // 9.5.3 HostCallJobCallback ( jobCallback, V, argumentsList ), https://tc39.es/ecma262/#sec-hostcalljobcallback -inline ThrowCompletionOr<Value> call_job_callback(GlobalObject& global_object, JobCallback& job_callback, Value this_value, MarkedVector<Value> arguments_list) +inline ThrowCompletionOr<Value> call_job_callback(VM& vm, JobCallback& job_callback, Value this_value, MarkedVector<Value> arguments_list) { + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); + // 1. Assert: IsCallable(jobCallback.[[Callback]]) is true. VERIFY(!job_callback.callback.is_null()); diff --git a/Userland/Libraries/LibJS/Runtime/Promise.cpp b/Userland/Libraries/LibJS/Runtime/Promise.cpp index 9da044340ee7..6e217a36d48f 100644 --- a/Userland/Libraries/LibJS/Runtime/Promise.cpp +++ b/Userland/Libraries/LibJS/Runtime/Promise.cpp @@ -19,9 +19,10 @@ namespace JS { // 27.2.4.7.1 PromiseResolve ( C, x ), https://tc39.es/ecma262/#sec-promise-resolve -ThrowCompletionOr<Object*> promise_resolve(GlobalObject& global_object, Object& constructor, Value value) +ThrowCompletionOr<Object*> promise_resolve(VM& vm, Object& constructor, Value value) { - auto& vm = global_object.vm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); // 1. If IsPromise(x) is true, then if (value.is_object() && is<Promise>(value.as_object())) { @@ -34,7 +35,7 @@ ThrowCompletionOr<Object*> promise_resolve(GlobalObject& global_object, Object& } // 2. Let promiseCapability be ? NewPromiseCapability(C). - auto promise_capability = TRY(new_promise_capability(global_object, &constructor)); + auto promise_capability = TRY(new_promise_capability(vm, &constructor)); // 3. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »). (void)TRY(call(global_object, *promise_capability.resolve, js_undefined(), value)); @@ -150,7 +151,7 @@ Promise::ResolvingFunctions Promise::create_resolving_functions() // 14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseResolveThenableJob for thenable {}", &promise, resolution); - auto job = create_promise_resolve_thenable_job(global_object, promise, resolution, move(then_job_callback)); + auto job = create_promise_resolve_thenable_job(vm, promise, resolution, move(then_job_callback)); // 15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {} in realm {}", &promise, &job.job, job.realm); @@ -274,7 +275,7 @@ void Promise::trigger_reactions() const for (auto& reaction : reactions) { // a. Let job be NewPromiseReactionJob(reaction, argument). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result); - auto [job, realm] = create_promise_reaction_job(global_object(), *reaction, m_result); + auto [job, realm] = create_promise_reaction_job(vm, *reaction, m_result); // b. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {} in realm {}", this, &job, realm); @@ -344,7 +345,7 @@ Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<Prom // b. Let fulfillJob be NewPromiseReactionJob(fulfillReaction, value). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value); - auto [fulfill_job, realm] = create_promise_reaction_job(global_object(), *fulfill_reaction, value); + auto [fulfill_job, realm] = create_promise_reaction_job(vm, *fulfill_reaction, value); // c. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &fulfill_job, realm); @@ -364,7 +365,7 @@ Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<Prom // d. Let rejectJob be NewPromiseReactionJob(rejectReaction, reason). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason); - auto [reject_job, realm] = create_promise_reaction_job(global_object(), *reject_reaction, reason); + auto [reject_job, realm] = create_promise_reaction_job(vm, *reject_reaction, reason); // e. Perform HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]). dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &reject_job, realm); diff --git a/Userland/Libraries/LibJS/Runtime/Promise.h b/Userland/Libraries/LibJS/Runtime/Promise.h index fe3b62ae5ae1..2a3bf7e9179d 100644 --- a/Userland/Libraries/LibJS/Runtime/Promise.h +++ b/Userland/Libraries/LibJS/Runtime/Promise.h @@ -11,7 +11,7 @@ namespace JS { -ThrowCompletionOr<Object*> promise_resolve(GlobalObject&, Object& constructor, Value); +ThrowCompletionOr<Object*> promise_resolve(VM&, Object& constructor, Value); class Promise : public Object { JS_OBJECT(Promise, Object); diff --git a/Userland/Libraries/LibJS/Runtime/PromiseConstructor.cpp b/Userland/Libraries/LibJS/Runtime/PromiseConstructor.cpp index 83af568932b1..7b888f78f42e 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/PromiseConstructor.cpp @@ -21,10 +21,9 @@ namespace JS { // 27.2.4.1.1 GetPromiseResolve ( promiseConstructor ), https://tc39.es/ecma262/#sec-getpromiseresolve -static ThrowCompletionOr<Value> get_promise_resolve(GlobalObject& global_object, Value constructor) +static ThrowCompletionOr<Value> get_promise_resolve(VM& vm, Value constructor) { VERIFY(constructor.is_constructor()); - auto& vm = global_object.vm(); // 1. Let promiseResolve be ? Get(promiseConstructor, "resolve"). auto promise_resolve = TRY(constructor.get(vm, vm.names.resolve)); @@ -40,9 +39,10 @@ static ThrowCompletionOr<Value> get_promise_resolve(GlobalObject& global_object, using EndOfElementsCallback = Function<ThrowCompletionOr<Value>(PromiseValueList&)>; using InvokeElementFunctionCallback = Function<ThrowCompletionOr<Value>(PromiseValueList&, RemainingElements&, Value, size_t)>; -static ThrowCompletionOr<Value> perform_promise_common(GlobalObject& global_object, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve, EndOfElementsCallback end_of_list, InvokeElementFunctionCallback invoke_element_function) +static ThrowCompletionOr<Value> perform_promise_common(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve, EndOfElementsCallback end_of_list, InvokeElementFunctionCallback invoke_element_function) { - auto& vm = global_object.vm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); VERIFY(constructor.is_constructor()); VERIFY(promise_resolve.is_function()); @@ -116,13 +116,13 @@ static ThrowCompletionOr<Value> perform_promise_common(GlobalObject& global_obje } // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseall -static ThrowCompletionOr<Value> perform_promise_all(GlobalObject& global_object, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) +static ThrowCompletionOr<Value> perform_promise_all(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) { - auto& vm = global_object.vm(); - auto& realm = *global_object.associated_realm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); return perform_promise_common( - global_object, iterator_record, constructor, result_capability, promise_resolve, + vm, iterator_record, constructor, result_capability, promise_resolve, [&](PromiseValueList& values) -> ThrowCompletionOr<Value> { // 1. Let valuesArray be CreateArrayFromList(values). auto* values_array = Array::create_from(realm, values.values()); @@ -151,13 +151,13 @@ static ThrowCompletionOr<Value> perform_promise_all(GlobalObject& global_object, } // 27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseallsettled -static ThrowCompletionOr<Value> perform_promise_all_settled(GlobalObject& global_object, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) +static ThrowCompletionOr<Value> perform_promise_all_settled(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) { - auto& vm = global_object.vm(); - auto& realm = *global_object.associated_realm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); return perform_promise_common( - global_object, iterator_record, constructor, result_capability, promise_resolve, + vm, iterator_record, constructor, result_capability, promise_resolve, [&](PromiseValueList& values) -> ThrowCompletionOr<Value> { auto* values_array = Array::create_from(realm, values.values()); @@ -195,13 +195,12 @@ static ThrowCompletionOr<Value> perform_promise_all_settled(GlobalObject& global } // 27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseany -static ThrowCompletionOr<Value> perform_promise_any(GlobalObject& global_object, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) +static ThrowCompletionOr<Value> perform_promise_any(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) { - auto& vm = global_object.vm(); - auto& realm = *global_object.associated_realm(); + auto& realm = *vm.current_realm(); return perform_promise_common( - global_object, iterator_record, constructor, result_capability, promise_resolve, + vm, iterator_record, constructor, result_capability, promise_resolve, [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> { // 1. Let error be a newly created AggregateError object. auto* error = AggregateError::create(realm); @@ -231,12 +230,10 @@ static ThrowCompletionOr<Value> perform_promise_any(GlobalObject& global_object, } // 27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiserace -static ThrowCompletionOr<Value> perform_promise_race(GlobalObject& global_object, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) +static ThrowCompletionOr<Value> perform_promise_race(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve) { - auto& vm = global_object.vm(); - return perform_promise_common( - global_object, iterator_record, constructor, result_capability, promise_resolve, + vm, iterator_record, constructor, result_capability, promise_resolve, [&](PromiseValueList&) -> ThrowCompletionOr<Value> { // ii. Return resultCapability.[[Promise]]. return Value(result_capability.promise); @@ -324,18 +321,18 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all) auto* constructor = TRY(vm.this_value().to_object(vm)); // 2. Let promiseCapability be ? NewPromiseCapability(C). - auto promise_capability = TRY(new_promise_capability(global_object, constructor)); + auto promise_capability = TRY(new_promise_capability(vm, constructor)); // 3. Let promiseResolve be Completion(GetPromiseResolve(C)). // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability). - auto promise_resolve = TRY_OR_REJECT(global_object, promise_capability, get_promise_resolve(global_object, constructor)); + auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor)); // 5. Let iteratorRecord be Completion(GetIterator(iterable)). // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability). - auto iterator_record = TRY_OR_REJECT(global_object, promise_capability, get_iterator(vm, vm.argument(0))); + auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0))); // 7. Let result be Completion(PerformPromiseAll(iteratorRecord, C, promiseCapability, promiseResolve)). - auto result = perform_promise_all(global_object, iterator_record, constructor, promise_capability, promise_resolve); + auto result = perform_promise_all(vm, iterator_record, constructor, promise_capability, promise_resolve); // 8. If result is an abrupt completion, then if (result.is_error()) { @@ -344,7 +341,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all) result = iterator_close(vm, iterator_record, result.release_error()); // b. IfAbruptRejectPromise(result, promiseCapability). - TRY_OR_REJECT(global_object, promise_capability, result); + TRY_OR_REJECT(vm, promise_capability, result); } // 9. Return ? result. @@ -358,18 +355,18 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled) auto* constructor = TRY(vm.this_value().to_object(vm)); // 2. Let promiseCapability be ? NewPromiseCapability(C). - auto promise_capability = TRY(new_promise_capability(global_object, constructor)); + auto promise_capability = TRY(new_promise_capability(vm, constructor)); // 3. Let promiseResolve be Completion(GetPromiseResolve(C)). // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability). - auto promise_resolve = TRY_OR_REJECT(global_object, promise_capability, get_promise_resolve(global_object, constructor)); + auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor)); // 5. Let iteratorRecord be Completion(GetIterator(iterable)). // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability). - auto iterator_record = TRY_OR_REJECT(global_object, promise_capability, get_iterator(vm, vm.argument(0))); + auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0))); // 7. Let result be Completion(PerformPromiseAllSettled(iteratorRecord, C, promiseCapability, promiseResolve)). - auto result = perform_promise_all_settled(global_object, iterator_record, constructor, promise_capability, promise_resolve); + auto result = perform_promise_all_settled(vm, iterator_record, constructor, promise_capability, promise_resolve); // 8. If result is an abrupt completion, then if (result.is_error()) { @@ -378,7 +375,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled) result = iterator_close(vm, iterator_record, result.release_error()); // b. IfAbruptRejectPromise(result, promiseCapability). - TRY_OR_REJECT(global_object, promise_capability, result); + TRY_OR_REJECT(vm, promise_capability, result); } // 9. Return ? result. @@ -392,18 +389,18 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any) auto* constructor = TRY(vm.this_value().to_object(vm)); // 2. Let promiseCapability be ? NewPromiseCapability(C). - auto promise_capability = TRY(new_promise_capability(global_object, constructor)); + auto promise_capability = TRY(new_promise_capability(vm, constructor)); // 3. Let promiseResolve be Completion(GetPromiseResolve(C)). // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability). - auto promise_resolve = TRY_OR_REJECT(global_object, promise_capability, get_promise_resolve(global_object, constructor)); + auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor)); // 5. Let iteratorRecord be Completion(GetIterator(iterable)). // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability). - auto iterator_record = TRY_OR_REJECT(global_object, promise_capability, get_iterator(vm, vm.argument(0))); + auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0))); // 7. Let result be Completion(PerformPromiseAny(iteratorRecord, C, promiseCapability, promiseResolve)). - auto result = perform_promise_any(global_object, iterator_record, constructor, promise_capability, promise_resolve); + auto result = perform_promise_any(vm, iterator_record, constructor, promise_capability, promise_resolve); // 8. If result is an abrupt completion, then if (result.is_error()) { @@ -412,7 +409,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any) result = iterator_close(vm, iterator_record, result.release_error()); // b. IfAbruptRejectPromise(result, promiseCapability). - TRY_OR_REJECT(global_object, promise_capability, result); + TRY_OR_REJECT(vm, promise_capability, result); } // 9. Return ? result. @@ -426,18 +423,18 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race) auto* constructor = TRY(vm.this_value().to_object(vm)); // 2. Let promiseCapability be ? NewPromiseCapability(C). - auto promise_capability = TRY(new_promise_capability(global_object, constructor)); + auto promise_capability = TRY(new_promise_capability(vm, constructor)); // 3. Let promiseResolve be Completion(GetPromiseResolve(C)). // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability). - auto promise_resolve = TRY_OR_REJECT(global_object, promise_capability, get_promise_resolve(global_object, constructor)); + auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor)); // 5. Let iteratorRecord be Completion(GetIterator(iterable)). // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability). - auto iterator_record = TRY_OR_REJECT(global_object, promise_capability, get_iterator(vm, vm.argument(0))); + auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0))); // 7. Let result be Completion(PerformPromiseRace(iteratorRecord, C, promiseCapability, promiseResolve)). - auto result = perform_promise_race(global_object, iterator_record, constructor, promise_capability, promise_resolve); + auto result = perform_promise_race(vm, iterator_record, constructor, promise_capability, promise_resolve); // 8. If result is an abrupt completion, then if (result.is_error()) { @@ -446,7 +443,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race) result = iterator_close(vm, iterator_record, result.release_error()); // b. IfAbruptRejectPromise(result, promiseCapability). - TRY_OR_REJECT(global_object, promise_capability, result); + TRY_OR_REJECT(vm, promise_capability, result); } // 9. Return ? result. @@ -462,7 +459,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::reject) auto* constructor = TRY(vm.this_value().to_object(vm)); // 2. Let promiseCapability be ? NewPromiseCapability(C). - auto promise_capability = TRY(new_promise_capability(global_object, constructor)); + auto promise_capability = TRY(new_promise_capability(vm, constructor)); // 3. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »). [[maybe_unused]] auto result = TRY(JS::call(global_object, *promise_capability.reject, js_undefined(), reason)); @@ -484,7 +481,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::resolve) return vm.throw_completion<TypeError>(ErrorType::NotAnObject, constructor.to_string_without_side_effects()); // 3. Return ? PromiseResolve(C, x). - return TRY(promise_resolve(global_object, constructor.as_object(), value)); + return TRY(promise_resolve(vm, constructor.as_object(), value)); } // 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species diff --git a/Userland/Libraries/LibJS/Runtime/PromiseJobs.cpp b/Userland/Libraries/LibJS/Runtime/PromiseJobs.cpp index 4d0eaa979a90..6cb4bb20b35f 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseJobs.cpp +++ b/Userland/Libraries/LibJS/Runtime/PromiseJobs.cpp @@ -16,9 +16,10 @@ namespace JS { // 27.2.2.1 NewPromiseReactionJob ( reaction, argument ), https://tc39.es/ecma262/#sec-newpromisereactionjob -static ThrowCompletionOr<Value> run_reaction_job(GlobalObject& global_object, PromiseReaction& reaction, Value argument) +static ThrowCompletionOr<Value> run_reaction_job(VM& vm, PromiseReaction& reaction, Value argument) { - auto& vm = global_object.vm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); // a. Let promiseCapability be reaction.[[Capability]]. auto& promise_capability = reaction.capability(); @@ -55,7 +56,7 @@ static ThrowCompletionOr<Value> run_reaction_job(GlobalObject& global_object, Pr dbgln_if(PROMISE_DEBUG, "run_reaction_job: Calling handler callback {} @ {} with argument {}", handler.value().callback.cell()->class_name(), handler.value().callback.cell(), argument); MarkedVector<Value> arguments(vm.heap()); arguments.append(argument); - handler_result = vm.host_call_job_callback(global_object, handler.value(), js_undefined(), move(arguments)); + handler_result = vm.host_call_job_callback(handler.value(), js_undefined(), move(arguments)); } // f. If promiseCapability is undefined, then @@ -89,12 +90,15 @@ static ThrowCompletionOr<Value> run_reaction_job(GlobalObject& global_object, Pr } // 27.2.2.1 NewPromiseReactionJob ( reaction, argument ), https://tc39.es/ecma262/#sec-newpromisereactionjob -PromiseJob create_promise_reaction_job(GlobalObject& global_object, PromiseReaction& reaction, Value argument) +PromiseJob create_promise_reaction_job(VM& vm, PromiseReaction& reaction, Value argument) { + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); + // 1. Let job be a new Job Abstract Closure with no parameters that captures reaction and argument and performs the following steps when called: // See run_reaction_job for "the following steps". - auto job = [global_object = make_handle(&global_object), reaction = make_handle(&reaction), argument = make_handle(argument)]() mutable { - return run_reaction_job(*global_object.cell(), *reaction.cell(), argument.value()); + auto job = [&vm, reaction = make_handle(&reaction), argument = make_handle(argument)]() mutable { + return run_reaction_job(vm, *reaction.cell(), argument.value()); }; // 2. Let handlerRealm be null. @@ -111,7 +115,7 @@ PromiseJob create_promise_reaction_job(GlobalObject& global_object, PromiseReact handler_realm = get_handler_realm_result.release_value(); } else { // c. Else, set handlerRealm to the current Realm Record. - handler_realm = global_object.vm().current_realm(); + handler_realm = vm.current_realm(); } // d. NOTE: handlerRealm is never null unless the handler is undefined. When the handler is a revoked Proxy and no ECMAScript code runs, handlerRealm is used to create error objects. @@ -122,9 +126,10 @@ PromiseJob create_promise_reaction_job(GlobalObject& global_object, PromiseReact } // 27.2.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then ), https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob -static ThrowCompletionOr<Value> run_resolve_thenable_job(GlobalObject& global_object, Promise& promise_to_resolve, Value thenable, JobCallback& then) +static ThrowCompletionOr<Value> run_resolve_thenable_job(VM& vm, Promise& promise_to_resolve, Value thenable, JobCallback& then) { - auto& vm = global_object.vm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); // a. Let resolvingFunctions be CreateResolvingFunctions(promiseToResolve). auto [resolve_function, reject_function] = promise_to_resolve.create_resolving_functions(); @@ -134,7 +139,7 @@ static ThrowCompletionOr<Value> run_resolve_thenable_job(GlobalObject& global_ob MarkedVector<Value> arguments(vm.heap()); arguments.append(Value(&resolve_function)); arguments.append(Value(&reject_function)); - auto then_call_result = vm.host_call_job_callback(global_object, then, thenable, move(arguments)); + auto then_call_result = vm.host_call_job_callback(then, thenable, move(arguments)); // c. If thenCallResult is an abrupt completion, then if (then_call_result.is_error()) { @@ -149,8 +154,11 @@ static ThrowCompletionOr<Value> run_resolve_thenable_job(GlobalObject& global_ob } // 27.2.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then ), https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob -PromiseJob create_promise_resolve_thenable_job(GlobalObject& global_object, Promise& promise_to_resolve, Value thenable, JobCallback then) +PromiseJob create_promise_resolve_thenable_job(VM& vm, Promise& promise_to_resolve, Value thenable, JobCallback then) { + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); + // 2. Let getThenRealmResult be Completion(GetFunctionRealm(then.[[Callback]])). auto get_then_realm_result = get_function_realm(global_object, *then.callback.cell()); @@ -161,7 +169,7 @@ PromiseJob create_promise_resolve_thenable_job(GlobalObject& global_object, Prom then_realm = get_then_realm_result.release_value(); } else { // 4. Else, let thenRealm be the current Realm Record. - then_realm = global_object.vm().current_realm(); + then_realm = vm.current_realm(); } // 5. NOTE: thenRealm is never null. When then.[[Callback]] is a revoked Proxy and no code runs, thenRealm is used to create error objects. @@ -170,8 +178,8 @@ PromiseJob create_promise_resolve_thenable_job(GlobalObject& global_object, Prom // 1. Let job be a new Job Abstract Closure with no parameters that captures promiseToResolve, thenable, and then and performs the following steps when called: // See PromiseResolveThenableJob::call() for "the following steps". // NOTE: This is done out of order, since `then` is moved into the lambda and `then` would be invalid if it was done at the start. - auto job = [global_object = make_handle(&global_object), promise_to_resolve = make_handle(&promise_to_resolve), thenable = make_handle(thenable), then = move(then)]() mutable { - return run_resolve_thenable_job(*global_object.cell(), *promise_to_resolve.cell(), thenable.value(), then); + auto job = [&vm, promise_to_resolve = make_handle(&promise_to_resolve), thenable = make_handle(thenable), then = move(then)]() mutable { + return run_resolve_thenable_job(vm, *promise_to_resolve.cell(), thenable.value(), then); }; // 6. Return the Record { [[Job]]: job, [[Realm]]: thenRealm }. diff --git a/Userland/Libraries/LibJS/Runtime/PromiseJobs.h b/Userland/Libraries/LibJS/Runtime/PromiseJobs.h index c46685bb9eb5..c7b95e0a26bc 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseJobs.h +++ b/Userland/Libraries/LibJS/Runtime/PromiseJobs.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Linus Groh <[email protected]> + * Copyright (c) 2021-2022, Linus Groh <[email protected]> * Copyright (c) 2021, Luke Wilde <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause @@ -20,7 +20,7 @@ struct PromiseJob { }; // NOTE: These return a PromiseJob to prevent awkward casting at call sites. -PromiseJob create_promise_reaction_job(GlobalObject&, PromiseReaction&, Value argument); -PromiseJob create_promise_resolve_thenable_job(GlobalObject&, Promise&, Value thenable, JobCallback then); +PromiseJob create_promise_reaction_job(VM&, PromiseReaction&, Value argument); +PromiseJob create_promise_resolve_thenable_job(VM&, Promise&, Value thenable, JobCallback then); } diff --git a/Userland/Libraries/LibJS/Runtime/PromisePrototype.cpp b/Userland/Libraries/LibJS/Runtime/PromisePrototype.cpp index 5b5d625fb8ca..184aec0a560a 100644 --- a/Userland/Libraries/LibJS/Runtime/PromisePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/PromisePrototype.cpp @@ -49,7 +49,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::then) auto* constructor = TRY(species_constructor(global_object, *promise, *global_object.promise_constructor())); // 4. Let resultCapability be ? NewPromiseCapability(C). - auto result_capability = TRY(new_promise_capability(global_object, constructor)); + auto result_capability = TRY(new_promise_capability(vm, constructor)); // 5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability). return promise->perform_then(on_fulfilled, on_rejected, result_capability); @@ -111,7 +111,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally) auto result = TRY(call(global_object, on_finally, js_undefined())); // ii. Let promise be ? PromiseResolve(C, result). - auto* promise = TRY(promise_resolve(global_object, constructor, result)); + auto* promise = TRY(promise_resolve(vm, constructor, result)); // iii. Let returnValue be a new Abstract Closure with no parameters that captures value and performs the following steps when called: auto return_value = [value_handle = make_handle(value)](auto&, auto&) -> ThrowCompletionOr<Value> { @@ -140,7 +140,7 @@ JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally) auto result = TRY(call(global_object, on_finally, js_undefined())); // ii. Let promise be ? PromiseResolve(C, result). - auto* promise = TRY(promise_resolve(global_object, constructor, result)); + auto* promise = TRY(promise_resolve(vm, constructor, result)); // iii. Let throwReason be a new Abstract Closure with no parameters that captures reason and performs the following steps when called: auto throw_reason = [reason_handle = make_handle(reason)](auto&, auto&) -> ThrowCompletionOr<Value> { diff --git a/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp b/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp index 3a41dc5b5c6e..aa93af92114a 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp +++ b/Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp @@ -12,10 +12,10 @@ namespace JS { // 27.2.1.5 NewPromiseCapability ( C ), https://tc39.es/ecma262/#sec-newpromisecapability -ThrowCompletionOr<PromiseCapability> new_promise_capability(GlobalObject& global_object, Value constructor) +ThrowCompletionOr<PromiseCapability> new_promise_capability(VM& vm, Value constructor) { - auto& vm = global_object.vm(); - auto& realm = *global_object.associated_realm(); + auto& realm = *vm.current_realm(); + auto& global_object = realm.global_object(); // 1. If IsConstructor(C) is false, throw a TypeError exception. if (!constructor.is_constructor()) diff --git a/Userland/Libraries/LibJS/Runtime/PromiseReaction.h b/Userland/Libraries/LibJS/Runtime/PromiseReaction.h index c1acb937d391..246434ca531b 100644 --- a/Userland/Libraries/LibJS/Runtime/PromiseReaction.h +++ b/Userland/Libraries/LibJS/Runtime/PromiseReaction.h @@ -21,47 +21,51 @@ struct PromiseCapability { }; // 27.2.1.1.1 IfAbruptRejectPromise ( value, capability ), https://tc39.es/ecma262/#sec-ifabruptrejectpromise -#define __TRY_OR_REJECT(global_object, capability, expression, CALL_CHECK) \ - ({ \ - auto _temporary_try_or_reject_result = (expression); \ - /* 1. If value is an abrupt completion, then */ \ - if (_temporary_try_or_reject_result.is_error()) { \ - /* a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »). */ \ - CALL_CHECK(JS::call(global_object, *capability.reject, js_undefined(), *_temporary_try_or_reject_result.release_error().value())); \ - \ - /* b. Return capability.[[Promise]]. */ \ - return capability.promise; \ - } \ - \ - /* 2. Else if value is a Completion Record, set value to value.[[Value]]. */ \ - _temporary_try_or_reject_result.release_value(); \ +#define __TRY_OR_REJECT(vm, capability, expression, CALL_CHECK) \ + ({ \ + auto& _realm = *vm.current_realm(); \ + auto& _global_object = _realm.global_object(); \ + auto _temporary_try_or_reject_result = (expression); \ + /* 1. If value is an abrupt completion, then */ \ + if (_temporary_try_or_reject_result.is_error()) { \ + /* a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »). */ \ + CALL_CHECK(JS::call(_global_object, *capability.reject, js_undefined(), *_temporary_try_or_reject_result.release_error().value())); \ + \ + /* b. Return capability.[[Promise]]. */ \ + return capability.promise; \ + } \ + \ + /* 2. Else if value is a Completion Record, set value to value.[[Value]]. */ \ + _temporary_try_or_reject_result.release_value(); \ }) -#define TRY_OR_REJECT(global_object, capability, expression) \ - __TRY_OR_REJECT(global_object, capability, expression, TRY) +#define TRY_OR_REJECT(vm, capability, expression) \ + __TRY_OR_REJECT(vm, capability, expression, TRY) -#define TRY_OR_MUST_REJECT(global_object, capability, expression) \ - __TRY_OR_REJECT(global_object, capability, expression, MUST) +#define TRY_OR_MUST_REJECT(vm, capability, expression) \ + __TRY_OR_REJECT(vm, capability, expression, MUST) // 27.2.1.1.1 IfAbruptRejectPromise ( value, capability ), https://tc39.es/ecma262/#sec-ifabruptrejectpromise -#define TRY_OR_REJECT_WITH_VALUE(global_object, capability, expression) \ - ({ \ - auto _temporary_try_or_reject_result = (expression); \ - /* 1. If value is an abrupt completion, then */ \ - if (_temporary_try_or_reject_result.is_error()) { \ - /* a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »). */ \ - TRY(JS::call(global_object, *capability.reject, js_undefined(), *_temporary_try_or_reject_result.release_error().value())); \ - \ - /* b. Return capability.[[Promise]]. */ \ - return Value { capability.promise }; \ - } \ - \ - /* 2. Else if value is a Completion Record, set value to value.[[Value]]. */ \ - _temporary_try_or_reject_result.release_value(); \ +#define TRY_OR_REJECT_WITH_VALUE(vm, capability, expression) \ + ({ \ + auto& _realm = *vm.current_realm(); \ + auto& _global_object = _realm.global_object(); \ + auto _temporary_try_or_reject_result = (expression); \ + /* 1. If value is an abrupt completion, then */ \ + if (_temporary_try_or_reject_result.is_error()) { \ + /* a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »). */ \ + TRY(JS::call(_global_object, *capability.reject, js_undefined(), *_temporary_try_or_reject_result.release_error().value())); \ + \ + /* b. Return capability.[[Promise]]. */ \ + return Value { capability.promise }; \ + } \ + \ + /* 2. Else if value is a Completion Record, set value to value.[[Value]]. */ \ + _temporary_try_or_reject_result.release_value(); \ }) // 27.2.1.5 NewPromiseCapability ( C ), https://tc39.es/ecma262/#sec-newpromisecapability -ThrowCompletionOr<PromiseCapability> new_promise_capability(GlobalObject& global_object, Value constructor); +ThrowCompletionOr<PromiseCapability> new_promise_capability(VM& vm, Value constructor); // 27.2.1.2 PromiseReaction Records, https://tc39.es/ecma262/#sec-promisereaction-records class PromiseReaction final : public Cell { diff --git a/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp b/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp index df9a7a8b2760..93df6f6fde47 100644 --- a/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp +++ b/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp @@ -214,7 +214,7 @@ ThrowCompletionOr<Value> shadow_realm_import_value(GlobalObject& global_object, // 1. Assert: evalContext is an execution context associated to a ShadowRealm instance's [[ExecutionContext]]. // 2. Let innerCapability be ! NewPromiseCapability(%Promise%). - auto inner_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto inner_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // 3. Let runningContext be the running execution context. // 4. If runningContext is not already suspended, suspend runningContext. @@ -269,7 +269,7 @@ ThrowCompletionOr<Value> shadow_realm_import_value(GlobalObject& global_object, auto* on_fulfilled = NativeFunction::create(realm, move(steps), 1, "", &caller_realm); // 12. Let promiseCapability be ! NewPromiseCapability(%Promise%). - auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor())); + auto promise_capability = MUST(new_promise_capability(vm, global_object.promise_constructor())); // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do. // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object). diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index 6b2901b463cf..eb71857b2f0a 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -51,8 +51,8 @@ VM::VM(OwnPtr<CustomData> custom_data) promise_rejection_tracker(promise, operation); }; - host_call_job_callback = [](GlobalObject& global_object, JobCallback& job_callback, Value this_value, MarkedVector<Value> arguments) { - return call_job_callback(global_object, job_callback, this_value, move(arguments)); + host_call_job_callback = [this](JobCallback& job_callback, Value this_value, MarkedVector<Value> arguments) { + return call_job_callback(*this, job_callback, this_value, move(arguments)); }; host_enqueue_finalization_registry_cleanup_job = [this](FinalizationRegistry& finalization_registry) { diff --git a/Userland/Libraries/LibJS/Runtime/VM.h b/Userland/Libraries/LibJS/Runtime/VM.h index 6825ef4adf25..7d47a56e7f1a 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.h +++ b/Userland/Libraries/LibJS/Runtime/VM.h @@ -229,7 +229,7 @@ class VM : public RefCounted<VM> { void enable_default_host_import_module_dynamically_hook(); Function<void(Promise&, Promise::RejectionOperation)> host_promise_rejection_tracker; - Function<ThrowCompletionOr<Value>(GlobalObject&, JobCallback&, Value, MarkedVector<Value>)> host_call_job_callback; + Function<ThrowCompletionOr<Value>(JobCallback&, Value, MarkedVector<Value>)> host_call_job_callback; Function<void(FinalizationRegistry&)> host_enqueue_finalization_registry_cleanup_job; Function<void(Function<ThrowCompletionOr<Value>()>, Realm*)> host_enqueue_promise_job; Function<JobCallback(FunctionObject&)> host_make_job_callback; diff --git a/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp index e5a74231c730..59d3eca956e5 100644 --- a/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp +++ b/Userland/Libraries/LibWeb/Bindings/MainThreadVM.cpp @@ -128,7 +128,9 @@ JS::VM& main_thread_vm() }; // 8.1.5.3.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback - vm->host_call_job_callback = [](JS::GlobalObject& global_object, JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) { + vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) { + auto& realm = *vm->current_realm(); + auto& global_object = realm.global_object(); auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data); // 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]]. (NOTE: Not necessary)
904c871727cca9fc53f6447228df9d8f8bcb2de8
2019-10-31 18:27:07
Andreas Kling
kernel: Allow userspace stacks to grow up to 4 MB by default
false
Allow userspace stacks to grow up to 4 MB by default
kernel
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index 467c4903ca85..ca6a3271aef1 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -502,7 +502,7 @@ void Thread::push_value_on_stack(u32 value) void Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment) { - auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)"); + auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)", PROT_READ | PROT_WRITE, false); ASSERT(region); m_tss.esp = region->vaddr().offset(default_userspace_stack_size).get(); @@ -537,7 +537,7 @@ void Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vect void Thread::make_userspace_stack_for_secondary_thread(void* argument) { - m_userspace_stack_region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, String::format("Stack (Thread %d)", tid())); + m_userspace_stack_region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, String::format("Stack (Thread %d)", tid()), PROT_READ | PROT_WRITE, false); ASSERT(m_userspace_stack_region); m_tss.esp = m_userspace_stack_region->vaddr().offset(default_userspace_stack_size).get(); diff --git a/Kernel/Thread.h b/Kernel/Thread.h index baeb85146deb..e0e34ad853f6 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -313,7 +313,7 @@ class Thread { } static constexpr u32 default_kernel_stack_size = 65536; - static constexpr u32 default_userspace_stack_size = 65536; + static constexpr u32 default_userspace_stack_size = 4 * MB; private: IntrusiveListNode m_runnable_list_node;
8b60305698f1d2fbd7083a9b370ea9af06133f68
2022-09-03 21:27:37
kleines Filmröllchen
pixelpaint: Specify histogram height in GML
false
Specify histogram height in GML
pixelpaint
diff --git a/Userland/Applications/PixelPaint/HistogramWidget.cpp b/Userland/Applications/PixelPaint/HistogramWidget.cpp index d8003a3482e1..6a9e7de66b3d 100644 --- a/Userland/Applications/PixelPaint/HistogramWidget.cpp +++ b/Userland/Applications/PixelPaint/HistogramWidget.cpp @@ -16,11 +16,6 @@ REGISTER_WIDGET(PixelPaint, HistogramWidget); namespace PixelPaint { -HistogramWidget::HistogramWidget() -{ - set_height(65); -} - HistogramWidget::~HistogramWidget() { if (m_image) diff --git a/Userland/Applications/PixelPaint/HistogramWidget.h b/Userland/Applications/PixelPaint/HistogramWidget.h index 72d0c1cff5f3..c50ff90d4fb2 100644 --- a/Userland/Applications/PixelPaint/HistogramWidget.h +++ b/Userland/Applications/PixelPaint/HistogramWidget.h @@ -24,7 +24,7 @@ class HistogramWidget final void set_color_at_mouseposition(Color); private: - HistogramWidget(); + HistogramWidget() = default; virtual void paint_event(GUI::PaintEvent&) override; diff --git a/Userland/Applications/PixelPaint/PixelPaintWindow.gml b/Userland/Applications/PixelPaint/PixelPaintWindow.gml index 30e017f4b1e3..c4a641899d01 100644 --- a/Userland/Applications/PixelPaint/PixelPaintWindow.gml +++ b/Userland/Applications/PixelPaint/PixelPaintWindow.gml @@ -66,14 +66,14 @@ @GUI::GroupBox { title: "Histogram" - max_height: 90 + preferred_height: "shrink" layout: @GUI::VerticalBoxLayout { margins: [6] } @PixelPaint::HistogramWidget { name: "histogram_widget" - max_height: 65 + min_height: 65 } }
652870c1783ec9c9185e3773a411f14848e8988e
2022-09-03 03:37:53
Karol Kosek
libgfx: Ignore incorrect .font files when building the Font Database
false
Ignore incorrect .font files when building the Font Database
libgfx
diff --git a/Userland/Libraries/LibGfx/Font/FontDatabase.cpp b/Userland/Libraries/LibGfx/Font/FontDatabase.cpp index 99fcc4861600..4be0a1acfa15 100644 --- a/Userland/Libraries/LibGfx/Font/FontDatabase.cpp +++ b/Userland/Libraries/LibGfx/Font/FontDatabase.cpp @@ -132,7 +132,8 @@ FontDatabase::FontDatabase() auto path = dir_iterator.next_full_path(); if (path.ends_with(".font"sv)) { - if (auto font = Gfx::BitmapFont::load_from_file(path)) { + if (auto font_or_error = Gfx::BitmapFont::try_load_from_file(path); !font_or_error.is_error()) { + auto font = font_or_error.release_value(); m_private->full_name_to_font_map.set(font->qualified_name(), *font); auto typeface = get_or_create_typeface(font->family(), font->variant()); typeface->add_bitmap_font(font);
93aa4d581d98155e7f49880ba600bb32acd2659f
2019-03-20 20:22:37
Andreas Kling
meta: Tweak ReadMe and add a new screenshot.
false
Tweak ReadMe and add a new screenshot.
meta
diff --git a/Meta/screenshot-cdb82f6.png b/Meta/screenshot-cdb82f6.png new file mode 100644 index 000000000000..aa0d0f23b34b Binary files /dev/null and b/Meta/screenshot-cdb82f6.png differ diff --git a/ReadMe.md b/ReadMe.md index 1115f8f8cb5a..fb3b3e3f1871 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -6,16 +6,19 @@ x86 Unix-like operating system for IBM PC-compatibles. I always wondered what it would be like to write my own operating system, but I never took it seriously. Until now. -I've grown tired of cutesy and condescending software that doesn't take itself or the user seriously. This is my effort to bring back the feeling of computing we once knew. +I've grown tired of cutesy and condescending software that doesn't take itself or the user seriously. This is my effort to bring back the feeling of computing I once knew. + +Roughly speaking, the goal here is a marriage between the aesthetic of late-1990s productivity software and the power-user accessibility of late-2000s \*nix. This is a system by me, for me, based on the things I like. ## Screenshot -![Screenshot as of b5521e1](https://raw.githubusercontent.com/awesomekling/serenity/master/Meta/screenshot-b5521e1.png) +![Screenshot as of cdb82f6](https://raw.githubusercontent.com/awesomekling/serenity/master/Meta/screenshot-cdb82f6.png) ## Current features * Pre-emptive multitasking * Compositing window server +* IPv4 networking with ARP, TCP, UDP and ICMP * ext2 filesystem * Unix-like libc and userland * mmap() @@ -23,22 +26,26 @@ I've grown tired of cutesy and condescending software that doesn't take itself o * Local sockets * Pseudoterminals * Event-driven GUI library -* Graphical text editor +* Text editor +* IRC client +* DNS lookup * Other stuff I can't think of right now... -## How do I get it to run? +## How do I build and run this? You need a freestanding cross-compiler for the i686-elf target (for the kernel) and another cross-compiler for the i686-pc-serenity target (for all the userspace stuff.) It's probably possible to coerce it into building with vanilla gcc/clang if you pass all the right compiler flags, but I haven't been doing that for a while. +There's [a helpful guide on building a GCC cross-compiler](https://wiki.osdev.org/GCC_Cross-Compiler) on the OSDev wiki. + I've only tested this on an Ubuntu 18.10 host with GCC 8.2.0, so I'm not sure it works anywhere else. If you'd like to run it, here's how you'd get it to boot: cd Kernel ./makeall.sh - ./run q # Runs in QEMU - ./run # Runs in bochs + ./run # Runs in QEMU + ./run b # Runs in bochs (limited networking support) ## Author
43285eec8f7a12dc4f3b41c036baf658a30a2bcc
2022-06-01 15:32:34
Tim Schumacher
ports: Restore the former `c-ray` HDR patch
false
Restore the former `c-ray` HDR patch
ports
diff --git a/Ports/c-ray/patches/0006-Reduce-HDR-scene-settings-a-bit.patch b/Ports/c-ray/patches/0006-Reduce-HDR-scene-settings-a-bit.patch index 841dd0ac2b3d..0d0b8f1c6779 100644 --- a/Ports/c-ray/patches/0006-Reduce-HDR-scene-settings-a-bit.patch +++ b/Ports/c-ray/patches/0006-Reduce-HDR-scene-settings-a-bit.patch @@ -1,413 +1,36 @@ -From 81f73eaff2d269158ee4cef7bd576af5bedb835e Mon Sep 17 00:00:00 2001 +From 252852219ee147c38a885ea3f1e6118244f7f57d Mon Sep 17 00:00:00 2001 From: Valtteri Koskivuori <[email protected]> Date: Sat, 13 Mar 2021 22:11:07 +0100 Subject: [PATCH 6/8] Reduce HDR scene settings a bit --- - input/hdr.json | 394 +++++++++++++++++++++++++++++++++++++++++++++++++ - 1 file changed, 394 insertions(+) - create mode 100644 input/hdr.json + input/hdr.json | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/input/hdr.json b/input/hdr.json -new file mode 100644 -index 0000000..b7b5b63 ---- /dev/null +index f2f45b1..b7b5b63 100644 +--- a/input/hdr.json +++ b/input/hdr.json -@@ -0,0 +1,394 @@ -+{ -+ "version": 1.0, -+ "renderer": { -+ "threads": 0, +@@ -2,7 +2,7 @@ + "version": 1.0, + "renderer": { + "threads": 0, +- "samples": 250, + "samples": 25, -+ "bounces": 30, -+ "tileWidth": 64, -+ "tileHeight": 64, -+ "tileOrder": "fromMiddle", -+ "outputFilePath": "output/", -+ "outputFileName": "rendered", -+ "fileType": "png", -+ "count": 0, + "bounces": 30, + "tileWidth": 64, + "tileHeight": 64, +@@ -11,8 +11,8 @@ + "outputFileName": "rendered", + "fileType": "png", + "count": 0, +- "width": 1280, +- "height": 800 + "width": 320, + "height": 200 -+ }, -+ "display": { -+ "isFullscreen": false, -+ "isBorderless": false, -+ "windowScale": 1.0 -+ }, -+ "camera": [ -+ { -+ "FOV": 30.0, -+ "focalDistance": 0.7, -+ "fstops": 6.5, -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 0, -+ "y": 0.1, -+ "z": -0.7 -+ }, -+ { -+ "type": "rotateX", -+ "degrees": 5 -+ }, -+ { -+ "type": "rotateZ", -+ "degrees": 0 -+ } -+ ] -+ }, -+ { -+ "FOV": 90.0, -+ "focalDistance": 0.2, -+ "fstops": 6.5, -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 0, -+ "y": 0.1, -+ "z": -0.2 -+ }, -+ { -+ "type": "rotateX", -+ "degrees": 5 -+ }, -+ { -+ "type": "rotateY", -+ "degrees": 5 -+ } -+ ] -+ } -+ ], -+ "scene": { -+ "ambientColor": { -+ "hdr": "HDRs/roof_garden_1k.hdr", -+ "offset": 0, -+ "down": { -+ "r": 1.0, -+ "g": 1.0, -+ "b": 1.0 -+ }, -+ "up": { -+ "r": 0.5, -+ "g": 0.7, -+ "b": 1.0 -+ } -+ }, -+ "primitives": [ -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": -0.25, -+ "y": 0.1001, -+ "z": 0.3 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 1.0, -+ "g": 0.0, -+ "b": 1.0 -+ }, -+ "bsdf": "metal", -+ "roughness": 0.05, -+ "radius": 0.1 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 0, -+ "y": 0.05, -+ "z": 0 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 0.8, -+ "g": 0.8, -+ "b": 0.8 -+ }, -+ "bsdf": "metal", -+ "roughness": 0.00, -+ "radius": 0.05 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 0.05, -+ "y": 0.05, -+ "z": 0.1 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 0.0, -+ "g": 0.8, -+ "b": 0.0 -+ }, -+ "bsdf": "metal", -+ "roughness": 0.00, -+ "radius": 0.05 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 0.15, -+ "y": 0.05, -+ "z": 0 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 1.0, -+ "g": 1.0, -+ "b": 1.0 -+ }, -+ "bsdf": "glass", -+ "IOR": 1.9, -+ "roughness": 0, -+ "radius": 0.05 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": -0.15, -+ "y": 0.025, -+ "z": 0.05 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 1.0, -+ "g": 0.1, -+ "b": 0.1 -+ }, -+ "bsdf": "glass", -+ "IOR": 1.9, -+ "roughness": 0, -+ "radius": 0.025 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": -0.120, -+ "y": 0.025, -+ "z": 0.1 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 0.1, -+ "g": 1.0, -+ "b": 0.1 -+ }, -+ "bsdf": "glass", -+ "IOR": 1.9, -+ "roughness": 0, -+ "radius": 0.025 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": -0.090, -+ "y": 0.025, -+ "z": 0.15 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 0.1, -+ "g": 0.1, -+ "b": 1.0 -+ }, -+ "bsdf": "glass", -+ "IOR": 1.9, -+ "roughness": 0, -+ "radius": 0.025 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": -0.03, -+ "y": 0.01, -+ "z": -0.25 -+ } -+ ] -+ } -+ ], -+ "radius": 0.01, -+ "color": { -+ "r": 1.0, -+ "g": 0.0, -+ "b": 0.0 -+ }, -+ "bsdf": "metal", -+ "roughness": 1.0 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 1070, -+ "y": 310, -+ "z": 820 -+ } -+ ] -+ } -+ ], -+ "radius": 2.5, -+ "color": { -+ "r": 0.0, -+ "g": 1.0, -+ "b": 0.0 -+ }, -+ "bsdf": "emissive", -+ "intensity": 10.0 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 1090, -+ "y": 310, -+ "z": 820 -+ } -+ ] -+ } -+ ], -+ "radius": 2.5, -+ "color": { -+ "r": 0.0, -+ "g": 0.0, -+ "b": 1.0 -+ }, -+ "bsdf": "emissive", -+ "intensity": 10.0 -+ }, -+ { -+ "type": "sphere", -+ "instances": [ -+ { -+ "transforms": [ -+ { -+ "type": "translate", -+ "x": 950, -+ "y": 420, -+ "z": 1500 -+ } -+ ] -+ } -+ ], -+ "color": { -+ "r": 1.0, -+ "g": 1.0, -+ "b": 1.0 -+ }, -+ "bsdf": "emissive", -+ "intensity": 10.0, -+ "radius": 10 -+ } -+ ], -+ "meshes": [ -+ { -+ "fileName": "shapes/gridplane.obj", -+ "instances": [ -+ { -+ "for": "Plane", -+ "material": [ -+ { -+ "type": "diffuse", -+ "color": "shapes/grid.png" -+ } -+ ], -+ "transforms": [ -+ { -+ "type": "scaleUniform", -+ "scale": 0.25 -+ }, -+ { -+ "type": "rotateX", -+ "degrees": 0 -+ } -+ ] -+ } -+ ] -+ }, -+ { -+ "fileName": "venusscaled.obj", -+ "instances": [ -+ { -+ "materials": { -+ "type": "plastic", -+ "roughness": 0, -+ "IOR": 1.45, -+ "color": [1.0, 0.2705, 0.0] -+ }, -+ "transforms": [ -+ { -+ "type": "scaleUniform", -+ "scale": 0.05 -+ }, -+ { -+ "type": "translate", -+ "X": 0.08 -+ }, -+ { -+ "type": "rotateY", -+ "degrees": 0 -+ } -+ ] -+ } -+ ] -+ } -+ ] -+ } -+} + }, + "display": { + "isFullscreen": false, -- 2.36.1
6090e79191b4f95475a007aa782503ef98ae5f28
2022-05-06 00:20:46
Jelle Raaijmakers
libsoftgpu: Use `u64` for `Device` statistics vars
false
Use `u64` for `Device` statistics vars
libsoftgpu
diff --git a/Userland/Libraries/LibSoftGPU/Device.cpp b/Userland/Libraries/LibSoftGPU/Device.cpp index 754520f91e94..cfb1bf5629bd 100644 --- a/Userland/Libraries/LibSoftGPU/Device.cpp +++ b/Userland/Libraries/LibSoftGPU/Device.cpp @@ -23,13 +23,13 @@ namespace SoftGPU { -static long long g_num_rasterized_triangles; -static long long g_num_pixels; -static long long g_num_pixels_shaded; -static long long g_num_pixels_blended; -static long long g_num_sampler_calls; -static long long g_num_stencil_writes; -static long long g_num_quads; +static u64 g_num_rasterized_triangles; +static u64 g_num_pixels; +static u64 g_num_pixels_shaded; +static u64 g_num_pixels_blended; +static u64 g_num_sampler_calls; +static u64 g_num_stencil_writes; +static u64 g_num_quads; using AK::SIMD::any; using AK::SIMD::exp;
daf421846c83ab1f748b33b52b1de1149d41c43c
2023-03-23 18:07:40
Srikavin Ramkumar
libweb: Return TypeError for [HTMLConstructor] IDL constructors
false
Return TypeError for [HTMLConstructor] IDL constructors
libweb
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp index 012e78fda20f..b102245dd22e 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp @@ -3011,6 +3011,15 @@ JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> @constructor_class@::constru generator.set("constructor.length", "0"); generator.append(R"~~~( return vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "@namespaced_name@"); +)~~~"); + } else if (interface.constructors.find_if([](auto const& x) { return x.extended_attributes.contains("HTMLConstructor"); }) != interface.constructors.end()) { + // https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor + VERIFY(interface.constructors.size() == 1); + + // FIXME: Properly implement HTMLConstructor extended attribute once custom elements are implemented + generator.set("constructor.length", "0"); + generator.append(R"~~~( + return vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "@namespaced_name@"); )~~~"); } else if (interface.constructors.size() == 1) { // Single constructor
194f85431f09763027e7c87d9113e5b16e76c0d5
2019-12-01 16:22:17
Brandon Scott
libvt: Fixed some debugging code that didn't compile
false
Fixed some debugging code that didn't compile
libvt
diff --git a/Libraries/LibVT/Terminal.cpp b/Libraries/LibVT/Terminal.cpp index 80b6c7ad7879..1de5206acddc 100644 --- a/Libraries/LibVT/Terminal.cpp +++ b/Libraries/LibVT/Terminal.cpp @@ -1,6 +1,8 @@ #include <AK/StringBuilder.h> #include <LibVT/Terminal.h> +//#define TERMINAL_DEBUG + namespace VT { Terminal::Terminal(TerminalClient& client) @@ -640,8 +642,8 @@ void Terminal::execute_escape_sequence(u8 final) dbgprintf("\n"); for (auto& line : m_lines) { dbgprintf("Terminal: Line: "); - for (int i = 0; i < line->length; i++) { - dbgprintf("%c", line->characters[i]); + for (int i = 0; i < line.m_length; i++) { + dbgprintf("%c", line.characters[i]); } dbgprintf("\n"); }
ebd510ef5e577d248024466407515edb96b834b6
2020-08-22 14:22:40
Nico Weber
libjs: Allow conversion from Symbol to String via explicit String() call
false
Allow conversion from Symbol to String via explicit String() call
libjs
diff --git a/Libraries/LibJS/Runtime/StringConstructor.cpp b/Libraries/LibJS/Runtime/StringConstructor.cpp index 7ab381e257d1..1edc7a141fa2 100644 --- a/Libraries/LibJS/Runtime/StringConstructor.cpp +++ b/Libraries/LibJS/Runtime/StringConstructor.cpp @@ -59,6 +59,8 @@ Value StringConstructor::call(Interpreter& interpreter) { if (!interpreter.argument_count()) return js_string(interpreter, ""); + if (interpreter.argument(0).is_symbol()) + return js_string(interpreter, interpreter.argument(0).as_symbol().to_string()); auto* string = interpreter.argument(0).to_primitive_string(interpreter); if (interpreter.exception()) return {}; diff --git a/Libraries/LibJS/Tests/builtins/Symbol/Symbol.prototype.toString.js b/Libraries/LibJS/Tests/builtins/Symbol/Symbol.prototype.toString.js index 734b7a219168..4a95fe2397bf 100644 --- a/Libraries/LibJS/Tests/builtins/Symbol/Symbol.prototype.toString.js +++ b/Libraries/LibJS/Tests/builtins/Symbol/Symbol.prototype.toString.js @@ -1,10 +1,12 @@ describe("correct behavior", () => { test("basic functionality", () => { const s1 = Symbol("baz"); - // const s2 = Symbol.for("qux"); + const s2 = Symbol.for("qux"); + // Explicit conversions to string are fine, but implicit toString via concatenation throws. expect(s1.toString()).toBe("Symbol(baz)"); - // expect(s2.toString()).toBe("Symbol(qux)"); + expect(String(s1)).toBe("Symbol(baz)"); + expect(s2.toString()).toBe("Symbol(qux)"); }); });
842b2a01e686698b259310d4ddead437ea57ea32
2023-09-12 23:33:12
Cubic Love
base: Add manpage for pkg
false
Add manpage for pkg
base
diff --git a/Base/usr/share/man/man1/pkg.md b/Base/usr/share/man/man1/pkg.md new file mode 100644 index 000000000000..3c335b9d693f --- /dev/null +++ b/Base/usr/share/man/man1/pkg.md @@ -0,0 +1,34 @@ +## Name + +pkg - Package Manager + +## Synopsis + +```**sh +$ pkg [-l] [-d] [-u] [-v] [-q package] +``` + +## Description + +This program can list installed packages and query for [available packages](https://github.com/SerenityOS/serenity/blob/master/Ports/AvailablePorts.md). The [Ports for SerenityOS website](https://ports.serenityos.net) has more detailed information about available packages. + +It does not currently support installing and uninstalling packages. To install third-party software use the [Ports system](https://github.com/SerenityOS/serenity/blob/master/Ports/README.md). + +## Options + +* `-l`, `--list-manual-ports`: Show all manually-installed ports +* `-d`, `--list-dependency-ports`: Show all dependencies' ports +* `-u`, `--update-ports-database`: Sync/Update ports database +* `-v`, `--verbose`: Verbose output +* `-q`, `--query-package`: Query the ports database for package name + +## Arguments + +* `package`: The name of the package you want to query + +## Example + +```sh +# Query the ports database for the serenity-theming package +$ pkg -q serenity-theming +```
a6324481e15579a13053c40cf0ddc1b6a872a0c5
2021-06-26 18:02:53
Luke
libjs: Add %TypedArray%.prototype.values
false
Add %TypedArray%.prototype.values
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp index 0ce14a7da5ea..887ea519142a 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp @@ -35,6 +35,7 @@ void TypedArrayPrototype::initialize(GlobalObject& object) define_native_function(vm.names.some, some, 1, attr); define_native_function(vm.names.join, join, 1, attr); define_native_function(vm.names.keys, keys, 0, attr); + define_native_function(vm.names.values, values, 0, attr); define_native_accessor(*vm.well_known_symbol_to_string_tag(), to_string_tag_getter, nullptr, Attribute::Configurable); @@ -249,6 +250,15 @@ JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::keys) return ArrayIterator::create(global_object, typed_array, Object::PropertyKind::Key); } +// 23.2.3.30 %TypedArray%.prototype.values ( ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.values +JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::values) +{ + auto typed_array = typed_array_from(vm, global_object); + if (!typed_array) + return {}; + return ArrayIterator::create(global_object, typed_array, Object::PropertyKind::Value); +} + // 23.2.3.1 get %TypedArray%.prototype.buffer, https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.buffer JS_DEFINE_NATIVE_GETTER(TypedArrayPrototype::buffer_getter) { diff --git a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h index fc9b1735fed4..06a802ff4fb6 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h @@ -33,6 +33,7 @@ class TypedArrayPrototype final : public Object { JS_DECLARE_NATIVE_FUNCTION(some); JS_DECLARE_NATIVE_FUNCTION(join); JS_DECLARE_NATIVE_FUNCTION(keys); + JS_DECLARE_NATIVE_FUNCTION(values); }; } diff --git a/Userland/Libraries/LibJS/Tests/builtins/TypedArray/TypedArray.prototype.values.js b/Userland/Libraries/LibJS/Tests/builtins/TypedArray/TypedArray.prototype.values.js new file mode 100644 index 000000000000..c25cc9402aed --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/TypedArray/TypedArray.prototype.values.js @@ -0,0 +1,46 @@ +const TYPED_ARRAYS = [ + Uint8Array, + Uint16Array, + Uint32Array, + Int8Array, + Int16Array, + Int32Array, + Float32Array, + Float64Array, +]; + +const BIGINT_TYPED_ARRAYS = [BigUint64Array, BigInt64Array]; + +test("length is 0", () => { + TYPED_ARRAYS.forEach(T => { + expect(T.prototype.values).toHaveLength(0); + }); + + BIGINT_TYPED_ARRAYS.forEach(T => { + expect(T.prototype.values).toHaveLength(0); + }); +}); + +test("basic functionality", () => { + TYPED_ARRAYS.forEach(T => { + const a = new T([30, 40, 50]); + const it = a.values(); + expect(it.next()).toEqual({ value: 30, done: false }); + expect(it.next()).toEqual({ value: 40, done: false }); + expect(it.next()).toEqual({ value: 50, done: false }); + expect(it.next()).toEqual({ value: undefined, done: true }); + expect(it.next()).toEqual({ value: undefined, done: true }); + expect(it.next()).toEqual({ value: undefined, done: true }); + }); + + BIGINT_TYPED_ARRAYS.forEach(T => { + const a = new T([30n, 40n, 50n]); + const it = a.values(); + expect(it.next()).toEqual({ value: 30n, done: false }); + expect(it.next()).toEqual({ value: 40n, done: false }); + expect(it.next()).toEqual({ value: 50n, done: false }); + expect(it.next()).toEqual({ value: undefined, done: true }); + expect(it.next()).toEqual({ value: undefined, done: true }); + expect(it.next()).toEqual({ value: undefined, done: true }); + }); +});
50b6ed2aa3c7452a2089589b1afdc65edeccccf4
2023-07-20 12:32:12
Sam Atkins
filemanager: Add "Image" tab to File Properties window
false
Add "Image" tab to File Properties window
filemanager
diff --git a/Userland/Applications/FileManager/CMakeLists.txt b/Userland/Applications/FileManager/CMakeLists.txt index baf6f811fc98..de1807bba833 100644 --- a/Userland/Applications/FileManager/CMakeLists.txt +++ b/Userland/Applications/FileManager/CMakeLists.txt @@ -9,6 +9,7 @@ compile_gml(FileManagerWindow.gml FileManagerWindowGML.h file_manager_window_gml compile_gml(FileOperationProgress.gml FileOperationProgressGML.h file_operation_progress_gml) compile_gml(PropertiesWindowAudioTab.gml PropertiesWindowAudioTabGML.h properties_window_audio_tab_gml) compile_gml(PropertiesWindowGeneralTab.gml PropertiesWindowGeneralTabGML.h properties_window_general_tab_gml) +compile_gml(PropertiesWindowImageTab.gml PropertiesWindowImageTabGML.h properties_window_image_tab_gml) set(SOURCES DesktopWidget.cpp @@ -24,6 +25,7 @@ set(GENERATED_SOURCES FileOperationProgressGML.h PropertiesWindowAudioTabGML.h PropertiesWindowGeneralTabGML.h + PropertiesWindowImageTabGML.h ) serenity_app(FileManager ICON app-file-manager) diff --git a/Userland/Applications/FileManager/PropertiesWindow.cpp b/Userland/Applications/FileManager/PropertiesWindow.cpp index 2c5bd97956fc..3b42801f1b56 100644 --- a/Userland/Applications/FileManager/PropertiesWindow.cpp +++ b/Userland/Applications/FileManager/PropertiesWindow.cpp @@ -12,6 +12,7 @@ #include <Applications/FileManager/DirectoryView.h> #include <Applications/FileManager/PropertiesWindowAudioTabGML.h> #include <Applications/FileManager/PropertiesWindowGeneralTabGML.h> +#include <Applications/FileManager/PropertiesWindowImageTabGML.h> #include <LibAudio/Loader.h> #include <LibCore/Directory.h> #include <LibCore/System.h> @@ -26,6 +27,8 @@ #include <LibGUI/MessageBox.h> #include <LibGUI/SeparatorWidget.h> #include <LibGUI/TabWidget.h> +#include <LibGfx/ICC/Profile.h> +#include <LibGfx/ICC/Tags.h> #include <grp.h> #include <pwd.h> #include <stdio.h> @@ -215,6 +218,9 @@ ErrorOr<void> PropertiesWindow::create_file_type_specific_tabs(GUI::TabWidget& t if (mime_type.starts_with("audio/"sv)) return create_audio_tab(tab_widget, move(mapped_file)); + if (mime_type.starts_with("image/"sv)) + return create_image_tab(tab_widget, move(mapped_file), mime_type); + return {}; } @@ -256,6 +262,64 @@ ErrorOr<void> PropertiesWindow::create_audio_tab(GUI::TabWidget& tab_widget, Non return {}; } +ErrorOr<void> PropertiesWindow::create_image_tab(GUI::TabWidget& tab_widget, NonnullRefPtr<Core::MappedFile> mapped_file, StringView mime_type) +{ + auto image_decoder = Gfx::ImageDecoder::try_create_for_raw_bytes(mapped_file->bytes(), mime_type); + if (!image_decoder) + return {}; + + auto tab = TRY(tab_widget.try_add_tab<GUI::Widget>("Image"_short_string)); + TRY(tab->load_from_gml(properties_window_image_tab_gml)); + + tab->find_descendant_of_type_named<GUI::Label>("image_type")->set_text(TRY(String::from_utf8(mime_type))); + tab->find_descendant_of_type_named<GUI::Label>("image_size")->set_text(TRY(String::formatted("{} x {}", image_decoder->width(), image_decoder->height()))); + + String animation_text; + if (image_decoder->is_animated()) { + auto loops = image_decoder->loop_count(); + auto frames = image_decoder->frame_count(); + StringBuilder builder; + if (loops == 0) { + TRY(builder.try_append("Loop indefinitely"sv)); + } else if (loops == 1) { + TRY(builder.try_append("Once"sv)); + } else { + TRY(builder.try_appendff("Loop {} times"sv, loops)); + } + TRY(builder.try_appendff(" ({} frames)"sv, frames)); + + animation_text = TRY(builder.to_string()); + } else { + animation_text = "None"_short_string; + } + tab->find_descendant_of_type_named<GUI::Label>("image_animation")->set_text(move(animation_text)); + + auto hide_icc_group = [&tab](String profile_text) { + tab->find_descendant_of_type_named<GUI::Label>("image_has_icc_profile")->set_text(profile_text); + tab->find_descendant_of_type_named<GUI::Widget>("image_icc_group")->set_visible(false); + }; + + if (auto embedded_icc_bytes = TRY(image_decoder->icc_data()); embedded_icc_bytes.has_value()) { + auto icc_profile_or_error = Gfx::ICC::Profile::try_load_from_externally_owned_memory(embedded_icc_bytes.value()); + if (icc_profile_or_error.is_error()) { + hide_icc_group(TRY("Present but invalid"_string)); + } else { + auto icc_profile = icc_profile_or_error.release_value(); + + tab->find_descendant_of_type_named<GUI::Label>("image_has_icc_profile")->set_text(TRY("See below"_string)); + tab->find_descendant_of_type_named<GUI::Label>("image_icc_profile")->set_text(icc_profile->tag_string_data(Gfx::ICC::profileDescriptionTag).value_or({})); + tab->find_descendant_of_type_named<GUI::Label>("image_icc_copyright")->set_text(icc_profile->tag_string_data(Gfx::ICC::copyrightTag).value_or({})); + tab->find_descendant_of_type_named<GUI::Label>("image_icc_color_space")->set_text(TRY(String::from_utf8(data_color_space_name(icc_profile->data_color_space())))); + tab->find_descendant_of_type_named<GUI::Label>("image_icc_device_class")->set_text(TRY(String::from_utf8((device_class_name(icc_profile->device_class()))))); + } + + } else { + hide_icc_group("None"_short_string); + } + + return {}; +} + void PropertiesWindow::update() { m_icon->set_bitmap(GUI::FileIconProvider::icon_for_path(make_full_path(m_name), m_mode).bitmap_for_size(32)); diff --git a/Userland/Applications/FileManager/PropertiesWindow.h b/Userland/Applications/FileManager/PropertiesWindow.h index 92aad1b46096..768236359aab 100644 --- a/Userland/Applications/FileManager/PropertiesWindow.h +++ b/Userland/Applications/FileManager/PropertiesWindow.h @@ -31,6 +31,7 @@ class PropertiesWindow final : public GUI::Window { ErrorOr<void> create_general_tab(GUI::TabWidget&, bool disable_rename); ErrorOr<void> create_file_type_specific_tabs(GUI::TabWidget&); ErrorOr<void> create_audio_tab(GUI::TabWidget&, NonnullRefPtr<Core::MappedFile>); + ErrorOr<void> create_image_tab(GUI::TabWidget&, NonnullRefPtr<Core::MappedFile>, StringView mime_type); struct PermissionMasks { mode_t read; diff --git a/Userland/Applications/FileManager/PropertiesWindowImageTab.gml b/Userland/Applications/FileManager/PropertiesWindowImageTab.gml new file mode 100644 index 000000000000..25ccb5cf7cd1 --- /dev/null +++ b/Userland/Applications/FileManager/PropertiesWindowImageTab.gml @@ -0,0 +1,171 @@ +@GUI::Widget { + layout: @GUI::VerticalBoxLayout { + margins: [8] + spacing: 12 + } + + @GUI::GroupBox { + title: "Image" + preferred_height: "shrink" + layout: @GUI::VerticalBoxLayout { + margins: [12, 8, 0] + spacing: 2 + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Type:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_type" + text: "JPEG" + text_alignment: "TopLeft" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Size:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_size" + text: "1920 x 1080" + text_alignment: "TopLeft" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Animation:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_animation" + text: "Loop indefinitely (12 frames)" + text_alignment: "TopLeft" + text_wrapping: "DontWrap" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "ICC profile:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_has_icc_profile" + text: "See below" + text_alignment: "TopLeft" + } + } + } + + @GUI::GroupBox { + name: "image_icc_group" + title: "ICC Profile" + preferred_height: "shrink" + layout: @GUI::VerticalBoxLayout { + margins: [12, 8, 0] + spacing: 2 + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Profile:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_icc_profile" + text: "e-sRGB" + text_alignment: "TopLeft" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Copyright:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_icc_copyright" + text: "(c) 1999 Adobe Systems Inc." + text_alignment: "TopLeft" + text_wrapping: "DontWrap" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Color space:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_icc_color_space" + text: "RGB" + text_alignment: "TopLeft" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + spacing: 12 + } + + @GUI::Label { + text: "Device class:" + text_alignment: "TopLeft" + fixed_width: 80 + } + + @GUI::Label { + name: "image_icc_device_class" + text: "DisplayDevice" + text_alignment: "TopLeft" + } + } + } +}
0d73da0328feeee063054b9ea532e1760854c48b
2022-01-16 15:37:02
Timothy Flynn
libjs: Implement Date.prototype.setUTCFullYear
false
Implement Date.prototype.setUTCFullYear
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp b/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp index 2f64d1694630..f9f8961c6e0c 100644 --- a/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp @@ -72,8 +72,8 @@ void DatePrototype::initialize(GlobalObject& global_object) define_native_function(vm.names.setMonth, set_month, 2, attr); define_native_function(vm.names.setSeconds, set_seconds, 2, attr); define_native_function(vm.names.setTime, set_time, 1, attr); - define_native_function(vm.names.setUTCDate, set_date, 1, attr); // FIXME: This is a hack, Serenity doesn't currently support timezones other than UTC. - define_native_function(vm.names.setUTCFullYear, set_full_year, 3, attr); // FIXME: see above + define_native_function(vm.names.setUTCDate, set_date, 1, attr); // FIXME: This is a hack, Serenity doesn't currently support timezones other than UTC. + define_native_function(vm.names.setUTCFullYear, set_utc_full_year, 3, attr); define_native_function(vm.names.setUTCHours, set_utc_hours, 4, attr); define_native_function(vm.names.setUTCMilliseconds, set_utc_milliseconds, 1, attr); define_native_function(vm.names.setUTCMinutes, set_utc_minutes, 3, attr); @@ -619,6 +619,41 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_time) return time; } +// 21.4.4.29 Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] ), https://tc39.es/ecma262/#sec-date.prototype.setutcfullyear +JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_full_year) +{ + // 1. Let t be ? thisTimeValue(this value). + auto this_time = TRY(this_time_value(global_object, vm.this_value(global_object))); + + // 2. If t is NaN, set t to +0𝔽. + double time = 0; + if (!this_time.is_nan()) + time = this_time.as_double(); + + // 3. Let y be ? ToNumber(year). + auto year = TRY(vm.argument(0).to_number(global_object)); + + // 4. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month). + auto month = TRY(argument_or_value(global_object, 1, month_from_time(time))); + + // 5. If date is not present, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date). + auto date = TRY(argument_or_value(global_object, 2, date_from_time(time))); + + // 6. Let newDate be MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)). + auto day = make_day(global_object, year, month, date); + auto new_date = make_date(day, Value(time_within_day(time))); + + // 7. Let v be TimeClip(newDate). + new_date = time_clip(global_object, new_date); + + // 8. Set the [[DateValue]] internal slot of this Date object to v. + auto* this_object = MUST(typed_this_object(global_object)); + this_object->set_date_value(new_date.as_double()); + + // 9. Return v. + return new_date; +} + // 21.4.4.30 Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] ), https://tc39.es/ecma262/#sec-date.prototype.setutchours JS_DEFINE_NATIVE_FUNCTION(DatePrototype::set_utc_hours) { diff --git a/Userland/Libraries/LibJS/Runtime/DatePrototype.h b/Userland/Libraries/LibJS/Runtime/DatePrototype.h index 5005ef457081..87df1305fb0b 100644 --- a/Userland/Libraries/LibJS/Runtime/DatePrototype.h +++ b/Userland/Libraries/LibJS/Runtime/DatePrototype.h @@ -46,6 +46,7 @@ class DatePrototype final : public PrototypeObject<DatePrototype, Date> { JS_DECLARE_NATIVE_FUNCTION(set_month); JS_DECLARE_NATIVE_FUNCTION(set_seconds); JS_DECLARE_NATIVE_FUNCTION(set_time); + JS_DECLARE_NATIVE_FUNCTION(set_utc_full_year); JS_DECLARE_NATIVE_FUNCTION(set_utc_hours); JS_DECLARE_NATIVE_FUNCTION(set_utc_milliseconds); JS_DECLARE_NATIVE_FUNCTION(set_utc_minutes); diff --git a/Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.setUTCFullYear.js b/Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.setUTCFullYear.js new file mode 100644 index 000000000000..7c6dd7978749 --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.setUTCFullYear.js @@ -0,0 +1,55 @@ +describe("errors", () => { + test("called on non-Date object", () => { + expect(() => { + Date.prototype.setUTCFullYear(); + }).toThrowWithMessage(TypeError, "Not an object of type Date"); + }); + + test("called with non-numeric parameters", () => { + expect(() => { + new Date().setUTCFullYear(Symbol.hasInstance); + }).toThrowWithMessage(TypeError, "Cannot convert symbol to number"); + + expect(() => { + new Date().setUTCFullYear(1989, Symbol.hasInstance); + }).toThrowWithMessage(TypeError, "Cannot convert symbol to number"); + + expect(() => { + new Date().setUTCFullYear(1989, 0, Symbol.hasInstance); + }).toThrowWithMessage(TypeError, "Cannot convert symbol to number"); + }); +}); + +describe("correct behavior", () => { + const d = new Date(2000, 2, 1); + + test("basic functionality", () => { + d.setUTCFullYear(1989); + expect(d.getUTCFullYear()).toBe(1989); + + d.setUTCFullYear(1990, 1); + expect(d.getUTCFullYear()).toBe(1990); + expect(d.getUTCMonth()).toBe(1); + + d.setUTCFullYear(1991, 2, 15); + expect(d.getUTCFullYear()).toBe(1991); + expect(d.getUTCMonth()).toBe(2); + expect(d.getUTCDate()).toBe(15); + + d.setUTCFullYear(""); + expect(d.getUTCFullYear()).toBe(0); + + d.setUTCFullYear("a"); + expect(d.getUTCFullYear()).toBe(NaN); + }); + + test("NaN", () => { + d.setUTCFullYear(NaN); + expect(d.getUTCFullYear()).toBeNaN(); + }); + + test("time clip", () => { + d.setUTCFullYear(8.65e15); + expect(d.getUTCFullYear()).toBeNaN(); + }); +});