FinalizationRegistry.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/FinalizationRegistry.h>
  8. namespace JS {
  9. FinalizationRegistry* FinalizationRegistry::create(GlobalObject& global_object, FunctionObject& cleanup_callback)
  10. {
  11. return global_object.heap().allocate<FinalizationRegistry>(global_object, cleanup_callback, *global_object.finalization_registry_prototype());
  12. }
  13. FinalizationRegistry::FinalizationRegistry(FunctionObject& cleanup_callback, Object& prototype)
  14. : Object(prototype)
  15. , WeakContainer(heap())
  16. , m_cleanup_callback(&cleanup_callback)
  17. {
  18. }
  19. FinalizationRegistry::~FinalizationRegistry()
  20. {
  21. }
  22. void FinalizationRegistry::add_finalization_record(Cell& target, Value held_value, Object* unregister_token)
  23. {
  24. VERIFY(!held_value.is_empty());
  25. m_records.append({ &target, held_value, unregister_token });
  26. }
  27. bool FinalizationRegistry::remove_by_token(Object& unregister_token)
  28. {
  29. auto removed = false;
  30. for (auto it = m_records.begin(); it != m_records.end(); ++it) {
  31. if (it->unregister_token == &unregister_token) {
  32. it.remove(m_records);
  33. removed = true;
  34. }
  35. }
  36. return removed;
  37. }
  38. void FinalizationRegistry::remove_dead_cells(Badge<Heap>)
  39. {
  40. auto any_cells_were_removed = false;
  41. for (auto& record : m_records) {
  42. if (!record.target || record.target->state() == Cell::State::Live)
  43. continue;
  44. record.target = nullptr;
  45. any_cells_were_removed = true;
  46. break;
  47. }
  48. if (any_cells_were_removed)
  49. vm().enqueue_finalization_registry_cleanup_job(*this);
  50. }
  51. // 9.13 CleanupFinalizationRegistry ( finalizationRegistry ), https://tc39.es/ecma262/#sec-cleanup-finalization-registry
  52. void FinalizationRegistry::cleanup(FunctionObject* callback)
  53. {
  54. auto& vm = this->vm();
  55. auto cleanup_callback = callback ?: m_cleanup_callback;
  56. for (auto it = m_records.begin(); it != m_records.end(); ++it) {
  57. if (it->target != nullptr)
  58. continue;
  59. (void)call(global_object(), *cleanup_callback, js_undefined(), it->held_value);
  60. it.remove(m_records);
  61. if (vm.exception())
  62. return;
  63. }
  64. }
  65. void FinalizationRegistry::visit_edges(Cell::Visitor& visitor)
  66. {
  67. Base::visit_edges(visitor);
  68. visitor.visit(m_cleanup_callback);
  69. for (auto& record : m_records) {
  70. visitor.visit(record.held_value);
  71. visitor.visit(record.unregister_token);
  72. }
  73. }
  74. }