HeapBlock.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, size_t cell_size)
  18. {
  19. #ifdef __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*>(heap.block_allocator().allocate_block(name));
  26. new (block) HeapBlock(heap, cell_size);
  27. return NonnullOwnPtr<HeapBlock>(NonnullOwnPtr<HeapBlock>::Adopt, *block);
  28. }
  29. HeapBlock::HeapBlock(Heap& heap, size_t cell_size)
  30. : m_heap(heap)
  31. , m_cell_size(cell_size)
  32. {
  33. VERIFY(cell_size >= sizeof(FreelistEntry));
  34. ASAN_POISON_MEMORY_REGION(m_storage, block_size);
  35. }
  36. void HeapBlock::deallocate(Cell* cell)
  37. {
  38. VERIFY(is_valid_cell_pointer(cell));
  39. VERIFY(!m_freelist || is_valid_cell_pointer(m_freelist));
  40. VERIFY(cell->state() == Cell::State::Live);
  41. VERIFY(!cell->is_marked());
  42. cell->~Cell();
  43. auto* freelist_entry = new (cell) FreelistEntry();
  44. freelist_entry->set_state(Cell::State::Dead);
  45. freelist_entry->next = m_freelist;
  46. m_freelist = freelist_entry;
  47. #ifdef HAS_ADDRESS_SANITIZER
  48. auto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);
  49. VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);
  50. VERIFY(m_cell_size >= sizeof(FreelistEntry));
  51. // We can't poision the cell tracking data, nor the FreeListEntry's vtable or next pointer
  52. // This means there's sizeof(FreelistEntry) data at the front of each cell that is always read/write
  53. // 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.
  54. ASAN_POISON_MEMORY_REGION(reinterpret_cast<void*>(dword_after_freelist), m_cell_size - sizeof(FreelistEntry));
  55. #endif
  56. }
  57. }