safe_list.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. #ifndef SAFE_LIST_H
  31. #define SAFE_LIST_H
  32. #include "core/os/memory.h"
  33. #include "core/typedefs.h"
  34. #include <atomic>
  35. #include <functional>
  36. #include <initializer_list>
  37. #include <type_traits>
  38. // Design goals for these classes:
  39. // - Accessing this list with an iterator will never result in a use-after free,
  40. // even if the element being accessed has been logically removed from the list on
  41. // another thread.
  42. // - Logical deletion from the list will not result in deallocation at that time,
  43. // instead the node will be deallocated at a later time when it is safe to do so.
  44. // - No blocking synchronization primitives will be used.
  45. // This is used in very specific areas of the engine where it's critical that these guarantees are held.
  46. template <typename T, typename A = DefaultAllocator>
  47. class SafeList {
  48. struct SafeListNode {
  49. std::atomic<SafeListNode *> next = nullptr;
  50. // If the node is logically deleted, this pointer will typically point
  51. // to the previous list item in time that was also logically deleted.
  52. std::atomic<SafeListNode *> graveyard_next = nullptr;
  53. std::function<void(T)> deletion_fn = [](T t) { return; };
  54. T val;
  55. };
  56. static_assert(std::atomic<T>::is_always_lock_free);
  57. std::atomic<SafeListNode *> head = nullptr;
  58. std::atomic<SafeListNode *> graveyard_head = nullptr;
  59. std::atomic_uint active_iterator_count = 0;
  60. public:
  61. class Iterator {
  62. friend class SafeList;
  63. SafeListNode *cursor = nullptr;
  64. SafeList *list = nullptr;
  65. Iterator(SafeListNode *p_cursor, SafeList *p_list) :
  66. cursor(p_cursor), list(p_list) {
  67. list->active_iterator_count++;
  68. }
  69. public:
  70. Iterator(const Iterator &p_other) :
  71. cursor(p_other.cursor), list(p_other.list) {
  72. list->active_iterator_count++;
  73. }
  74. ~Iterator() {
  75. list->active_iterator_count--;
  76. }
  77. public:
  78. T &operator*() {
  79. return cursor->val;
  80. }
  81. Iterator &operator++() {
  82. cursor = cursor->next;
  83. return *this;
  84. }
  85. // These two operators are mostly useful for comparisons to nullptr.
  86. bool operator==(const void *p_other) const {
  87. return cursor == p_other;
  88. }
  89. bool operator!=(const void *p_other) const {
  90. return cursor != p_other;
  91. }
  92. // These two allow easy range-based for loops.
  93. bool operator==(const Iterator &p_other) const {
  94. return cursor == p_other.cursor;
  95. }
  96. bool operator!=(const Iterator &p_other) const {
  97. return cursor != p_other.cursor;
  98. }
  99. };
  100. public:
  101. // Calling this will cause an allocation.
  102. void insert(T p_value) {
  103. SafeListNode *new_node = memnew_allocator(SafeListNode, A);
  104. new_node->val = p_value;
  105. SafeListNode *expected_head = nullptr;
  106. do {
  107. expected_head = head.load();
  108. new_node->next.store(expected_head);
  109. } while (!head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ new_node));
  110. }
  111. Iterator find(T p_value) {
  112. for (Iterator it = begin(); it != end(); ++it) {
  113. if (*it == p_value) {
  114. return it;
  115. }
  116. }
  117. return end();
  118. }
  119. void erase(T p_value, std::function<void(T)> p_deletion_fn) {
  120. Iterator tmp = find(p_value);
  121. erase(tmp, p_deletion_fn);
  122. }
  123. void erase(T p_value) {
  124. Iterator tmp = find(p_value);
  125. erase(tmp, [](T t) { return; });
  126. }
  127. void erase(Iterator &p_iterator, std::function<void(T)> p_deletion_fn) {
  128. p_iterator.cursor->deletion_fn = p_deletion_fn;
  129. erase(p_iterator);
  130. }
  131. void erase(Iterator &p_iterator) {
  132. if (find(p_iterator.cursor->val) == nullptr) {
  133. // Not in the list, nothing to do.
  134. return;
  135. }
  136. // First, remove the node from the list.
  137. while (true) {
  138. Iterator prev = begin();
  139. SafeListNode *expected_head = prev.cursor;
  140. for (; prev != end(); ++prev) {
  141. if (prev.cursor && prev.cursor->next == p_iterator.cursor) {
  142. break;
  143. }
  144. }
  145. if (prev != end()) {
  146. // There exists a node before this.
  147. prev.cursor->next.store(p_iterator.cursor->next.load());
  148. // Done.
  149. break;
  150. } else {
  151. if (head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ p_iterator.cursor->next.load())) {
  152. // Successfully reassigned the head pointer before another thread changed it to something else.
  153. break;
  154. }
  155. // Fall through upon failure, try again.
  156. }
  157. }
  158. // Then queue it for deletion by putting it in the node graveyard.
  159. // Don't touch `next` because an iterator might still be pointing at this node.
  160. SafeListNode *expected_head = nullptr;
  161. do {
  162. expected_head = graveyard_head.load();
  163. p_iterator.cursor->graveyard_next.store(expected_head);
  164. } while (!graveyard_head.compare_exchange_strong(/* expected= */ expected_head, /* new= */ p_iterator.cursor));
  165. }
  166. Iterator begin() {
  167. return Iterator(head.load(), this);
  168. }
  169. Iterator end() {
  170. return Iterator(nullptr, this);
  171. }
  172. // Calling this will cause zero to many deallocations.
  173. bool maybe_cleanup() {
  174. SafeListNode *cursor = nullptr;
  175. SafeListNode *new_graveyard_head = nullptr;
  176. do {
  177. // The access order here is theoretically important.
  178. cursor = graveyard_head.load();
  179. if (active_iterator_count.load() != 0) {
  180. // It's not safe to clean up with an active iterator, because that iterator
  181. // could be pointing to an element that we want to delete.
  182. return false;
  183. }
  184. // Any iterator created after this point will never point to a deleted node.
  185. // Swap it out with the current graveyard head.
  186. } while (!graveyard_head.compare_exchange_strong(/* expected= */ cursor, /* new= */ new_graveyard_head));
  187. // Our graveyard list is now unreachable by any active iterators,
  188. // detached from the main graveyard head and ready for deletion.
  189. while (cursor) {
  190. SafeListNode *tmp = cursor;
  191. cursor = cursor->graveyard_next;
  192. tmp->deletion_fn(tmp->val);
  193. memdelete_allocator<SafeListNode, A>(tmp);
  194. }
  195. return true;
  196. }
  197. _FORCE_INLINE_ SafeList() {}
  198. _FORCE_INLINE_ SafeList(std::initializer_list<T> p_init) {
  199. for (const T &E : p_init) {
  200. insert(E);
  201. }
  202. }
  203. ~SafeList() {
  204. #ifdef DEBUG_ENABLED
  205. if (!maybe_cleanup()) {
  206. ERR_PRINT("There are still iterators around when destructing a SafeList. Memory will be leaked. This is a bug.");
  207. }
  208. #else
  209. maybe_cleanup();
  210. #endif
  211. }
  212. };
  213. #endif // SAFE_LIST_H