Commit graph

677 commits

Author SHA1 Message Date
Andreas Kling
b6bef6b688 Libraries: Use UTF-16 for JS-visible runtime strings
Produce JS-visible string results as UTF-16 at their source, including
numeric formatting, BigInt and BigFraction formatting, URI encoding,
console formatting, parser errors, regular expression errors, Intl and
Temporal records, LibUnicode locale boundaries, and LibWeb bindings.

Handle fractional radix formatting through the UTF-16 builder view.
2026-06-22 19:51:25 +02:00
Andreas Kling
0fca7d1a6e LibCore: Own addrinfo results without OwnPtr
Store the getaddrinfo result pointer directly in AddressInfoVector and
free it with freeaddrinfo from the destructor. This keeps the special
cleanup logic local to LibCore instead of relying on OwnPtr custom
deleter support.
2026-06-13 22:49:15 +02:00
Sam Atkins
4050c32dab Everywhere: Make use of Badge with multiple or derived types
Now that Badge can have multiple types, and a Badge of a derived class
can convert into a Badge of the superclass, we can simplify a few method
signatures and overloads.
2026-06-11 21:55:56 +02:00
Andreas Kling
ab5709edfd LibCore: Tighten EventLoop current-loop checks
Make EventLoop::current() enforce the presence of a current event loop
directly, and make EventLoop::pump() verify that it is pumping the
current thread event loop. This keeps the one-loop-per-thread invariant
explicit across the public EventLoop entry points.
2026-06-05 09:18:39 +02:00
Andreas Kling
83b293e4f2 LibCore: Keep main event loops alive
Add an explicit initializer for process-lifetime event loops and use it
for browser, helper service, and utility main loops. This preserves weak
event loop references for cross-thread users while making main thread
loop lifetime independent of normal program teardown.
2026-06-05 09:18:39 +02:00
Andreas Kling
02b205361d LibCore: Remove nested EventLoop support
Replace the per-thread EventLoop stack with a single thread-local
pointer. Constructing an EventLoop now requires that the current thread
does not already have one, and exec() and spin_until() operate only on
that current loop instead of pushing a temporary nested loop.

LibLine was the last user that needed nested Core event loops, so the
stack allocation and pthread cleanup machinery can go away.
2026-06-05 00:09:37 +02:00
Andreas Kling
164ed80244 Meta: Enable exit-time destructor warnings for libraries
Enable -Wexit-time-destructors for all in-tree library targets and
update process-lifetime library statics so they no longer register
exit-time destructors. Long-lived caches, lookup tables, singleton
registries, and generated constants now use NeverDestroyed or leaked
references where the data is intended to live until process exit.

Update LibWeb, LibLine, and the binding generators so regenerated
sources follow the same rule instead of reintroducing destructed
statics.
2026-06-04 19:20:49 +02:00
Andreas Kling
8c7b5b4de6 LibCore: Add immediate process termination helper
Add Core::Process::terminate_immediately() as the shared primitive
for terminating a process without running exit-time destructors. Use
_exit() on POSIX and TerminateProcess() on Windows.
2026-06-04 19:20:49 +02:00
Andreas Kling
6f616ae9a9 LibGfx: Remove TinyVG image decoding
Remove the TinyVG decoder now that the Qt chrome no longer depends on
TVG resources. Drop the decoder registration, MIME and supported image
type entries, fuzzer target, decoder tests, and TinyVG test inputs.
2026-05-31 19:20:59 +02:00
Aliaksandr Kalenik
cdacc11624 LibCore: Release IOSurface creation properties
IOSurfaceHandle::create() builds a CoreFoundation dictionary for
IOSurfaceCreate() and previously left that dictionary alive after the
surface was created. Each locally created IOSurface therefore leaked
the temporary properties dictionary.
2026-05-28 10:33:38 +02:00
Andreas Kling
8e85f5a0c4 LibWebView: Tie helper processes to browser lifetime
Add an opt-in Core::Process spawn mode that asks supported kernels to
terminate the child when its parent exits. On Linux, use a fork/exec
path for this mode so the child can install PR_SET_PDEATHSIG before
execing the helper process. The existing posix_spawn path remains in
place for other process launches.

Opt LibWebView helper processes into this mode so WebContent,
WebWorker, and other browser children do not survive a crashed or
exited UI process.
2026-05-26 20:40:25 +02:00
Shannon Booth
74b76e21b9 LibCore: Keep ICU and libc time zones in sync
Add Core::TimeZone as the single entry point for changing the
current time zone. This updates both ICU and the process TZ/tzset
state so libc-backed helpers such as AK::UnixDateTime::to_string()
agree with JS/ICU time zone state. Previously only the ICU timezone
would be updated, which could result in inconsistent results being
returned.
2026-05-20 07:26:23 -04:00
Andreas Kling
26504d84bb LibCore: Add immutable byte storage for mapped ranges
Allow MappedFile to expose a byte range within an fd. It maps the
page-aligned region required by mmap internally.

