safe_list.h 8.0 KB

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