Truly independent web browser
LibJS+LibWeb: Escape control characters in what pages log to stderr
sideshowbarker538e94bf75bf
diff --git a/Libraries/LibJS/Console.cpp b/Libraries/LibJS/Console.cppindex d8535e768a4..7233165acbf 100644--- a/Libraries/LibJS/Console.cpp+++ b/Libraries/LibJS/Console.cpp@@ -6,6 +6,8 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/StringBuilder.h>+#include <AK/Utf8View.h>#include <LibJS/Console.h>#include <LibJS/EmbeddingABIConversions.h>#include <LibJS/Runtime/Realm.h>@@ -160,54 +162,70 @@ Realm& Console::realm() constreturn cell_ref_from_abi<Realm>(js_console_realm(console_to_abi(*this)));}-void Console::output_debug_message(LogLevel log_level, StringView output) const+static bool is_terminal_control_character(u32 code_point){- switch (log_level) {- case Console::LogLevel::Debug:- dbgln("\033[32;1m(js debug)\033[0m {}", output);- break;- case Console::LogLevel::Error:- dbgln("\033[32;1m(js error)\033[0m {}", output);- break;- case Console::LogLevel::Info:- dbgln("\033[32;1m(js info)\033[0m {}", output);- break;- case Console::LogLevel::Log:- dbgln("\033[32;1m(js log)\033[0m {}", output);- break;- case Console::LogLevel::Warn:- dbgln("\033[32;1m(js warn)\033[0m {}", output);- break;- default:- dbgln("\033[32;1m(js)\033[0m {}", output);- break;+ if (code_point == '\n' || code_point == '\t')+ return false;+ return code_point < 0x20 || (code_point >= 0x7f && code_point < 0xa0);+}++template<typename CodePoints>+static ByteString escape_control_characters(CodePoints const& code_points)+{+ StringBuilder builder;+ for (u32 code_point : code_points) {+ if (is_terminal_control_character(code_point))+ builder.appendff("\\x{:02x}", code_point);+ else+ builder.append_code_point(code_point);}+ return builder.to_byte_string();}-void Console::output_debug_message(LogLevel log_level, Utf16View output) const+ByteString Console::escape_for_terminal(StringView text)+{+ return escape_control_characters(Utf8View { text });+}++ByteString Console::escape_for_terminal(Utf16View text)+{+ return escape_control_characters(text);+}++static void print_debug_message(Console::LogLevel log_level, StringView escaped_output){switch (log_level) {case Console::LogLevel::Debug:- dbgln("\033[32;1m(js debug)\033[0m {}", output);+ dbgln("\033[32;1m(js debug)\033[0m {}", escaped_output);break;case Console::LogLevel::Error:- dbgln("\033[32;1m(js error)\033[0m {}", output);+ dbgln("\033[32;1m(js error)\033[0m {}", escaped_output);break;case Console::LogLevel::Info:- dbgln("\033[32;1m(js info)\033[0m {}", output);+ dbgln("\033[32;1m(js info)\033[0m {}", escaped_output);break;case Console::LogLevel::Log:- dbgln("\033[32;1m(js log)\033[0m {}", output);+ dbgln("\033[32;1m(js log)\033[0m {}", escaped_output);break;case Console::LogLevel::Warn:- dbgln("\033[32;1m(js warn)\033[0m {}", output);+ dbgln("\033[32;1m(js warn)\033[0m {}", escaped_output);break;default:- dbgln("\033[32;1m(js)\033[0m {}", output);+ dbgln("\033[32;1m(js)\033[0m {}", escaped_output);break;}}+void Console::output_debug_message(LogLevel log_level, StringView output) const+{+ print_debug_message(log_level, escape_for_terminal(output));+}++void Console::output_debug_message(LogLevel log_level, Utf16View output) const+{+ print_debug_message(log_level, escape_for_terminal(output));+}+void Console::report_exception(Utf16View name, Utf16View message, ErrorData const& error_data, bool in_promise) const{js_console_report_exception(console_to_abi(*this), utf16_view_to_abi(name), utf16_view_to_abi(message), error_data_to_abi(error_data), in_promise);diff --git a/Libraries/LibJS/Console.h b/Libraries/LibJS/Console.hindex 048d146e3cb..df1d8686b04 100644--- a/Libraries/LibJS/Console.h+++ b/Libraries/LibJS/Console.h@@ -61,6 +61,11 @@ public:void output_debug_message(LogLevel log_level, StringView output) const;void output_debug_message(LogLevel log_level, Utf16View output) const;++ // What a page logs also goes to the terminal Ladybird runs in, so control characters other than a newline or a+ // tab are written as escapes (\x1b): Written as they are, they would take effect there, e.g. clearing the screen.+ static ByteString escape_for_terminal(StringView);+ static ByteString escape_for_terminal(Utf16View);void report_exception(Utf16View name, Utf16View message, JS::ErrorData const&, bool) const;void report_exception(Utf16View name, Utf16View message, Utf16View filename, u32 line, u32 column, bool in_promise) const;};diff --git a/Libraries/LibJS/Rust/src/console.rs b/Libraries/LibJS/Rust/src/console.rsindex 9720b6ef259..38a0ebbc8d6 100644--- a/Libraries/LibJS/Rust/src/console.rs+++ b/Libraries/LibJS/Rust/src/console.rs@@ -714,7 +714,7 @@ impl Console {LogLevel::Warn => "\x1b[32;1m(js warn)\x1b[0m",_ => "\x1b[32;1m(js)\x1b[0m",};- eprintln!("{prefix} {}", output.to_utf8());+ eprintln!("{prefix} {}", crate::terminal::escape_for_terminal(&output.to_utf8()));}pub fn report_exception(diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rsindex 52e47a4215c..85c09448783 100644--- a/Libraries/LibJS/Rust/src/lib.rs+++ b/Libraries/LibJS/Rust/src/lib.rs@@ -152,6 +152,7 @@ pub mod source_range;pub mod source_text;#[cfg(not(test))]pub mod standard_output;+pub mod terminal;pub mod token;pub mod tokenize;#[cfg(not(test))]diff --git a/Libraries/LibJS/Rust/src/terminal.rs b/Libraries/LibJS/Rust/src/terminal.rsnew file mode 100644index 00000000000..33c98832176--- /dev/null+++ b/Libraries/LibJS/Rust/src/terminal.rs@@ -0,0 +1,41 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++/// Writes control characters other than a newline or a tab as escapes (\x1b). What a page logs also goes to the+/// terminal Ladybird runs in, and written as they are, they would take effect there, e.g. clearing the screen.+pub fn escape_for_terminal(text: &str) -> String {+ let mut escaped = String::with_capacity(text.len());+ for character in text.chars() {+ let code_point = u32::from(character);+ let is_control =+ (code_point < 0x20 && character != '\n' && character != '\t') || (0x7f..0xa0).contains(&code_point);+ if is_control {+ escaped.push_str(&format!("\\x{code_point:02x}"));+ } else {+ escaped.push(character);+ }+ }+ escaped+}++#[cfg(test)]+mod tests {+ use super::escape_for_terminal;++ #[test]+ fn control_characters_come_out_as_escapes() {+ assert_eq!(escape_for_terminal("a\u{1b}[2Jb"), "a\\x1b[2Jb");+ assert_eq!(escape_for_terminal("\r\u{7f}\u{9b}"), "\\x0d\\x7f\\x9b");+ }++ #[test]+ fn newlines_tabs_and_other_text_pass_through() {+ assert_eq!(+ escape_for_terminal("one\ntwo\tthree \u{a0}\u{e9}\u{1f600}"),+ "one\ntwo\tthree \u{a0}\u{e9}\u{1f600}"+ );+ }+}diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cppindex 89a1bfc84d5..81e750a23ff 100644--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp@@ -41,12 +41,12 @@ void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromiif (name.is_accessor() || message.is_accessor()) {// The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.if (auto exception = Bindings::dom_exception_report_details(object); exception.has_value()) {- dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}: {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", exception->name, exception->message);+ dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Console::escape_for_terminal(ByteString::formatted("{}: {}", exception->name, exception->message)));} else {- dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Value(&object));+ dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Console::escape_for_terminal(ByteString::formatted("{}", JS::Value(&object))));}} else {- dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m [{}] {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", name, message);+ dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Console::escape_for_terminal(ByteString::formatted("[{}] {}", name, message)));}if (auto const* error_data = object.error_data()) {Utf16String exception_name;@@ -58,12 +58,13 @@ void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromiexception_name = name.to_utf16_string_without_side_effects();exception_message = message.to_utf16_string_without_side_effects();}- dbgln("{}", error_data->stack_string(JS::CompactTraceback::Yes));+ auto stack = error_data->stack_string(JS::CompactTraceback::Yes);+ dbgln("{}", JS::Console::escape_for_terminal(stack.utf16_view()));console.report_exception(exception_name, exception_message, *error_data, error_in_promise == ErrorInPromise::Yes);return;}} else {- dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", value);+ dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Console::escape_for_terminal(ByteString::formatted("{}", value)));}auto utf16_message = value.to_utf16_string_without_side_effects();@@ -182,8 +183,8 @@ void report_an_exception(JS::Object& global, JS::Value exception, Optional<Error}// 3. Otherwise, the user agent may report exception to a developer console.else if (has_precomputed_error_info) {- dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", error_info.message);- dbgln(" at {}:{}:{}", error_info.filename, error_info.lineno, error_info.colno);+ dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", JS::Console::escape_for_terminal(error_info.message.utf16_view()));+ dbgln(" at {}:{}:{}", JS::Console::escape_for_terminal(error_info.filename.utf16_view()), error_info.lineno, error_info.colno);realm.intrinsics().console_object()->console().report_exception("Error"_utf16, error_info.message, error_info.filename, error_info.lineno, error_info.colno, false);} else {report_exception_to_console(exception, realm, ErrorInPromise::No);diff --git a/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp b/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cppindex 18bfe18fad4..1dbf34212f4 100644--- a/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp+++ b/Libraries/LibWeb/HTML/WorkerDebugConsoleClient.cpp@@ -19,11 +19,10 @@ WorkerDebugConsoleClient::WorkerDebugConsoleClient(JS::Console& console){}+// The terminal isn't the page's to clear, so this only ends the groups.void WorkerDebugConsoleClient::clear(){- dbgln("\033[3J\033[H\033[2J");m_group_stack_depth = 0;- fflush(stdout);}void WorkerDebugConsoleClient::end_group()@@ -43,10 +42,10 @@ JS::ThrowCompletionOr<JS::Value> WorkerDebugConsoleClient::printer(JS::Console::auto trace = arguments.get<JS::Console::Trace>();StringBuilder builder;if (!trace.label.is_empty())- builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);+ builder.appendff("{}\033[36;1m{}\033[0m\n", indent, JS::Console::escape_for_terminal(trace.label.utf16_view()));for (auto& frame : trace.stack)- builder.appendff("{}-> {}\n", indent, frame.function_name);+ builder.appendff("{}-> {}\n", indent, JS::Console::escape_for_terminal(frame.function_name.utf16_view()));dbgln("{}", builder.string_view());return JS::js_undefined();@@ -54,7 +53,7 @@ JS::ThrowCompletionOr<JS::Value> WorkerDebugConsoleClient::printer(JS::Console::if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {auto group = arguments.get<JS::Console::Group>();- dbgln("{}\033[36;1m{}\033[0m", indent, group.label);+ dbgln("{}\033[36;1m{}\033[0m", indent, JS::Console::escape_for_terminal(group.label.utf16_view()));m_group_stack_depth++;return JS::js_undefined();}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex e9547d0abe1..230b99af642 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -5,6 +5,7 @@ if (BUILD_TESTING AND NOT WIN32)ladybird_python_test(test-devtools-network-events.py ARGS $<TARGET_FILE:ladybird>)ladybird_python_test(test-iframe-console.py ARGS $<TARGET_FILE:ladybird>)ladybird_python_test(test-console-previews.py ARGS $<TARGET_FILE:ladybird>)+ ladybird_python_test(test-console-output-escapes-control-characters.py ARGS $<TARGET_FILE:ladybird>)ladybird_python_test(test-message-port-collection.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-shared-stylesheet-memory.py ARGS $<TARGET_FILE:WebDriver> TIMEOUT 180)ladybird_python_test(test-user-agent-preset-reaches-child-frames.py ARGS $<TARGET_FILE:ladybird>)diff --git a/Tests/LibWebView/test-console-output-escapes-control-characters.py b/Tests/LibWebView/test-console-output-escapes-control-characters.pynew file mode 100755index 00000000000..2fc28d99741--- /dev/null+++ b/Tests/LibWebView/test-console-output-escapes-control-characters.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++# What a page logs to its console, and the exceptions it doesn't catch, also go to the terminal Ladybird runs in. The+# page decides what's in them, so a control character in one must come out as an escape: Written as it is, it would+# take effect in the terminal.++import argparse+import http.server+import queue+import subprocess+import sys+import tempfile+import threading+import time++TIMEOUT_SECONDS = 60+DONE = "console-escapes-done"++PAGE = b"""<!doctype html><title>console-escapes</title>+<script>+console.log("page-log[\\x1b[2J]");+console.warn("page-warn[\\x1b]0;title\\x07]");+console.error("page-error[\\x9b2J]");+console.group("page-group[\\x1b[31m]");+console.groupEnd();+console.trace("page-trace[\\x1b[H]");+new Worker("/worker.js").onmessage = () => {+ setTimeout(() => { throw new Error("page-exception[\\x1b[2J]"); });+ setTimeout(() => { throw "page-thrown-string[\\x1b[2J]"; });+ setTimeout(() => console.log("%s", "%DONE%"), 100);+};+</script>""".replace(b"%DONE%", DONE.encode())+WORKER = b"""+console.clear();+console.log("worker-log[\\x1b[2J]");+console.group("worker-group[\\r\\x1b[31m]");+console.groupEnd();+console.trace("worker-trace[\\x1b[H]");+postMessage("logged");+"""++# The colors Ladybird gives its own prefixes and labels.+OWN_COLORS = ["\x1b[0m", "\x1b[31;1m", "\x1b[32;1m", "\x1b[36;1m"]++# Each page-chosen string, as its control characters must appear in the output.+EXPECTED = [+ "page-log[\\x1b[2J]",+ "page-warn[\\x1b]0;title\\x07]",+ "page-error[\\x9b2J]",+ "page-group[\\x1b[31m]",+ "page-trace[\\x1b[H]",+ "page-exception[\\x1b[2J]",+ "page-thrown-string[\\x1b[2J]",+ "worker-log[\\x1b[2J]",+ "worker-group[\\x0d\\x1b[31m]",+ "worker-trace[\\x1b[H]",+]+++def is_control_character(character):+ code_point = ord(character)+ return (code_point < 0x20 and character != "\t") or 0x7F <= code_point < 0xA0+++class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-Type", "text/javascript" if self.path == "/worker.js" else "text/html")+ self.end_headers()+ self.wfile.write(WORKER if self.path == "/worker.js" else PAGE)++ def log_message(self, format, *args):+ pass+++def read_output_until_done(process):+ lines = queue.Queue()++ def forward():+ # Read bytes and split them only at newlines: Text mode would turn a carriage return into a newline, and the+ # check below couldn't see it.+ for line in process.stderr:+ lines.put(line.decode("utf-8", errors="surrogateescape"))+ lines.put(None)++ threading.Thread(target=forward, daemon=True).start()+ output = []+ deadline = time.monotonic() + TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ try:+ line = lines.get(timeout=deadline - time.monotonic())+ except queue.Empty:+ break+ if line is None:+ break+ output.append(line)+ if DONE in line:+ return "".join(output)+ sys.stderr.write("".join(output))+ raise AssertionError("the page never logged that it was done")+++def find_failures(output):+ failures = [expected for expected in EXPECTED if expected not in output]+ # The escapes Ladybird adds itself color the prefixes, so look for raw control characters only where the page's+ # strings are.+ for line in output.split("\n"):+ starts = [line.find(tag) for tag in ("page-", "worker-") if tag in line]+ if not starts:+ continue+ payload = line[min(starts) :]+ for own_color in OWN_COLORS:+ payload = payload.replace(own_color, "")+ if any(is_control_character(character) for character in payload):+ failures.append(f"raw control character in: {line!r}")+ if "\x1b[3J" in output or "\x1b[H\x1b[2J" in output:+ failures.append("a worker's console.clear() wrote a clear-screen sequence")+ return failures+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("ladybird_binary")+ ladybird_binary = parser.parse_args().ladybird_binary+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ url = f"http://127.0.0.1:{server.server_port}/page"+ try:+ with tempfile.TemporaryDirectory(prefix="ladybird-console-escapes-") as profile:+ process = subprocess.Popen(+ [ladybird_binary, "--headless=manual", f"--profile-path={profile}", url],+ stderr=subprocess.PIPE,+ )+ try:+ output = read_output_until_done(process)+ finally:+ process.kill()+ process.wait()+ finally:+ server.shutdown()++ failures = find_failures(output)+ if failures:+ sys.stderr.write(output)+ for failure in failures:+ print(f"FAIL: {failure}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())