Skip to content

Truly independent web browser

LibIPC+Everywhere: Generate IPC implementations in separate source files

Timothy Flynna157fff9d802
diff --git a/Libraries/LibIPC/ConnectionFromClient.h b/Libraries/LibIPC/ConnectionFromClient.h
index f0d4850d4cb..10f8875211b 100644
--- a/Libraries/LibIPC/ConnectionFromClient.h
+++ b/Libraries/LibIPC/ConnectionFromClient.h
@@ -21,14 +21,14 @@ NonnullRefPtr<T> new_client_connection(Args&&... args)
template<typename ClientEndpoint, typename ServerEndpoint>
class ConnectionFromClient : public Connection<ServerEndpoint, ClientEndpoint>
, public ServerEndpoint::Stub
- , public ClientEndpoint::template Proxy<ServerEndpoint> {
+ , public ClientEndpoint::Proxy {
public:
using ServerStub = typename ServerEndpoint::Stub;
- using IPCProxy = typename ClientEndpoint::template Proxy<ServerEndpoint>;
+ using IPCProxy = typename ClientEndpoint::Proxy;
ConnectionFromClient(ServerStub& stub, NonnullOwnPtr<Transport> transport, int client_id)
: IPC::Connection<ServerEndpoint, ClientEndpoint>(stub, move(transport))
- , ClientEndpoint::template Proxy<ServerEndpoint>(*this, {})
+ , ClientEndpoint::Proxy(*this, {})
, m_client_id(client_id)
{
}
diff --git a/Libraries/LibIPC/ConnectionToServer.h b/Libraries/LibIPC/ConnectionToServer.h
index f7955d3e5e2..065aa1a7285 100644
--- a/Libraries/LibIPC/ConnectionToServer.h
+++ b/Libraries/LibIPC/ConnectionToServer.h
@@ -10,17 +10,16 @@
namespace IPC {
-template<typename ClientEndpoint, typename ServerEndpoint>
+template<typename ClientEndpoint, typename ServerEndpoint, typename LocalStub = typename ClientEndpoint::Stub>
class ConnectionToServer : public IPC::Connection<ClientEndpoint, ServerEndpoint>
- , public ClientEndpoint::Stub
- , public ServerEndpoint::template Proxy<ClientEndpoint> {
+ , public LocalStub
+ , public ServerEndpoint::Proxy {
public:
- using ClientStub = typename ClientEndpoint::Stub;
- using IPCProxy = typename ServerEndpoint::template Proxy<ClientEndpoint>;
+ using IPCProxy = typename ServerEndpoint::Proxy;
- ConnectionToServer(ClientStub& local_endpoint, NonnullOwnPtr<Transport> transport)
+ ConnectionToServer(LocalStub& local_endpoint, NonnullOwnPtr<Transport> transport)
: Connection<ClientEndpoint, ServerEndpoint>(local_endpoint, move(transport))
- , ServerEndpoint::template Proxy<ClientEndpoint>(*this, {})
+ , ServerEndpoint::Proxy(*this, {})
{
}
diff --git a/Libraries/LibIPC/SenderClaim.h b/Libraries/LibIPC/SenderClaim.h
index f4427e7aac1..b8c7fcddbad 100644
--- a/Libraries/LibIPC/SenderClaim.h
+++ b/Libraries/LibIPC/SenderClaim.h
@@ -60,23 +60,27 @@ bool verify_message_argument(Stub& stub, T const& argument)
return verify_sender_claim(stub, argument);
}
-// The value a routed synchronous message with one output gets when there is no object to send it to.
-// A message whose output cannot be empty is marked [NotRouted] so that it never reaches this.
+// The value a bound synchronous send gets when its object no longer has a connection. If the reply
+// cannot be empty, there is no value we can invent: like a failed mandatory synchronous send, it fails.
template<typename Value>
Value empty_value()
{
- static_assert(requires { Value {}; }, "A routed synchronous message needs a reply that can be value-initialized");
- return Value {};
+ if constexpr (requires { Value {}; })
+ return Value {};
+ else
+ VERIFY_NOT_REACHED();
}
-// The reply a routed synchronous message gets when there is no object to route it to: every output
-// value-initialized. A message whose outputs cannot all be empty is marked [NotRouted] so that it never
-// reaches this.
+// The reply a bound synchronous send gets when its object no longer has a connection: every output
+// value-initialized. If a reply cannot be empty, there is no value we can invent, so it fails like a
+// mandatory synchronous send on a closed connection.
template<typename Response, typename... Outputs>
Response empty_response()
{
- static_assert(requires { Response { Outputs {}... }; }, "A routed synchronous message needs a reply that can be value-initialized");
- return Response { Outputs {}... };
+ if constexpr (requires { Response { Outputs {}... }; })
+ return Response { Outputs {}... };
+ else
+ VERIFY_NOT_REACHED();
}
// The reply a refused synchronous message is answered with: every output value-initialized, so the
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index 5537de16c57..984e33c882d 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -136,7 +136,7 @@ endif()
ladybird_lib(LibWebCommon webcommon EXPLICIT_SYMBOL_EXPORT)
# NB: The enumerations of LibWeb's IDL modules are generated into LibWebCommon along with LibWeb's bindings.
add_dependencies(LibWebCommon generate_bindings)
-target_link_libraries(LibWebCommon PRIVATE LibCore LibCrypto LibFileSystem LibGfx LibHTTP LibIPC LibURL)
+target_link_libraries(LibWebCommon PRIVATE LibCore LibCrypto LibFileSystem LibGfx LibHTTP LibIPC LibRequests LibURL)
if (ENABLE_INSTALL_HEADERS)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/CSS/PropertyList.h" "${CMAKE_CURRENT_BINARY_DIR}/CSS/PseudoElement.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/LibWebCommon/CSS")
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 06a62975e29..6232d887646 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -107,7 +107,7 @@ static constexpr auto close_server_exit_timeout_ms = 5000;
static constexpr auto detached_page_forced_exit_timeout_ms = detached_page_close_timeout_ms + close_server_exit_timeout_ms;
WebContentClient::WebContentClient(NonnullOwnPtr<IPC::Transport> transport, IsPrivate is_private, Web::PageId initial_page_id, Web::HTML::CrossProcessId root_navigable_id)
- : WebContentClientPageRoutingStub(*this, move(transport))
+ : IPC::ConnectionToServer<WebContentClientEndpoint, WebContentServerEndpoint, WebContentClientPageRoutingStub>(*this, move(transport))
, m_is_private(is_private)
, m_session(Application::existing_session(is_private))
, m_unassigned_initial_page_id(initial_page_id)
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index 573167f6f07..0c2867f79ec 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -67,7 +67,7 @@ namespace WebView {
class ViewImplementation;
class WEBVIEW_API WebContentClient final
- : public WebContentClientPageRoutingStub<IPC::ConnectionToServer<WebContentClientEndpoint, WebContentServerEndpoint>>
+ : public IPC::ConnectionToServer<WebContentClientEndpoint, WebContentServerEndpoint, WebContentClientPageRoutingStub>
, public WebContentClientEndpoint {
C_OBJECT_ABSTRACT(WebContentClient);
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 49cad869cdb..13f3a33e970 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -154,6 +154,11 @@ WebContentPage::WebContentPage(WebContentClient& client, Web::PageId id, Canonic
WebContentPage::~WebContentPage() = default;
+WebContentServerProxy* WebContentPage::routed_proxy() const
+{
+ return routed_connection();
+}
+
WebContentClient& WebContentPage::client() const
{
VERIFY(m_client);
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index d73f994a30b..be8e36f6331 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -64,7 +64,7 @@ class WEBVIEW_API WebContentPage final
: public RefCounted<WebContentPage>
, public WebContentClientPageStub
, public WebContentTestClientPageStub
- , public WebContentServerPageProxy<WebContentPage> {
+ , public WebContentServerPageProxy {
AK_MAKE_NONCOPYABLE(WebContentPage);
AK_MAKE_NONMOVABLE(WebContentPage);
AK_ALLOC_WITH_KMALLOC;
@@ -79,7 +79,8 @@ public:
WebContentClient& client() const;
Web::PageId id() const { return m_id; }
WebContentClient* routed_connection() const { return m_is_open ? m_client.ptr() : nullptr; }
- Web::PageId routed_page_id() const { return m_id; }
+ virtual WebContentServerProxy* routed_proxy() const override;
+ virtual Web::PageId routed_page_id() const override { return m_id; }
CanonicalTraversable& traversable() const;
ViewImplementation& view() const;
diff --git a/Libraries/LibWebView/WebContentTestClient.cpp b/Libraries/LibWebView/WebContentTestClient.cpp
index 93b0644a428..e4abf3a64c3 100644
--- a/Libraries/LibWebView/WebContentTestClient.cpp
+++ b/Libraries/LibWebView/WebContentTestClient.cpp
@@ -14,7 +14,7 @@
namespace WebView {
WebContentTestClient::WebContentTestClient(NonnullOwnPtr<IPC::Transport> transport, WebContentClient& client)
- : WebContentTestClientPageRoutingStub(*this, move(transport))
+ : IPC::ConnectionToServer<WebContentTestClientEndpoint, WebContentTestServerEndpoint, WebContentTestClientPageRoutingStub>(*this, move(transport))
, m_client(client)
{
}
diff --git a/Libraries/LibWebView/WebContentTestClient.h b/Libraries/LibWebView/WebContentTestClient.h
index f1e906bc085..2c3eed90719 100644
--- a/Libraries/LibWebView/WebContentTestClient.h
+++ b/Libraries/LibWebView/WebContentTestClient.h
@@ -17,7 +17,7 @@ namespace WebView {
// The test-only half of the WebContent protocol. The UI process connects this second transport only when it runs
// tests, so a WebContent process serving a real browsing session cannot send these messages at all.
class WEBVIEW_API WebContentTestClient final
- : public WebContentTestClientPageRoutingStub<IPC::ConnectionToServer<WebContentTestClientEndpoint, WebContentTestServerEndpoint>>
+ : public IPC::ConnectionToServer<WebContentTestClientEndpoint, WebContentTestServerEndpoint, WebContentTestClientPageRoutingStub>
, public WebContentTestClientEndpoint {
C_OBJECT_ABSTRACT(WebContentTestClient);
diff --git a/Meta/CMake/code_generators.cmake b/Meta/CMake/code_generators.cmake
index 0721e1bfd18..e6a2ce6973c 100644
--- a/Meta/CMake/code_generators.cmake
+++ b/Meta/CMake/code_generators.cmake
@@ -26,22 +26,36 @@ function(compile_ipc source output)
if (NOT IS_ABSOLUTE ${source})
set(source ${CMAKE_CURRENT_SOURCE_DIR}/${source})
endif()
+ if (NOT IS_ABSOLUTE ${output})
+ set(output ${CMAKE_CURRENT_BINARY_DIR}/${output})
+ endif()
+ cmake_path(REPLACE_EXTENSION output LAST_ONLY .cpp OUTPUT_VARIABLE implementation)
+ get_filename_component(output_name ${output} NAME)
+ cmake_path(RELATIVE_PATH CMAKE_CURRENT_SOURCE_DIR BASE_DIRECTORY ${LADYBIRD_SOURCE_DIR} OUTPUT_VARIABLE current_source_dir_relative)
+ set(library_arguments)
+ if (current_source_dir_relative MATCHES "^Libraries/(Lib[^/]+)(/|$)")
+ list(APPEND library_arguments --library ${CMAKE_MATCH_1})
+ set(GENERATED_IPC TRUE PARENT_SCOPE)
+ endif()
find_package(Python3 REQUIRED COMPONENTS Interpreter)
add_custom_command(
- OUTPUT ${output}
- COMMAND "${Python3_EXECUTABLE}" "${LADYBIRD_SOURCE_DIR}/Meta/Generators/generate_ipc_definitions.py" --input ${source} --output ${output}.tmp
+ OUTPUT ${output} ${implementation}
+ COMMAND "${Python3_EXECUTABLE}" "${LADYBIRD_SOURCE_DIR}/Meta/Generators/generate_ipc_definitions.py"
+ --input ${source} --output ${output}.tmp --implementation ${implementation}.tmp
+ --header-name ${output_name} ${library_arguments}
COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${output}.tmp ${output}
- COMMAND "${CMAKE_COMMAND}" -E remove ${output}.tmp
+ COMMAND "${CMAKE_COMMAND}" -E copy_if_different ${implementation}.tmp ${implementation}
+ COMMAND "${CMAKE_COMMAND}" -E remove ${output}.tmp ${implementation}.tmp
VERBATIM
DEPENDS "${LADYBIRD_SOURCE_DIR}/Meta/Generators/generate_ipc_definitions.py"
MAIN_DEPENDENCY ${source}
)
- get_filename_component(output_name ${output} NAME)
- add_custom_target(generate_${output_name} DEPENDS ${output})
+ add_custom_target(generate_${output_name} DEPENDS ${output} ${implementation})
add_dependencies(ladybird_codegen_accumulator generate_${output_name})
+ list(APPEND SOURCES ${implementation})
+ set(SOURCES ${SOURCES} PARENT_SCOPE)
- cmake_path(RELATIVE_PATH CMAKE_CURRENT_SOURCE_DIR BASE_DIRECTORY ${LADYBIRD_SOURCE_DIR} OUTPUT_VARIABLE current_source_dir_relative)
if (ENABLE_INSTALL_HEADERS)
- install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${output} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${current_source_dir_relative}" OPTIONAL)
+ install(FILES ${output} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${current_source_dir_relative}" OPTIONAL)
endif()
endfunction()
diff --git a/Meta/CMake/targets.cmake b/Meta/CMake/targets.cmake
index 732e2c61111..7f9d50b13f9 100644
--- a/Meta/CMake/targets.cmake
+++ b/Meta/CMake/targets.cmake
@@ -168,6 +168,9 @@ function(ladybird_lib name fs_name)
if (LADYBIRD_LIB_EXPLICIT_SYMBOL_EXPORT)
ladybird_generate_export_header(${name} ${fs_name})
endif()
+ if (ENABLE_INSTALL_HEADERS AND GENERATED_IPC AND LADYBIRD_LIB_EXPLICIT_SYMBOL_EXPORT)
+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/Export.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${name}")
+ endif()
endfunction()
function(ladybird_test test_src sub_dir)
diff --git a/Meta/Generators/generate_ipc_definitions.py b/Meta/Generators/generate_ipc_definitions.py
index 17c529c2419..85efb5365c0 100644
--- a/Meta/Generators/generate_ipc_definitions.py
+++ b/Meta/Generators/generate_ipc_definitions.py
@@ -7,7 +7,10 @@
import argparse
+import io
+import re
import sys
+import textwrap
from dataclasses import dataclass
from dataclasses import field
@@ -93,6 +96,7 @@ class Endpoint:
# The argument a message can be routed by: messages whose first parameter is this one are about the
# object it names, so a receiver can hand them to that object and a sender can bind a proxy to it.
route: Optional[Parameter] = None
+ export_macro: str = ""
def binds(self, message: Message) -> bool:
if self.route is None or not message.inputs:
@@ -364,17 +368,34 @@ def parse(contents: str) -> List[Endpoint]:
return endpoints
-def constructor_for_message(name: str, parameters: List[Parameter]) -> str:
- if not parameters:
- return f"{name}() = default;"
+def class_declaration(endpoint: Endpoint, name: str) -> str:
+ export = f"{endpoint.export_macro} " if endpoint.export_macro else ""
+ return f"class {export}{name}"
- params = ", ".join(f"{p.type} {p.name}" for p in parameters)
- initializers = "\n , ".join(f"m_{p.name}(move({p.name}))" for p in parameters)
- return f"""{name}({params})
- : {initializers}
- {{
- }}"""
+def write_method(
+ header: TextIO,
+ implementation: TextIO,
+ class_name: str,
+ signature: str,
+ body: str = "",
+ initializers: str = "",
+) -> None:
+ """Write a generated member's declaration and matching out-of-line definition."""
+ header.write(f"\n {signature};\n")
+ definition = signature.removeprefix("virtual ").removeprefix("static ").removeprefix("NEVER_INLINE ")
+ definition = definition.removesuffix(" override")
+ result_and_name, parameters = definition.split("(", 1)
+ if " " in result_and_name:
+ result, name = result_and_name.rsplit(" ", 1)
+ result += " "
+ else:
+ result, name = "", result_and_name
+ implementation.write(f"\n{result}{class_name}::{name}({parameters}\n{initializers}{{\n")
+ implementation.write(textwrap.indent(textwrap.dedent(body).strip("\n"), " "))
+ if body.strip():
+ implementation.write("\n")
+ implementation.write("}\n")
def write_message_ids_enum(out: TextIO, endpoint: Endpoint) -> None:
@@ -394,28 +415,28 @@ def write_message_ids_enum(out: TextIO, endpoint: Endpoint) -> None:
def write_message_class(
out: TextIO,
+ implementation: TextIO,
endpoint: Endpoint,
name: str,
parameters: List[Parameter],
response_type: str = "",
) -> None:
pascal_name = pascal_case(name)
-
- out.write(f"""
-class {pascal_name} final : public IPC::Message {{
-public:""")
-
+ qualified_name = pascal_name
+ out.write(f"\n{class_declaration(endpoint, pascal_name)} final : public IPC::Message {{\npublic:")
if response_type:
out.write(f"\n typedef class {response_type} ResponseType;\n")
-
+ if parameters:
+ params = ", ".join(f"{p.type} {p.name}" for p in parameters)
+ initializers = " : " + "\n , ".join(f"m_{p.name}(move({p.name}))" for p in parameters) + "\n"
+ write_method(out, implementation, qualified_name, f"{pascal_name}({params})", initializers=initializers)
+ else:
+ out.write(f"\n {pascal_name}() = default;\n")
out.write(f"""
- {constructor_for_message(pascal_name, parameters)}
-
{pascal_name}({pascal_name} const&) = default;
{pascal_name}({pascal_name}&&) = default;
{pascal_name}& operator=({pascal_name} const&) = default;
""")
-
if len(parameters) == 1:
out.write(f"""
template<typename WrappedReturnType>
@@ -425,66 +446,79 @@ public:""")
{{
}}
""")
-
- out.write(f"""
- static constexpr u32 ENDPOINT_MAGIC = {endpoint.magic};
-
- virtual u32 endpoint_magic() const override {{ return ENDPOINT_MAGIC; }}
- virtual i32 message_id() const override {{ return (int)MessageID::{pascal_name}; }}
- static i32 static_message_id() {{ return (int)MessageID::{pascal_name}; }}
- virtual StringView message_name() const override {{ return "{endpoint.name}::{pascal_name}"sv; }}
-
- static ErrorOr<NonnullOwnPtr<{pascal_name}>> decode(FixedMemoryStream& stream, Queue<IPC::Attachment>& attachments)
- {{
- IPC::Decoder decoder {{ stream, attachments }};""")
-
+ out.write(f"\n static constexpr u32 ENDPOINT_MAGIC = {endpoint.magic};\n")
+ write_method(
+ out, implementation, qualified_name, "virtual u32 endpoint_magic() const override", "return ENDPOINT_MAGIC;"
+ )
+ write_method(
+ out,
+ implementation,
+ qualified_name,
+ "virtual i32 message_id() const override",
+ f"return (int)MessageID::{pascal_name};",
+ )
+ out.write(f" static i32 static_message_id() {{ return (int)MessageID::{pascal_name}; }}\n")
+ write_method(
+ out,
+ implementation,
+ qualified_name,
+ "virtual StringView message_name() const override",
+ f'return "{endpoint.name}::{pascal_name}"sv;',
+ )
+ body = io.StringIO()
+ body.write("IPC::Decoder decoder { stream, attachments };\n")
for parameter in parameters:
- out.write(f"\n auto {parameter.name} = TRY((decoder.decode<{parameter.type}>()));")
-
+ body.write(f"auto {parameter.name} = TRY((decoder.decode<{parameter.type}>()));\n")
if "UTF8" in parameter.attributes:
- out.write(f"""
- if (!Utf8View({parameter.name}).validate())
- return Error::from_string_literal("Decoded {parameter.name} is invalid UTF-8");
+ body.write(f"""if (!Utf8View({parameter.name}).validate())
+ return Error::from_string_literal("Decoded {parameter.name} is invalid UTF-8");
""")
-
constructor_args = ", ".join(f"move({p.name})" for p in parameters)
- out.write(f"""
- return make<{pascal_name}>({constructor_args});
- }}
-""")
-
+ body.write(f"return make<{pascal_name}>({constructor_args});\n")
+ write_method(
+ out,
+ implementation,
+ qualified_name,
+ f"static ErrorOr<NonnullOwnPtr<{pascal_name}>> decode(AK::FixedMemoryStream& stream, Queue<IPC::Attachment>& attachments)",
+ body.getvalue(),
+ )
encode_params = ", ".join(f"{make_argument_type(p.type_for_encoding)} {p.name}" for p in parameters)
- out.write(f"""
- static ErrorOr<IPC::MessageBuffer> static_encode({encode_params})
- {{
- IPC::MessageBuffer buffer;
- IPC::Encoder stream(buffer);
- TRY(stream.encode(ENDPOINT_MAGIC));
- TRY(stream.encode((int)MessageID::{pascal_name}));""")
-
+ body = io.StringIO()
+ body.write(f"""IPC::MessageBuffer buffer;
+IPC::Encoder stream(buffer);
+TRY(stream.encode(ENDPOINT_MAGIC));
+TRY(stream.encode((int)MessageID::{pascal_name}));
+""")
for parameter in parameters:
- out.write(f"\n TRY(stream.encode({parameter.name}));")
-
+ body.write(f"TRY(stream.encode({parameter.name}));\n")
+ body.write("return buffer;\n")
+ write_method(
+ out,
+ implementation,
+ qualified_name,
+ f"static ErrorOr<IPC::MessageBuffer> static_encode({encode_params})",
+ body.getvalue(),
+ )
member_args = ", ".join(f"m_{p.name}" for p in parameters)
- out.write(f"""
- return buffer;
- }}
-
- virtual ErrorOr<IPC::MessageBuffer> encode() const override
- {{
- return static_encode({member_args});
- }}
-""")
-
+ write_method(
+ out,
+ implementation,
+ qualified_name,
+ "virtual ErrorOr<IPC::MessageBuffer> encode() const override",
+ f"return static_encode({member_args});",
+ )
for parameter in parameters:
if is_primitive_or_simple_type(parameter.type):
out.write(f"\n {parameter.type} {parameter.name}() const {{ return m_{parameter.name}; }}\n")
else:
- out.write(f"""
- {parameter.type} const& {parameter.name}() const {{ return m_{parameter.name}; }}
- {parameter.type} take_{parameter.name}() {{ return move(m_{parameter.name}); }}
-""")
-
+ out.write(f"\n {parameter.type} const& {parameter.name}() const {{ return m_{parameter.name}; }}\n")
+ write_method(
+ out,
+ implementation,
+ qualified_name,
+ f"{parameter.type} take_{parameter.name}()",
+ f"return move(m_{parameter.name});",
+ )
out.write("\nprivate:")
for parameter in parameters:
out.write(f"\n {parameter.type} m_{parameter.name};")
@@ -493,6 +527,7 @@ public:""")
def write_proxy_method(
out: TextIO,
+ implementation: TextIO,
endpoint: Endpoint,
message: Message,
parameters: List[Parameter],
@@ -534,15 +569,16 @@ def write_proxy_method(
signature_params.append(f"{type} {parameter.name}")
- out.write(f"\n {return_type} {method_name}({', '.join(signature_params)})\n {{")
+ signature = f"{return_type} {method_name}({', '.join(signature_params)})"
+ body = io.StringIO()
if not is_synchronous and not is_try and not is_unicode_string_overload:
for parameter in parameters:
if parameter.type == "String" and parameter.type_for_encoding == "StringView":
- out.write(f"\n VERIFY(Utf8View {{ {parameter.name} }}.validate());")
+ body.write(f"\n VERIFY(Utf8View {{ {parameter.name} }}.validate());")
generate_unicode_string_overload = True
elif parameter.type == "Utf16String" and parameter.type_for_encoding == "Utf16View":
- out.write(f"\n VERIFY({parameter.name}.validate());")
+ body.write(f"\n VERIFY({parameter.name}.validate());")
generate_unicode_string_overload = True
call_args_parts: List[str] = []
@@ -555,16 +591,16 @@ def write_proxy_method(
call_args = ", ".join(call_args_parts)
if is_synchronous and not is_try:
- sync_call = f"m_connection.template send_sync<Messages::{endpoint.name}::{pascal_name}>({call_args})"
+ sync_call = f"m_connection.send_sync<Messages::{endpoint.name}::{pascal_name}>({call_args})"
if return_type == "void":
- out.write(f"\n (void){sync_call};")
+ body.write(f"\n (void){sync_call};")
elif len(message.outputs) == 1:
output = message.outputs[0]
accessor = output.name if is_primitive_or_simple_type(output.type) else f"take_{output.name}"
- out.write(f"\n return {sync_call}->{accessor}();")
+ body.write(f"\n return {sync_call}->{accessor}();")
else:
- out.write(f"\n return move(*{sync_call});")
+ body.write(f"\n return move(*{sync_call});")
elif is_try:
if inner_return_type == "void":
success_return = "{}"
@@ -574,22 +610,23 @@ def write_proxy_method(
success_return = f"result->{accessor}()"
else:
success_return = "move(*result)"
- out.write(f"""
- if (auto result = m_connection.template send_sync_but_allow_failure<Messages::{endpoint.name}::{pascal_name}>({call_args}))
+ body.write(f"""
+ if (auto result = m_connection.send_sync_but_allow_failure<Messages::{endpoint.name}::{pascal_name}>({call_args}))
return {success_return};
m_connection.shutdown();
return IPC::ErrorCode::PeerDisconnected;""")
else:
# Async messages silently ignore send failures (e.g. peer disconnected).
- out.write(f"""
+ body.write(f"""
auto message_buffer = MUST(Messages::{endpoint.name}::{pascal_name}::static_encode({call_args}));
(void)m_connection.post_message(message_buffer);""")
- out.write("\n }\n")
+ write_method(out, implementation, f"{endpoint.name}Proxy", signature, body.getvalue())
if generate_unicode_string_overload:
write_proxy_method(
out,
+ implementation,
endpoint,
message,
message.inputs,
@@ -599,50 +636,46 @@ def write_proxy_method(
)
-def write_proxy_class(out: TextIO, endpoint: Endpoint) -> None:
+def write_proxy_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
+ name = f"{endpoint.name}Proxy"
+ connection_parameter = "IPC::ConnectionBase& connection" if endpoint.messages else "IPC::ConnectionBase&"
+ initializer = " : m_connection(connection)\n" if endpoint.messages else ""
out.write(f"""
-template<typename LocalEndpoint, typename PeerEndpoint>
-class {endpoint.name}Proxy {{
+{class_declaration(endpoint, name)} {{
public:
// Used to disambiguate the constructor call.
struct Tag {{ }};
- {endpoint.name}Proxy(IPC::Connection<LocalEndpoint, PeerEndpoint>& connection, Tag)
- : m_connection(connection)
- {{
+ {name}({connection_parameter}, Tag)
+{initializer} {{
}}
""")
-
for message in endpoint.messages:
- write_proxy_method(out, endpoint, message, message.inputs, message.is_synchronous, is_try=False)
+ write_proxy_method(out, implementation, endpoint, message, message.inputs, message.is_synchronous, is_try=False)
if message.is_synchronous:
- write_proxy_method(out, endpoint, message, message.inputs, is_synchronous=False, is_try=False)
- write_proxy_method(out, endpoint, message, message.inputs, is_synchronous=True, is_try=True)
-
- out.write("""
-private:
- IPC::Connection<LocalEndpoint, PeerEndpoint>& m_connection;
-};
-""")
+ write_proxy_method(
+ out, implementation, endpoint, message, message.inputs, is_synchronous=False, is_try=False
+ )
+ write_proxy_method(out, implementation, endpoint, message, message.inputs, is_synchronous=True, is_try=True)
+ if endpoint.messages:
+ out.write("\nprivate:\n IPC::ConnectionBase& m_connection;\n")
+ out.write("};\n")
-def write_endpoint_class(out: TextIO, endpoint: Endpoint) -> None:
+def write_endpoint_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
out.write(f"""
-template<typename LocalEndpoint, typename PeerEndpoint>
-class {endpoint.name}Proxy;
-class {endpoint.name}Stub;
+{class_declaration(endpoint, f"{endpoint.name}Stub")};
-class {endpoint.name}Endpoint {{
+{class_declaration(endpoint, f"{endpoint.name}Endpoint")} {{
public:
- template<typename LocalEndpoint>
- using Proxy = {endpoint.name}Proxy<LocalEndpoint, {endpoint.name}Endpoint>;
+ using Proxy = {endpoint.name}Proxy;
using Stub = {endpoint.name}Stub;
static u32 static_magic() {{ return {endpoint.magic}; }}
-
- static ErrorOr<NonnullOwnPtr<IPC::Message>> decode_message(ReadonlyBytes buffer, [[maybe_unused]] Queue<IPC::Attachment>& attachments)
- {{
- FixedMemoryStream stream {{ buffer }};
+""")
+ body = io.StringIO()
+ body.write("""
+ FixedMemoryStream stream { buffer };
auto message_endpoint_magic = TRY(stream.read_value<u32>());
if (message_endpoint_magic != static_magic())
@@ -650,7 +683,7 @@ public:
auto message_id = TRY(stream.read_value<i32>());
- switch (message_id) {{""")
+ switch (message_id) {""")
for message in endpoint.messages:
names = [message.name]
@@ -659,22 +692,28 @@ public:
for name in names:
pascal_name = pascal_case(name)
- out.write(f"""
+ body.write(f"""
case (int)Messages::{endpoint.name}::MessageID::{pascal_name}:
return Messages::{endpoint.name}::{pascal_name}::decode(stream, attachments);""")
- out.write(f"""
+ body.write(f"""
default:
return Error::from_string_literal("Failed to decode {endpoint.name} message");
}}
VERIFY_NOT_REACHED();
- }}
-}};
""")
+ write_method(
+ out,
+ implementation,
+ f"{endpoint.name}Endpoint",
+ "static ErrorOr<NonnullOwnPtr<IPC::Message>> decode_message(ReadonlyBytes buffer, [[maybe_unused]] Queue<IPC::Attachment>& attachments)",
+ body.getvalue(),
+ )
+ out.write("};\n")
-def write_stub_class(out: TextIO, endpoint: Endpoint) -> None:
+def write_stub_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
# The receiver answers for every argument type its endpoint carries. Which of those types ask
# anything of it is decided by the types themselves.
argument_types: List[str] = []
@@ -688,7 +727,7 @@ def write_stub_class(out: TextIO, endpoint: Endpoint) -> None:
bases += f"\n , public IPC::SenderClaimReceivers<{', '.join(argument_types)}>"
out.write(f"""
-class {endpoint.name}Stub : {bases} {{
+{class_declaration(endpoint, f"{endpoint.name}Stub")} : {bases} {{
public:
{endpoint.name}Stub() {{ }}
virtual ~{endpoint.name}Stub() override {{ }}
@@ -696,25 +735,31 @@ public:
virtual u32 magic() const override {{ return {endpoint.magic}; }}
virtual ByteString name() const override {{ return "{endpoint.name}"; }}
- virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle(NonnullOwnPtr<IPC::Message> message) override
- {{
- switch (message->message_id()) {{""")
+""")
+ body = io.StringIO()
+ body.write("\n switch (message->message_id()) {\n")
for message in endpoint.messages:
pascal_name = pascal_case(message.name)
- out.write(f"\n case (int)Messages::{endpoint.name}::MessageID::{pascal_name}:\n")
+ body.write(f"\n case (int)Messages::{endpoint.name}::MessageID::{pascal_name}:\n")
if message.inputs:
- out.write(f" return handle_{message.name}(*message);")
+ body.write(f" return handle_{message.name}(*message);")
else:
- out.write(f" return handle_{message.name}();")
+ body.write(f" return handle_{message.name}();")
- out.write(f"""
+ body.write(f"""
default:
return Error::from_string_literal("Unknown message ID for {endpoint.name} endpoint");
}}
- }}
""")
+ write_method(
+ out,
+ implementation,
+ f"{endpoint.name}Stub",
+ "virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle(NonnullOwnPtr<IPC::Message> message) override",
+ body.getvalue(),
+ )
for message in endpoint.messages:
pascal_name = pascal_case(message.name)
@@ -725,43 +770,44 @@ public:
arg_parts.append(f"request.{accessor}()")
arguments = ", ".join(arg_parts)
- out.write(f"\n NEVER_INLINE ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_{message.name}(")
+ body = io.StringIO()
+ signature = f"NEVER_INLINE ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_{message.name}("
if message.inputs:
- out.write("IPC::Message& message)\n {\n")
- out.write(f" auto& request = static_cast<Messages::{endpoint.name}::{pascal_name}&>(message);\n")
+ signature += "IPC::Message& message)"
+ body.write(f" auto& request = static_cast<Messages::{endpoint.name}::{pascal_name}&>(message);\n")
else:
- out.write(")\n {\n")
+ signature += ")"
# An argument whose type is a claim by the sender about itself is verified before the handler
# runs. Which types make a claim is decided by the types, not here.
for parameter in message.inputs:
reason = f"argument '{parameter.name}' is not a valid claim for this sender"
- out.write(f" if (!IPC::verify_message_argument(*this, request.{parameter.name}())) {{\n")
- out.write(f' did_misbehave("{message.name}"sv, "{reason}"sv);\n')
+ body.write(f" if (!IPC::verify_message_argument(*this, request.{parameter.name}())) {{\n")
+ body.write(f' did_misbehave("{message.name}"sv, "{reason}"sv);\n')
if not message.is_synchronous:
- out.write(" return nullptr;\n")
+ body.write(" return nullptr;\n")
else:
refused_types = [message_name_qualified(endpoint.name, message.name, True)]
refused_types += [output.type for output in message.outputs]
- out.write(f" return IPC::refused_reply<{', '.join(refused_types)}>();\n")
+ body.write(f" return IPC::refused_reply<{', '.join(refused_types)}>();\n")
- out.write(" }\n")
+ body.write(" }\n")
if not message.is_synchronous:
- out.write(f" {message.name}({arguments});\n")
- out.write(" return nullptr;\n")
+ body.write(f" {message.name}({arguments});\n")
+ body.write(" return nullptr;\n")
elif not message.outputs:
response_pascal_name = pascal_case(message.response_name())
- out.write(f" {message.name}({arguments});\n")
- out.write(f" auto response = Messages::{endpoint.name}::{response_pascal_name} {{}};\n")
- out.write(" return make<IPC::MessageBuffer>(TRY(response.encode()));\n")
+ body.write(f" {message.name}({arguments});\n")
+ body.write(f" auto response = Messages::{endpoint.name}::{response_pascal_name} {{}};\n")
+ body.write(" return make<IPC::MessageBuffer>(TRY(response.encode()));\n")
else:
- out.write(f" auto response = {message.name}({arguments});\n")
- out.write(" return make<IPC::MessageBuffer>(TRY(response.encode()));\n")
+ body.write(f" auto response = {message.name}({arguments});\n")
+ body.write(" return make<IPC::MessageBuffer>(TRY(response.encode()));\n")
- out.write(" }\n")
+ write_method(out, implementation, f"{endpoint.name}Stub", signature, body.getvalue())
out.write("\n")
@@ -783,7 +829,7 @@ def write_routed_stub_class(out: TextIO, endpoint: Endpoint) -> None:
out.write(f"""
// The receiver of the messages about one {endpoint.route_scope()}: those whose first argument is the {endpoint.route.name}.
-class {endpoint.name}{scope}Stub {{
+{class_declaration(endpoint, f"{endpoint.name}{scope}Stub")} {{
public:
virtual ~{endpoint.name}{scope}Stub() = default;
@@ -801,7 +847,7 @@ public:
out.write("};\n")
-def write_routing_stub_mixin(out: TextIO, endpoint: Endpoint) -> None:
+def write_routing_stub_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
assert endpoint.route is not None
scope = endpoint.route_scope_pascal()
route = endpoint.route
@@ -811,11 +857,8 @@ def write_routing_stub_mixin(out: TextIO, endpoint: Endpoint) -> None:
// A receiver that hands each message about a {endpoint.route_scope()} to that {endpoint.route_scope()}'s stub, and drops
// it when there is none. It still answers the unrouted messages itself, and may take a routed one back by
// overriding it.
-template<typename Base>
-class {endpoint.name}{scope}RoutingStub : public Base {{
+{class_declaration(endpoint, f"{endpoint.name}{scope}RoutingStub")} : public {endpoint.name}Stub {{
public:
- using Base::Base;
-
virtual {endpoint.name}{scope}Stub* {stub_accessor}({route.type} const&) = 0;
""")
@@ -826,17 +869,20 @@ public:
args = ", ".join(
p.name if is_primitive_or_simple_type(p.type) else f"move({p.name})" for p in message.inputs[1:]
)
- out.write(f"\n virtual void {message.name}({params}) override\n {{\n")
- out.write(
- f" if (auto* stub = {stub_accessor}({route.name}))\n stub->{message.name}({args});\n"
+ write_method(
+ out,
+ implementation,
+ f"{endpoint.name}{scope}RoutingStub",
+ f"virtual void {message.name}({params}) override",
+ f"if (auto* stub = {stub_accessor}({route.name}))\n stub->{message.name}({args});",
)
- out.write(" }\n")
out.write("};\n")
def write_bound_proxy_method(
out: TextIO,
+ implementation: TextIO,
endpoint: Endpoint,
message: Message,
is_synchronous: bool,
@@ -858,7 +904,7 @@ def write_bound_proxy_method(
method_name = ("try_" if is_try else "") + ("" if is_synchronous else "async_") + message.name
signature_params: List[str] = []
- call_args: List[str] = [f"derived().routed_{endpoint.route.name}()"]
+ call_args: List[str] = [f"routed_{endpoint.route.name}()"]
generate_unicode_string_overload = False
for parameter in parameters:
if is_synchronous or is_try:
@@ -879,127 +925,179 @@ def write_bound_proxy_method(
call_args.append(parameter.name if is_primitive_or_simple_type(forwarded_type) else f"move({parameter.name})")
call = f"connection->{method_name}({', '.join(call_args)})"
- out.write(f"\n {return_type} {method_name}({', '.join(signature_params)}) const\n {{\n")
- out.write(" if (auto* connection = derived().routed_connection())\n")
+ signature = f"{return_type} {method_name}({', '.join(signature_params)}) const"
+ body = io.StringIO()
+ body.write(" if (auto* connection = routed_proxy())\n")
if return_type == "void":
- out.write(f" {call};\n")
+ body.write(f" {call};\n")
else:
- out.write(f" return {call};\n")
+ body.write(f" return {call};\n")
if is_try:
- out.write(" return IPC::ErrorCode::PeerDisconnected;\n")
+ body.write(" return IPC::ErrorCode::PeerDisconnected;\n")
elif len(message.outputs) == 1:
- out.write(f" return IPC::empty_value<{return_type}>();\n")
+ body.write(f" return IPC::empty_value<{return_type}>();\n")
else:
outputs = ", ".join(output.type for output in message.outputs)
- out.write(f" return IPC::empty_response<{return_type}, {outputs}>();\n")
- out.write(" }\n")
+ body.write(f" return IPC::empty_response<{return_type}, {outputs}>();\n")
+ write_method(
+ out, implementation, f"{endpoint.name}{endpoint.route_scope_pascal()}Proxy", signature, body.getvalue()
+ )
if generate_unicode_string_overload:
- write_bound_proxy_method(out, endpoint, message, is_synchronous, is_try, is_unicode_string_overload=True)
+ write_bound_proxy_method(
+ out, implementation, endpoint, message, is_synchronous, is_try, is_unicode_string_overload=True
+ )
-def write_bound_proxy_class(out: TextIO, endpoint: Endpoint) -> None:
+def write_bound_proxy_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
assert endpoint.route is not None
scope = endpoint.route_scope_pascal()
out.write(f"""
// Sends the messages about one {endpoint.route_scope()} without naming it each time. The class deriving this provides
-// routed_connection(), the proxy the messages go through, or null once the {endpoint.route_scope()} has none, and
+// routed_proxy(), the proxy the messages go through, or null once the {endpoint.route_scope()} has none, and
// routed_{endpoint.route.name}(). A message for a {endpoint.route_scope()} without a connection is dropped.
-template<typename Derived>
-class {endpoint.name}{scope}Proxy {{
+{class_declaration(endpoint, f"{endpoint.name}{scope}Proxy")} {{
public:
+ virtual ~{endpoint.name}{scope}Proxy() = default;
""")
for message in endpoint.messages:
if not endpoint.binds(message):
continue
- write_bound_proxy_method(out, endpoint, message, message.is_synchronous, is_try=False)
+ write_bound_proxy_method(out, implementation, endpoint, message, message.is_synchronous, is_try=False)
if message.is_synchronous:
- write_bound_proxy_method(out, endpoint, message, is_synchronous=False, is_try=False)
- write_bound_proxy_method(out, endpoint, message, is_synchronous=True, is_try=True)
+ write_bound_proxy_method(out, implementation, endpoint, message, is_synchronous=False, is_try=False)
+ write_bound_proxy_method(out, implementation, endpoint, message, is_synchronous=True, is_try=True)
- out.write("""
-private:
- Derived const& derived() const { return static_cast<Derived const&>(*this); }
-};
+ out.write(f"""
+protected:
+ virtual {endpoint.name}Proxy* routed_proxy() const = 0;
+ virtual {endpoint.route.type} routed_{endpoint.route.name}() const = 0;
+}};
""")
-def write_endpoint(out: TextIO, endpoint: Endpoint) -> None:
+def write_endpoint(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
out.write(f"\nnamespace Messages::{endpoint.name} {{\n")
+ implementation.write(f"\nnamespace Messages::{endpoint.name} {{\n")
write_message_ids_enum(out, endpoint)
-
for message in endpoint.messages:
response_name = ""
-
if message.is_synchronous:
response_name = message.response_name()
- write_message_class(out, endpoint, response_name, message.outputs)
-
- write_message_class(out, endpoint, message.name, message.inputs, response_name)
-
+ write_message_class(out, implementation, endpoint, response_name, message.outputs)
+ write_message_class(out, implementation, endpoint, message.name, message.inputs, response_name)
out.write(f"\n}} // namespace Messages::{endpoint.name}\n")
-
- write_proxy_class(out, endpoint)
- write_endpoint_class(out, endpoint)
- write_stub_class(out, endpoint)
+ implementation.write(f"\n}} // namespace Messages::{endpoint.name}\n")
+ write_proxy_class(out, implementation, endpoint)
+ write_endpoint_class(out, implementation, endpoint)
+ write_stub_class(out, implementation, endpoint)
if endpoint.route is not None:
write_routed_stub_class(out, endpoint)
- write_routing_stub_mixin(out, endpoint)
- write_bound_proxy_class(out, endpoint)
-
- out.write("""
-#if defined(AK_COMPILER_CLANG)
-#pragma clang diagnostic pop
-#endif
-""")
+ write_routing_stub_class(out, implementation, endpoint)
+ write_bound_proxy_class(out, implementation, endpoint)
-def build(out: TextIO, endpoints: List[Endpoint]) -> None:
+def build(
+ out: TextIO,
+ endpoints: List[Endpoint],
+ implementation: TextIO,
+ header_name: str,
+ library: str = "",
+) -> None:
out.write("#pragma once\n\n")
+ export_macro = ""
+ if library:
+ export_macro = f"{library.removeprefix('Lib').upper()}_API"
+ out.write(f"""\
+#if __has_include(<{library}/Export.h>)
+#include <{library}/Export.h>
+#else
+#define {export_macro}
+#endif
+""")
for endpoint in endpoints:
for include in endpoint.includes:
out.write(f"{include}\n")
-
+ # Message members need complete owning types even when an endpoint has no explicit includes.
+ parameter_types = " ".join(
+ parameter.type
+ for endpoint in endpoints
+ for message in endpoint.messages
+ for parameter in message.inputs + message.outputs
+ )
+ for name in ["ByteBuffer", "ByteString", "JsonValue", "Optional", "String", "Utf16String", "Vector"]:
+ if re.search(rf"\b{name}\b", parameter_types):
+ out.write(f"#include <AK/{name}.h>\n")
out.write("""\
#include <AK/Error.h>
-#include <AK/MemoryStream.h>
#include <AK/OwnPtr.h>
#include <AK/Platform.h>
#include <AK/Result.h>
-#include <AK/Utf8View.h>
-#include <LibIPC/Attachment.h>
-#include <LibIPC/Connection.h>
-#include <LibIPC/Decoder.h>
-#include <LibIPC/Encoder.h>
#include <LibIPC/File.h>
#include <LibIPC/Message.h>
#include <LibIPC/SenderClaim.h>
#include <LibIPC/Stub.h>
+namespace AK {
+class FixedMemoryStream;
+}
+
+namespace IPC {
+class ConnectionBase;
+}
+
#if defined(AK_COMPILER_CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdefaulted-function-deleted"
#endif
""")
-
+ implementation.write(f'#include "{header_name}"\n\n')
+ implementation.write("""\
+#include <AK/MemoryStream.h>
+#include <AK/Utf8View.h>
+#include <LibIPC/Attachment.h>
+#include <LibIPC/Connection.h>
+#include <LibIPC/Decoder.h>
+#include <LibIPC/Encoder.h>
+""")
for endpoint in endpoints:
- write_endpoint(out, endpoint)
+ endpoint.export_macro = export_macro
+ write_endpoint(out, implementation, endpoint)
+ out.write("""
+#if defined(AK_COMPILER_CLANG)
+#pragma clang diagnostic pop
+#endif
+""")
def main():
parser = argparse.ArgumentParser(description="Ladybird IPC endpoint compiler")
parser.add_argument("--input", required=True, help="IPC endpoint definition file")
- parser.add_argument("--output", required=True, help="File to write file generated header")
+ parser.add_argument("--output", required=True, help="Generated header file")
+ parser.add_argument("--implementation", required=True, help="Generated implementation file")
+ parser.add_argument("--header-name", help="Header name to include from the implementation")
+ parser.add_argument(
+ "--library", default="", help="Owning library, e.g. LibWebCommon; determines the export header and macro"
+ )
args = parser.parse_args()
with open(args.input, "r", encoding="utf-8") as input_file:
endpoints = parse(input_file.read())
- with open(args.output, "w", encoding="utf-8") as output_file:
- build(output_file, endpoints)
+ with (
+ open(args.output, "w", encoding="utf-8") as output_file,
+ open(args.implementation, "w", encoding="utf-8") as implementation_file,
+ ):
+ build(
+ output_file,
+ endpoints,
+ implementation_file,
+ args.header_name or Path(args.output).name,
+ args.library,
+ )
if __name__ == "__main__":
diff --git a/Services/ImageDecoder/ImageDecoderServer.ipc b/Services/ImageDecoder/ImageDecoderServer.ipc
index daa23428e0a..b3dfcfc8b28 100644
--- a/Services/ImageDecoder/ImageDecoderServer.ipc
+++ b/Services/ImageDecoder/ImageDecoderServer.ipc
@@ -1,4 +1,5 @@
#include <LibCore/AnonymousBuffer.h>
+#include <LibGfx/Size.h>
endpoint ImageDecoderServer
{
diff --git a/Services/MediaServer/CMakeLists.txt b/Services/MediaServer/CMakeLists.txt
index 70684841c56..2767c0e6ec3 100644
--- a/Services/MediaServer/CMakeLists.txt
+++ b/Services/MediaServer/CMakeLists.txt
@@ -23,7 +23,7 @@ target_include_directories(mediaserverservice PRIVATE ${CMAKE_CURRENT_BINARY_DIR
target_include_directories(mediaserverservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)
target_link_libraries(MediaServer PRIVATE mediaserverservice LibCore LibMain LibMedia LibSandbox)
-target_link_libraries(mediaserverservice PRIVATE LibAudio LibCore LibGfx LibIPC LibMedia LibThreading)
+target_link_libraries(mediaserverservice PRIVATE LibAudio LibCore LibGfx LibIPC LibMedia LibMediaClient LibThreading)
target_link_libraries(MediaServer PRIVATE LibThreading)
if (WIN32)
diff --git a/Services/WasmCompiler/CMakeLists.txt b/Services/WasmCompiler/CMakeLists.txt
index 15206fe075c..d5f1fe06185 100644
--- a/Services/WasmCompiler/CMakeLists.txt
+++ b/Services/WasmCompiler/CMakeLists.txt
@@ -23,7 +23,7 @@ target_include_directories(wasmcompilerservice PRIVATE ${CMAKE_CURRENT_BINARY_DI
target_include_directories(wasmcompilerservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)
target_link_libraries(WasmCompiler PRIVATE wasmcompilerservice LibCore LibMain LibSandbox LibThreading)
-target_link_libraries(wasmcompilerservice PRIVATE LibCore LibCrypto LibIPC LibThreading LibWasm)
+target_link_libraries(wasmcompilerservice PRIVATE LibCore LibCrypto LibIPC LibThreading LibWasm LibWasmCompilerClient)
if (WIN32)
ladybird_windows_bin(WasmCompiler CONSOLE)
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index bd1c30828d5..4012a630f3b 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -53,6 +53,7 @@
#include <LibWebCommon/Page/CompositorContextId.h>
#include <LibWebCommon/Page/ContextMenuForInputEventsTarget.h>
#include <LibWebCommon/Page/EventResult.h>
+#include <LibWebCommon/Page/InputEvent.h>
#include <LibWebCommon/Page/MediaContextMenu.h>
#include <LibWebCommon/Page/NavigationTarget.h>
#include <LibWebCommon/Page/PageId.h>
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 72c01aa4155..7f095d4cc3f 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -1,4 +1,5 @@
#include <LibCore/SharedVersion.h>
+#include <LibGfx/Color.h>
#include <LibGfx/Rect.h>
#include <LibHTTP/Cookie/Cookie.h>
#include <LibIPC/File.h>
diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipc
index d354162acaf..59282bb158e 100644
--- a/Services/WebContent/WebContentTestClient.ipc
+++ b/Services/WebContent/WebContentTestClient.ipc
@@ -2,6 +2,7 @@
#include <LibURL/Origin.h>
#include <LibWebCommon/Gamepad/GamepadSnapshot.h>
#include <LibWebCommon/HTML/CrossProcessId.h>
+#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
#include <LibWebCommon/HTML/SessionHistoryEntryDescriptor.h>
#include <LibWebCommon/Page/PageId.h>
diff --git a/Tests/Meta/test-ipc-generator.py b/Tests/Meta/test-ipc-generator.py
index 0d54bb0b723..2e088288eab 100644
--- a/Tests/Meta/test-ipc-generator.py
+++ b/Tests/Meta/test-ipc-generator.py
@@ -19,23 +19,69 @@ endpoint TestClient {
"""
-def generate(contents: str) -> str:
+def generate_files(contents: str) -> tuple[str, str]:
out = io.StringIO()
- build(out, parse(contents))
- return out.getvalue()
+ implementation = io.StringIO()
+ build(out, parse(contents), implementation, "TestEndpoint.h")
+ return out.getvalue(), implementation.getvalue()
+
+
+def generate(contents: str) -> str:
+ header, implementation = generate_files(contents)
+ return header + implementation
class TestIPCGenerator(unittest.TestCase):
+ def test_non_template_implementations_are_only_in_the_cpp_file(self) -> None:
+ header, implementation = generate_files(ENDPOINT)
+ self.assertIn('#include "TestEndpoint.h"', implementation)
+ self.assertIn("static ErrorOr<NonnullOwnPtr<PageChanged>> decode(AK::FixedMemoryStream& stream", header)
+ self.assertNotIn("decoder.decode<", header)
+ self.assertNotIn("stream.encode(", header)
+ self.assertNotIn("IPC::verify_message_argument", header)
+ self.assertNotIn("m_connection.send_sync", header)
+ self.assertIn("PageChanged::decode(AK::FixedMemoryStream& stream", implementation)
+ self.assertIn("TestClientProxy::page_wants_cookie", implementation)
+ self.assertIn("TestClientStub::handle_page_changed", implementation)
+ self.assertNotIn("template<typename LocalEndpoint", header)
+
+ def test_exports_are_applied_to_the_generated_api(self) -> None:
+ header = io.StringIO()
+ implementation = io.StringIO()
+ build(header, parse(ROUTED_ENDPOINT), implementation, "TestEndpoint.h", "LibWebCommon")
+ self.assertIn(
+ """\
+#if __has_include(<LibWebCommon/Export.h>)
+#include <LibWebCommon/Export.h>
+#else
+#define WEBCOMMON_API
+#endif
+""",
+ header.getvalue(),
+ )
+ for name in [
+ "PageChanged",
+ "TestClientProxy",
+ "TestClientEndpoint",
+ "TestClientStub",
+ "TestClientPageRoutingStub",
+ "TestClientPageProxy",
+ ]:
+ self.assertIn(f"class WEBCOMMON_API {name}", header.getvalue())
+ self.assertNotIn("class WEBCOMMON_API TestClientProxy;", header.getvalue())
+ self.assertNotIn("template<typename Derived>", header.getvalue())
+ self.assertNotIn("template<typename Base>", header.getvalue())
+
def test_asynchronous_message_verifies_every_argument_before_dispatch(self) -> None:
generated = generate(ENDPOINT)
for argument in ("page_id", "revision"):
self.assertIn(
f"""\
- if (!IPC::verify_message_argument(*this, request.{argument}())) {{
- did_misbehave("page_changed"sv, "argument '{argument}' is not a valid claim for this sender"sv);
- return nullptr;
- }}
+ if (!IPC::verify_message_argument(*this, request.{argument}())) {{
+ did_misbehave("page_changed"sv, "argument '{argument}' is not a valid claim for this sender"sv);
+ return nullptr;
+ }}
""",
generated,
)
@@ -49,10 +95,10 @@ class TestIPCGenerator(unittest.TestCase):
self.assertIn(
"""\
- if (!IPC::verify_message_argument(*this, request.page_id())) {
- did_misbehave("page_wants_cookie"sv, "argument 'page_id' is not a valid claim for this sender"sv);
- return IPC::refused_reply<Messages::TestClient::PageWantsCookieResponse, HTTP::Cookie::VersionedCookie>();
- }
+ if (!IPC::verify_message_argument(*this, request.page_id())) {
+ did_misbehave("page_wants_cookie"sv, "argument 'page_id' is not a valid claim for this sender"sv);
+ return IPC::refused_reply<Messages::TestClient::PageWantsCookieResponse, HTTP::Cookie::VersionedCookie>();
+ }
""",
generated,
)
@@ -62,11 +108,11 @@ class TestIPCGenerator(unittest.TestCase):
self.assertIn(
"""\
- NEVER_INLINE ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_ping()
- {
- ping();
- return nullptr;
- }
+ErrorOr<OwnPtr<IPC::MessageBuffer>> TestClientStub::handle_ping()
+{
+ ping();
+ return nullptr;
+}
""",
generated,
)
@@ -101,21 +147,21 @@ class TestIPCGeneratorRouting(unittest.TestCase):
self.assertIn("virtual TestClientPageStub* page_stub(Web::PageId const&) = 0;", generated)
self.assertIn(
"""\
- virtual void page_changed(Web::PageId page_id, u32 revision) override
- {
- if (auto* stub = page_stub(page_id))
- stub->page_changed(revision);
- }
+void TestClientPageRoutingStub::page_changed(Web::PageId page_id, u32 revision)
+{
+ if (auto* stub = page_stub(page_id))
+ stub->page_changed(revision);
+}
""",
generated,
)
self.assertIn(
"""\
- virtual void page_acknowledged(Web::PageId page_id) override
- {
- if (auto* stub = page_stub(page_id))
- stub->page_acknowledged();
- }
+void TestClientPageRoutingStub::page_acknowledged(Web::PageId page_id)
+{
+ if (auto* stub = page_stub(page_id))
+ stub->page_acknowledged();
+}
""",
generated,
)
@@ -126,16 +172,17 @@ class TestIPCGeneratorRouting(unittest.TestCase):
self.assertIn("class TestClientPageProxy {", generated)
self.assertIn(
"""\
- void async_page_changed(u32 revision) const
- {
- if (auto* connection = derived().routed_connection())
- connection->async_page_changed(derived().routed_page_id(), revision);
- }
+void TestClientPageProxy::async_page_changed(u32 revision) const
+{
+ if (auto* connection = routed_proxy())
+ connection->async_page_changed(routed_page_id(), revision);
+}
""",
generated,
)
- self.assertIn(" HTTP::Cookie::VersionedCookie page_wants_cookie() const\n", generated)
- self.assertNotIn("async_ping", generated.split("class TestClientPageProxy {")[1])
+ self.assertIn(" HTTP::Cookie::VersionedCookie page_wants_cookie() const;\n", generated)
+ header, _ = generate_files(ROUTED_ENDPOINT)
+ self.assertNotIn("async_ping", header.split("class TestClientPageProxy {")[1])
def test_a_message_marked_not_routed_stays_on_the_connection(self) -> None:
generated = generate(ROUTED_ENDPOINT)