HeapBlock.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2020-2024, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/NonnullOwnPtr.h>
  8. #include <AK/Platform.h>
  9. #include <LibJS/Heap/Heap.h>
  10. #include <LibJS/Heap/HeapBlock.h>
  11. #include <stdio.h>
  12. #include <sys/mman.h>
  13. #ifdef HAS_ADDRESS_SANITIZER
  14. # include <sanitizer/asan_interface.h>
  15. #endif
  16. namespace JS {
  17. size_t HeapBlockBase::block_size = PAGE_SIZE;
  18. NonnullOwnPtr<HeapBlock> HeapBlock::create_with_cell_size(Heap& heap, CellAllocator& cell_allocator, size_t cell_size, [[maybe_unused]] char const* class_name)
  19. {
  20. char const* name = nullptr;
  21. auto* block = static_cast<HeapBlock*>(cell_allocator.block_allocator().allocate_block(name));
  22. new (block) HeapBlock(heap, cell_allocator, cell_size);
  23. return NonnullOwnPtr<HeapBlock>(NonnullOwnPtr<HeapBlock>::Adopt, *block);
  24. }
  25. HeapBlock::HeapBlock(Heap& heap, CellAllocator& cell_allocator, size_t cell_size)
  26. : HeapBlockBase(heap)
  27. , m_cell_allocator(cell_allocator)
  28. , m_cell_size(cell_size)
  29. {
  30. VERIFY(cell_size >= sizeof(FreelistEntry));
  31. ASAN_POISON_MEMORY_REGION(m_storage, block_size - sizeof(HeapBlock));
  32. }
  33. void HeapBlock::deallocate(CellImpl* cell)
  34. {
  35. VERIFY(is_valid_cell_pointer(cell));
  36. VERIFY(!m_freelist || is_valid_cell_pointer(m_freelist));
  37. VERIFY(cell->state() == CellImpl::State::Live);
  38. VERIFY(!cell->is_marked());
  39. cell->~CellImpl();
  40. auto* freelist_entry = new (cell) FreelistEntry();
  41. freelist_entry->set_state(CellImpl::State::Dead);
  42. freelist_entry->next = m_freelist;
  43. m_freelist = freelist_entry;
  44. #ifdef HAS_ADDRESS_SANITIZER
  45. auto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);
  46. VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);
  47. VERIFY(m_cell_size >= sizeof(FreelistEntry));
  48. // We can't poision the cell tracking data, nor the FreeListEntry's vtable or next pointer
  49. // This means there's sizeof(FreelistEntry) data at the front of each cell that is always read/write
  50. // 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.
  51. ASAN_POISON_MEMORY_REGION(reinterpret_cast<void*>(dword_after_freelist), m_cell_size - sizeof(FreelistEntry));
  52. #endif
  53. }
  54. }