#include "config.h"
#include "WasmTable.h"
#if ENABLE(WEBASSEMBLY)
#include <wtf/CheckedArithmetic.h>
#include <wtf/StdLibExtras.h>
#include <type_traits>
namespace JSC { namespace Wasm {
uint32_t Table::allocatedLength(uint32_t length)
{
return WTF::roundUpToPowerOfTwo(length);
}
void Table::setLength(uint32_t length)
{
m_length = length;
m_mask = WTF::maskForSize(length);
ASSERT(isValidLength(length));
ASSERT(m_mask == WTF::maskForSize(allocatedLength(length)));
}
RefPtr<Table> Table::create(uint32_t initial, std::optional<uint32_t> maximum)
{
if (!isValidLength(initial))
return nullptr;
return adoptRef(new (NotNull, fastMalloc(sizeof(Table))) Table(initial, maximum));
}
Table::~Table()
{
}
Table::Table(uint32_t initial, std::optional<uint32_t> maximum)
{
setLength(initial);
m_maximum = maximum;
ASSERT(!m_maximum || *m_maximum >= m_length);
m_functions = MallocPtr<Wasm::CallableFunction>::malloc((sizeof(Wasm::CallableFunction) * Checked<size_t>(allocatedLength(m_length))).unsafeGet());
m_instances = MallocPtr<Instance*>::malloc((sizeof(Instance*) * Checked<size_t>(allocatedLength(m_length))).unsafeGet());
for (uint32_t i = 0; i < allocatedLength(m_length); ++i) {
new (&m_functions.get()[i]) CallableFunction();
ASSERT(m_functions.get()[i].signatureIndex == Wasm::Signature::invalidIndex); m_instances.get()[i] = nullptr;
}
}
std::optional<uint32_t> Table::grow(uint32_t delta)
{
if (delta == 0)
return length();
using Checked = Checked<uint32_t, RecordOverflow>;
Checked newLengthChecked = length();
newLengthChecked += delta;
uint32_t newLength;
if (newLengthChecked.safeGet(newLength) == CheckedState::DidOverflow)
return std::nullopt;
if (maximum() && newLength > *maximum())
return std::nullopt;
if (!isValidLength(newLength))
return std::nullopt;
auto checkedGrow = [&] (auto& container) {
if (newLengthChecked.unsafeGet() > allocatedLength(m_length)) {
Checked reallocSizeChecked = allocatedLength(newLengthChecked.unsafeGet());
reallocSizeChecked *= sizeof(*container.get());
uint32_t reallocSize;
if (reallocSizeChecked.safeGet(reallocSize) == CheckedState::DidOverflow)
return false;
container.realloc(reallocSize);
}
for (uint32_t i = m_length; i < allocatedLength(newLength); ++i)
new (&container.get()[i]) std::remove_reference_t<decltype(*container.get())>();
return true;
};
if (!checkedGrow(m_functions))
return std::nullopt;
if (!checkedGrow(m_instances))
return std::nullopt;
setLength(newLength);
return newLength;
}
void Table::clearFunction(uint32_t index)
{
RELEASE_ASSERT(index < length());
m_functions.get()[index & m_mask] = Wasm::CallableFunction();
ASSERT(m_functions.get()[index & m_mask].signatureIndex == Wasm::Signature::invalidIndex); m_instances.get()[index & m_mask] = nullptr;
}
void Table::setFunction(uint32_t index, CallableFunction function, Instance* instance)
{
RELEASE_ASSERT(index < length());
m_functions.get()[index & m_mask] = function;
m_instances.get()[index & m_mask] = instance;
}
} }
#endif // ENABLE(WEBASSEMBLY)