HeapBlock.cpp 2.5 KB

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