safe_list.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*************************************************************************/
  2. /* safe_list.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 <functional>
  35. #if !defined(NO_THREADS)
  36. #include <atomic>
  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 <class T, class 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. void 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;
  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. }
  196. };
  197. #else // NO_THREADS
  198. // Effectively the same structure without the atomics. It's probably possible to simplify it but the semantics shouldn't differ greatly.
  199. template <class T, class A = DefaultAllocator>
  200. class SafeList {
  201. struct SafeListNode {
  202. SafeListNode *next = nullptr;
  203. // If the node is logically deleted, this pointer will typically point to the previous list item in time that was also logically deleted.
  204. SafeListNode *graveyard_next = nullptr;
  205. std::function<void(T)> deletion_fn = [](T t) { return; };
  206. T val;
  207. };
  208. SafeListNode *head = nullptr;
  209. SafeListNode *graveyard_head = nullptr;
  210. unsigned int active_iterator_count = 0;
  211. public:
  212. class Iterator {
  213. friend class SafeList;
  214. SafeListNode *cursor = nullptr;
  215. SafeList *list = nullptr;
  216. public:
  217. Iterator(SafeListNode *p_cursor, SafeList *p_list) :
  218. cursor(p_cursor), list(p_list) {
  219. list->active_iterator_count++;
  220. }
  221. ~Iterator() {
  222. list->active_iterator_count--;
  223. }
  224. T &operator*() {
  225. return cursor->val;
  226. }
  227. Iterator &operator++() {
  228. cursor = cursor->next;
  229. return *this;
  230. }
  231. // These two operators are mostly useful for comparisons to nullptr.
  232. bool operator==(const void *p_other) const {
  233. return cursor == p_other;
  234. }
  235. bool operator!=(const void *p_other) const {
  236. return cursor != p_other;
  237. }
  238. // These two allow easy range-based for loops.
  239. bool operator==(const Iterator &p_other) const {
  240. return cursor == p_other.cursor;
  241. }
  242. bool operator!=(const Iterator &p_other) const {
  243. return cursor != p_other.cursor;
  244. }
  245. };
  246. public:
  247. // Calling this will cause an allocation.
  248. void insert(T p_value) {
  249. SafeListNode *new_node = memnew_allocator(SafeListNode, A);
  250. new_node->val = p_value;
  251. new_node->next = head;
  252. head = new_node;
  253. }
  254. Iterator find(T p_value) {
  255. for (Iterator it = begin(); it != end(); ++it) {
  256. if (*it == p_value) {
  257. return it;
  258. }
  259. }
  260. return end();
  261. }
  262. void erase(T p_value, std::function<void(T)> p_deletion_fn) {
  263. erase(find(p_value), p_deletion_fn);
  264. }
  265. void erase(T p_value) {
  266. erase(find(p_value), [](T t) { return; });
  267. }
  268. void erase(Iterator p_iterator, std::function<void(T)> p_deletion_fn) {
  269. p_iterator.cursor->deletion_fn = p_deletion_fn;
  270. erase(p_iterator);
  271. }
  272. void erase(Iterator p_iterator) {
  273. Iterator prev = begin();
  274. for (; prev != end(); ++prev) {
  275. if (prev.cursor && prev.cursor->next == p_iterator.cursor) {
  276. break;
  277. }
  278. }
  279. if (prev == end()) {
  280. // Not in the list, nothing to do.
  281. return;
  282. }
  283. // First, remove the node from the list.
  284. prev.cursor->next = p_iterator.cursor->next;
  285. // Then queue it for deletion by putting it in the node graveyard. Don't touch `next` because an iterator might still be pointing at this node.
  286. p_iterator.cursor->graveyard_next = graveyard_head;
  287. graveyard_head = p_iterator.cursor;
  288. }
  289. Iterator begin() {
  290. return Iterator(head, this);
  291. }
  292. Iterator end() {
  293. return Iterator(nullptr, this);
  294. }
  295. // Calling this will cause zero to many deallocations.
  296. void maybe_cleanup() {
  297. SafeListNode *cursor = graveyard_head;
  298. if (active_iterator_count != 0) {
  299. // It's not safe to clean up with an active iterator, because that iterator could be pointing to an element that we want to delete.
  300. return;
  301. }
  302. graveyard_head = nullptr;
  303. // Our graveyard list is now unreachable by any active iterators, detached from the main graveyard head and ready for deletion.
  304. while (cursor) {
  305. SafeListNode *tmp = cursor;
  306. cursor = cursor->next;
  307. tmp->deletion_fn(tmp->val);
  308. memdelete_allocator<SafeListNode, A>(tmp);
  309. }
  310. }
  311. };
  312. #endif
  313. #endif // SAFE_LIST_H