Add ImmutableBytes as a small shared holder for either owned bytes or a
mapped file. This lets cache code thread file-backed response bodies
through without copying response data into anonymous memory.

Cover non-page-aligned ranges, empty ranges, invalid ranges, and mapped
ImmutableBytes in TestLibCoreMappedFile.
2026-05-16 08:13:35 +02:00
Ali Mohammad Pur
0a7bef349d LibCore: Add functions to reserve and commit non-backed address space 2026-05-10 16:41:42 +02:00
R-Goc
50be9493d2 LibSync: Abstract away Mutex implementation
This commit adds in-place pimpl to abstract away the implementation of
Mutex. It also adds policies to configure the type of mutex desired.

Because of the tight integration between mutex and condition variables
they also needed to be reworked and the changes have to be in one commit
to retain atomicity.

A win32 and pthread implemenation is provided to make sure the api
works with both.
2026-05-08 18:58:35 -05:00
R-Goc
02bb892d7a LibThreading/LibSync: Split out sync primitives
This commit splits out synchronization primitives from LibThreading into
LibSync. This is because LibThreading depends on LibCore, while LibCore
needs the synchronization primitives from LibThreading. This worked
while they were header only, but when I tried to add an implementation
file it ran into the circular dependency. To abstract away the pthread
implementation using cpp files is necessary so the synchronization
primitives were moved to a separate library.
2026-05-08 18:58:35 -05:00
R-Goc
1d8751363b LibCore: Use call_once from LibThreading
This commit makes ThreadEventQueue use call_once instead of
pthread_once_t. The aim is to limit the pthread dependency to
LibThreading.
2026-05-08 18:58:35 -05:00
Andreas Kling
f70f485e48 LibHTTP: Store associated data with disk cache entries
Add disk cache helpers that store and retrieve sidecar payloads with
the same cache key and vary key as the HTTP response entry. The first
consumer is JavaScript bytecode.

Delete sidecars when the owning entry is removed, evicted, or replaced
by a fresh response. Count their on-disk size toward the cache budget so
bytecode data cannot grow outside eviction accounting.

Disk cache tests cover sidecar round-trips, replacement cleanup, and
eviction size accounting.
2026-05-06 08:20:06 +02:00
Jelle Raaijmakers
60e81938db LibCore: Remove EventSwift.h
This went unused.
2026-04-30 21:15:24 +02:00
Jelle Raaijmakers
daea7ee340 LibCore: Remove NetworkResponse
This went unused.
2026-04-30 21:15:24 +02:00
Jelle Raaijmakers
23a3ce1f2f LibCore+LibIPC: Remove SharedSingleProducerCircularQueue
This went unused.
2026-04-30 21:15:24 +02:00
Andreas Kling
6f4096a4ca LibDNS: Run getaddrinfo on a thread pool to avoid event-loop freezes
getaddrinfo can hang for many seconds when the system stub resolver
misbehaves; running it inline on the event loop froze every other
request, IPC, and curl socket event for the duration.

New PendingSystemResolution coalesces concurrent lookups for the same
name, dispatches the call to a Threading::ThreadPool worker, and
deferred-invokes the result back to the originating event loop. Each
caller of lookup() gets its own Core::Promise so concurrent
when_resolved/when_rejected handlers can't clobber each other; the
pending state fans out to every joined caller on completion.

Workers issue A and AAAA in parallel on separate sockets to sidestep
the systemd-resolved AAAA-drop bug, and resolve the user's promise
after the first side returns records (with a 50 ms RFC 8305 grace
window for the other side).

Adds Core::Socket::AddressFamily and an optional parameter to
resolve_host so workers can request A or AAAA specifically.
2026-04-26 17:59:52 +02:00
Tim Ledbetter
884a0140aa LibCore: Allow zero-size AnonymousBuffer creation
Previously, `AnonymousBuffer::create_with_size(0)` returned an error
because POSIX `mmap` rejects a zero length with `EINVAL`, and Windows
`CreateFileMapping` rejects a zero maximum size for an anonymous
mapping. This caused a crash when using `--headless=text` with zero
size pages like `about:blank`.
2026-04-22 09:08:39 -04:00
ayeteadoe
4cb7743915 LibCore: Expose register_process and implement for Windows event loop
This is the closest Windows equivalent to integrating process exit
handlers into the event loop.

