Commit Graph

2061 Commits

Author SHA1 Message Date
Max Wipfli
56253bf389 AK: Reimplement StringView::find methods in StringUtils
This patch reimplements the StringView::find methods in StringUtils, so
they can also be used by String. The methods now also take an optional
start parameter, which moves their API in line with String's respective
methods.

This also implements a StringView::find_ast(char) method, which is
currently functionally equivalent to find_last_of(char). This is because
find_last_of(char) will be removed in a further commit.
2021-07-02 21:54:21 +02:00
Max Wipfli
3ea65200d8 AK: Implement StringView::to_{lower,upper}case_string
This patch refactors StringImpl::to_{lower,upper}case to use the new
static methods StringImpl::create_{lower,upper}cased if they have to use
to create a new StringImpl. This allows implementing StringView's
to_{lower,upper}case_string using the same methods.

It also replaces the usage of hand-written to_ascii_lowercase() and
similar methods with those from CharacterTypes.h.
2021-07-02 21:54:21 +02:00
Hediadyoin1
8ed3315dec AK: Support long doubles in format strings 2021-07-02 19:50:43 +02:00
Brian Gianforcaro
59ba316ac6 AK: Annotate more AK::Span methods as nodiscard 2021-07-01 22:44:06 +02:00
Andreas Kling
6f0e8f823b Kernel: Don't compile JsonValue & friends into the kernel 2021-06-30 11:31:12 +02:00
Max Wipfli
fb8bbdabb7 AK: Use canonicalized_path in LexicalPath::relative_path
This avoids construction of LexicalPath objects.
2021-06-30 11:13:54 +02:00
Max Wipfli
36c3962670 AK: Add [[nodiscard]] to LexicalPath methods construction objects 2021-06-30 11:13:54 +02:00
Max Wipfli
dde888a3d4 AK: Move path canonicalization into LexicalPath::canonicalized_path
This moves the path canonicalization from the LexicalPath constructor to
canonicalized_path. This allows canonicalized path to no longer
construct a LexicalPath object and initialize all its member variables.
2021-06-30 11:13:54 +02:00
Max Wipfli
d8be530397 AK+Everywhere: Remove "null state" of LexicalPath
This removes the default constructor of LexicalPath, and subsequently
modifies all its users to accommodate the change.
2021-06-30 11:13:54 +02:00
Max Wipfli
4c018909f7 AK: Make LexicalPath immutable
This replaces the current LexicalPath::append() API with a new method
that returns a new LexicalPath object and doesn't touch the this-object.
With this, LexicalPath is now immutable. It also adds a
LexicalPath::parent() method and the relevant test cases.
2021-06-30 11:13:54 +02:00
Max Wipfli
7405536a1a AK+Everywhere: Use mostly StringView in LexicalPath
This changes the m_parts, m_dirname, m_basename, m_title and m_extension
member variables to StringViews onto the m_string String. It also
removes the m_is_absolute member in favour of computing if a path is
absolute in the is_absolute() getter. Due to this, the canonicalize()
method has been completely rewritten.

The parts() getter still returns a Vector<String>, although it is no
longer a const reference as m_parts is no longer a Vector<String>.
Rather, it is constructed from the StringViews in m_parts upon request.
The parts_view() getter has been added, which returns Vector<StringView>
const&. Most previous users of parts() have been changed to use
parts_view(), except where Strings are required.

Due to this change, it's is now no longer allow to create temporary
LexicalPath objects to call the dirname, basename, title, or extension
getters on them because the returned StringViews will point to possible
freed memory.
2021-06-30 11:13:54 +02:00
Max Wipfli
fc6d051dfd AK+Everywhere: Add and use static APIs for LexicalPath
The LexicalPath instance methods dirname(), basename(), title() and
extension() will be changed to return StringView const& in a further
commit. Due to this, users creating temporary LexicalPath objects just
to call one of those getters will recieve a StringView const& pointing
to a possible freed buffer.

To avoid this, static methods for those APIs have been added, which will
return a String by value to avoid those problems. All cases where
temporary LexicalPath objects have been used as described above haven
been changed to use the static APIs.
2021-06-30 11:13:54 +02:00
Max Wipfli
9b8f35259c AK: Remove the LexicalPath::is_valid() API
Since this is always set to true on the non-default constructor and
subsequently never modified, it is somewhat pointless. Furthermore,
there are arguably no invalid relative paths.
2021-06-30 11:13:54 +02:00
Max Wipfli
caa9daf59e AK: Use east const style in LexicalPath.{cpp,h} 2021-06-30 11:13:54 +02:00
Andreas Kling
0dbf786aed Kernel+AK: Don't compile JSON parser into the kernel
The kernel doesn't consume JSON, it only produces it. So there's no
need for the kernel to have a JSON parser built into it. :^)
2021-06-29 22:19:29 +02:00
Daniel Bertalan
23d66fe719 AK: Add RETURNS_NONNULL attribute and use it
This attribute tells compilers that the pointer returned by a function
is never null, which lets it optimize away null checks in some places.
This seems like a nice addition to `NonnullOwnPtr` and `NonnullRefPtr`.

Using this attribute causes extra UBSan checks to be emitted. To offset
its performance loss, some additional methods were marked ALWAYS_INLINE,
which lets the compiler optimize duplicate checks
2021-06-29 22:57:52 +04:30
Idan Horowitz
a768131720 AK: Ensure StringBuilder capacity in String::reverse 2021-06-29 16:55:54 +01:00
Idan Horowitz
4a2a084789 AK: Add the to_ascii_base36_digit helper method 2021-06-29 16:55:54 +01:00
Max Wipfli
ed2bf0a753 AK: Use [[nodiscard]] in JsonObject and JsonArray 2021-06-29 13:18:03 +02:00
Max Wipfli
9c8a2a5f69 AK+Spreadsheet+LibWeb: Remove JsonObject::get_or()
This removes JsonObject::get_or(), which is inefficient because it has
to copy the returned value. It was only used in a few cases, some of
which resulted in copying JsonObjects, which can become quite large.
2021-06-29 13:18:03 +02:00
Max Wipfli
e82611bb87 AK: Add JsonObject::has_* methods
This adds methods to JsonObject to check if a key exists with a certain
type. This simplifies code that validates whether a JsonObject has the
expected structure.
2021-06-29 13:18:03 +02:00
Max Wipfli
f45273649f AK+Everywhere: Change int to size_t in JsonObject and JsonArray 2021-06-29 13:18:03 +02:00
Max Wipfli
66526cbbaf AK: Return const& from JsonObject::get()
This adds a static JsonValue* s_null_value, which allows
JsonObject::get to return a reference instaed of copying the return
value. Since JsonValue is only 16 bytes, this seems like a reasonable
compromise.
2021-06-29 13:18:03 +02:00
Max Wipfli
e0ed160372 AK: Use OrderedHashMap in JsonObject
This changes JsonObject to use the new OrderedHashMap instead of an
extra vector for tracking the insertion order.

This also adds a default value for the KeyTraits template argument in
OrderedHashMap. Furthermore, it fixes two cases where code iterating
over a JsonObject relied on the value argument being copied before
invoking the callback.
2021-06-29 13:18:03 +02:00
Max Wipfli
13b2067da6 AK: Make JsonValue::as_string_or() const 2021-06-29 13:18:03 +02:00
Max Wipfli
53480180cb AK: Use east const style in Json{Array,Object}.h 2021-06-29 13:18:03 +02:00
Itamar
316fef5602 AK: Store the 'extra' field of ScopeLogger as String
It was previously stored as a StringView, which prevented us from
using temporary strings in the 'extra' argument.

The performance hit doesn't really matter because ScopeLogger is used
exclusively for debugging.
2021-06-29 00:07:19 +04:30
Itamar
87e6d5351e AK: Don't colorize the 'extra' field of ScopeLogger in dbgln()
It's easier to spot it in the debug logs this way :)
2021-06-29 00:07:19 +04:30
Gunnar Beutner
e56a0d6af7 Kernel: Fix memset() on x86_64
Previously memset() only set half of the bytes to the requested value.
2021-06-28 15:55:00 +02:00
Ali Mohammad Pur
745a1dbb5d AK: Add and use the RemoveCVReference<T> type trait 2021-06-28 01:08:41 +04:30
Ali Mohammad Pur
37b0f55104 AK: Make the constexpr StringView methods actually constexpr
Also add some tests to ensure that they _remain_ constexpr.
In general, any runtime assertions, weirdo C casts, pointer aliasing,
and such shenanigans should be gated behind the (helpfully newly added)
AK::is_constant_evaluated() function when the intention is to write
constexpr-capable code.
a.k.a. deliver promises of constexpr-ness :P
2021-06-27 20:54:59 +01:00
Ali Mohammad Pur
bda19a9ff3 AK: Add explicit Variant conversion operators
This allows converting between Variants of different types with less
pain.
2021-06-27 12:49:49 +01:00
Andreas Kling
beb43f673e AK: Undo bogus Variant::downcast() rename
I accidentally renamed these to verify_cast() when doing the global
AK::downcast() rename.
2021-06-26 21:27:58 +02:00
Itamar
eecbcff6af AK: Add NOTE about VERIFY in Function::clear 2021-06-25 18:58:34 +02:00
kleines Filmröllchen
9d4c50ca60 AK: Add big endian bit reading to InputBitStream
The existing InputBitStream methods only read in little endian, as this
is what the rest of the system requires. Two new methods allow the input
bitstream to read bits in big endian as well, while using the existing
state infrastructure.

