HeapBlock.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.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. NonnullOwnPtr<HeapBlock> HeapBlock::create_with_cell_size(Heap& heap, CellAllocator& cell_allocator, size_t cell_size)
  18. {
  19. #ifdef AK_OS_SERENITY
  20. char name[64];
  21. snprintf(name, sizeof(name), "LibJS: HeapBlock(%zu)", cell_size);
  22. #else
  23. char const* name = nullptr;
  24. #endif
  25. auto* block = static_cast<HeapBlock*>(cell_allocator.block_allocator().allocate_block(name));
  26. new (block) HeapBlock(heap, cell_allocator, cell_size);
  27. return NonnullOwnPtr<HeapBlock>(NonnullOwnPtr<HeapBlock>::Adopt, *block);
  28. }
  29. HeapBlock::HeapBlock(Heap& heap, CellAllocator& cell_allocator, size_t cell_size)
  30. : HeapBlockBase(heap)
  31. , m_cell_allocator(cell_allocator)
  32. , m_cell_size(cell_size)
  33. {
  34. VERIFY(cell_size >= sizeof(FreelistEntry));
  35. ASAN_POISON_MEMORY_REGION(m_storage, block_size - sizeof(HeapBlock));
  36. }
  37. void HeapBlock::deallocate(Cell* cell)
  38. {
  39. VERIFY(is_valid_cell_pointer(cell));
  40. VERIFY(!m_freelist || is_valid_cell_pointer(m_freelist));
  41. VERIFY(cell->state() == Cell::State::Live);
  42. VERIFY(!cell->is_marked());
  43. cell->~Cell();
  44. auto* freelist_entry = new (cell) FreelistEntry();
  45. freelist_entry->set_state(Cell::State::Dead);
  46. freelist_entry->next = m_freelist;
  47. m_freelist = freelist_entry;
  48. #ifdef HAS_ADDRESS_SANITIZER
  49. auto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);
  50. VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);
  51. VERIFY(m_cell_size >= sizeof(FreelistEntry));
  52. // We can't poision the cell tracking data, nor the FreeListEntry's vtable or next pointer
  53. // This means there's sizeof(FreelistEntry) data at the front of each cell that is always read/write
  54. // 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.
  55. ASAN_POISON_MEMORY_REGION(reinterpret_cast<void*>(dword_after_freelist), m_cell_size - sizeof(FreelistEntry));
  56. #endif
  57. }
  58. }