Linux could also integrate register_process() into the poll() based
Unix event loop via the SYS_pidfd_open syscall; however, macOS requires
a kqueue. So for now register_process will only be used by Windows to
implement WebView::ProcessMonitor.

Co-authored-by: Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
2026-04-12 16:08:07 +02:00
Tim Ledbetter
2f82040cb1 LibCore: Add a CORE_API annotation to log_timing_info()
This is required to use the `REPORT_TIME` and `REPORT_TIME_EVERY`
macros.
2026-04-02 20:00:06 -04:00
sideshowbarker
d7053a8eb8 LibCore: Don’t pass O_CLOEXEC to shm_open
Bug: Ladybird crashes on launch on macOS 26.4+ with “UNEXPECTED ERROR:
close: Bad file descriptor” in SharedVersion.cpp — because
AnonymousBuffer creation fails.

Cause: anon_create() passed O_CLOEXEC in the oflag argument to shm_open.
macOS 26.4+ rejects that with EINVAL. POSIX only specifies O_RDONLY,
O_RDWR, O_CREAT, O_EXCL, and O_TRUNC as valid shm_open flags; on earlier
macOS versions, O_CLOEXEC just happened to also be silently accepted.

Fix: Filter O_CLOEXEC from the oflag argument we pass to shm_open flags,
and instead set FD_CLOEXEC via fcntl — after opening.
2026-03-31 17:21:17 +01:00
Shannon Booth
3beeb11e74 LibCore: Remove unneeded is_null checks on StringView 2026-03-31 13:48:50 +01:00
Aliaksandr Kalenik
1d025620e3 Everywhere: Move Mach bootstrap listener into LibIPC
Move MachPortServer from LibWebView into LibIPC as MachBootstrapListener
and move the Mach message structs from MachMessageTypes.h into LibIPC.

These types are IPC infrastructure, not UI or platform concerns.
Consolidating them in LibIPC keeps the Mach bootstrap handshake
self-contained in a single library and removes LibWebView's dependency
on LibThreading.
2026-03-24 19:51:52 +01:00
Aliaksandr Kalenik
3cb644500e Everywhere: Send IOSurface backing stores via main IPC route on macOS
Now that LibIPC uses Mach ports for transport on macOS, IOSurface port
rights can be sent as regular IPC message attachments instead of through
a separate ad-hoc Mach message side-channel. Introduce
Web::SharedBackingStore that wraps either a MachPort (macOS) or
ShareableBitmap (other platforms) with IPC encode/decode support,
unifying backing store allocation into the existing
did_allocate_backing_stores IPC message.
2026-03-23 23:22:38 +01:00
Aliaksandr Kalenik
4ea4d63008 Everywhere: Replace Unix socket IPC transport with Mach ports on macOS
On macOS, use Mach port messaging instead of Unix domain sockets for
all IPC transport. This makes the transport capable of carrying Mach
port rights as message attachments, which is a prerequisite for sending
IOSurface handles over the main IPC channel (currently sent via a
separate out-of-band path). It also avoids the need for the FD
acknowledgement protocol that TransportSocket requires, since Mach port
right transfers are atomic in the kernel.

Three connection establishment patterns:

- Spawned helper processes (WebContent, RequestServer, etc.) use the
  existing MachPortServer: the child sends its task port with a reply
  port, and the parent responds with a pre-created port pair.

- Socket-bootstrapped connections (WebDriver, BrowserProcess) exchange
  Mach port names over the socket, then drop the socket.

- Pre-created pairs for IPC tests and in-message transport transfer.

Attachment on macOS now wraps a MachPort instead of a file descriptor,
converting between the two via fileport_makeport()/fileport_makefd().

The LibIPC socket transport tests are disabled on macOS since they are
socket-specific.
2026-03-23 18:50:48 +01:00
Andreas Kling
a25fc5ad8a LibCore+LibWeb: Add ScopedAutoreleasePool and use it on macOS
On macOS, Objective-C methods frequently return autoreleased objects
that accumulate until an autorelease pool is drained. Our event loop
(Core::EventLoop) and rendering thread both lacked autorelease pools,
causing unbounded accumulation of autoreleased objects.

The rendering thread was the worst offender: every Skia flush triggers
Metal resource allocation which sets labels on GPU textures via
-[IOGPUMetalResource setLabel:], creating autoreleased CFData objects.
With ~1M+ such objects at 112 bytes each, this leaked ~121MB. Metal
command buffer objects (_MTLCommandBufferEncoderInfo, etc.) also
accumulated, adding another ~128MB.