Note that it can lead to issues if little endian and big endian reads
are used out of order without aligning to a byte boundary first.
2021-06-25 20:48:14 +04:30
kleines Filmröllchen
988763c0ef Toolchain: Add the AFLACLOADER_DEBUG macro
This enables FLAC debugging output, which is used
with the new FLAC loader introduced in later commits.
2021-06-25 20:48:14 +04:30
Andreas Kling
ee3a73ddbb AK: Rename downcast<T> => verify_cast<T>
This makes it much clearer what this cast actually does: it will
VERIFY that the thing we're casting is a T (using is<T>()).
2021-06-24 19:57:01 +02:00
Daniel Bertalan
2d2747cb15 LibCore+AK: Use proper atomics in Singleton 2021-06-24 17:35:49 +04:30
Daniel Bertalan
eee44c85d4 AK: Use __attribute__((name)) for functions everywhere
Clang enforces the ordering that attributes specified with the
`[[attr_name]]` syntax must comes before those defines as
`__attribute__((attr_name))`. We don't want to deal with that, so we
should stick to a single syntax (for functions, at least).

This commit favors the latter, as it's used more widely in the code
(for declaring more "exotic" options), and changing those would be a
larger effort than modifying this single file.
2021-06-24 17:35:49 +04:30
Daniel Bertalan
00915e8948 AK: Add factory methods for creating smart pointers
These functions abstract away the need to call the proper new operator
("throwing" or "non-throwing") and manually adopt the resulting raw
pointer. Modelled after the existing `NonnullOwnPtr<T> make()`
functions, these forward their parameters to the object's constructor.

Note: These can't be used in the common "factory method" idiom, as
private constructors can't be called from a standalone function.

The naming is consistent with AK's and Shell's previous implementation
of these:
- `make` creates a `NonnullOwnPtr<T>` and aborts if the allocation could
  not be performed.
- `try_make` creates an `OwnPtr<T>`, which may be null if the allocation
  failed.
- `create` creates a `NonnullRefPtr<T>`, and aborts on allocation
  failure.
- `try_create` creates a `RefPtr<T>`, which may be null if the
  allocation was not successful.
2021-06-24 17:35:49 +04:30
Daniel Bertalan
5491e0cdcc AK+Kernel: Make fallible allocations compiler-agnostic
In standard C++, operators `new` and `new[]` are guaranteed to return a
valid (non-null) pointer and throw an exception if the allocation
couldn't be performed. Based on this, compilers did not check the
returned pointer before attempting to use them for object construction.

To avoid this, the allocator operators were changed to be `noexcept` in
PR #7026, which made GCC emit the desired null checks. Unfortunately,
this is a non-standard feature which meant that Clang would not accept
these function definitions, as it did not match its expected
declaration.

To make compiling using Clang possible, the special "nothrow" versions
of `new` are implemented in this commit. These take a tag type of
`std::nothrow_t` (used for disambiguating from placement new/etc.), and
are allowed by the standard to return null. There is a global variable,
`std::nothrow`, declared with this type, which is also exported into the
global namespace.

To perform fallible allocations, the following syntax should be used:

```cpp
auto ptr = new (nothrow) T;
```

As we don't support exceptions in the kernel, the only way of uphold the
"throwing" new's guarantee is to abort if the allocation couldn't be
performed. Once we have proper OOM handling in the kernel, this should
only be used for critical allocations, where we wouldn't be able to
recover from allocation failures anyway.
2021-06-24 17:35:49 +04:30
Daniel Bertalan
d6138df490 AK: Specialize Atomic<Integral> for clang compatibility
While Clang claims to implement GCC's atomics libcall API, a small
incompatibility caused our builds to fail on Clang.

Clang requires requires the operands to its fixed-size functions to be
integer types, while GCC will take any type with the same size and
alignment as the various integer primitives. This was problematic, as
atomic `enum class`es would not compile.

Furthermore, Clang does not like if only one operand pointer is marked
volatile. Because it only affects the standalone atomic functions, that
will be fixed in a later commit.

As an added benefit, the code is more type-safe, as it won't let us
perform arithmetic on non-integer types. Types with overloaded
arithmetic types won't cause unexpected behavior anymore.

The constructors for the various atomic types can now be used in
constant expressions.
2021-06-24 17:35:49 +04:30
Daniel Bertalan
985adcca38 AK: Make C++ concepts support mandatory for compilers
The latest GCC and Clang versions both support this, so we can freely
use these in our code.
2021-06-24 17:35:49 +04:30
Gunnar Beutner
15e25a8c1f AK: Fix building Ptr32 on x86_64 2021-06-24 09:27:13 +02:00
Hendiadyoin1
7ca3d413f7 Kernel: Pull apart CPU.h
This does not add any functional changes
2021-06-24 00:38:23 +02:00
Ali Mohammad Pur
c38fafbf4e AK: Make {min,max,clamp}(T, U) work when U can be implicitly cast to T
It was really annoying to `static_cast` the arguments to be the same
type, so instead of doing that, just convert the second one to the first
one, and let the compiler warn about sign differences and truncation.
2021-06-23 19:04:08 +02:00
Lenny Maiorani
24225df979 AK: Reimplement any_of in terms of find_if
Problem:
- Now that a generic free-function form of `find_if` is implemented
  the code in `any_of` is redundant.

Solution:
- Follow the "don't repeat yourself" mantra and make the code DRY by
  implementing `any_of` in terms of `find_if`.
2021-06-20 10:54:09 +01:00
Idan Horowitz
5e53a690ac AK: Add support for keeping trailing zeros in fixed precision floats
This uses the same syntax as zero padding integers:
String::formatted("{:0.5}", 1.234) => "1.23400"
2021-06-19 16:13:59 +01:00
Itamar
03ef2a479a LibCoreDump: Include source locations of inlined functions in backtrace 2021-06-19 14:51:18 +02:00
Itamar
d26f4f9e8c AK: Add RedBlackTree::find_largest_not_above_iterator
It's a version of find_largest_not_above that returns an iterator.
2021-06-19 14:51:18 +02:00
sin-ack
3abcfcc178 AK: Add a way to disable the trimming of whitespace in to_*int
This behavior might not always be desirable, and so this patch adds a
way to disable it.
2021-06-18 19:18:15 +01:00
Ali Mohammad Pur
7eda164c25 AK: Add a :hex-dump mode to AK::Format
This will just hexdump the given value.
Note that not all formatters respect this, the ones that do are:
- (Readonly)Bytes: formatter added in this commit
- StringView / char const*
- integral types
2021-06-17 18:44:00 +04:30
Gunnar Beutner
0dd03413d6 Meta: Add support for declaring components
Components are a group of build targets that can be built and installed
separately. Whether a component should be built can be configured with
CMake arguments: -DBUILD_<NAME>=ON|OFF, where <NAME> is the name of the
component (in all caps).

Components can be marked as REQUIRED if they're necessary for a
minimally functional base system or they can be marked as RECOMMENDED
if they're not strictly necessary but are useful for most users.

A component can have an optional description which isn't used by the
build system but may be useful for a configuration UI.

Components specify the TARGETS which should be built when the component
is enabled. They can also specify other components which they depend on
(with DEPENDS).

This also adds the BUILD_EVERYTHING CMake variable which lets the user
build all optional components. For now this defaults to ON to make the
transition to the components-based build system easier.

The list of components is exported as an INI file in the build directory
(e.g. Build/i686/components.ini).

Fixes #8048.
2021-06-17 11:03:51 +02:00
Idan Horowitz
fea6d952a4 AK: Add the Utf8View::{contains, trim} helper methods 2021-06-16 20:05:18 +01:00
Brian Gianforcaro
31081e8ebf AK: Remove now unused InlineLinkedList class
All usages of AK::InlineLinkedList have been converted to
AK::IntrusiveList. So it's time to retire our old friend.

Note: The empty white space change in AK/CMakeLists.txt is to
force CMake to re-glob the header files in the AK directory so
incremental build will work when folks git pull this change locally.

Otherwise they'll get errors, because CMake will attempt to install
a file which no longer exists.
2021-06-16 10:40:01 +02:00
Brian Gianforcaro
b7f8343f87 AK+Tests: Add IntrusiveList<T,...>::insert_before(..) method
The insert_before method on AK::InlineLinkedList is used, so in order to
achieve feature parity, we need to implement it for AK::IntrusiveList as
well.
2021-06-16 10:40:01 +02:00
Brian Gianforcaro
4586668fc3 AK: Use IntrusiveList::remove() in the IntrusiveList::prepend() prolog
All other functions use the functionality for removal, use it in the
prepend function as well for consistency.
2021-06-16 10:40:01 +02:00
Idan Horowitz
8c7fe8d6c8 AK: Add support for removing SinglyLinkedList nodes during iteration
This commit also fixes the now-broken usage of SinglyLinkedList::remove
in the Piano application.
2021-06-15 23:59:21 +01:00
Idan Horowitz
f1f00be691 AK: Add a missing using AK::OrderedHashMap statement 2021-06-15 23:51:20 +01:00
Hediadyoin1
4a81c79909 AK: Add Ordering support to HashTable and HashMap
Adds a IsOrdered flag to Hashtable and HashMap, which allows iteration
in insertion order
2021-06-15 22:16:55 +02:00
Ali Mohammad Pur
f7f88adc78 AK: Add a function that casts an enum to its underlying type
This is basically the same thing as `std::to_underlying(Enum)`.
2021-06-15 22:06:33 +04:30
Andreas Kling
cd12b182ca AK: Add FlyString::from_fly_impl()
This allows you to create a FlyString directly from a known-fly
StringImpl instance.
2021-06-13 19:11:29 +02:00
Gunnar Beutner
d476144565 Userland: Allow building SerenityOS with -funsigned-char
Some of the code assumed that chars were always signed while that is
not the case on ARM hosts.

