2021-05-27 13:01:26 -04:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <AK/Vector.h>
|
|
|
|
#include <LibJS/Forward.h>
|
|
|
|
#include <LibJS/Heap/BlockAllocator.h>
|
|
|
|
#include <LibJS/Heap/HeapBlock.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <sys/mman.h>
|
|
|
|
|
|
|
|
namespace JS {
|
|
|
|
|
|
|
|
BlockAllocator::BlockAllocator()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
BlockAllocator::~BlockAllocator()
|
|
|
|
{
|
|
|
|
for (auto* block : m_blocks) {
|
2021-05-27 14:06:47 -04:00
|
|
|
#ifdef __serenity__
|
2021-05-27 13:01:26 -04:00
|
|
|
if (munmap(block, HeapBlock::block_size) < 0) {
|
|
|
|
perror("munmap");
|
|
|
|
VERIFY_NOT_REACHED();
|
|
|
|
}
|
2021-05-27 14:06:47 -04:00
|
|
|
#else
|
|
|
|
free(block);
|
|
|
|
#endif
|
2021-05-27 13:01:26 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void* BlockAllocator::allocate_block([[maybe_unused]] char const* name)
|
|
|
|
{
|
|
|
|
if (!m_blocks.is_empty())
|
|
|
|
return m_blocks.take_last();
|
|
|
|
|
|
|
|
#ifdef __serenity__
|
|
|
|
auto* block = (HeapBlock*)serenity_mmap(nullptr, HeapBlock::block_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_RANDOMIZED | MAP_PRIVATE, 0, 0, HeapBlock::block_size, name);
|
|
|
|
#else
|
|
|
|
auto* block = (HeapBlock*)aligned_alloc(HeapBlock::block_size, HeapBlock::block_size);
|
|
|
|
#endif
|
|
|
|
VERIFY(block != MAP_FAILED);
|
|
|
|
return block;
|
|
|
|
}
|
|
|
|
|
|
|
|
void BlockAllocator::deallocate_block(void* block)
|
|
|
|
{
|
|
|
|
VERIFY(block);
|
|
|
|
if (m_blocks.size() >= max_cached_blocks) {
|
2021-05-27 14:06:47 -04:00
|
|
|
#ifdef __serenity__
|
2021-05-27 13:01:26 -04:00
|
|
|
if (munmap(block, HeapBlock::block_size) < 0) {
|
|
|
|
perror("munmap");
|
|
|
|
VERIFY_NOT_REACHED();
|
|
|
|
}
|
2021-05-27 14:06:47 -04:00
|
|
|
#else
|
|
|
|
free(block);
|
|
|
|
#endif
|
2021-05-27 13:01:26 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
m_blocks.append(block);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|