Add Core::ScopedAutoreleasePool, a RAII wrapper around the ObjC runtime
autorelease pool (no-op on non-macOS), and drain it:
- Every event loop pump (like NSRunLoop does)
- Every compositor loop iteration on the rendering thread
2026-03-15 11:42:43 +01:00
Andreas Kling
643f2884cc LibCore: Fix signal handler deadlock in EventLoopImplementationUnix
handle_signal() called ThreadData::the() which can acquire a write
lock on s_thread_data_lock if the thread hasn't initialized its
ThreadData yet. If the signal interrupts a thread that already holds
a read lock on s_thread_data_lock (e.g. in unregister_notifier()),
this deadlocks — the write lock waits for the read lock, but the
read lock holder is blocked in the signal handler.

Fix by accessing the thread-local s_this_thread_data directly. If
the thread has no ThreadData, there's no wake pipe to write to, so
we just return.
2026-03-07 13:09:50 +01:00
Andreas Kling
656a84e180 LibThreading: Fix data race in RWLock::unlock()
The generic unlock() wrote to m_write_locked from every thread
regardless of whether a read or write lock was held. When multiple
threads held concurrent read locks, their unlock() calls would race
on the non-atomic m_write_locked and m_read_locked_with_write_lock
fields.

Split unlock() into unlock_read() and unlock_write() so that read
unlocks never touch the write-lock tracking fields. The RWLockLocker
template dispatches at compile time based on LockMode.
2026-03-07 13:09:50 +01:00
Zaggy1024
8c96f7b3aa LibCore: Stop atomically ref-counting EventReceiver
Inheriting from AtomicRefCounted and Weakable is asking for misuse of
WeakPtr to result in TOCTOU-caused UAFs.

In order to ensure we're not misusing EventReceiver across threads, I
ran test-web and some sites with a temporary hack to verify that ref()s
and unref()s are always called from the same thread on the class.
2026-03-02 17:06:39 -06:00
Zaggy1024
d6ff027593 LibCore: Remove the pending jobs functionality from ThreadEventQueue
This is no longer used.
2026-03-02 17:06:39 -06:00
Zaggy1024
035b489266 LibCore: Prevent UAF on event loop wake handles on Windows
We were holding a reference to ThreadData, which could be destroyed
earlier than the EventLoop itself, causing other threads to UAF trying
to signal a wake.
2026-03-02 17:06:39 -06:00
Zaggy1024
04e95b7dd1 LibCore: Avoid UAF on the array of wake pipes when exit()ing
If exit() is called on a thread with an EventLoop in the stack, the
ThreadData storing the array of wake pipes will be destroyed first.
Threads can still take a strong reference to the EventLoop after that,
and will read the fds from freed memory.

Instead, take a copy of the write fd, and swallow EBADF when writing to
it, since that only indicates that the thread and event loop are
exiting, so there's nothing to do with the wake.
2026-03-02 17:06:39 -06:00
R-Goc
919f44f3a5 LibCore: Explicitly export symbols from LibCore
This patch adds explicit symbol export to LibCore. This leads to about
350 less symbols being exported.
2026-02-26 18:31:57 +01:00
R-Goc
57b12d3ca0 LibCore: Remove LibCoreMinimal 2026-02-26 18:31:57 +01:00
Ben Wiederhake
1fd672c4c2 LibCore: Remove unused header in File 2026-02-23 12:15:23 +01:00
Ben Wiederhake
7093082d75 LibCore: Remove forward declaration of non-existent type 2026-02-23 12:15:23 +01:00
Ben Wiederhake
0206150b70 LibCore: Remove unused header in TimeZoneWatcherUnix 2026-02-21 19:27:35 +01:00
Ben Wiederhake
08f4cf10ed LibCore: Remove unused header in LocalServer 2026-02-21 19:27:35 +01:00
Ben Wiederhake
084f5ababd LibCore: Remove unused header in EventLoopImplementationUnix 2026-02-21 19:27:35 +01:00
Ben Wiederhake
ee5a6e1b28 LibCore: Remove unused header in AnonymousBuffer 2026-02-21 19:27:35 +01:00
Ben Wiederhake
6a34849238 LibCore: Remove unused header in ThreadEventQueue 2026-02-21 19:27:35 +01:00
Ben Wiederhake
e27bdaafe7 LibCore: Remove unused header in ResourceImplementationFile 2026-02-21 19:27:35 +01:00
Ben Wiederhake
387f378f45 LibCore: Remove unused header in ResourceImplementation 2026-02-21 19:27:35 +01:00
Ben Wiederhake
fb7095ab88 LibCore: Remove unused header in Resource 2026-02-21 19:27:35 +01:00
Ben Wiederhake
6335f4745f LibCore: Remove unused header in MimeData 2026-02-21 19:27:35 +01:00