Also, some of the code tried to use EOF (-1) in a way similar to what
fgetc() does, however instead of storing the characters in an int
variable a char was used.

While this seemed to work it also meant that character 0xFF would be
incorrectly seen as an end-of-file.

Careful reading of fgetc() reveals that fgetc() stores character
data in an int where valid characters are in the range of 0-255 and
the EOF value is explicitly outside of that range (usually -1).
2021-06-13 18:52:58 +02:00
Matthew Olsson
ffda24373a AK: Add ByteBuffer::append(ReadonlyBytes) 2021-06-12 22:45:01 +04:30
Hediadyoin1
8a739f986a AK: Make Ptr32 more transparent
This adds a transparent dereference operator, aswell as a constant
arrow operator

Also increaces the verbosity of the code
2021-06-12 20:43:47 +04:30
Andreas Kling
dc65f54c06 AK: Rename Vector::append(Vector) => Vector::extend(Vector)
Let's make it a bit more clear when we're appending the elements from
one vector to the end of another vector.
2021-06-12 13:24:45 +02:00
Hendiadyoin1
5ffe23e4f3 AK+LibX86: Generalize u128/256 to AK::UFixedBigInt
Doing these as custom classes might be faster, especially when writing
them in SSE, but this would cause a lot of Code duplication and due to
the nature of constexprs and the intelligence of the compiler they might
be using SSE/MMX either way
2021-06-11 18:14:11 +04:30
Ali Mohammad Pur
7b2c838162 AK: Make NonnullRefPtrVector constructible from Vector<NonnullRefPtr> 2021-06-11 00:30:09 +02:00
Ali Mohammad Pur
d3db45c60b AK: Make Vector::take_last() ALWAYS_INLINE
This function doesn't do a whole lot, but is called quite a bit.
2021-06-09 23:05:32 +04:30
Ali Mohammad Pur
8410d6aadb AK: Make a bunch of Variant methods ALWAYS_INLINE 2021-06-09 23:05:32 +04:30
Ali Mohammad Pur
50349de38c Meta: Disable -Wmaybe-uninitialized
It's prone to finding "technically uninitialized but can never happen"
cases, particularly in Optional<T> and Variant<Ts...>.
The general case seems to be that it cannot infer the dependency
between Variant's index (or Optional's boolean state) and a particular
alternative (or Optional's buffer) being untouched.
So it can flag cases like this:
```c++
if (index == StaticIndexForF)
    new (new_buffer) F(move(*bit_cast<F*>(old_buffer)));
```
The code in that branch can _technically_ make a partially initialized
`F`, but that path can never be taken since the buffer holding an
object of type `F` and the condition being true are correlated, and so
will never be taken _unless_ the buffer holds an object of type `F`.

This commit also removed the various 'diagnostic ignored' pragmas used
to work around this warning, as they no longer do anything.
2021-06-09 23:05:32 +04:30
Max Wipfli
d1dae5f4d1 AK: Implement IPv4Address::to_string_reversed() 2021-06-09 17:43:32 +04:30
Idan Horowitz
71c54198fa AK: Allow changing the HashTable behaviour for sets on existing entries
Specifically, replacing the existing entry or just keeping it and
canceling the set.
2021-06-09 11:48:04 +01:00
Ali Mohammad Pur
3d94b5051d AK: Make Vector capable of holding reference types
This commit makes it possible to instantiate `Vector<T&>` and use it
to store references to `T` in a vector.
All non-pointer observers are made to return the reference, and the
pointer observers simply yield the underlying pointer.
Note that the 'find_*' methods act on the values and not the pointers
that are stored in the vector.
This commit also makes errors in various vector methods much more
readable by directly using requires-clauses on them.
And finally, it should be noted that Vector cannot hold temporaries :^)
2021-06-08 19:14:24 +02:00
Ali Mohammad Pur
48195b7c30 AK: Switch to east const in Vector.h
Let's get this out of the way before touching the file.
2021-06-08 19:14:24 +02:00
Ali Mohammad Pur
b7b0b199a8 AK: Reorder Vector methods to place similar methods next to each other
The methods of this class were all over the place, this commit reorders
them to place them in a more logical order:
- Constructors/Destructor
- Observers
- Comparisons and const existence checks
- Mutators: insert
- Mutators: append
- Mutators: prepend
- Mutators: assignment
- Mutators: remove
- OOM-safe mutators: insert
- OOM-safe mutators: append
- OOM-safe mutators: prepend
- OOM-safe size management
- Size management
- Iterators
2021-06-08 19:14:24 +02:00
Ali Mohammad Pur
c3fa13fa73 AK: Rename Vector::{value_type => ValueType} 2021-06-08 19:14:24 +02:00
Max Wipfli
3b04420490 AK: Don't create Utf8View from temporary String in URLParser
This fixes a bug where a Utf8View was created with data from a temporary
string, which was immediately deleted. This lead to a use-after-free
issue. This also changes most occurences for StringBuilder::to_string in
URLParser to use ::string_view(), as the value is passed as StringView
const& most of the time anyways.

This fixes oss-fuzz issue 34973.
2021-06-08 19:08:02 +02:00
Max Wipfli
3c7e775a9a AK: Utf8CodePointIterator: Don't output full string to debug output
When a code point is invalid, the full string was outputted to the debug
output. For large strings, this can make the system quite slow.
Furthermore, one of the cases incorrectly assumed the data to be null
terminated. This patch modifies the debug statements not to print the
full string.

This fixes oss-fuzz issue 35050.
2021-06-08 19:08:02 +02:00
Gunnar Beutner
d2662df57c LibC+AK: Remove our custom macros from <assert.h>
Other software might not expect these to be defined and behave
differently if they _are_ defined, e.g. scummvm which checks if
the TODO macro is defined and fails to build if it is.
2021-06-08 17:29:57 +02:00
Max Wipfli
1e8006ebb8 AK: Add children() accessor to Trie 2021-06-08 12:15:04 +02:00
Andreas Kling
7cbe4daa7c LibJS: Move bytecode debug spam behind JS_BYTECODE_DEBUG :^) 2021-06-07 18:11:59 +02:00
Brian Gianforcaro
f5e04759cc AK: Add IntrusiveList::size_slow() to match InlineLinkedList
The functionality is needed to replace InlineLinkedList with
IntrusiveList in the Kernel Process class.
2021-06-07 09:42:55 +02:00
FalseHonesty
403bb07443 LibVideo: Scaffold LibVideo and implement simplistic Matroska parser
This commit initializes the LibVideo library and implements parsing
basic Matroska container files. Currently, it will only parse audio
and video tracks.
2021-06-06 17:47:00 +02:00
Linus Groh
0a7e91329f Revert "Revert "AK: Always inline FlyString::view()""
This reverts commit f09216ac42.
This was supposed to be a local test only, didn't mean to push it. :^)
2021-06-06 08:05:49 +01:00
Linus Groh
f09216ac42 Revert "AK: Always inline FlyString::view()"
This reverts commit 66f15c2e0c.
2021-06-06 01:58:09 +01:00
Idan Horowitz
2011fcff24 AK: Add the parse_ascii_base36_digit method
This is similar to parse_ascii_hex_digit but can parse the whole A-Z
range (also known as base36).
2021-06-06 01:34:22 +01:00
Ali Mohammad Pur
51c2c69357 AK+Everywhere: Disallow constructing Functions from incompatible types
Previously, AK::Function would accept _any_ callable type, and try to
call it when called, first with the given set of arguments, then with
zero arguments, and if all of those failed, it would simply not call the
function and **return a value-constructed Out type**.
This lead to many, many, many hard to debug situations when someone
forgot a `const` in their lambda argument types, and many cases of
people taking zero arguments in their lambdas to ignore them.
This commit reworks the Function interface to not include any such
surprising behaviour, if your function instance is not callable with
the declared argument set of the Function, it can simply not be
assigned to that Function instance, end of story.
2021-06-06 00:27:30 +04:30
Andreas Kling
66f15c2e0c AK: Always inline FlyString::view() 2021-06-05 12:36:14 +02:00
Max Wipfli
2164d8aae8 AK: Stop using U+0000 as end of file code point in URL parser
This changes URL parser to use the 0xFFFFFFFF constant instead of 0 to
indicate end of file. This fixes a bug where inputs containing null
bytes would terminate the parser early, because they were interpreted
as end of file.
2021-06-05 10:53:31 +02:00
Max Wipfli
97425c7dfb AK: Make debugging URLParser easier
This patch adds a state_name method to URLParser to convert a state to a
string. With this, the debugging statements now display the state names.

