Serenity Operating System
1/*
2 * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/Assertions.h>
8#include <AK/NonnullOwnPtr.h>
9#include <AK/Platform.h>
10#include <LibJS/Heap/Heap.h>
11#include <LibJS/Heap/HeapBlock.h>
12#include <stdio.h>
13#include <sys/mman.h>
14
15#ifdef HAS_ADDRESS_SANITIZER
16# include <sanitizer/asan_interface.h>
17#endif
18
19namespace JS {
20
21NonnullOwnPtr<HeapBlock> HeapBlock::create_with_cell_size(Heap& heap, size_t cell_size)
22{
23#ifdef AK_OS_SERENITY
24 char name[64];
25 snprintf(name, sizeof(name), "LibJS: HeapBlock(%zu)", cell_size);
26#else
27 char const* name = nullptr;
28#endif
29 auto* block = static_cast<HeapBlock*>(heap.block_allocator().allocate_block(name));
30 new (block) HeapBlock(heap, cell_size);
31 return NonnullOwnPtr<HeapBlock>(NonnullOwnPtr<HeapBlock>::Adopt, *block);
32}
33
34HeapBlock::HeapBlock(Heap& heap, size_t cell_size)
35 : m_heap(heap)
36 , m_cell_size(cell_size)
37{
38 VERIFY(cell_size >= sizeof(FreelistEntry));
39 ASAN_POISON_MEMORY_REGION(m_storage, block_size - sizeof(HeapBlock));
40}
41
42void HeapBlock::deallocate(Cell* cell)
43{
44 VERIFY(is_valid_cell_pointer(cell));
45 VERIFY(!m_freelist || is_valid_cell_pointer(m_freelist));
46 VERIFY(cell->state() == Cell::State::Live);
47 VERIFY(!cell->is_marked());
48
49 cell->~Cell();
50 auto* freelist_entry = new (cell) FreelistEntry();
51 freelist_entry->set_state(Cell::State::Dead);
52 freelist_entry->next = m_freelist;
53 m_freelist = freelist_entry;
54
55#ifdef HAS_ADDRESS_SANITIZER
56 auto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);
57 VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);
58 VERIFY(m_cell_size >= sizeof(FreelistEntry));
59 // We can't poision the cell tracking data, nor the FreeListEntry's vtable or next pointer
60 // This means there's sizeof(FreelistEntry) data at the front of each cell that is always read/write
61 // On x86_64, this ends up being 24 bytes due to the size of the FreeListEntry's vtable, while on x86, it's only 12 bytes.
62 ASAN_POISON_MEMORY_REGION(reinterpret_cast<void*>(dword_after_freelist), m_cell_size - sizeof(FreelistEntry));
63#endif
64}
65
66}