Truly independent web browser
LibJS: Run the agents of test262 tests on threads
Andreas Kling76eeb8b75ce3
diff --git a/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rsindex b7e29006089..0c439102c1c 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs@@ -21,7 +21,7 @@ use crate::runtime::realm::Realm;#[cfg(unix)]use {- crate::contrib::test262::agents::{self, AgentFailure, AgentRole, BroadcastNumber},+ crate::contrib::test262::agents::{self, AgentFailure, AgentRole, Broadcast, BroadcastNumber},crate::runtime::abstract_operations::call,crate::runtime::array_buffer::{ArrayBuffer, DataBlockStorage},crate::runtime::big_int::{BigInt, SignedBigInteger},@@ -67,7 +67,6 @@ impl AgentObject {define("monotonicNow", raw_native!(AgentObject::monotonic_now), 0);define("sleep", raw_native!(AgentObject::sleep), 1);- // Agents run in processes of their own, which only Unix hosts set up.#[cfg(unix)]match agents::role() {AgentRole::Test => {@@ -149,12 +148,15 @@ impl AgentObject {"Agents cannot map a SharedArrayBuffer that is not in shared memory".to_string(),);};- agents::broadcast(- shared_memory.as_fd(),- shared_array_buffer.byte_length(),- object_id,- &number,- );+ let byte_length = shared_array_buffer.byte_length();+ agents::broadcast(|| {+ Ok(Broadcast {+ shared_memory: shared_memory.as_fd().try_clone_to_owned()?,+ byte_length,+ object_id,+ number: number.clone(),+ })+ });Ok(Value::UNDEFINED)}@@ -175,7 +177,6 @@ impl AgentObject {Err(AgentFailure::UncaughtException { name, message }) => {vm.throw_completion_with_message(ErrorKind::Error, format!("An agent threw {name}: {message}"))}- Err(AgentFailure::Panic(message) | AgentFailure::Exited(message)) => panic!("{message}"),}}@@ -188,7 +189,9 @@ impl AgentObject {);}- let broadcast = agents::receive_broadcast();+ let Some(broadcast) = agents::receive_broadcast() else {+ return vm.throw_interrupt();+ };let realm = vm.current_realm().expect("$262.agent.receiveBroadcast() runs in a realm");diff --git a/Libraries/LibJS/Rust/src/contrib/test262/agents.rs b/Libraries/LibJS/Rust/src/contrib/test262/agents.rsindex 33b96464a1c..91284502fd7 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/agents.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/agents.rs@@ -4,51 +4,24 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The processes behind $262.agent, as test262's INTERPRETING.md describes it.+//! The threads behind $262.agent, as test262's INTERPRETING.md describes it.//!-//! A LibGC heap belongs to one thread, so every agent a test starts is a child process: the tool runs again in agent-//! mode, with a VM of its own. Each agent has a Unix domain socket to the test, which sends it its source and then the-//! broadcasts, passing the shared memory of a SharedArrayBuffer with SCM_RIGHTS. The agent answers on the socket once-//! it is running and whenever a broadcast reaches it. Reports from all of a test's agents share one pipe, so the test-//! reads them in the order the agents wrote them. An agent exits when the test's end of its socket closes, so no agent-//! outlives the test that started it, even when the test is killed for running too long.--use core::ffi::c_int;+//! Every agent a test starts is a thread with a VM of its own, in the process of the test, as agents that share memory+//! have to be: Atomics.wait() and Atomics.notify() meet in the waiter lists of the process. The test hands an agent its+//! source, and then the broadcasts. Reports from all of a test's agents share one queue, so the test reads them in the+//! order the agents made them. Ending the test interrupts its agents and joins their threads, so no agent outlives the+//! test that started it.+use std::cell::RefCell;-use std::collections::{HashMap, VecDeque};-use std::ffi::OsString;-use std::fs::File;-use std::io::{Read, Write};-use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};-use std::os::unix::net::UnixStream;-use std::os::unix::process::ExitStatusExt;-use std::path::PathBuf;-use std::process::{Child, Command, Stdio};-use std::sync::{Condvar, Mutex, OnceLock, PoisonError};--const SOURCE_MESSAGE: u8 = 1;-const BROADCAST_MESSAGE: u8 = 2;-const AGENT_STARTED_ACKNOWLEDGEMENT: u8 = 3;-const BROADCAST_RECEIVED_ACKNOWLEDGEMENT: u8 = 4;--const UNDEFINED_BROADCAST_NUMBER: u8 = 0;-const NUMBER_BROADCAST_NUMBER: u8 = 1;-const BIGINT_BROADCAST_NUMBER: u8 = 2;--const REPORT_FRAME: u8 = 0;-const UNCAUGHT_EXCEPTION_FRAME: u8 = 1;-const PANIC_FRAME: u8 = 2;--/// _POSIX_PIPE_BUF: the most a write to a pipe may hold and still never interleave with what other agents write.-const ATOMIC_PIPE_WRITE_SIZE: usize = 512;-/// The agent's index, the frame kind, whether the frame ends its message, and the length of what follows.-const FRAME_HEADER_SIZE: usize = 4 + 1 + 1 + 2;-const FRAME_PAYLOAD_LIMIT: usize = ATOMIC_PIPE_WRITE_SIZE - FRAME_HEADER_SIZE;--#[cfg(target_vendor = "apple")]-const SEND_FLAGS: c_int = 0;-#[cfg(not(target_vendor = "apple"))]-const SEND_FLAGS: c_int = libc::MSG_NOSIGNAL;+use std::collections::VecDeque;+use std::os::fd::OwnedFd;+use std::sync::{Arc, Condvar, Mutex, PoisonError};+use std::thread::JoinHandle;++use crate::interpreter::vm::Vm;++/// JS::VM::MINIMUM_THREAD_STACK_SIZE, which the thread of a VM needs.+const AGENT_THREAD_STACK_SIZE: usize = 8 * 1024 * 1024;/// The number that $262.agent.broadcast() passes along with its SharedArrayBuffer.#[derive(Clone, Debug, PartialEq)]@@ -73,11 +46,9 @@ pub struct Broadcast {#[derive(Clone, Debug, PartialEq)]pub enum AgentFailure {UncaughtException { name: String, message: String },- Panic(String),- Exited(String),}-/// Which half of $262.agent this process provides.+/// Which half of $262.agent this thread provides.#[derive(Clone, Copy, PartialEq, Eq)]pub enum AgentRole {/// Neither: the tool did not set up agents.@@ -89,512 +60,142 @@ pub enum AgentRole {}pub fn role() -> AgentRole {- if TEST_CONNECTION.get().is_some() {+ if THIS_AGENT.with_borrow(Option::is_some) {return AgentRole::Agent;}- if AGENT_LAUNCHER.with_borrow(Option::is_some) {+ if AGENT_ENTRY.get().is_some() {return AgentRole::Test;}AgentRole::Unavailable}-/// How to run this tool in agent mode.-struct AgentLauncher {- program: PathBuf,- arguments: Vec<OsString>,-}+/// What the thread of an agent runs, with the WTF-8 source of the agent's script.+pub type AgentEntry = fn(&[u8]);thread_local! {- static AGENT_LAUNCHER: RefCell<Option<AgentLauncher>> = const { RefCell::new(None) };+ static AGENT_ENTRY: core::cell::Cell<Option<AgentEntry>> = const { core::cell::Cell::new(None) };static RUNNING_AGENTS: RefCell<RunningAgents> = RefCell::new(RunningAgents::default());+ static THIS_AGENT: RefCell<Option<Arc<Agent>>> = const { RefCell::new(None) };}-/// Lets tests start agents, each of which runs `program` with `arguments`, which must make it call connect_to_test().-pub fn enable_agents(program: PathBuf, arguments: Vec<OsString>) {- AGENT_LAUNCHER.set(Some(AgentLauncher { program, arguments }));-}--fn send_all(socket: BorrowedFd<'_>, mut bytes: &[u8]) -> std::io::Result<()> {- while !bytes.is_empty() {- // SAFETY: The bytes are valid for their length.- let sent = unsafe { libc::send(socket.as_raw_fd(), bytes.as_ptr().cast(), bytes.len(), SEND_FLAGS) };- if sent < 0 {- let error = std::io::Error::last_os_error();- if error.kind() == std::io::ErrorKind::Interrupted {- continue;- }- return Err(error);- }- bytes = &bytes[sent.cast_unsigned()..];- }- Ok(())-}--/// Sends `bytes` with a duplicate of `descriptor` attached to the first of them.-fn send_with_descriptor(socket: BorrowedFd<'_>, bytes: &[u8], descriptor: BorrowedFd<'_>) -> std::io::Result<()> {- let mut control_buffer = [0u64; 4];- let mut io_vector = libc::iovec {- iov_base: bytes.as_ptr().cast_mut().cast(),- iov_len: bytes.len(),- };- // SAFETY: An all-zero msghdr is an empty message.- let mut message: libc::msghdr = unsafe { core::mem::zeroed() };- message.msg_iov = &raw mut io_vector;- message.msg_iovlen = 1;- message.msg_control = control_buffer.as_mut_ptr().cast();- let descriptor_size = size_of::<c_int>() as u32;- // SAFETY: CMSG_SPACE only computes a size.- message.msg_controllen = unsafe { libc::CMSG_SPACE(descriptor_size) } as _;- // SAFETY: The control buffer has room for one control message with one descriptor, which this fills in.- unsafe {- let header = libc::CMSG_FIRSTHDR(&raw const message);- (*header).cmsg_level = libc::SOL_SOCKET;- (*header).cmsg_type = libc::SCM_RIGHTS;- (*header).cmsg_len = libc::CMSG_LEN(descriptor_size) as _;- libc::CMSG_DATA(header)- .cast::<c_int>()- .write_unaligned(descriptor.as_raw_fd());- }- let sent = loop {- // SAFETY: The message describes the bytes and the control buffer, which are all live.- let sent = unsafe { libc::sendmsg(socket.as_raw_fd(), &raw const message, SEND_FLAGS) };- if sent >= 0 {- break sent.cast_unsigned();- }- let error = std::io::Error::last_os_error();- if error.kind() != std::io::ErrorKind::Interrupted {- return Err(error);- }- };- send_all(socket, &bytes[sent..])+/// Lets tests on this thread start agents, each of which runs `entry` on a thread of its own.+pub fn enable_agents(entry: AgentEntry) {+ AGENT_ENTRY.set(Some(entry));}-/// Keeps a write to a socket whose peer is gone from raising SIGPIPE, where send() has no flag for that.-#[cfg_attr(not(target_vendor = "apple"), allow(clippy::unnecessary_wraps))]-fn never_raise_sigpipe(socket: &UnixStream) -> std::io::Result<()> {- #[cfg(target_vendor = "apple")]- {- let enabled: c_int = 1;- // SAFETY: The option value is a c_int that outlives the call.- let result = unsafe {- libc::setsockopt(- socket.as_raw_fd(),- libc::SOL_SOCKET,- libc::SO_NOSIGPIPE,- (&raw const enabled).cast(),- size_of::<c_int>() as libc::socklen_t,- )- };- if result != 0 {- return Err(std::io::Error::last_os_error());- }- }- #[cfg(not(target_vendor = "apple"))]- let _ = socket;- Ok(())-}--/// What the test sends an agent.-#[derive(Debug)]-enum ControlMessage {- Source { agent_index: u32, source: Vec<u8> },- Broadcast(Broadcast),-}--fn encode_source_message(agent_index: u32, source: &[u8]) -> Vec<u8> {- let mut message = vec![SOURCE_MESSAGE];- message.extend_from_slice(&agent_index.to_le_bytes());- message.extend_from_slice(- &u32::try_from(source.len())- .expect("an agent's source fits in u32")- .to_le_bytes(),- );- message.extend_from_slice(source);- message-}--/// A broadcast without its shared memory, which goes along as a descriptor.-fn encode_broadcast_message(byte_length: usize, object_id: u64, number: &BroadcastNumber) -> Vec<u8> {- let mut message = vec![BROADCAST_MESSAGE];- message.extend_from_slice(&(byte_length as u64).to_le_bytes());- message.extend_from_slice(&object_id.to_le_bytes());- match number {- BroadcastNumber::Undefined => message.push(UNDEFINED_BROADCAST_NUMBER),- BroadcastNumber::Number(number) => {- message.push(NUMBER_BROADCAST_NUMBER);- message.extend_from_slice(&number.to_bits().to_le_bytes());- }- BroadcastNumber::BigInt(bytes) => {- message.push(BIGINT_BROADCAST_NUMBER);- message.extend_from_slice(&u32::try_from(bytes.len()).expect("a BigInt fits in u32").to_le_bytes());- message.extend_from_slice(bytes);- }- }- message-}--/// Reads the messages of the test from an agent's socket, with the descriptors that came along.-#[derive(Debug)]-struct ControlReader {- socket: OwnedFd,- unread_bytes: VecDeque<u8>,- received_descriptors: VecDeque<OwnedFd>,-}--impl ControlReader {- fn new(socket: OwnedFd) -> Self {- Self {- socket,- unread_bytes: VecDeque::new(),- received_descriptors: VecDeque::new(),- }- }-- fn receive_more(&mut self) -> std::io::Result<()> {- let mut buffer = [0u8; 4096];- let mut control_buffer = [0u64; 32];- let mut io_vector = libc::iovec {- iov_base: buffer.as_mut_ptr().cast(),- iov_len: buffer.len(),- };- // SAFETY: An all-zero msghdr is an empty message.- let mut message: libc::msghdr = unsafe { core::mem::zeroed() };- message.msg_iov = &raw mut io_vector;- message.msg_iovlen = 1;- message.msg_control = control_buffer.as_mut_ptr().cast();- message.msg_controllen = size_of_val(&control_buffer) as _;- let received = loop {- // SAFETY: The message describes the buffers, which are live and writable.- let received = unsafe { libc::recvmsg(self.socket.as_raw_fd(), &raw mut message, 0) };- if received >= 0 {- break received.cast_unsigned();- }- let error = std::io::Error::last_os_error();- if error.kind() != std::io::ErrorKind::Interrupted {- return Err(error);- }- };-- // SAFETY: recvmsg() filled in the control messages that the walk visits, and the kernel installed the- // descriptors of SCM_RIGHTS ones in this process, which now owns them.- unsafe {- let mut header = libc::CMSG_FIRSTHDR(&raw const message);- while !header.is_null() {- if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS {- let data = libc::CMSG_DATA(header);- #[allow(clippy::unnecessary_cast, reason = "cmsg_len is a socklen_t on some platforms")]- let data_length =- (*header).cmsg_len as usize - data.offset_from(header.cast::<u8>()).cast_unsigned();- for index in 0..data_length / size_of::<c_int>() {- let descriptor = data.cast::<c_int>().add(index).read_unaligned();- self.received_descriptors.push_back(OwnedFd::from_raw_fd(descriptor));- }- }- header = libc::CMSG_NXTHDR(&raw const message, header);- }- }-- if received == 0 {- return Err(std::io::ErrorKind::UnexpectedEof.into());- }- self.unread_bytes.extend(&buffer[..received]);- Ok(())- }-- fn read_bytes<const COUNT: usize>(&mut self) -> std::io::Result<[u8; COUNT]> {- let mut bytes = [0u8; COUNT];- self.read_into(&mut bytes)?;- Ok(bytes)- }-- fn read_into(&mut self, bytes: &mut [u8]) -> std::io::Result<()> {- while self.unread_bytes.len() < bytes.len() {- self.receive_more()?;- }- for byte in bytes {- *byte = self.unread_bytes.pop_front().expect("enough bytes were received");- }- Ok(())- }-- fn read_vector(&mut self, length: usize) -> std::io::Result<Vec<u8>> {- let mut bytes = vec![0u8; length];- self.read_into(&mut bytes)?;- Ok(bytes)- }-- fn read_message(&mut self) -> std::io::Result<ControlMessage> {- let invalid_data = || std::io::Error::from(std::io::ErrorKind::InvalidData);- match self.read_bytes::<1>()?[0] {- SOURCE_MESSAGE => {- let agent_index = u32::from_le_bytes(self.read_bytes()?);- let length = u32::from_le_bytes(self.read_bytes()?);- let source = self.read_vector(length as usize)?;- Ok(ControlMessage::Source { agent_index, source })- }- BROADCAST_MESSAGE => {- let byte_length =- usize::try_from(u64::from_le_bytes(self.read_bytes()?)).map_err(|_| invalid_data())?;- let object_id = u64::from_le_bytes(self.read_bytes()?);- let number = match self.read_bytes::<1>()?[0] {- UNDEFINED_BROADCAST_NUMBER => BroadcastNumber::Undefined,- NUMBER_BROADCAST_NUMBER => {- BroadcastNumber::Number(f64::from_bits(u64::from_le_bytes(self.read_bytes()?)))- }- BIGINT_BROADCAST_NUMBER => {- let length = u32::from_le_bytes(self.read_bytes()?);- BroadcastNumber::BigInt(self.read_vector(length as usize)?)- }- _ => return Err(invalid_data()),- };- // The descriptor came with the first byte of the message.- let shared_memory = self.received_descriptors.pop_front().ok_or_else(invalid_data)?;- Ok(ControlMessage::Broadcast(Broadcast {- shared_memory,- byte_length,- object_id,- number,- }))- }- _ => Err(invalid_data()),- }- }-}--/// Splits a message into frames that each fit into one atomic write to the report pipe.-fn encode_frames(agent_index: u32, kind: u8, payload: &[u8]) -> Vec<Vec<u8>> {- let mut chunks: Vec<&[u8]> = payload.chunks(FRAME_PAYLOAD_LIMIT).collect();- if chunks.is_empty() {- chunks.push(&[]);- }- let last_index = chunks.len() - 1;- chunks- .into_iter()- .enumerate()- .map(|(index, chunk)| {- let mut frame = Vec::with_capacity(FRAME_HEADER_SIZE + chunk.len());- frame.extend_from_slice(&agent_index.to_le_bytes());- frame.push(kind);- frame.push(u8::from(index == last_index));- frame.extend_from_slice(&u16::try_from(chunk.len()).expect("a frame fits in u16").to_le_bytes());- frame.extend_from_slice(chunk);- frame- })- .collect()-}--fn encode_uncaught_exception(name: &str, message: &str) -> Vec<u8> {- let mut payload = u32::try_from(name.len()).unwrap_or(u32::MAX).to_le_bytes().to_vec();- payload.extend_from_slice(name.as_bytes());- payload.extend_from_slice(message.as_bytes());- payload-}--fn decode_uncaught_exception(payload: &[u8]) -> AgentFailure {- let name_length = payload- .first_chunk::<4>()- .map_or(0, |length| u32::from_le_bytes(*length) as usize)- .min(payload.len().saturating_sub(4));- let (name, message) = payload.get(4..).unwrap_or_default().split_at(name_length);- AgentFailure::UncaughtException {- name: String::from_utf8_lossy(name).into_owned(),- message: String::from_utf8_lossy(message).into_owned(),- }-}--/// Puts the frames that agents wrote to the report pipe back together into messages, in the order their last frames-/// arrived.+/// What the agents of a test report, in the order they did.#[derive(Default)]-struct ReportAssembler {- unparsed_bytes: Vec<u8>,- partial_messages: HashMap<u32, Vec<u8>>,+struct Reports {reports: VecDeque<Vec<u8>>,failures: Vec<AgentFailure>,}-impl ReportAssembler {- fn push_bytes(&mut self, bytes: &[u8]) {- self.unparsed_bytes.extend_from_slice(bytes);- let mut offset = 0;- while let Some(header) = self.unparsed_bytes[offset..].first_chunk::<FRAME_HEADER_SIZE>() {- let agent_index = u32::from_le_bytes([header[0], header[1], header[2], header[3]]);- let kind = header[4];- let is_last_frame = header[5] != 0;- let payload_length = usize::from(u16::from_le_bytes([header[6], header[7]]));- let frame_end = offset + FRAME_HEADER_SIZE + payload_length;- if frame_end > self.unparsed_bytes.len() {- break;- }- let payload = &self.unparsed_bytes[offset + FRAME_HEADER_SIZE..frame_end];- let message = self.partial_messages.entry(agent_index).or_default();- message.extend_from_slice(payload);- if is_last_frame {- let message = self.partial_messages.remove(&agent_index).unwrap_or_default();- match kind {- REPORT_FRAME => self.reports.push_back(message),- UNCAUGHT_EXCEPTION_FRAME => self.failures.push(decode_uncaught_exception(&message)),- _ => self.failures.push(AgentFailure::Panic(format!(- "Agent {agent_index} panicked: {}",- String::from_utf8_lossy(&message)- ))),- }- }- offset = frame_end;- }- self.unparsed_bytes.drain(..offset);- }-}--struct RunningAgent {- process: Child,- socket: UnixStream,- exit_was_reported: bool,-}--impl RunningAgent {- fn wait_for_acknowledgement(&mut self, acknowledgement: u8) -> std::io::Result<()> {- loop {- let mut byte = [0u8; 1];- self.socket.read_exact(&mut byte)?;- if byte[0] == acknowledgement {- return Ok(());- }- }+#[derive(Default)]+struct AgentState {+ broadcasts: VecDeque<Broadcast>,+ is_running: bool,+ has_finished: bool,+ is_terminated: bool,+ /// The VM of the agent's thread, for as long as the thread has one.+ vm: Option<*const Vm>,+}++// SAFETY: The VM pointer goes away under the lock before its VM does, and is only used to call Vm::request_interrupt(),+// which any thread may call.+unsafe impl Send for AgentState {}++/// The state a test and one of its agents share.+struct Agent {+ state: Mutex<AgentState>,+ state_changed: Condvar,+ reports: Arc<Mutex<Reports>>,+}++impl Agent {+ fn update<R>(&self, update: impl FnOnce(&mut AgentState) -> R) -> R {+ let result = update(&mut self.state.lock().unwrap_or_else(PoisonError::into_inner));+ self.state_changed.notify_all();+ result}- /// Why the agent is gone, if it went in a way that it could not report.- fn unreported_exit(&mut self, agent_index: usize) -> Option<AgentFailure> {- if self.exit_was_reported {- return None;- }- let status = self.process.try_wait().ok()??;- if status.success() {- return None;+ fn wait_until_running(&self) {+ let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);+ while !state.is_running && !state.has_finished {+ state = self.state_changed.wait(state).unwrap_or_else(PoisonError::into_inner);}- self.exit_was_reported = true;- let description = match status.signal() {- Some(signal) => format!("Agent {agent_index} was terminated by signal {signal}"),- None => format!("Agent {agent_index} exited with {status}"),- };- Some(AgentFailure::Exited(description))}-}-/// The pipe that all agents of a test write their reports to.-struct ReportPipe {- reader: File,- writer: OwnedFd,- assembler: ReportAssembler,-}--impl ReportPipe {- fn create() -> std::io::Result<Self> {- let (reader, writer) = std::io::pipe()?;- let reader = File::from(OwnedFd::from(reader));- // SAFETY: Only changes the status flags of the pipe's read end.- unsafe {- let flags = libc::fcntl(reader.as_raw_fd(), libc::F_GETFL);- if flags < 0 || libc::fcntl(reader.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {- return Err(std::io::Error::last_os_error());+ fn terminate(&self) {+ self.update(|state| {+ state.is_terminated = true;+ if let Some(vm) = state.vm {+ // SAFETY: The agent's thread clears the pointer under the lock this holds before the VM goes away.+ unsafe { (*vm).request_interrupt() };}- }- Ok(Self {- reader,- writer: writer.into(),- assembler: ReportAssembler::default(),- })+ });}+}- fn read_available_frames(&mut self) {- let mut buffer = [0u8; 4096];- loop {- match self.reader.read(&mut buffer) {- Ok(0) => return,- Ok(count) => self.assembler.push_bytes(&buffer[..count]),- Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}- Err(_) => return,- }- }- }+/// An agent as the test sees it.+struct RunningAgent {+ agent: Arc<Agent>,+ thread: JoinHandle<()>,}/// The agents that the running test started.#[derive(Default)]struct RunningAgents {agents: Vec<RunningAgent>,- report_pipe: Option<ReportPipe>,- /// How many of the failures in the report pipe getReport() has thrown.+ reports: Arc<Mutex<Reports>>,+ /// How many of the failures in the reports getReport() has thrown.thrown_failure_count: usize,}impl RunningAgents {- fn start(&mut self, launcher: &AgentLauncher, source: &[u8]) -> std::io::Result<()> {- let report_pipe = match &mut self.report_pipe {- Some(report_pipe) => report_pipe,- None => self.report_pipe.insert(ReportPipe::create()?),- };- let (test_socket, agent_socket) = UnixStream::pair()?;- never_raise_sigpipe(&test_socket)?;- let agent_index = u32::try_from(self.agents.len()).expect("a test starts fewer than 2^32 agents");- let process = Command::new(&launcher.program)- .args(&launcher.arguments)- .stdin(Stdio::from(OwnedFd::from(agent_socket)))- .stdout(Stdio::from(report_pipe.writer.try_clone()?))- .stderr(Stdio::inherit())- .spawn()?;- self.agents.push(RunningAgent {- process,- socket: test_socket,- exit_was_reported: false,+ fn start(&mut self, entry: AgentEntry, source: &[u8]) -> std::io::Result<()> {+ let agent = Arc::new(Agent {+ state: Mutex::default(),+ state_changed: Condvar::new(),+ reports: Arc::clone(&self.reports),});- let agent = self.agents.last_mut().expect("the agent was just added");- send_all(agent.socket.as_fd(), &encode_source_message(agent_index, source))?;- agent.wait_for_acknowledgement(AGENT_STARTED_ACKNOWLEDGEMENT)+ let agent_of_thread = Arc::clone(&agent);+ let source = source.to_vec();+ let thread = std::thread::Builder::new()+ .name("test262 agent".to_string())+ .stack_size(AGENT_THREAD_STACK_SIZE)+ .spawn(move || {+ THIS_AGENT.set(Some(Arc::clone(&agent_of_thread)));+ entry(&source);+ THIS_AGENT.set(None);+ agent_of_thread.update(|state| state.has_finished = true);+ })?;+ agent.wait_until_running();+ self.agents.push(RunningAgent { agent, thread });+ Ok(())}- fn broadcast(- &mut self,- shared_memory: BorrowedFd<'_>,- byte_length: usize,- object_id: u64,- number: &BroadcastNumber,- ) {- let message = encode_broadcast_message(byte_length, object_id, number);- let mut receiving_agents = Vec::new();- for (index, agent) in self.agents.iter().enumerate() {+ fn broadcast(&mut self, broadcast: impl Fn() -> std::io::Result<Broadcast>) {+ for agent in &self.agents {// An agent that already exited cannot take the message, and the test cannot expect it to.- if send_with_descriptor(agent.socket.as_fd(), &message, shared_memory).is_ok() {- receiving_agents.push(index);- }- }- for index in receiving_agents {- let _ = self.agents[index].wait_for_acknowledgement(BROADCAST_RECEIVED_ACKNOWLEDGEMENT);+ let Ok(broadcast) = broadcast() else {+ continue;+ };+ agent.agent.update(|state| {+ if !state.has_finished {+ state.broadcasts.push_back(broadcast);+ }+ });}}fn take_report(&mut self) -> Result<Option<Vec<u8>>, AgentFailure> {- let Some(report_pipe) = &mut self.report_pipe else {- return Ok(None);- };- report_pipe.read_available_frames();- if let Some(report) = report_pipe.assembler.reports.pop_front() {+ let mut reports = self.reports.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(report) = reports.reports.pop_front() {return Ok(Some(report));}// With nothing to report, tell the test whether an agent failed, which would leave it waiting forever.- let unreported_exits: Vec<AgentFailure> = self- .agents- .iter_mut()- .enumerate()- .filter_map(|(index, agent)| agent.unreported_exit(index))- .collect();- // What an agent wrote before it exited is in the pipe by now, and comes before its exit.- report_pipe.read_available_frames();- if let Some(report) = report_pipe.assembler.reports.pop_front() {- return Ok(Some(report));- }- report_pipe.assembler.failures.extend(unreported_exits);- let Some(failure) = report_pipe.assembler.failures.get(self.thrown_failure_count) else {+ let Some(failure) = reports.failures.get(self.thrown_failure_count) else {return Ok(None);};self.thrown_failure_count += 1;@@ -604,20 +205,15 @@ impl RunningAgents {/// $262.agent.start(): runs `source`, the WTF-8 of a script, in a new agent and returns once the agent is running.pub fn start_agent(source: &[u8]) -> Result<(), String> {- AGENT_LAUNCHER.with_borrow(|launcher| {- let launcher = launcher.as_ref().ok_or("Agents are unavailable")?;- RUNNING_AGENTS- .with_borrow_mut(|running_agents| running_agents.start(launcher, source))- .map_err(|error| format!("Could not start an agent: {error}"))- })+ let entry = AGENT_ENTRY.get().ok_or("Agents are unavailable")?;+ RUNNING_AGENTS+ .with_borrow_mut(|running_agents| running_agents.start(entry, source))+ .map_err(|error| format!("Could not start an agent: {error}"))}-/// $262.agent.broadcast(): hands a SharedArrayBuffer's shared memory and `number` to every running agent, and returns-/// once each has them.-pub fn broadcast(shared_memory: BorrowedFd<'_>, byte_length: usize, object_id: u64, number: &BroadcastNumber) {- RUNNING_AGENTS.with_borrow_mut(|running_agents| {- running_agents.broadcast(shared_memory, byte_length, object_id, number);- });+/// $262.agent.broadcast(): hands every running agent what `broadcast` makes for it, and returns once each has it.+pub fn broadcast(broadcast: impl Fn() -> std::io::Result<Broadcast>) {+ RUNNING_AGENTS.with_borrow_mut(|running_agents| running_agents.broadcast(broadcast));}/// $262.agent.getReport(): the next report of any agent, which is WTF-8, or None if there is none yet. Fails instead of@@ -630,134 +226,77 @@ pub fn take_report() -> Result<Option<Vec<u8>>, AgentFailure> {/// or not.pub fn terminate_agents() -> Vec<AgentFailure> {let running_agents = RUNNING_AGENTS.take();- let failures = running_agents- .report_pipe- .map(|mut report_pipe| {- report_pipe.read_available_frames();- report_pipe.assembler.failures- })- .unwrap_or_default();- for mut agent in running_agents.agents {- let _ = agent.process.kill();- let _ = agent.process.wait();- }- failures-}--/// An agent's side of the connection to the test that started it.-struct TestConnection {- agent_index: u32,- socket: OwnedFd,- report_pipe: File,- broadcasts: Mutex<VecDeque<Broadcast>>,- broadcast_arrived: Condvar,-}--static TEST_CONNECTION: OnceLock<TestConnection> = OnceLock::new();--/// Moves a descriptor that the test handed down out of the way of the standard streams, and puts /dev/null there.-fn take_inherited_descriptor(descriptor: RawFd) -> std::io::Result<OwnedFd> {- // SAFETY: Duplicates a descriptor this process inherited; the duplicate is owned here.- let duplicate = unsafe { libc::fcntl(descriptor, libc::F_DUPFD_CLOEXEC, 3) };- if duplicate < 0 {- return Err(std::io::Error::last_os_error());- }- // SAFETY: fcntl() just created the descriptor.- let duplicate = unsafe { OwnedFd::from_raw_fd(duplicate) };- let null = File::options().read(true).write(true).open("/dev/null")?;- // SAFETY: Replaces the inherited descriptor, which nothing else owns.- if unsafe { libc::dup2(null.as_raw_fd(), descriptor) } < 0 {- return Err(std::io::Error::last_os_error());+ let failures = core::mem::take(+ &mut running_agents+ .reports+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .failures,+ );+ for running_agent in &running_agents.agents {+ running_agent.agent.terminate();}- Ok(duplicate)-}--/// Agent mode: connects to the test that started this process, which passed it the socket as standard input and the-/// report pipe as standard output, and returns the WTF-8 source of the agent's script.-pub fn connect_to_test() -> std::io::Result<Vec<u8>> {- let socket = take_inherited_descriptor(libc::STDIN_FILENO)?;- let report_pipe = take_inherited_descriptor(libc::STDOUT_FILENO)?;- let mut reader = ControlReader::new(socket.try_clone()?);- let ControlMessage::Source { agent_index, source } = reader.read_message()? else {- return Err(std::io::ErrorKind::InvalidData.into());- };- let connection = TestConnection {- agent_index,- socket,- report_pipe: report_pipe.into(),- broadcasts: Mutex::new(VecDeque::new()),- broadcast_arrived: Condvar::new(),- };- if TEST_CONNECTION.set(connection).is_err() {- return Err(std::io::ErrorKind::AlreadyExists.into());+ for running_agent in running_agents.agents {+ let _ = running_agent.thread.join();}- std::thread::Builder::new()- .name("Agent control".to_string())- .spawn(move || receive_broadcasts(reader))?;- Ok(source)+ failures}-fn test_connection() -> &'static TestConnection {- TEST_CONNECTION.get().expect("agent mode connected to the test")+fn this_agent() -> Arc<Agent> {+ THIS_AGENT.with_borrow(Clone::clone).expect("this thread runs an agent")}-fn receive_broadcasts(mut reader: ControlReader) {- let connection = test_connection();- while let Ok(ControlMessage::Broadcast(broadcast)) = reader.read_message() {- connection- .broadcasts- .lock()- .unwrap_or_else(PoisonError::into_inner)- .push_back(broadcast);- connection.broadcast_arrived.notify_all();- if send_all(connection.socket.as_fd(), &[BROADCAST_RECEIVED_ACKNOWLEDGEMENT]).is_err() {- break;+/// Tells the test that this agent is running, on `vm`, which ends $262.agent.start(). The agent must call+/// agent_vm_went_away() before the VM goes.+pub fn acknowledge_start(vm: &Vm) {+ this_agent().update(|state| {+ state.is_running = true;+ state.vm = Some(core::ptr::from_ref(vm));+ if state.is_terminated {+ vm.request_interrupt();}- }- // SAFETY: The test is gone, or no longer speaks the protocol, so nobody waits for this agent any more. Exiting- // from here also stops a main thread that is waiting or running forever.- unsafe { libc::_exit(0) }+ });}-/// Tells the test that this agent is running, which ends $262.agent.start().-pub fn acknowledge_start() {- let _ = send_all(test_connection().socket.as_fd(), &[AGENT_STARTED_ACKNOWLEDGEMENT]);+/// Keeps the test from reaching the VM of this agent, which is about to go.+pub fn agent_vm_went_away() {+ this_agent().update(|state| state.vm = None);}-/// $262.agent.receiveBroadcast(): waits for the next broadcast.-pub fn receive_broadcast() -> Broadcast {- let connection = test_connection();- let mut broadcasts = connection.broadcasts.lock().unwrap_or_else(PoisonError::into_inner);+/// $262.agent.receiveBroadcast(): waits for the next broadcast, or None once the test ended.+pub fn receive_broadcast() -> Option<Broadcast> {+ let agent = this_agent();+ let mut state = agent.state.lock().unwrap_or_else(PoisonError::into_inner);loop {- if let Some(broadcast) = broadcasts.pop_front() {- return broadcast;+ if state.is_terminated {+ return None;}- broadcasts = connection- .broadcast_arrived- .wait(broadcasts)- .unwrap_or_else(PoisonError::into_inner);- }-}--fn write_to_report_pipe(kind: u8, payload: &[u8]) {- let connection = test_connection();- for frame in encode_frames(connection.agent_index, kind, payload) {- // A report that cannot be written has nobody left to read it.- let _ = (&connection.report_pipe).write_all(&frame);+ if let Some(broadcast) = state.broadcasts.pop_front() {+ return Some(broadcast);+ }+ state = agent.state_changed.wait(state).unwrap_or_else(PoisonError::into_inner);}}/// $262.agent.report(), with the WTF-8 of the reported string.pub fn report(message: &[u8]) {- write_to_report_pipe(REPORT_FRAME, message);+ this_agent()+ .reports+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .reports+ .push_back(message.to_vec());}/// Tells the test that the agent's script threw, or left a promise rejected without a handler.pub fn report_uncaught_exception(name: &str, message: &str) {- write_to_report_pipe(UNCAUGHT_EXCEPTION_FRAME, &encode_uncaught_exception(name, message));-}--/// Tells the test that the agent panicked, as a failed assertion in the runtime does.-pub fn report_panic(message: &str) {- write_to_report_pipe(PANIC_FRAME, message.as_bytes());+ this_agent()+ .reports+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .failures+ .push(AgentFailure::UncaughtException {+ name: name.to_string(),+ message: message.to_string(),+ });}diff --git a/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/global_object.rsindex 17f5a3b4df5..a81064192b3 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs@@ -9,6 +9,8 @@ use core::cell::Cell;use ak::Utf16FlyString;use libjs_runtime_macros::Trace;+#[cfg(unix)]+use crate::contrib::test262::agents::{self, AgentRole};use crate::contrib::test262::dollar_262_object::Dollar262Object;use crate::gc::class::{GcCell, cast_ref, define_cell};use crate::interpreter::vm::Vm;@@ -84,6 +86,11 @@ impl Test262GlobalObject {fn print(vm: &Vm) -> ThrowCompletionOr<Value> {let string = vm.argument(0).to_utf16_string(vm)?;+ // NB: What a test prints is its result, which agents have no say in.+ #[cfg(unix)]+ if agents::role() == AgentRole::Agent {+ return Ok(Value::UNDEFINED);+ }outln(&Utf16View::of_string(&string).to_wtf8());Ok(Value::UNDEFINED)}diff --git a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs b/Libraries/LibJS/Rust/src/utilities/test262_runner.rsindex 94bf736a0ce..7a7e6ca2e27 100644--- a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs+++ b/Libraries/LibJS/Rust/src/utilities/test262_runner.rs@@ -12,8 +12,8 @@//! than the timeout is killed by SIGALRM, which the driver records as a timeout. A panic, including one from a runtime//! function that is not implemented yet, reports `assert_fail` for the running test and exits with status 12.//!-//! With --agent, the runner is instead one of the agents that a test starts with $262.agent.start(): it runs the-//! agent's script, which the test sends it, in a VM of its own (see contrib/test262/agents.rs).+//! The agents that a test starts with $262.agent.start() are threads of the runner, each with a VM of its own (see+//! contrib/test262/agents.rs).use core::ffi::{c_char, c_int};use std::collections::HashMap;@@ -674,7 +674,6 @@ fn is_unimplemented_feature_error(error_type: &str, details: &str) -> bool {fn is_unimplemented_feature_failure(failure: &AgentFailure) -> bool {match failure {AgentFailure::UncaughtException { name, message } => is_unimplemented_feature_error(name, message),- AgentFailure::Panic(_) | AgentFailure::Exited(_) => false,}}@@ -757,7 +756,6 @@ struct Options {parse_only: bool,timeout_in_seconds: i64,disable_core_dumping: bool,- run_as_agent: bool,}fn parse_options(arguments: &[String]) -> Result<Options, String> {@@ -766,7 +764,6 @@ fn parse_options(arguments: &[String]) -> Result<Options, String> {parse_only: false,timeout_in_seconds: 10,disable_core_dumping: false,- run_as_agent: false,};let mut arguments = arguments.iter().skip(1);while let Some(argument) = arguments.next() {@@ -790,7 +787,6 @@ fn parse_options(arguments: &[String]) -> Result<Options, String> {// The runtime has no debug logging to enable, so this is accepted and does nothing."-d" | "--debug" => {}"--disable-core-dump" => options.disable_core_dumping = true,- "--agent" => options.run_as_agent = true,_ => return Err(format!("Unknown option {argument}")),}}@@ -942,9 +938,7 @@ fn run(options: &Options) -> c_int {install_assertion_failure_hook(current_test.clone(), saved_stdout);#[cfg(unix)]- if let Ok(program) = std::env::current_exe() {- agents::enable_agents(program, vec!["--agent".into()]);- }+ agents::enable_agents(agent_mode::run_agent);let mut harness_files = HarnessFiles {directory: harness_directory,@@ -1002,15 +996,14 @@ fn run(options: &Options) -> c_int {0}-/// --agent: the runner as one of the agents that a test starts.+/// The thread of one of the agents that a test starts.#[cfg(unix)]mod agent_mode {use core::cell::RefCell;- use core::ffi::c_int;use super::{- EXIT_ASSERTION_FAILED, EXIT_SETUP_INPUT_FAILURE, NegativePhase, ScriptOrModuleProgram, TestError, create_vm,- decoded_source, describe_panic, describe_thrown_value, first_parser_error, run_program,+ NegativePhase, ScriptOrModuleProgram, TestError, create_vm, decoded_source, describe_thrown_value,+ first_parser_error, run_program,};use crate::contrib::test262::agents;use crate::contrib::test262::global_object::Test262GlobalObject;@@ -1050,33 +1043,21 @@ mod agent_mode {}/// Runs the script of one agent of a test, and tells the test if it failed.- pub(super) fn run_agent() -> c_int {- let source = match agents::connect_to_test() {- Ok(source) => source,- Err(error) => {- eprintln!("test262-runner: an agent could not connect to its test: {error}");- return EXIT_SETUP_INPUT_FAILURE;- }- };- std::panic::set_hook(Box::new(|info| {- agents::report_panic(&describe_panic(info));- // SAFETY: Exits without unwinding or running destructors, from a state that may be broken.- unsafe { libc::_exit(EXIT_ASSERTION_FAILED) }- }));-+ pub(super) fn run_agent(source: &[u8]) {let vm = create_vm();vm.set_on_promise_unhandled_rejection(Some(remember_unhandled_rejection));vm.set_on_promise_rejection_handled(Some(forget_handled_rejection));let root_execution_context =initialize_realm_with_global_object(&vm, &|realm| Test262GlobalObject::allocate(&vm, realm).upcast());- agents::acknowledge_start();+ agents::acknowledge_start(&vm);- if let Err(error) = run_agent_script(&vm, root_execution_context.realm(), &source) {+ let result = run_agent_script(&vm, root_execution_context.realm(), source);+ if let Err(error) = result+ && !vm.interrupt_requested()+ {agents::report_uncaught_exception(&error.error_type, &error.details);}- // SAFETY: Ends the agent without tearing down its VM, which nothing needs any more, while the thread that- // listens to the test still waits.- unsafe { libc::_exit(0) }+ agents::agent_vm_went_away();}}@@ -1215,8 +1196,6 @@ pub unsafe extern "C" fn libjs_rust_test262_runner_main(argc: c_int, argv: *cons}).collect();match parse_options(&arguments) {- #[cfg(unix)]- Ok(options) if options.run_as_agent => agent_mode::run_agent(),Ok(options) => run(&options),Err(error) => {eprintln!("test262-runner: {error}");