Furthermore, this fixes a bug where non-ASCII code points were
formatted as characters, which fails an assertion in the formatting
system.
2021-06-05 10:53:31 +02:00
Max Wipfli
99d5555134 AK: Do not trim away non-ASCII bytes when parsing URL
Because non-ASCII code points have negative byte values, trimming away
control characters requires checking for negative bytes values.

This also adds a test case with a URL containing non-ASCII code points.
2021-06-05 10:53:31 +02:00
Max Wipfli
44937e2dfc AK: Update URLParser.{cpp,h} to use east const 2021-06-05 10:53:31 +02:00
Gunnar Beutner
8f81d9ad90 AK: Verify that functions aren't modified while they're being invoked
A Function object should not be set to a different functor while the
original functor is currently executing.
2021-06-04 19:32:25 +02:00
Gunnar Beutner
44418cb351 AK: Allow deferring clear() for the Function class
Ideally a Function should not be clear()ed while it's running.
Unfortunately a number of callers do just that and identifying all of
them would require inspecting all call sites for operator() and clear().

Instead this adds support for deferring clear() until after the
function has finished executing.
2021-06-04 19:32:25 +02:00
Ali Mohammad Pur
824a40e95b AK: Inline *String::is_one_of<Ts...>()
Previously this was generating a crazy number of symbols, and it was
also pretty-damn-slow as it was defined recursively, which made the
compiler incapable of inlining it (due to the many many layers of
recursion before it terminated).
This commit replaces the recursion with a pack expansion and marks it
always-inline.
2021-06-04 12:57:14 +02:00
R Smith
5a6f0ef1bc AK: Don’t drop lines between \r and \n in StringView::lines() (#7662)
StringView::lines() supports line-separators “\n”, “\r”, and “\r\n”.
The method will drop an entire line if it is surrounded by “\r”
and “\n” separators on the left and right sides respectively.
2021-06-04 12:06:08 +04:30
DexesTTP
e01f1c949f AK: Do not VERIFY on invalid code point bytes in UTF8View
The previous behavior was to always VERIFY that the UTF-8 bytes were
valid when iterating over the code points of an UTF8View. This change
makes it so we instead output the 0xFFFD 'REPLACEMENT CHARACTER'
code point when encountering invalid bytes, and keep iterating the
view after skipping one byte.

Leaving the decision to the consumer would break symmetry with the
UTF32View API, which would in turn require heavy refactoring and/or
code duplication in generic code such as the one found in
Gfx::Painter and the Shell.

To make it easier for the consumers to detect the original bytes, we
provide a new method on the iterator that returns a Span over the
data that has been decoded. This method is immediately used in the
TextNode::compute_text_for_rendering method, which previously did
this in a ad-hoc waay.

This also add tests for the new behavior in TestUtf8.cpp, as well
as reinforcements to the existing tests to check if the underlying
bytes match up with their expected values.
2021-06-03 18:28:27 +04:30
Max Wipfli
bc8d16ad28 Everywhere: Replace ctype.h to avoid narrowing conversions
This replaces ctype.h with CharacterType.h everywhere I could find
issues with narrowing conversions. While using it will probably make
sense almost everywhere in the future, the most critical places should
have been addressed.
2021-06-03 13:31:46 +02:00
Max Wipfli
f4a4c36fa0 AK: Add CharacterTypes.h
This patch introduces CharacterTypes.h, which aims to be a replacement
for most usages of ctype.h. In contrast to that implementation, this
header makes use of exclusively constexpr functions and support the full
Unicode code point set without any narrowing-conversion issues.
2021-06-03 13:31:46 +02:00
Brian Gianforcaro
ef4fdcf76f AK: Add reverse iterator support to AK::IntrusiveList
In order for IntrusiveList to be capable of replacing InlineLinkedList,
it needs to support reverse iteration. InlineLinkedList currently
supports manual reverse iteration by calling list->last() followed by
node->prev().
2021-06-03 13:27:40 +02:00
Gunnar Beutner
48da8a568d
AK: Remove unused JsonValue <=> IPv4Address conversion code
This removes code that isn't used anywhere.
2021-06-03 11:56:32 +01:00
Gunnar Beutner
a4f320c76b AK: Allow inlining more string functions 2021-06-03 08:06:51 +02:00
Gunnar Beutner
ed0068d04d AK: Allow inlining ref-count functionality
Previously we'd incur the costs for a function call via the PLT even
for the most trivial ref-count actions like increasing/decreasing the
reference count.

By moving the code to the header file we allow the compiler to inline
this code into the caller's function.
2021-06-03 08:06:51 +02:00
Ali Mohammad Pur
ea7ba34a31 AK+LibWasm+LibJS: Disallow Variant.has() on types that aren't contained
Checking for this (and get()'ing it) is always invalid, so let's just
disallow it.
This also finds two bugs where the code is checking for types that can
never actually be in the variant (which was actually a refactor
artifact).
2021-06-02 18:02:47 +02:00
Ali Mohammad Pur
6cd9906f60 AK: Make checked division also check for divide by zero 2021-06-02 16:09:16 +04:30
Ali Mohammad Pur
944855ca18 AK+Everywhere: Fix compiletime format parsing of replacement fields 2021-06-01 23:12:17 +04:30
Andreas Kling
c0d1a75881 AK: Strip leading/trailing C0-control-or-space in URLs correctly
We have to stop scanning once we hit a non-strippable character.
Add some tests to cover this.
2021-06-01 13:22:04 +02:00
Max Wipfli
2e23954271 AK: Move identity check from URL::operator==() to equals() 2021-06-01 12:23:16 +02:00
Max Wipfli
33396494f6 AK+LibWeb: Remove URL::to_string_encoded()
This replaces URL::to_string_encoded() with to_string() and removes the
former, since they are now equivalent.
2021-06-01 12:23:16 +02:00
Max Wipfli
a9114be1b8 AK: Use correct constness in URL class methods
This changes the URL class to use the correct constness for getters,
setters and other methods. It also changes the entire class to use east
const style.
2021-06-01 12:23:16 +02:00
Max Wipfli
f3fda59abd AK: Enable direct comparsion of Optional<T> and T
This patch introduces a new operator== to compare an Optional to its
contained type directly. If the Optional does not contain a value, the
comparison will always return false.

This also adds a test case for the new behavior as well as comparison
between Optional objects themselves.
2021-06-01 11:38:17 +02:00
Andreas Kling
12a42edd13 Everywhere: codepoint => code point 2021-06-01 10:01:11 +02:00
Andreas Kling
a8ae8b24de AK: Rename Utf32CodepointIterator => Utf32CodePointIterator 2021-06-01 09:46:19 +02:00
Andreas Kling
407d6cd9e4 AK: Rename Utf8CodepointIterator => Utf8CodePointIterator 2021-06-01 09:45:52 +02:00
Max Wipfli
5caaa52bee AK: Add hostname parameter to URL::create_with_file_scheme()
This adds a hostname parameter as the third parameter to
URL::create_with_file_scheme(). If the hostname is "localhost", it will
be ignored (as per the URL specification).

This can for example be used by ls(1) to create more conforming file
URLs.
2021-06-01 09:28:05 +02:00
Max Wipfli
ebf074ca29 AK: Rewrite URL::compute_validity() to conform to new parser
This rewrites the URL validation check to be more specific, so it can
more accurately detect if a user of URL class constructs invalid URLs by
hand.
2021-06-01 09:28:05 +02:00
Max Wipfli
522ef53b98 AK: Remove deprecated m_path member variable from URL
The m_path member variable has been superseded by m_paths. Thus, it has
been removed. The path() getter will continue to exist as a convenience
method for getting the path joined together as a string.
2021-06-01 09:28:05 +02:00
Max Wipfli
b7c6af0a04 AK: Replace URL::to_string() with new serialize() implementation 2021-06-01 09:28:05 +02:00
Max Wipfli
81f03e7a5d AK: Replace old URL parser with new URLParser::parse()
This replaces the old URL::parse() and URL::complete_url() parsing
mechanisms with the new spec-compliant URLParser::parse().
2021-06-01 09:28:05 +02:00
Max Wipfli
1697f3c35b AK: Add spec-compliant URL serialization methods
This adds URL serialization methods which are more in line with the
specification.

The serialize_for_display() method should be used e.g. in the browser
address bar, and as per the spec should not display username and
password. Furthermore, it could decode most percent-encoded code points,
although that is not implemented yet.
2021-06-01 09:28:05 +02:00
Max Wipfli
0d0ed4962f AK: Add a new, spec-compliant URLParser
This adds a new URL parser, which aims to be compliant with the URL
specification (https://url.spec.whatwg.org/). It also contains a
rudimentary data URL parser.
2021-06-01 09:28:05 +02:00
Max Wipfli
8a938a3e25 AK: Add helper functions and private data URL constructor to URL
This adds a few helper functions and a private constructor to
instantiate a data URL to the URL class. These will be needed by the
upcoming URL parser.
2021-06-01 09:28:05 +02:00
Max Wipfli
dd392dfa03 AK: Add member variables to the URL class
This adds the m_username, m_password, m_paths and m_cannot_be_a_base_url
member variables to the URL class. These are necessary for the upcoming
new URL parser.

The deprecated m_path variable shadows the m_paths variable if it is
non-null. This behavior will be removed once the old URL parser has been
removed.
2021-06-01 09:28:05 +02:00
Max Wipfli
0d41a7d39a AK: Remove URLParser
This removes URLParser, because its two exposed functions, urlencode()
and urldecode(), have been superseded by URL::percent_encode() and
URL::percent_decode(). This is in preparation for the introduction of a
new URL parser.
2021-06-01 09:28:05 +02:00
Max Wipfli
a603e69599 AK+Everywhere: Replace usages of URLParser::urlencode() and urldecode()
This replaces all occurrences of those functions with the newly
implemented functions URL::percent_encode() and URL::percent_decode().
The old functions will be removed in a further commit.
2021-06-01 09:28:05 +02:00
Max Wipfli
2a6c9bc5f7 AK: Implement more conforming URL percent encode/decode mechanism
This adds a few new functions to percent encode/decode strings according
to the URL specification. The functions allow specifying a
PercentEncodeSet, which is defined by the specification. It will be used
to replace the current urlencode() and urldecode() functions in a
further commit.

This commit adds a few duplicate helper functions in the URL class, such
as is_digit() and is_ascii_digit(). This will be cleaned up as soon as
the upcoming new URL parser will replace the current one.
2021-06-01 09:28:05 +02:00
Max Wipfli
0e4f7aa8e8 AK: Add trim() method to String, StringView and StringUtils
The methods added make it possible to use the trim mechanism with
specified characters, unlike trim_whitespace(), which uses predefined
characters.
2021-06-01 09:28:05 +02:00
Max Wipfli
14506e8f5e AK: Implement Utf8CodepointIterator::peek(size_t)
This adds a peek method for Utf8CodepointIterator, which enables it to
be used in some parsing cases where peeking is necessary.

peek(0) is equivalent to operator*, expect that peek() does not contain
any assertions and will just return an empty Optional<u32>.

This also implements a test case for iterating UTF-8.
2021-06-01 09:28:05 +02:00
Max Wipfli
31f6ba0952 AK: Internally rename protocol to scheme in URL
This renames all references to protocol to scheme, which is the name
used by the URL standard (https://url.spec.whatwg.org/). Externally, all
methods referencing "protocol" were duplicated with "scheme". The old
methods still exist as compatibility.
2021-06-01 09:28:05 +02:00
Max Wipfli
d6709ac87d AK: Omit unnecessary function parameter names in URL
This patch removes unnecessary function parameter names in declarations
of the URL class. It also changes parameter types from String to
StringView where applicable.
2021-06-01 09:28:05 +02:00
Linus Groh
028a337a6d AK: Add Formatter<unsigned char[Size]> 2021-05-31 17:43:54 +01:00
Andrew Kaster
b3746f9745 AK: Guard inline assembly with ARCH(I386) and provide alternative
For non-x86 targets, it's not very nice to define inline functions in
AK/Memory.h with asm volatile implementations. Guard this inline
assembly with ARCH(I386) and provide portable alternatives. Since we
always compile with optimizations, the hand-vectorized memset and
memcpy seem to be of dubious value, but we'll keep them here until
proven one way or another.

This should fix the Lagom build on native M1 macOS that was reported
on Discord the other day.
2021-05-31 17:29:09 +01:00
Ali Mohammad Pur
2b5732ab77 AK+Kernel: Disallow implicitly lifting pointers to OwnPtr's
This doesn't really _fix_ anything, it just gets rid of the API and
instead makes the users explicitly use `adopt_own_if_non_null()`.
2021-05-31 17:09:12 +04:30
Gunnar Beutner
de0aa44bb6 AK: Remove the m_length member for StringBuilder
Instead we can just use ByteBuffer::size() which already keeps track
of the buffer's size.
2021-05-31 14:49:00 +04:30
Gunnar Beutner
4c32a128ef AK: Fix accidentally-quadratic behavior in StringBuilder
Found by OSS Fuzz:

Related commit: 3908a49661

Co-authored-by: Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
2021-05-31 14:49:00 +04:30
Gunnar Beutner
8f755c9d07 AK: Use ByteBuffer::append for the StringBuilder class
Previously the StringBuilder class would use memcpy() to write
directly into the ByteBuffer's buffer. Instead we should use the
append() method which ensures we don't overrun the buffer.
2021-05-31 14:49:00 +04:30
Gunnar Beutner
425bfabd66 AK: Split the ByteBuffer::trim method into two methods
This allows us to mark the slow part (i.e. where we copy the buffer) as
NEVER_INLINE because this should almost never get called and therefore
should also not get inlined into callers.
2021-05-31 14:49:00 +04:30
Gunnar Beutner
d8b5fa9dfe AK: Remove the public ByteBuffer::trim method
This removes the public trim() method because it is no longer
necessary. Callers can instead use resize().
2021-05-31 14:49:00 +04:30
Gunnar Beutner
5f18cf75c5 AK: Replace ByteBuffer::grow with resize()/ensure_capacity()
Previously ByteBuffer::grow() behaved like Vector<T>::resize().
However the function name was somewhat ambiguous - and so this patch
updates ByteBuffer to behave more like Vector<T> by replacing grow()
with resize() and adding an ensure_capacity() method.

This also lets the user change the buffer's capacity without affecting
the size which was not previously possible.

Additionally this patch makes the capacity() method public (again).
2021-05-31 14:49:00 +04:30
Andrew Kaster
0af192ff8d AK: Handle LEB128 encoded values that are too large for the result type
Previously, we would go crazy and shift things way out of bounds.
Add tests to verify that the decoding algorithm is safe around the
limits of the result type.
2021-05-31 14:25:27 +04:30
Ben Wiederhake
dfd988707c Revert "AK: Fix accidentally-quadratic behavior in StringBuilder"
This reverts commit 2d011961c9.
2021-05-30 21:39:39 +01:00
Tim Schumacher
8c3e4ccd72 AK: Honor variable precision argument when formatting
printf didn't check whether the additional integer variable belongs to
the field width specifier or to the precision specifier, and always
applied it to the field width instead.

Implement the case distinction that we already use in literal width
and precision specifiers for the variable version as well so that
they are correctly attributed.
2021-05-30 18:45:06 +01:00
Edwin Hoksberg
e68780e1ad WebServer: Put dbgln's behind WEBSERVER_DEBUG
These dbgln's caused excessive load in the WebServer process,
accounting for ~67% of the processing time when serving a webpage
with a bunch of resources like serenityos.org/happy/2nd/.
2021-05-30 17:41:56 +01:00
Max Wipfli
a557f83f8c AK: Verify that m_impl is non-null in String::operator[]
This helps to find bugs where null strings are indexed into with
operator[], as this would previously only report a RefPtr null
dereference.
2021-05-30 17:41:49 +01:00
Ben Wiederhake
2d011961c9 AK: Fix accidentally-quadratic behavior in StringBuilder
Found by OSS Fuzz:
#34451 (old bug)

Related commit: 3908a49661
2021-05-30 14:39:30 +01:00
Andrew Kaster
7b4dc590e7 AK+Userland: Use akaster@serenityos.org for my copyright headers 2021-05-30 14:35:34 +01:00
Andreas Kling
c584421592 AK: Make HashTable::operator=(HashTable&&) clear the moved-from table
This is consistent with how other AK containers behave when moved from.
2021-05-30 14:34:32 +02:00
sin-ack
8be98af77c AK: Declare malloc_good_size as extern "C"
This would otherwise cause an error with clang when __serenity__ wasn't
defined.
2021-05-30 11:10:47 +01:00
Andreas Kling
66f3ec687b AK: Move RefCountedBase definitions out-of-line
This dramatically reduces code size since we no longer inline all these
VERIFY() checks everywhere. Appears to be performance neutral.
2021-05-29 20:18:57 +02:00
Andrew Kaster
eae14f4ba6 AK: Extend round_to_power_of_two to types other than unsigned
The previous implementation hardcoded unsigned, when the same logic
easily extends to unsigned long, signed types, and other Integral types.
2021-05-29 17:47:29 +01:00
Brian Gianforcaro
99e23a711d AK+Kernel: Hide AK::adopt_own from usage in the Kernel
We want to discourage folks from using APIs which lull you into a sense
of false safety in terms of OOM. There are cases where you want to force
allocations to succeed or crash, but those should use a more explicit
API than `AK::adopt_own(.)`.
2021-05-29 09:04:05 +02:00
Andrew Kaster
212365130d AK: Add platform macros to detect presence of AddressSanitizer
The ASAN_[UN]POISON_MEMORY_REGION macros can be used to manually notify
the AddressSanitizer runtime about the reachability of instrumented code
accessing a memory region. This is most useful for manually managed
heaps and arenas that do not go directly to malloc or alligned_alloc.
2021-05-28 07:59:41 +02:00
Gunnar Beutner
bacb2dea70 AK: Convince GCC that m_outline_capacity isn't being read
Previously GCC came to the conclusion that we were reading
m_outline_capacity via ByteBuffer(ByteBuffer const&) -> grow()
-> capacity() even though that could never be the case because
m_size is 0 at that point which means we have an inline buffer
and capacity() would return inline_capacity in that case without
reading m_outline_capacity.

This makes GCC inline parts of the grow() function into the
ByteBuffer copy constructor which seems sufficient for GCC to
realize that m_outline_capacity isn't actually being read.
2021-05-27 22:39:25 +02:00
Tim Schumacher
0aaa992c1c LexicalPath: Reset dirname if it's empty
dirname ends up empty if the canonical path only contains one element.

Reset it to the default for relative/absolute paths if that is the case.
2021-05-27 18:21:36 +04:30
Andrew Kaster
505f84daae Kernel+AK: Move UBSanitizer to AK, and to AK namespace
In preparation for copying UBSanitizer to userspace, move the header to
AK :^)
2021-05-27 15:18:03 +02:00
Ali Mohammad Pur
c022b6d74e AK: Add a way to slice from the end of a span 2021-05-27 17:28:41 +04:30
Andrew Kaster
6459c5a713 AK: Explicitly initialize buffer member in ByteBuffer
When compiling the Kernel with Og, the compiler complains that
m_outline_capacity might be uninitialized when calling capacity()

Note that this fix is not really what we want. Ideally only outline
buffer and outline capacity would need initialized, not the entire
inline buffer. However, clang considers the class to not be
default-constructible if we make that change, while gcc accepts it.
2021-05-27 10:21:30 +02:00
Jesse Buhagiar
2b123cc592 AK: Implement AK::Stack 2021-05-26 16:36:53 +04:30
Ali Mohammad Pur
59e01e2813 AK: Define MakeSigned<...>::Type as void in the base struct
This was probably forgotten in the last rewrite, this would make
IsIntegeral<T> not work for floating points.
2021-05-26 15:34:13 +04:30
Matthew Olsson
777c232e16 AK: Add String::repeated(StringView, size_t count) 2021-05-25 00:24:09 +04:30
Andreas Kling
de395a3df2 AK+Everywhere: Consolidate String::index_of() and String::find()
We had two functions for doing mostly the same thing. Combine both
of them into String::find() and use that everywhere.

Also add some tests to cover basic behavior.
2021-05-24 11:59:18 +02:00
Jelle Raaijmakers
2137675047 AK/NumericLimits: Add lowest() for floating-point types 2021-05-22 13:38:34 +01:00
Lenny Maiorani
1c6d2ff21c IntrusiveList: Remove redundant constructor
Problem:
- The constructor is defined to be the default constructor.

Solution:
- Let the compiler generate the destructor by setting it to the
  default.
2021-05-22 10:11:14 +01:00
Jelle Raaijmakers
3dc0657e58 AK/Vector: Constify find_first_index() 2021-05-22 09:34:55 +02:00
Ali Mohammad Pur
6b4d7b6c19 AK: Fix Variant construction from lvalue references
Fixes #7371 and appends its test cases.
2021-05-22 09:34:31 +02:00
Ali Mohammad Pur
3f350c3b65 AK: Remove [[gnu::noinline]] attribute from some variant members
These were left-overs from a debugging session :P
2021-05-22 09:34:31 +02:00
Idan Horowitz
3bc3a7a23a AK: Use calculate_base64_encoded_length in encode_base64
We were accidentally calling calculate_base64_decoded_length instead,
which resulted in extra allocations during the StringBuilder::append
calls that can be avoided.
2021-05-22 08:54:32 +04:30
Gunnar Beutner
c3efae85f2 Games: Add Hearts 2021-05-21 23:38:18 +02:00
Max Wipfli
a72bb34970 AK: Add Utf8View::iterator_at_byte_offset method
This implements a method to get a Utf8CodepointIterator at a specified
byte offset.
2021-05-21 21:57:03 +02:00
Max Wipfli
c1b452f754 AK: Add substring methods to Utf8View
This patch implements a Unicode-safe substring method, which can be used
when offset and length should be specified in actual characters instead
of bytes.

This can be used to mitigate issues where a string is split in the
middle of a UTF-8 multi-byte character, which leads to invalid UTF-8.

Furthermore, it implements to common shorthands for substring methods
which take only an offset and return the substring until the end of the
string.
2021-05-21 21:57:03 +02:00
Max Wipfli
8c19c2f296 AK: Change some argument and return types in Utf8View from int to size_t
This changes the return type of Utf8View::byte_length and the argument
types of substring_view from int to size_t.
2021-05-21 21:57:03 +02:00
Andrew Kaster
a5889b9aad Shell: Hide job times behind SHELL_JOB_DEBUG flag 2021-05-21 12:05:34 +04:30
r-paiva
943f4eb287 LibCore: Let IODevice::can_read_line() buffer until \n or EOF
If a line was larger than 1024 bytes or the file ended without a
newline character, can_read_line would return false.

IODevice::can_read_line() now reads until a newline is found or
EOF is reached.

fixes #5907
2021-05-20 23:53:06 +02:00
r-paiva
edcfbdf4bd AK: Added contains_in_range to Vector
Vector::contains_in_range() allows the search of an element in a given
range on a vector object.
Also added testcases for the new Vector method.
2021-05-20 23:53:06 +02:00
Max Wipfli
3c2565da94 AK: Add UnicodeUtils with Unicode-related helper functions
This introduces the UnicodeUtils file, which contains helper functions
related to Unicode. This is in contrast to StringUtils, whose functions
are not directly related to Unicode and are, in theory,
encoding-agnostic.
2021-05-20 22:10:45 +02:00
Lenny Maiorani
98468ae2d2 Variant: Remove redundant inline keyword
Problem:
- `constexpr inline` is redundant because `constexpr` implies `inline`.

Solution:
- Remove redundancy.
2021-05-20 18:58:18 +02:00
Gunnar Beutner
96b75af5d1 AK: Don't unlink intrusive list elements in the destructor
Removing the element from the intrusive linked list might not be safe
if doing so requires a lock. Instead this is something the caller
should have done so let's verify instead that we're not on any lists.
2021-05-20 09:09:10 +02:00
Lenny Maiorani
d25d4ec0ee Bitmap: De-duplicate bitmasks
Problem:
- Bitmasks are duplicated.
- Bitmasks are C-style arrays.

Solution:
- Move bitmasks to BitmapView.h.
- Change C-style arrays to be AK::Array for added safety.
2021-05-19 23:37:10 +01:00
Maciej Zygmanowski
80077cea86 AK: Add String::find_all() and String::count() 2021-05-19 20:51:51 +01:00
Gunnar Beutner
661d1aa8d1 AK: Add inline storage support for the Function class
This allows us to allocate most Function objects on the stack or as
part of other objects and gets rid of quite a few allocations.
2021-05-19 21:36:57 +02:00
Gunnar Beutner
d954c11f66 Everywhere: Add missing includes for <AK/OwnPtr.h>
Previously <AK/Function.h> also included <AK/OwnPtr.h>. That's about to
change though. This patch fixes a few build problems that will occur
when that change happens.
2021-05-19 21:36:57 +02:00
Timothy Flynn
145e246a5e AK: Allow AK::Variant::visit to return a value
This changes Variant::visit() to forward the value returned by the
selected visitor invocation. By perfectly forwarding the returned value,
this allows for the visitor to return by value or reference.

Note that all provided visitors must return the same type - the compiler
will otherwise fail with the message: "inconsistent deduction for auto
return type".
2021-05-19 20:41:09 +02:00
Lenny Maiorani
0681086cad Time: Remove static from function local constexpr variable
Problem:
- Function local `constexpr` variables do not need to be
  `static`. This consumes memory which is unnecessary and can prevent
  some optimizations.
- C-style arrays are not as safe as AK::Arrays and require the user to
  specify the length of the array manually.

Solution:
- Remove `static` keyword.
- Change from C-style array for AK::Array.
2021-05-19 16:24:02 +02:00
Ali Mohammad Pur
73cb566041 AK: Make vout() log to debug instead of VERIFY()'ing
In case the write was to stderr/stdout, and it just so happened to fail
because of an issue like "the pty is gone", VERIFY() would end up
calling vout() back to write to stderr, which would then fail forever
until the stack is exhausted.
"Fixes" the issue where the Shell would crash in horrible ways when the
terminal is closed.
2021-05-19 09:19:29 +02:00
Gunnar Beutner
598d7f4127 AK: StringBuilder should prefer to use its inline capacity first
Previously StringBuilder would start allocating an external buffer
once the caller has used up more than half of the inline buffer's
capacity. Instead we should prefer to use the inline buffer until
it is full and only then start to allocate an external buffer.
2021-05-18 21:49:10 +02:00
Max Wipfli
f51b0729f5 AK: Implement StringBuilder::append_as_lowercase(char ch)
This patch adds a convenience method to AK::StringBuilder which converts
ASCII uppercase characters to lowercase before appending them.
2021-05-18 21:02:07 +02:00
Ali Mohammad Pur
b6e5c76427 AK: Add deduction guides to Tuple 2021-05-18 18:48:15 +01:00
Ali Mohammad Pur
5bf37d758c AK: Let HashMap export its key and value types 2021-05-18 18:48:15 +01:00
stelar7
24c5b0e81c LibGfx: Add support for DDS images 2021-05-18 08:45:53 +01:00
Gunnar Beutner
c99fd217e2 AK: Make LexicalPath handle relative paths correctly
Previously LexicalPath would consider "." and ".." as equivalent to
"/". This is not true though.
2021-05-18 08:11:21 +02:00
Lenny Maiorani
ebb1d9740e BitmapView: Disable mutations of the underlying Bitmap
Problem:
- `BitmapView` permits changing the underlying `Bitmap`. This violates
  the idea of a "view" since views are simply overlays which can
  themselves change but do not change the underlying data.

Solution:
- Migrate all non-`const` member functions to Bitmap.
2021-05-18 08:10:45 +02:00
Lenny Maiorani
44a9c7c23e AK/PrintfImplementation: Change static constexpr array to function local
Problem:
- Static variables take memory and can be subject to less optimization.
- This static variable is only used in 1 place.

Solution:
- Move the variable into the function and make it non-static.
2021-05-18 08:07:01 +02:00
Gunnar Beutner
3908a49661 AK: Revert removal of StringBuilder::will_append optimization
This was removed as part of the ByteBuffer changes but the allocation
optimization is still necessary at least for non-SerenityOS targets
where malloc_good_size() isn't supported or returns a small value and
causes a whole bunch of unnecessary reallocations.
2021-05-18 08:06:32 +02:00
Linus Groh
61e132ddfa AK: Sort all the debug macros 2021-05-17 22:33:35 +01:00
Ali Mohammad Pur
056be42c0b LibWasm: Start implementing a naive bytecode interpreter
As the parser now flattens out the instructions and inserts synthetic
nesting/structured instructions where needed, we can treat the whole
thing as a simple parsed bytecode stream.
This currently knows how to execute the following instructions:
- unreachable
- nop
- local.get
- local.set
- {i,f}{32,64}.const
- block
- loop
- if/else
- branch / branch_if
- i32_add
- i32_and/or/xor
- i32_ne

This also extends the 'wasm' utility to optionally execute the first
function in the module with optionally user-supplied arguments.
2021-05-17 23:25:30 +02:00
Ali Mohammad Pur
e9b746a723 AK: Include HashTable.h in StringImpl.cpp
This was used without an include, I'm not sure how it didn't break
before :P
2021-05-17 23:25:30 +02:00
Ali Mohammad Pur
1ad6ac1cb4 AK: Include String.h in ScopeLogger 2021-05-17 23:25:30 +02:00
Linus Groh
0aab774343 Everywhere: Fix a bunch of typos 2021-05-17 17:48:55 +01:00
Andreas Kling
bebbeda726 Revert "BitmapView: Disable mutations of the underlying Bitmap"
This reverts commit f25209113f.
2021-05-17 18:29:47 +02:00
Lenny Maiorani
f25209113f BitmapView: Disable mutations of the underlying Bitmap
Problem:
- `BitmapView` permits changing the underlying `Bitmap`. This violates
  the idea of a "view" since views are simply overlays which can
  themselves change but do not change the underlying data.

Solution:
- Migrate all non-`const` member functions to Bitmap.
2021-05-17 18:16:35 +02:00
Andrew Kaster
73adbb319c AK: Don't read past the end in BitmapView::count_in_range()
The current code is factored such that reads to the entirety of the last
byte should be dropped. This was relying on the fact that last would be
one past the end in that case. Instead of actually reading that byte
when it's completely out of bounds of the bitmask, just skip reads that
would be invalid. Add more tests to make sure that the behavior is
correct for byte aligned reads of byte aligned bitmaps.
2021-05-16 21:58:14 +01:00
Andrew Kaster
11214bc94d AK: Don't call memcpy with null argument in ByteBuffer::copy()
This was happening in TestBase64.test_decode, while copying an empty
string.
2021-05-16 21:58:14 +01:00
Liav A
20743e8aed Kernel/Graphics + SystemServer: Support text mode properly
As we removed the support of VBE modesetting that was done by GRUB early
on boot, we need to determine if we can modeset the resolution with our
drivers, and if not, we should enable text mode and ensure that
SystemServer knows about it too.

Also, SystemServer should first check if there's a framebuffer device
node, which is an indication that text mode was not even if it was
requested. Then, if it doesn't find it, it should check what boot_mode
argument the user specified (in case it's self-test). This way if we
try to use bochs-display device (which is not VGA compatible) and
request a text mode, it will not honor the request and will continue
with graphical mode.

Also try to print critical messages with mininum memory allocations
possible.

In LibVT, We make the implementation flexible for kernel-specific
methods that are implemented in ConsoleImpl class.
2021-05-16 19:58:33 +02:00
Gunnar Beutner
53d0150827 AK+Userland: Remove nullability feature for the ByteBuffer type
Nobody seems to use this particular feature, in fact there were some
bugs which were uncovered by removing operator bool.
2021-05-16 17:49:42 +02:00
Gunnar Beutner
fcaf98361f AK: Turn ByteBuffer into a value type
Previously ByteBuffer would internally hold a RefPtr to the byte
buffer and would behave like a reference type, i.e. copying a
ByteBuffer would not create a duplicate byte buffer, but rather
two objects which refer to the same internal buffer.

This also changes ByteBuffer so that it has some internal capacity
much like the Vector<T> type. Unlike Vector<T> however a byte
buffer's data may be uninitialized.

With this commit ByteBuffer makes use of the kmalloc_good_size()
API to pick an optimal allocation size for its internal buffer.
2021-05-16 17:49:42 +02:00
Gunnar Beutner
f0fa51773a AK+Userland: Fix some compiler warnings and make variables const-ref
This fixes a few compiler warnings and makes some variables const-ref
in preparation for the next commit which changes how ByteBuffer works.
2021-05-16 17:49:42 +02:00
Timothy Flynn
ce030ca584 AK+Meta: Add a debug option for Solitaire 2021-05-16 16:37:51 +02:00
Daniel Bertalan
be519022c3 LibVT: Implement new ANSI escape sequence parser
This commit replaces the former, hand-written parser with a new one that
can be generated automatically according to a state change diagram.

The new `EscapeSequenceParser` class provides a more ergonomic interface
to dealing with escape sequences. This interface has been inspired by
Alacritty's [vte library](https://github.com/alacritty/vte/).

I tried to avoid changing the application logic inside the `Terminal`
class. While this code has not been thoroughly tested, I can't find
regressions in the basic command line utilities or `vttest`.

`Terminal` now displays nicer debug messages when it encounters an
unknown escape sequence. Defensive programming and bounds checks have
been added where we access parameters, and as a result, we can now
endure 4-5 seconds of `cat /dev/urandom`. :D

We generate EscapeSequenceStateMachine.h when building the in-kernel
LibVT, and we assume that the file is already in place when the userland
library is being built. This will probably cause problems later on, but
I can't find a way to do it nicely.
2021-05-16 11:50:56 +02:00
Nicholas Baron
aa4d41fe2c
AK+Kernel+LibELF: Remove the need for IteratorDecision::Continue
By constraining two implementations, the compiler will select the best
fitting one. All this will require is duplicating the implementation and
simplifying for the `void` case.

This constraining also informs both the caller and compiler by passing
the callback parameter types as part of the constraint
(e.g.: `IterationFunction<int>`).

Some `for_each` functions in LibELF only take functions which return
`void`. This is a minimal correctness check, as it removes one way for a
function to incompletely do something.

There seems to be a possible idiom where inside a lambda, a `return;` is
the same as `continue;` in a for-loop.
2021-05-16 10:36:52 +01:00
Gunnar Beutner
f89e8fb71a AK+LibC: Implement malloc_good_size() and use it for Vector/HashTable
This implements the macOS API malloc_good_size() which returns the
true allocation size for a given requested allocation size. This
allows us to make use of all the available memory in a malloc chunk.

For example, for a malloc request of 35 bytes our malloc would
internally use a chunk of size 64, however the remaining 29 bytes
would be unused.

Knowing the true allocation size allows us to request more usable
memory that would otherwise be wasted and make that available for
Vector, HashTable and potentially other callers in the future.
2021-05-15 16:30:14 +02:00
Andreas Kling
a4099fc756 AK: Try to avoid String allocation in FlyString(StringView)
If we're constructing a FlyString from a StringView, and we already
have a matching StringImpl in the table, use HashTable::find() to
locate the existing string without creating a temporary String.
2021-05-15 11:01:05 +02:00
Jean-Baptiste Boric
069bf988ed AK: Introduce get_random_uniform()
This is arc4random_uniform(), but inside AK.
2021-05-14 22:24:02 +02:00
Jean-Baptiste Boric
ad7cd05fc1 AK: Fix redefinition of macro inside AK/Platform.h 2021-05-14 22:24:02 +02:00
Andreas Kling
d039542c7c AK: Remove unused STRINGIMPL_DEBUG instrumentation 2021-05-14 17:17:32 +02:00
Andreas Kling
3e603b2f32 AK: Make StringView::hash() constexpr
This required moving string_hash() to its own header so that everyone
can see it.
2021-05-14 15:24:32 +02:00
Gunnar Beutner
a8e6cdc0d8 AK: Avoid allocations in ByteBuffer
Creating a ByteBuffer involves two allocations:

-One for the ByteBufferImpl object
-Another one for the actual byte buffer

This changes the ByteBuffer and ByteBufferImpl classes
so only one allocation is necessary.
2021-05-14 12:51:13 +02:00
Andreas Kling
fccfc33dfb AK: Use move semantics to avoid copying in JSON parser
The JSON parser was deep-copying JsonValues left and right, and it was
all totally avoidable. :^)
2021-05-14 11:54:43 +02:00
Ali Mohammad Pur
df515e1d85 LibCrypto+LibTLS: Avoid unaligned reads and writes
This adds an `AK::ByteReader` to help with that so we don't duplicate
the logic all over the place.
No more `*(const u16*)` and `*(const u32*)` for anyone.
This should help a little with #7060.
2021-05-14 08:39:29 +01:00
Ali Mohammad Pur
bfd4c7a16c AK: Avoid passing nullptr to __buitin_memcpy() in ByteBuffer::grow() 2021-05-14 08:39:29 +01:00
Andrew Kaster
28987d1b56 AK: Add #define for [[gnu::no_sanitize_address]]
This lines up with other attribute global #defines
2021-05-14 08:34:00 +01:00
Gunnar Beutner
a11a1cd4d6 AK: Vector::resize() should initialize new slots for primitive types
We call placement new for the newly added slots. However, we should
also specify an initializer so primitive data types like u64 are
initialized appropriately.
2021-05-14 00:35:57 +02:00
Ali Mohammad Pur
06a1c27e4d AK: Fix Variant's copy constructor trying to delegate to the wrong base
This was forgotten in 4fdbac2.
2021-05-13 19:44:32 +01:00
Brian Gianforcaro
d07309a180 AK: Introduce adopt_ref_if_nonnull(..) to aid in Kernel OOM hardening
Unfortunately adopt_ref requires a reference, which obviously does not
work well with when attempting to harden against allocation failure.
The adopt_ref_if_nonnull() variant will allow you to avoid using bare
pointers, while still allowing you to handle allocation failure.
2021-05-13 08:29:01 +02:00
Brian Gianforcaro
b0fef03e3f AK: Introduce adopt_own_if_nonnull(..) to aid in Kernel OOM hardening
Unfortunately adopt_own requires a reference, which obviously does not
work well with when attempting to harden against allocation failure.
The adopt_own_if_nonnull() variant will allow you to avoid using bare
pointers, while still allowing you to handle allocation failure.
2021-05-13 08:29:01 +02:00
sin-ack
2de11b0dc8 AK: Add LexicalPath::append and LexicalPath::join
This patch adds two new methods to LexicalPath.  LexicalPath::append
appends a new path component to a LexicalPath, and LexicalPath::join
constructs a new LexicalPath from one or more components.

Co-authored-by: Gunnar Beutner <gunnar@beutner.name>
2021-05-12 22:38:20 +02:00
Mart G
b00cdf8ed8 Kernel+LibC: Make get_dir_entries syscall retriable
The get_dir_entries syscall failed if the serialized form of all the
directory entries together was too large to fit in its temporary buffer.

Now the kernel uses a fixed size buffer, that is flushed to an output
buffer when it is full. If this flushing operation fails because there
is not enough space available, the syscall will return -EINVAL. That
error code is then used in userspace as a signal to allocate a larger
buffer and retry the syscall.
2021-05-12 12:50:23 +02:00
Ali Mohammad Pur
02de813950 AK: Add a Tuple implementation
Please don't use this outside of metaprogramming needs, *please*.
2021-05-11 14:09:17 +01:00
Ali Mohammad Pur
4fdbac236d AK/Variant: Deduplicate the contained types
This allows the construction of `Variant<int, int, int>`.
While this might not seem useful, it is very useful for making variants
that contain a series of member function pointers, which I plan to use
in LibGL for glGenLists() and co.
2021-05-11 14:09:17 +01:00
Ali Mohammad Pur
3038b6b7dc AK: Avoid the use of typeinfo in Variant
typeid() and RTTI was a nice clutch to implement this, but let's move
away from the horrible slowness and implement variants using type
indices for faster variants.
2021-05-11 14:09:17 +01:00
Matthew Olsson
8c745ad0d9 LibPDF: Parse page structures
This commit introduces the ability to parse the document catalog dict,
as well as the page tree and individual pages. Pages obviously aren't
fully parsed, as we won't care about most of the fields until we
start actually rendering PDFs.

One of the primary benefits of the PDF format is laziness. PDFs are
not meant to be parsed all at once, and the same is true for pages.
When a Document is constructed, it builds a map of page number to
object index, but it does not fetch and parse any of the pages. A page
is only parsed when a caller requests that particular page (and is
cached going forwards).

Additionally, this commit also adds an object_cast function which
logs bad casts if DEBUG_PDF is set. Additionally, utility functions
were added to ArrayObject and DictObject to get all types of objects
from the collections to avoid having to manually cast.
2021-05-10 10:32:39 +02:00
Matthew Olsson
af9a7b1374 AK: Add missing 'const' in Span 2021-05-10 10:32:39 +02:00
Ali Mohammad Pur
aa4d8d26b9 LibWasm: Start implementing a basic WebAssembly binary format parser
This can currently parse a really simple module.
Note that it cannot parse the DataCount section, and it's still missing
almost all of the instructions.
This commit also adds a 'wasm' test utility that tries to parse a given
webassembly binary file.
It currently does nothing but exit when the parse fails, but it's a
start :^)
2021-05-08 22:14:39 +02:00
Ali Mohammad Pur
56a6d7924e AK: Let Result<T, E> know its Value and Error types
It's much easier to ask for T::ValueType than for
RemoveReference<decltype(declval<T>().release_value())>
2021-05-08 22:14:39 +02:00
Ali Mohammad Pur
62af7c4bdf AK+LibCpp: Remove DEBUG_SPAM in favour of per-application defines
What happens if one file defines DEBUG_SPAM, and another doesn't,
then we link them together and get ODR violations? -- @ADKaster
2021-05-08 22:14:39 +02:00
Ali Mohammad Pur
080f2c0e3e AK: Add an optional 'extra' descriptive field to ScopeLogger
Often it's easier to know what the functions are doing with a unique
name next to the function's name :)
2021-05-08 22:14:39 +02:00
Itamar
8a01167c7d AK: Add missing GenericTraits<NonnullRefPtr>
This enables us to use keys of type NonnullRefPtr in HashMaps and
HashTables.

This commit also includes fixes in various places that used
HashMap<T, NonnullRefPtr<U>>::get() and expected to get an
Optional<NonnullRefPtr<U>> and now get an Optional<U*>.
2021-05-08 18:10:56 +02:00
Itamar
1da0d402b7 AK: Add constructors to Optional that accept non const qualified inputs 2021-05-08 18:10:56 +02:00
Itamar
484823e9d5 AK: Add a non-const overload to HapMap::get()
Additionally, the const version of get() returns Optional<ConstPeekType>
for smart pointers.

For example, if the value in the HashMap is OwnPtr<u32>,
HashMap::get() const returns Optional<const u32*>.
2021-05-08 18:10:56 +02:00
Itamar
b816bd0806 AK: Add ConstPeekType to Traits
Also, the PeekType of smart pointers is now T* instead of const T*.

Note: This commit doesn't compile, it breaks HashMap::get() for some
types. Fixed in the next commit.
2021-05-08 18:10:56 +02:00
Jesse Buhagiar
4807d32139 LibGL: Implement a basic OpenGL 1.x compatible library
This currently (obviously) doesn't support any actual 3D hardware,
hence all calls are done via software rendering.

Note that any modern constructs such as shaders are unsupported,
as this driver only implements Fixed Function Pipeline functionality.

The library is split into a base GLContext interface and a software
based renderer implementation of said interface. The global glXXX
functions serve as an OpenGL compatible c-style interface to the
currently bound context instance.

Co-authored-by: Stephan Unverwerth <s.unverwerth@gmx.de>
2021-05-08 10:13:22 +02:00
Stephan Unverwerth
0a557d65a0 AK: Add epsilon() to NumericLimits for float, double, long double 2021-05-08 10:13:22 +02:00
Andreas Kling
834b6508d7 AK: Remove StringBuilder::appendf()
All users have been converted to using AK::Format via appendff().
2021-05-07 21:12:09 +02:00
Valtteri Koskivuori
1069979ddf AK: Implement Span::starts_with()
Useful for checking for contents at the start of a span.
2021-05-07 11:46:53 +01:00
Ali Mohammad Pur
da68c4580c AK: Make Checked<T> check for division overflow as well
Signed integer overflow can occur with division when the RHS is -1,
as the negative values' range is one larger than the positives.
2021-05-07 09:26:11 +02:00
Brian Gianforcaro
67322b0702 Tests: Move AK tests to Tests/AK 2021-05-06 17:54:28 +02:00
AnotherTest
ba6c9423b8 AK: Implement printf fraction length specification for strings
This adds support for '%.20s' and friends :^)
2021-05-06 15:20:31 +01:00
Ali Mohammad Pur
a51113c58e AK: Add a Variant<Ts...> implementation
Also adds an AK::Empty struct, because 'empty' variants are useful, but
this implementation leaves that to the user (i.e. a variant cannot
actually be empty, but it can contain an instance of Empty - i.e. a
byte).
Note that this is more of a constrained Any type, but they basically do
the same things anyway :^)
2021-05-05 19:02:51 +02:00
Ali Mohammad Pur
ab03c6fadf AK: Export integer_sequence_generate_array() 2021-05-05 19:02:51 +02:00
Ali Mohammad Pur
b361793ad8 AK: Add min() and max() methods to Array<T, N>
...That are only defined when min() and max() are defined on the
elements.
2021-05-05 19:02:51 +02:00