safe_list.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /**************************************************************************/
  2. /* safe_list.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #include "core/os/memory.h"
  32. #include "core/typedefs.h"
  33. #include <atomic>
  34. #include <functional>
  35. #include <initializer_list>
  36. // Design goals for these classes:
  37. // - Accessing this list with an iterator will never result in a use-after free,
  38. // even if the element being accessed has been logically removed from the list on
  39. // another thread.
  40. // - Logical deletion from the list will not result in deallocation at that time,
  41. // instead the node will be deallocated at a later time when it is safe to do so.
  42. // - No blocking synchronization primitives will be used.
  43. // This is used in very specific areas of the engine where it's critical that these guarantees are held.
  44. template <typename T, typename A = DefaultAllocator>
  45. class SafeList {
  46. struct SafeListNode {
  47. std::atomic<SafeListNode *> next = nullptr;
  48. // If the node is logically deleted, this pointer will typically point
  49. // to the previous list item in time that was also logically deleted.
  50. std::atomic<SafeListNode *> graveyard_next = nullptr;
  51. std::function<void(T)> deletion_fn = [](T t) { return; };
  52. T val;
  53. };
  54. static_assert(std::atomic<T>::is_always_lock_free);
  55. std::atomic<SafeListNode *> head = nullptr;
  56. std::atomic<SafeListNode *> graveyard_head = nullptr;
  57. std::atomic_uint active_iterator_count = 0;
  58. public:
  59. class Iterator {
  60. friend class SafeList;
  61. SafeListNode *cursor = nullptr;
  62. SafeList *list = nullptr;
  63. Iterator(SafeListNode *p_cursor, SafeList *p_list) :
  64. cursor(p_cursor), list(p_list) {
  65. list->active_iterator_count++;
  66. }
  67. public:
  68. Iterator(const Iterator &p_other) :
  69. cursor(p_other.cursor), list(p_other.list) {
  70. list->active_iterator_count++;
  71. }
  72. ~Iterator() {
  73. list->active_iterator_count--;
  74. }
  75. public:
  76. T &operator*() {
  77. return cursor->val;
  78. }
  79. Iterator &operator++() {
  80. cursor = cursor->next;
  81. return *this;
  82. }
  83. // These two operators are mostly useful for comparisons to nullptr.
  84. bool operator==(const void *p_other) const {
  85. return cursor == p_other;
  86. }
  87. bool operator!=(const void *p_other) const {
  88. return cursor != p_other;
  89. }
  90. // These two allow easy range-based for loops.
  91. bool operator==(const Iterator &p_other) const {
  92. return cursor == p_other.cursor;
  93. }
  94. bool operator!=(const Iterator &p_other) const {
  95. return cursor != p_other.cursor;
  96. }
  97. };
  98. public:
  99. // Calling this will cause an allocation.
  100. void insert(T p_value) {
  101. SafeListNode *new_node = memnew_allocator(SafeListNode, A);
  102. new_node->val = p_value;
  103. SafeListNode *expected_head = nullptr;
  104. do {
  105. expected_head = head.load();
  106. new_node->next.store(expected_head);
  107. } while (!head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ new_node));
  108. }
  109. Iterator find(T p_value) {
  110. for (Iterator it = begin(); it != end(); ++it) {
  111. if (*it == p_value) {
  112. return it;
  113. }
  114. }
  115. return end();
  116. }
  117. void erase(T p_value, std::function<void(T)> p_deletion_fn) {
  118. Iterator tmp = find(p_value);
  119. erase(tmp, p_deletion_fn);
  120. }
  121. void erase(T p_value) {
  122. Iterator tmp = find(p_value);
  123. erase(tmp, [](T t) { return; });
  124. }
  125. void erase(Iterator &p_iterator, std::function<void(T)> p_deletion_fn) {
  126. p_iterator.cursor->deletion_fn = p_deletion_fn;
  127. erase(p_iterator);
  128. }
  129. void erase(Iterator &p_iterator) {
  130. if (find(p_iterator.cursor->val) == nullptr) {
  131. // Not in the list, nothing to do.
  132. return;
  133. }
  134. // First, remove the node from the list.
  135. while (true) {
  136. Iterator prev = begin();
  137. SafeListNode *expected_head = prev.cursor;
  138. for (; prev != end(); ++prev) {
  139. if (prev.cursor && prev.cursor->next == p_iterator.cursor) {
  140. break;
  141. }
  142. }
  143. if (prev != end()) {
  144. // There exists a node before this.
  145. prev.cursor->next.store(p_iterator.cursor->next.load());
  146. // Done.
  147. break;
  148. } else {
  149. if (head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ p_iterator.cursor->next.load())) {
  150. // Successfully reassigned the head pointer before another thread changed it to something else.
  151. break;
  152. }
  153. // Fall through upon failure, try again.
  154. }
  155. }
  156. // Then queue it for deletion by putting it in the node graveyard.
  157. // Don't touch `next` because an iterator might still be pointing at this node.
  158. SafeListNode *expected_head = nullptr;
  159. do {
  160. expected_head = graveyard_head.load();
  161. p_iterator.cursor->graveyard_next.store(expected_head);
  162. } while (!graveyard_head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ p_iterator.cursor));
  163. }
  164. Iterator begin() {
  165. return Iterator(head.load(), this);
  166. }
  167. Iterator end() {
  168. return Iterator(nullptr, this);
  169. }
  170. // Calling this will cause zero to many deallocations.
  171. bool maybe_cleanup() {
  172. SafeListNode *cursor = nullptr;
  173. SafeListNode *new_graveyard_head = nullptr;
  174. do {
  175. // The access order here is theoretically important.
  176. cursor = graveyard_head.load();
  177. if (active_iterator_count.load() != 0) {
  178. // It's not safe to clean up with an active iterator, because that iterator
  179. // could be pointing to an element that we want to delete.
  180. return false;
  181. }
  182. // Any iterator created after this point will never point to a deleted node.
  183. // Swap it out with the current graveyard head.
  184. } while (!graveyard_head.compare_exchange_strong(/* expected= */ cursor, /* new= */ new_graveyard_head));
  185. // Our graveyard list is now unreachable by any active iterators,
  186. // detached from the main graveyard head and ready for deletion.
  187. while (cursor) {
  188. SafeListNode *tmp = cursor;
  189. cursor = cursor->graveyard_next;
  190. tmp->deletion_fn(tmp->val);
  191. memdelete_allocator<SafeListNode, A>(tmp);
  192. }
  193. return true;
  194. }
  195. _FORCE_INLINE_ SafeList() {}
  196. _FORCE_INLINE_ SafeList(std::initializer_list<T> p_init) {
  197. for (const T &E : p_init) {
  198. insert(E);
  199. }
  200. }
  201. ~SafeList() {
  202. #ifdef DEBUG_ENABLED
  203. if (!maybe_cleanup()) {
  204. ERR_PRINT("There are still iterators around when destructing a SafeList. Memory will be leaked. This is a bug.");
  205. }
  206. #else
  207. maybe_cleanup();
  208. #endif
  209. }
  210. };