Skip to content

Truly independent web browser

LibJS: Let the embedder pick the stack frame and native function text

sideshowbarkerb35931f2b038
diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cpp
index c490f0837f1..1b80f72acef 100644
--- a/Libraries/LibJS/Runtime/VM.cpp
+++ b/Libraries/LibJS/Runtime/VM.cpp
@@ -542,6 +542,11 @@ Completion VM::throw_engine_error(EngineErrorKind kind, Utf16String message)
return throw_completion_from_abi(js_error_throw_with_owned_message(vm_abi(*this), to_underlying(kind), owned_utf16_string_to_abi(move(message))));
}
+void VM::set_source_text_syntaxes(StackFrameSyntax stack_frames, NativeFunctionSourceSyntax native_functions)
+{
+ js_vm_set_source_text_syntaxes(vm_abi(*this), to_underlying(stack_frames), to_underlying(native_functions));
+}
+
void VM::set_agent(OwnPtr<Agent> agent)
{
m_agent = move(agent);
diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.h
index 13b2dce0011..740f498c7bc 100644
--- a/Libraries/LibJS/Runtime/VM.h
+++ b/Libraries/LibJS/Runtime/VM.h
@@ -403,6 +403,18 @@ public:
Function<void(Object const&, PropertyKey const&)> on_unimplemented_property_access;
void set_agent(OwnPtr<Agent>);
+
+ // How Error.prototype.stack writes its frames and how Function.prototype.toString writes a built-in function: the
+ // embedder's choice, since scripts read both to tell engines apart.
+ enum class StackFrameSyntax : u8 {
+ Indented, // " at f (url:line:col)", under a "Name: message" line
+ AtSign, // "f@url:line:col", frames only
+ };
+ enum class NativeFunctionSourceSyntax : u8 {
+ SingleLine, // "function f() { [native code] }"
+ MultiLine, // "function f() {\n [native code]\n}"
+ };
+ void set_source_text_syntaxes(StackFrameSyntax, NativeFunctionSourceSyntax);
Agent* agent() { return m_agent; }
Agent const* agent() const { return m_agent; }
diff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rs
index ad78a89f640..6c7b598c50a 100644
--- a/Libraries/LibJS/Rust/src/embedding/vm.rs
+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs
@@ -27,7 +27,9 @@ use crate::layout::value::Value;
use crate::layout::vm::{VM_ALIGN, VM_SIZE};
use crate::runtime::agent::AgentRecord;
use crate::runtime::array_buffer::ArrayBuffer;
+use crate::runtime::error_data::StackFrameSyntax;
use crate::runtime::finalization_registry::FinalizationRegistry;
+use crate::runtime::function_prototype::NativeFunctionSourceSyntax;
use crate::runtime::job_callback::call_job_callback;
// LibJS/Embedding/Layout.h tells an embedder to reserve this much storage for the VM.
@@ -182,6 +184,23 @@ pub unsafe extern "C" fn js_vm_set_embedder(vm: *mut JSVM, hooks: *const JSVmHos
install_embedder(vm, hooks.map(|hooks| Embedder { hooks, data }));
}
+/// Chooses how the VM writes the two strings scripts read to tell engines apart: Error.prototype.stack's frames
+/// (0: indented " at f (url:line:col)", 1: "f@url:line:col") and Function.prototype.toString of a built-in function
+/// (0: on one line, 1: with "[native code]" on a line of its own). Only the VM's thread may call this.
+///
+/// # Safety
+///
+/// `vm` must be a live VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_vm_set_source_text_syntaxes(vm: *mut JSVM, stack_frames: u8, native_functions: u8) {
+ // SAFETY: The caller passes a live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ vm.set_source_text_syntaxes(
+ StackFrameSyntax::from_abi(stack_frames),
+ NativeFunctionSourceSyntax::from_abi(native_functions),
+ );
+}
+
/// Makes `agent` the surrounding agent of the VM: its [[CanBlock]] says whether Atomics.wait() may block, and await in
/// native code spins its event loop until the awaited promise settles. Without an agent, which a null `agent` sets,
/// Atomics.wait() may block and await runs the VM's own queue of promise jobs, which is empty if an enqueue_promise_job
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index b0cce1a38e9..1b9a0e40131 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -62,9 +62,11 @@ use crate::runtime::declarative_environment::DeclarativeEnvironment;
use crate::runtime::ecmascript_function_object::as_ecmascript_function_object;
use crate::runtime::environment_coordinate::EnvironmentCoordinate;
use crate::runtime::error::ErrorKind;
+use crate::runtime::error_data::StackFrameSyntax;
use crate::runtime::error_types::ErrorType;
use crate::runtime::finalization_registry::FinalizationRegistry;
use crate::runtime::function_environment::FunctionEnvironment;
+use crate::runtime::function_prototype::NativeFunctionSourceSyntax;
use crate::runtime::job_callback::{JobCallback, call_job_callback, make_job_callback};
use crate::runtime::json_object::JsonStringifyCache;
use crate::runtime::json_text_parser::JsonParseCache;
@@ -591,6 +593,10 @@ pub struct Vm {
options: VmOptions,
embedder: Cell<Option<Embedder>>,
agent: Cell<AgentRecord>,
+ /// How Error.prototype.stack writes its frames, and how Function.prototype.toString writes a built-in function:
+ /// the embedder's choice, since scripts read both to tell engines apart.
+ stack_frame_syntax: Cell<StackFrameSyntax>,
+ native_function_source_syntax: Cell<NativeFunctionSourceSyntax>,
saved_execution_context_stacks: RefCell<Vec<SavedExecutionContextStack>>,
host_classes: RefCell<HostClassRegistry>,
pub jit: JitState,
@@ -725,6 +731,8 @@ impl Vm {
options,
embedder: Cell::new(None),
agent: Cell::new(AgentRecord::default()),
+ stack_frame_syntax: Cell::new(StackFrameSyntax::default()),
+ native_function_source_syntax: Cell::new(NativeFunctionSourceSyntax::default()),
saved_execution_context_stacks: RefCell::new(Vec::new()),
host_classes: RefCell::new(HashMap::default()),
jit: JitState::new(JitOptions::from_environment()),
@@ -1222,6 +1230,23 @@ impl Vm {
self.agent.set(agent);
}
+ pub fn stack_frame_syntax(&self) -> StackFrameSyntax {
+ self.stack_frame_syntax.get()
+ }
+
+ pub fn native_function_source_syntax(&self) -> NativeFunctionSourceSyntax {
+ self.native_function_source_syntax.get()
+ }
+
+ pub fn set_source_text_syntaxes(
+ &self,
+ stack_frames: StackFrameSyntax,
+ native_functions: NativeFunctionSourceSyntax,
+ ) {
+ self.stack_frame_syntax.set(stack_frames);
+ self.native_function_source_syntax.set(native_functions);
+ }
+
pub fn host_classes(&self) -> &RefCell<HostClassRegistry> {
&self.host_classes
}
diff --git a/Libraries/LibJS/Rust/src/runtime/error_data.rs b/Libraries/LibJS/Rust/src/runtime/error_data.rs
index e7491ca2a3a..d1c12f3d28b 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_data.rs
@@ -41,6 +41,25 @@ pub enum CompactTraceback {
Yes,
}
+/// How a stack string writes each frame: indented, as " at f (url:line:col)", or with an at sign, as
+/// "f@url:line:col". The embedder picks the syntax, since scripts read it to tell engines apart.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum StackFrameSyntax {
+ #[default]
+ Indented = 0,
+ AtSign = 1,
+}
+
+impl StackFrameSyntax {
+ pub fn from_abi(syntax: u8) -> Self {
+ match syntax {
+ 1 => Self::AtSign,
+ _ => Self::Indented,
+ }
+ }
+}
+
/// [[ErrorData]]: the call stack an error was created on.
#[derive(Trace)]
pub struct ErrorData {
@@ -107,16 +126,32 @@ impl ErrorData {
}
pub fn stack_string(&self, compact: CompactTraceback) -> Utf16String {
+ self.stack_string_with_syntax(compact, StackFrameSyntax::Indented)
+ }
+
+ pub fn stack_string_with_syntax(&self, compact: CompactTraceback, syntax: StackFrameSyntax) -> Utf16String {
if self.traceback.is_empty() {
return Utf16String::default();
}
let mut stack_string_builder: Vec<u16> = Vec::new();
- // Note: We roughly follow V8's formatting
let append_frame = |builder: &mut Vec<u16>, frame: &TracebackFrame| {
let function_name = Utf16View::of_string(&frame.function_name);
let (filename, line, column) = frame.source_position();
+ if syntax == StackFrameSyntax::AtSign {
+ // "f@url:line:col", "@url:line:col" for a frame without a name, and "[native code]" in place of a
+ // location for a frame without one.
+ function_name.append_to(builder);
+ builder.push(u16::from(b'@'));
+ if !filename.is_empty() || line != 0 || column != 0 {
+ filename.append_to(builder);
+ builder.extend(format!(":{line}:{column}\n").encode_utf16());
+ } else {
+ builder.extend("[native code]\n".encode_utf16());
+ }
+ return;
+ }
builder.extend(" at ".encode_utf16());
// Note: Since we don't know whether we have a valid SourceRange here we just check for some default values.
if !filename.is_empty() || line != 0 || column != 0 {
diff --git a/Libraries/LibJS/Rust/src/runtime/error_prototype.rs b/Libraries/LibJS/Rust/src/runtime/error_prototype.rs
index e1777cae13f..03f81fb8f73 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_prototype.rs
@@ -14,7 +14,7 @@ use crate::layout::object::Object;
use crate::layout::value::Value;
use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::error::ErrorKind;
-use crate::runtime::error_data::CompactTraceback;
+use crate::runtime::error_data::{CompactTraceback, StackFrameSyntax};
use crate::runtime::error_types::ErrorType;
use crate::runtime::native_function::raw_native;
use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ORDINARY_OBJECT_METHODS, define_object_class};
@@ -182,15 +182,21 @@ impl ErrorPrototype {
])
};
- let stack_string = error_data.stack_string(CompactTraceback::No);
- let string = PrimitiveString::create(
- vm,
- concatenate(&[
- Utf16View::of_string(&header),
- Utf16View::Ascii(b"\n"),
- Utf16View::of_string(&stack_string),
- ]),
- );
+ let syntax = vm.stack_frame_syntax();
+ let stack_string = error_data.stack_string_with_syntax(CompactTraceback::No, syntax);
+ // The at-sign syntax is frames only; the name and message head the indented one.
+ let string = if syntax == StackFrameSyntax::AtSign {
+ PrimitiveString::create(vm, stack_string)
+ } else {
+ PrimitiveString::create(
+ vm,
+ concatenate(&[
+ Utf16View::of_string(&header),
+ Utf16View::Ascii(b"\n"),
+ Utf16View::of_string(&stack_string),
+ ]),
+ )
+ };
error_data.set_cached_string(string);
Ok(Value::from_string(string))
}
diff --git a/Libraries/LibJS/Rust/src/runtime/function_prototype.rs b/Libraries/LibJS/Rust/src/runtime/function_prototype.rs
index 0e15023d51b..266b56136dd 100644
--- a/Libraries/LibJS/Rust/src/runtime/function_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/function_prototype.rs
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use ak::{Utf16FlyString, Utf16String};
+use ak::Utf16String;
use libjs_abi::Builtin;
use libjs_runtime_macros::Trace;
@@ -12,6 +12,32 @@ use crate::gc::class::{GcCell, define_cell};
use crate::gc::root::MarkedVec;
use crate::interpreter::slow_paths::feedback::record_forwarded_call_from_native;
use crate::interpreter::vm::Vm;
+
+/// How Function.prototype.toString writes a built-in function's body: on one line, as "() { [native code] }", or on
+/// three, as "() {\n [native code]\n}". The embedder picks the syntax, since scripts read it to tell engines apart.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum NativeFunctionSourceSyntax {
+ #[default]
+ SingleLine = 0,
+ MultiLine = 1,
+}
+
+impl NativeFunctionSourceSyntax {
+ pub fn from_abi(syntax: u8) -> Self {
+ match syntax {
+ 1 => Self::MultiLine,
+ _ => Self::SingleLine,
+ }
+ }
+
+ fn body(self) -> &'static [u8] {
+ match self {
+ Self::SingleLine => b"() { [native code] }",
+ Self::MultiLine => b"() {\n [native code]\n}",
+ }
+ }
+}
use crate::layout::cell::Gc;
use crate::layout::execution_context::ExecutionContext;
use crate::layout::feedback::CallFeedbackForwarding;
@@ -412,16 +438,19 @@ impl FunctionPrototype {
concatenate(&[
Utf16View::Ascii(b"function "),
Utf16View::of_fly_string(&name),
- Utf16View::Ascii(b"() { [native code] }"),
+ Utf16View::Ascii(vm.native_function_source_syntax().body()),
]),
)));
}
// 4. If Type(func) is Object and IsCallable(func) is true, return an implementation-defined String source code representation of func. The representation must have the syntax of a NativeFunction.
// NOTE: ProxyObject, BoundFunction, WrappedFunction
- Ok(Value::from_string(PrimitiveString::create_from_fly_string(
+ Ok(Value::from_string(PrimitiveString::create(
vm,
- &Utf16FlyString::from_utf8("function () { [native code] }"),
+ concatenate(&[
+ Utf16View::Ascii(b"function "),
+ Utf16View::Ascii(vm.native_function_source_syntax().body()),
+ ]),
)))
}
diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cpp
index 0990c258ce6..10aa14deded 100644
--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp
+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp
@@ -16,6 +16,7 @@
#include <LibRequests/Request.h>
#include <LibRequests/RequestClient.h>
#include <LibURL/Parser.h>
+#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/URL.h>
@@ -85,6 +86,14 @@ NavigatorCompatibilityMode ResourceLoader::s_navigator_compatibility_mode = defa
void ResourceLoader::set_navigator_compatibility_mode(NavigatorCompatibilityMode mode)
{
s_navigator_compatibility_mode = mode;
+
+ // A script reads two strings to tell engines apart that no navigator attribute covers: the frames of an error's
+ // stack, and the source text of a built-in function. Both follow the engine the navigator claims.
+ auto& vm = Bindings::main_thread_vm();
+ if (mode == NavigatorCompatibilityMode::Chrome)
+ vm.set_source_text_syntaxes(JS::VM::StackFrameSyntax::Indented, JS::VM::NativeFunctionSourceSyntax::SingleLine);
+ else
+ vm.set_source_text_syntaxes(JS::VM::StackFrameSyntax::AtSign, JS::VM::NativeFunctionSourceSyntax::MultiLine);
}
void ResourceLoader::set_client(NonnullRefPtr<Requests::RequestClient> request_client)
diff --git a/Tests/LibWeb/Text/expected/navigator-compatibility-mode-source-text.txt b/Tests/LibWeb/Text/expected/navigator-compatibility-mode-source-text.txt
new file mode 100644
index 00000000000..4723dfbc947
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/navigator-compatibility-mode-source-text.txt
@@ -0,0 +1,9 @@
+chrome: stack "Error: boom\n at inner (<url>)\n at <url>\n"
+chrome: XMLDocument "function XMLDocument() { [native code] }"
+chrome: bound "function () { [native code] }"
+gecko: stack "inner@<url>\n@<url>\n"
+gecko: XMLDocument "function XMLDocument() {\n [native code]\n}"
+gecko: bound "function () {\n [native code]\n}"
+webkit: stack "inner@<url>\n@<url>\n"
+webkit: XMLDocument "function XMLDocument() {\n [native code]\n}"
+webkit: bound "function () {\n [native code]\n}"
diff --git a/Tests/LibWeb/Text/input/navigator-compatibility-mode-source-text.html b/Tests/LibWeb/Text/input/navigator-compatibility-mode-source-text.html
new file mode 100644
index 00000000000..b40d726f7d5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/navigator-compatibility-mode-source-text.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<script>
+ // The two strings a script reads to tell engines apart that no navigator attribute covers follow the engine the
+ // navigator claims: the frames of an error's stack, and the source text of a built-in function.
+ test(() => {
+ function inner() { return new Error("boom").stack; }
+ const shape = stack => JSON.stringify(stack.replace(/(file|blob|http)[^\s)]+/g, "<url>"));
+ try {
+ for (const mode of ["chrome", "gecko", "webkit"]) {
+ internals.setNavigatorCompatibilityMode(mode);
+ println(`${mode}: stack ${shape(inner())}`);
+ println(`${mode}: XMLDocument ${JSON.stringify(XMLDocument.toString())}`);
+ println(`${mode}: bound ${JSON.stringify(inner.bind(null).toString())}`);
+ }
+ } finally {
+ internals.setNavigatorCompatibilityMode("chrome");
+ }
+ });
+</script>