Commit graph

4015 commits

Author SHA1 Message Date
Andreas Kling
096eddfd5a LibIPC: Encode spans of trivial arithmetic types more efficiently
For stuff like Span<u8>, we should obviously grow the message buffer
once, and then copy all the bytes in one go.
2025-12-01 15:12:52 +01:00
Callum Law
1f7fe97ac3 LibJS/AK: Move XorShift128PlusRNG to AK
This will be useful for CSS random functions so it should be in a
reusable place.

This does require us to use `AK::get_random` instead of
`Crypto::get_secure_random`, but this is fine since the latter is in the
process of being removed (see #6564).
2025-12-01 11:00:33 +00:00
Andreas Kling
c9c98a150d AK: Avoid temporary Vector<u8> when encoding Base64
Instead, decode directly into an uninitialized StringData object.
This avoids the redundant vector allocation + memory copy.
2025-11-29 09:39:43 -05:00
Tim Ledbetter
c1742fa989 AK: Introduce Vector::unchecked_empend()
This does the same thing as `Vector::empend()` without attempting to
grow the underlying buffer.
2025-11-26 14:33:59 +00:00
Aliaksandr Kalenik
69cede4a0f AK+LibWeb: Make StringBase::bytes() lvalue-only
Disallow calling `StringBase::bytes()` on temporaries to avoid returning
`ReadonlyBytes` that outlive the underlying string.

With this change, we catch a real UAF:
`load_result.data = maybe_response.release_value().bytes();`
All other updated call sites were already safe, they just needed to use
an intermediate named variable to satisfy the new lvalue-only
requirement.
2025-11-25 13:02:20 -05:00
Ali Mohammad Pur
d5d37abfa5 AK+LibRegex: Only set node metadata on Trie::ensure_child if missing
a290034a81 passed an empty vector to this,
which caused nodes that appeared multiple times to reset the trie
metadata...which broke the optimisation.

This patchset makes the function take a 'provide missing metadata'
function instead, and only invokes it when the node is missing rather
than unconditionally setting the metadata on all nodes.
2025-11-21 02:46:33 +01:00
Hendiadyoin1
bcd01da91d AK: Use Deducing this for OptionalBase
This is taken from and akin to
https://github.com/SerenityOS/serenity/pull/25894
2025-11-20 16:27:07 +01:00
R-Goc
b97892729f AK: Print backtrace with warnln
Printing the backtrace with our print function makes sure it is in one
piece when multiple threads are printing.
2025-11-20 15:44:25 +01:00
Timothy Flynn
911ecf1450 AK: Avoid copying the iterable container in AK::enumerate
There are actually a couple of issues here:

1. We are not properly perfect-forwarding the iterable to the Enumerator
   member. We are using the class template as the constructor type, but
   we would actually have to do something like this to achieve perfect
   forwarding:

   template <typname Iter = Iterable>
   Enumerator(Iter&&)

2. The begin / end methods on Enumerator (although they return by const-
   ref) are making copies during for-each loops. The compiler basically
   generates this when we call enumerate:

   for (auto it = Enumerator::begin(); it != Enumerator::end(); ++it)

   The creation of `it` above actually creates a copy of the returned
   Enumerator instance.

To avoid all of this, let's create an intermediate structure to act as
the enumerated iterator. This structure does not hold the iterable and
thus is fine to copy. We can then let the compiler handle forwarding
the iterable to the Enumerator.

Cherry-picked from:
0edcd19615
2025-11-18 13:31:52 +01:00
Zaggy1024
a1358fa970 AK+Tests: Add time units conversion functions to Duration
These take a numerator and denominator defining the unit in a fractions
of a second. Conversion is done in integers, meaning that these must
clamp when approaching numeric limits.
2025-11-17 16:51:18 +01:00
Hendiadyoin1
39a2a854be AK: Ignore -Wfree-nonheap-object on RefCounted::unref
GCC 15 seems to raise a false positive here in some cases

(cherry picked from commit 129c3ec0df061930e58f6d15d2ee4ad3e7599aad)
2025-11-13 13:52:07 +01:00
Zaggy1024
ae73280178 AK+Tests: Add a formatter for Duration
This will format Duration as seconds, with as much decimal precision as
necessary to fully represent its value. The alternate format specifier
can be used to make it print the units on the end, i.e. "1.23s".
2025-11-12 14:41:46 -06:00
Zaggy1024
c8958c9e7b AK: Simplify calculation of the right padding when formatting u64 2025-11-12 14:41:46 -06:00
Tim Ledbetter
298e934077 AK: Add human_readable_short_time()
This gives a more compact version of `human_readable_time()` to
nanosecond precision.
2025-11-11 11:47:59 +01:00
Undefine
cde3941d9f AK: Remove a clang-15 consteval workaround
This is a really really old workaround and it doesn't seem to be needed
anymore as clang-15 is supported for a really long time.
2025-11-07 11:27:51 +01:00
Undefine
80003ecc09 AK: Remove unused __ptrdiff_t declaration
The project compiles just fine without and this seems a remnant from
SerenityOS.
2025-11-07 11:27:51 +01:00
Undefine
0582c01c89 AK+Tests: Remove NoAllocationGuard
On systems other than SerenityOS this was a no-op anyways.
2025-11-07 11:27:51 +01:00
Undefine
4f8a4c196f AK: Get rid of an unused NAKED macro
This went unused.
2025-11-07 11:27:51 +01:00
Undefine
6b7a8cb8c3 AK: Get rid of unused VALIDATE_ARCH macros
Those were used primarily in the SerenityOS kernel and are a relict
of the past.
2025-11-07 11:27:51 +01:00
Undefine
c6046dfe0f AK: Remove unused architecture specific TODO macros
As far as I can tell those remained unused from the SerenityOS days
2025-11-07 11:27:51 +01:00
Undefine
17d3b881d3 AK+Everywhere: Remove ifdefs for WASM and Emscripten
Building the Ladybird code for Emscripten doesn't really make sense
and I doubt it is even possible with all the dependencies now.
2025-11-07 11:27:51 +01:00
R-Goc
86b95b1d7a LibCore: Use IOCP for the event loop on Windows
This commit changes the event loop to use IOCPs instead of
WaitForMultipleObjects to wait on events. This is done through the Nt
kernel api NtAssociateWaitCompletionPacket which associates an event
with a completion packet. Each completion packet notifies only once, as
they are normally used to signal completion of an operation so to use
them for notifiers they are associated again after each time they are
triggered.
There are more optimizations that can be done, such as reusing the
EventLoopNotifier and EventLoopTimer structures to reduce the number of
allocations and context switches for timer and notifier registration.
2025-11-07 08:42:43 +01:00
R-Goc
af1bf342f9 AK: Make windows error formatter use stack buffer
This change makes the error formatter on windows use a stack array
instead of a heap allocated array. This is because the heap allocation
fails when being ran during process teardown.
2025-11-07 08:42:43 +01:00
Tim Ledbetter
fe377977d9 RequestServer: Add a CURL_DEBUG flag
This sets `CURLOPT_VERBOSE` to 1, which enables detailed logging of
all cURL connections to stderr.
2025-11-03 11:55:56 -05:00
R-Goc
991ab62dd7 AK: Increase MonotonicTime precision on Windows
MonotonicTime was using 32 bit floats for operations on the values
converted from an i64 returned by the performance counter. This caused
to either precision losses or complete losses of the data for timing
even things as long as hundreds of miliseconds, which should never be a
problem with the resolution of the performance counter. This change
fixes that behavior.
2025-10-30 09:42:40 -06:00
ayeteadoe
7683f1285f AK: Expose helpers to invoke Windows runtime config directly in main()
When shutting down helper processes, PosixSocketHelper::close() in
SocketWindows when trying to close the socket fd with
WSANOTINITIALISED. This was due to us initiating WinSock2 during static
initialization and presumably also not terminating WinSock2 properly.

Similar to WinSock2 initiation, calling CRT during static
initialization is considered dangerous given the CRT DLL itself may not
yet be initialized.

Because of the above, we move to perform this Windows-specific
runtime setup/teardown calls into the main() functions.
2025-10-29 21:07:52 -06:00
Zaggy1024
aa8c28eb24 AK+Tests: Allow creating a Duration from 64-bit floating point seconds 2025-10-27 17:28:49 -07:00
Jelle Raaijmakers
2c78fd5b89 AK: Remove unused Checked<T> code
We could never hit the #else branches for some of these methods, because
we already relied on having __builtin_*_overflow() readily available in
earlier methods.

multiplication_would_overflow() with three arguments was only used in a
test, so let's get rid of that as well.
2025-10-22 00:26:23 +02:00
Ali Mohammad Pur
553a7a9278 AK: Remove unused and unintuitive Trait for char*
We don't use char* in containers, and the expectation would be a pointer
compare instead of a string compare; so remove this specialisation
entirely.
2025-10-21 18:20:48 +02:00
Luke Wilde
afd170d16c AK: Add the ability to reinterpret a Span to a given type
This allows you to reinterpret a Span to any given type, maintaining
the original data and working out the new size for you.

The target type must evenly fit into the Span's original type, ensuring
bytes are not dropped.
2025-10-20 16:26:12 +02:00
Andreas Kling
25a5ed94d6 LibGC: Add GC::Weak<T> as an alternative to AK::WeakPtr<T>
This is a weak pointer that integrates with the garbage collector.
It has a number of differences compared to AK::WeakPtr, including:

- The "control block" is allocated from a well-packed WeakBlock owned by
  the GC heap, not just a generic malloc allocation.

- Pointers to dead cells are nulled out by the garbage collector
  immediately before running destructors.

- It works on any GC::Cell derived type, meaning you don't have to
  inherit from AK::Weakable for the ability to be weakly referenced.

- The Weak always points to a control block, even when "null" (it then
  points to a null WeakImpl), which means one less null check when
  chasing pointers.
2025-10-17 17:22:16 +02:00
R-Goc
ba5ef052e4 AK: Fix libbacktrace fallback
Introducing cpptrace as the primary backtrace library broke the
backtrace fallback during the code move. This commit properly links AK
to libbacktrace.

It also fixes the function signatures for the fallback backtrace
handlers.
2025-10-10 12:46:20 +02:00
R-Goc
62e7d1b5c8 AK: Remove FreeLibrary call in assertion handler
The call to FreeLibrary was incorrect as GetModuleHandle does not
increment the reference count of the DLL.
2025-10-08 07:07:57 +02:00
R-Goc
3c7bad32cd AK: Clean up backtraces
This commit replaces the default backtrace logic with cpptrace, for
nicer, colored backtraces. Cpptrace runs on all of our supported
platforms excpet android. As such backtrace.h is left in place.

All the backtrace functions are made noinline to have a consistent
number of frames. A maximum depth parameter is added to dump_backtrace
with a default of 100. This should be enough, and can be easily
changed, and allows for limiting the maximum depth.

Setting the LADYBIRD_BACKTRACE_SNIPPETS environment variable enables
surrouding code snippets in the backtrace. Specifically 2 lines above
and below. This number can be changed by calling snippet_context on the
formatter. For the whole list of options of what can be done with
formatting see the cpptrace repository.

On Windows we skipped frames when verification fails and when
dump_backtrace was added the logic was wrong and would have skipped
frames we care about.

This commit also implements skipping frames on Linux.
The only time where this does not skip all frames is when the call to
backtrace gets intercepted. Then we will end up skipping one frame less
than needed.

To keep delayload on Windows a patch and overlay port is used. When
upstream accepts these changes and vcpkg bumps the version the patch
could be removed to have just the cmake define.
2025-10-08 07:07:57 +02:00
Andreas Kling
ce16bdd07d Revert "AK: Use HashMap::ensure() for FlyString and Utf16FlyString lookups"
This reverts commit 9425ee6d2b.

Appears to have introduced flakiness on WPT.
2025-10-06 10:07:40 +02:00
Andreas Kling
9425ee6d2b AK: Use HashMap::ensure() for FlyString and Utf16FlyString lookups
This consolidates sometimes-two hash lookups into always-one, which is
less work in the case where a new fly-string is introduced.
2025-10-05 21:44:06 +02:00
Andreas Kling
ca772caee6 AK: Add HashTable::ensure(hash, predicate, init_callback)
...and use it to make HashMap::ensure() do a single hash lookup instead
of three.

We achieve this by factoring out everything but the bucket construction
logic from HashTable::write_value() into a lookup_for_writing() helper
so we can use it from more places.
2025-10-05 21:44:06 +02:00
Andreas Kling
24934ba479 LibJS: Make single-character ASCII string cache strings be Utf16String
Just another little step towards all strings being Utf16String.
2025-10-05 16:39:14 +02:00
Andreas Kling
72ea158f16 AK: Initialize StringBuilder buffer in place
Before this change, we'd construct a ByteBuffer for the internal buffer,
and then move-construct StringBuilder::m_buffer from it.

Due to ByteBuffer's inline capacity, this meant we had to memmove the
inline buffer an extra time for every StringBuilder created.
2025-10-05 11:24:46 +02:00
Andreas Kling
1ec72de0a6 AK: Remove unnecessary StringBuilder::create() factory 2025-10-05 11:24:46 +02:00
Andreas Kling
bb93107a7d AK: Avoid redundant ASCII validation in StringBuilder::append(Utf16View)
If the UTF-16 data comes from ASCII-only storage, we can skip the ASCII
validation and save ourselves the effort.
2025-10-05 11:24:46 +02:00
Andreas Kling
b50ff02da4 AK: Skip ASCII validation in {Utf16String,String}::number() 2025-10-05 11:24:46 +02:00
Andreas Kling
1c04b6da3b AK: Make Utf16String::number(Integral) fast like String::number()
Move the fast String::number() implementation to a shareable place
so both string types can make use of it.
2025-10-05 11:24:46 +02:00
Ali Mohammad Pur
15bb9fee71 AK: Use OOB pointer for "empty" last-fast-access Vector last ptr
This is a _significant_ perf improvement as we no longer have to think
about tracking state transitions from empty <-> nonempty.
(corresponds to a ~20% perf improvement in LibWasm)
2025-10-01 23:47:29 +02:00
Ali Mohammad Pur
80e5356853 AK: Add Vector::remove_all(container)/remove_all(it, end)
Instead of repeatedly removing elements off the vector, this allows for
specifying all the removed indices at once, and does not perform any
extra reallocations or unnecessary moves.
2025-10-01 23:47:29 +02:00
Tomasz Strejczek
5cde267979 AK: Implement Formatter<UnixDateTime>
Implement StringBuilder's Formatter<UnixDateTime>. Add necessary tests.
2025-09-30 12:39:01 +02:00
Tomasz Strejczek
ea32e39d68 AK: Add UnixDateTime::parse() method
Copy parse() method from LibCore::DateTime::parse(). Augment the method
to handle parsing from GMT time. Fix incorrect handling of year in '%D'
format specifier. Remove all format specifiers related to time zones.
Copy relevant tests and add additional ones.
2025-09-30 12:39:01 +02:00
me-it-is
b76f1fb011 AK: Fix is_within_range when converting from float
Within range now uses the max capacity of a type rather than its size.
This fixes some subtests in
https://wpt.fyi/results/wasm/core/conversions.wast.js.html?product=ladybird
2025-09-24 10:40:24 +01:00
Zaggy1024
744568c912 AK: Destroy non-trivial types by ref in HashTable::clear_with_capacity
Buckets being iterated by pointer instead of reference was causing a
compilation error when calling clear_with_capacity() on a HashTable
containing a non-trivially-destructible type.
2025-09-22 17:28:00 -05:00
Andreas Kling
bc368110ab AK: Make is<T const> use fast_is<T>
We were missing many opportunities to use the fast_is optimization due
to requiring T be non-const.
2025-09-22 15:00:50 +02:00