ladybird/Userland/Libraries/LibJS/Runtime/BigInt.cpp
Andreas Kling 3c74dc9f4d LibJS: Segregate GC-allocated objects by type
This patch adds two macros to declare per-type allocators:

- JS_DECLARE_ALLOCATOR(TypeName)
- JS_DEFINE_ALLOCATOR(TypeName)

When used, they add a type-specific CellAllocator that the Heap will
delegate allocation requests to.

The result of this is that GC objects of the same type always end up
within the same HeapBlock, drastically reducing the ability to perform
type confusion attacks.

It also improves HeapBlock utilization, since each block now has cells
sized exactly to the type used within that block. (Previously we only
had a handful of block sizes available, and most GC allocations ended
up with a large amount of slack in their tails.)

There is a small performance hit from this, but I'm sure we can make
up for it elsewhere.

Note that the old size-based allocators still exist, and we fall back
to them for any type that doesn't have its own CellAllocator.
2023-11-19 12:10:31 +01:00

45 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibJS/Heap/Heap.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/GlobalObject.h>
namespace JS {
JS_DEFINE_ALLOCATOR(BigInt);
NonnullGCPtr<BigInt> BigInt::create(VM& vm, Crypto::SignedBigInteger big_integer)
{
return vm.heap().allocate_without_realm<BigInt>(move(big_integer));
}
BigInt::BigInt(Crypto::SignedBigInteger big_integer)
: m_big_integer(move(big_integer))
{
VERIFY(!m_big_integer.is_invalid());
}
ErrorOr<String> BigInt::to_string() const
{
return String::formatted("{}n", TRY(m_big_integer.to_base(10)));
}
// 21.2.1.1.1 NumberToBigInt ( number ), https://tc39.es/ecma262/#sec-numbertobigint
ThrowCompletionOr<BigInt*> number_to_bigint(VM& vm, Value number)
{
VERIFY(number.is_number());
// 1. If IsIntegralNumber(number) is false, throw a RangeError exception.
if (!number.is_integral_number())
return vm.throw_completion<RangeError>(ErrorType::BigIntFromNonIntegral);
// 2. Return the BigInt value that represents (number).
return BigInt::create(vm, Crypto::SignedBigInteger { number.as_double() }).ptr();
}
}