1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 00:17:46 +00:00

LibIPC+LibC: Add and use a helper to encode/decoder container sizes

While refactoring the IPC encoders and decoders for fallibility, the
inconsistency in which we transfer container sizes was a frequent thing
to trip over. We currently transfer sizes as any of i32, u32, and u64.
This adds a helper to transfer sizes in one consistent way.

Two special cases here are DeprecatedString and Vector, whose encoding
is depended upon by netdb, so that is also updated here.
This commit is contained in:
Timothy Flynn 2023-01-04 07:08:29 -05:00 committed by Linus Groh
parent 40165f5846
commit 7c6b5ed161
5 changed files with 48 additions and 35 deletions

View file

@ -5,6 +5,7 @@
*/
#include <AK/JsonValue.h>
#include <AK/NumericLimits.h>
#include <AK/URL.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibCore/DateTime.h>
@ -16,19 +17,24 @@
namespace IPC {
ErrorOr<size_t> Decoder::decode_size()
{
return static_cast<size_t>(TRY(decode<u32>()));
}
template<>
ErrorOr<DeprecatedString> decode(Decoder& decoder)
{
auto length = TRY(decoder.decode<i32>());
if (length < 0)
auto length = TRY(decoder.decode_size());
if (length == NumericLimits<u32>::max())
return DeprecatedString {};
if (length == 0)
return DeprecatedString::empty();
char* text_buffer = nullptr;
auto text_impl = StringImpl::create_uninitialized(static_cast<size_t>(length), text_buffer);
auto text_impl = StringImpl::create_uninitialized(length, text_buffer);
Bytes bytes { text_buffer, static_cast<size_t>(length) };
Bytes bytes { text_buffer, length };
TRY(decoder.decode_into(bytes));
return DeprecatedString { *text_impl };
@ -37,8 +43,8 @@ ErrorOr<DeprecatedString> decode(Decoder& decoder)
template<>
ErrorOr<ByteBuffer> decode(Decoder& decoder)
{
auto length = TRY(decoder.decode<i32>());
if (length <= 0)
auto length = TRY(decoder.decode_size());
if (length == 0)
return ByteBuffer {};
auto buffer = TRY(ByteBuffer::create_uninitialized(length));
@ -65,10 +71,7 @@ ErrorOr<URL> decode(Decoder& decoder)
template<>
ErrorOr<Dictionary> decode(Decoder& decoder)
{
auto size = TRY(decoder.decode<u64>());
if (size >= NumericLimits<i32>::max())
VERIFY_NOT_REACHED();
auto size = TRY(decoder.decode_size());
Dictionary dictionary {};
for (size_t i = 0; i < size; ++i) {
@ -99,7 +102,7 @@ ErrorOr<Core::AnonymousBuffer> decode(Decoder& decoder)
if (auto valid = TRY(decoder.decode<bool>()); !valid)
return Core::AnonymousBuffer {};
auto size = TRY(decoder.decode<u32>());
auto size = TRY(decoder.decode_size());
auto anon_file = TRY(decoder.decode<IPC::File>());
return Core::AnonymousBuffer::create_from_anon_fd(anon_file.take_fd(), size);